diff --git a/.github/workflows/third_party_review.yml b/.github/workflows/third_party_review.yml index 879ebaa345594a..58172d002ed628 100644 --- a/.github/workflows/third_party_review.yml +++ b/.github/workflows/third_party_review.yml @@ -64,9 +64,24 @@ jobs: allow-licenses: >- BSD-2-Clause, BSD-3-Clause, BSD-2-Clause-Views, MIT, MIT-0, ISC, Apache-2.0, EPL-2.0, MPL-2.0, CC0-1.0, Python-2.0, BlueOak-1.0.0 + # ([String]). Packages excluded from the license check, in purl format (optional). + # The action matches a purl on type and name only - it ignores the version - so an entry + # here allows every version of that package. + # # caniuse-lite is browser-compatibility data used only by the UI build toolchain. # Keep this exception package-specific because CC-BY-4.0 is not generally allow-listed. - allow-dependencies-licenses: pkg:npm/caniuse-lite@1.0.30001809 + # + # Both JUnit coordinates are test-scope dependencies that no release artifact ships; + # fail-on-scopes below covers `development`, which is why they reach this check at all. + # org.junit.jupiter:junit-jupiter is EPL-2.0, a licence allow-licenses above already + # carries, but GitHub's dependency graph reports it as LicenseRef-bad-non-standard, so + # every pull request that adds a module with a JUnit 5 test fails on a licence the + # project has already approved. junit:junit is EPL-1.0, an ASF Category B licence, and + # the JUnit 4 tests that need it run through junit-vintage-engine. + allow-dependencies-licenses: >- + pkg:npm/caniuse-lite@1.0.30001809, + pkg:maven/org.junit.jupiter/junit-jupiter, + pkg:maven/junit/junit # ([String]). Acknowledged advisories that must not fail the review (optional) # org.codehaus.jackson:jackson-mapper-asl (GHSA-c27h-mcmw-48hv, GHSA-r6j9-8759-g62w): # legacy Jackson 1.x is EOL and neither advisory has a fixed version. Hive's metastore diff --git a/fe/check/checkstyle/checkstyle.xml b/fe/check/checkstyle/checkstyle.xml index c97fbeed110b84..7e45b274463370 100644 --- a/fe/check/checkstyle/checkstyle.xml +++ b/fe/check/checkstyle/checkstyle.xml @@ -66,6 +66,26 @@ under the License. + + + + + + + + + diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/ConfigTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/ConfigTest.java index 395ff41f620a0b..64778f4109127d 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/ConfigTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/ConfigTest.java @@ -17,9 +17,9 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.nio.file.Files; @@ -28,7 +28,7 @@ import java.util.Map; public class ConfigTest { - @BeforeClass + @BeforeAll public static void setUp() throws Exception { Config config = new Config(); // create an empty config file to initialize Config @@ -46,10 +46,10 @@ public void testSensitiveConfigIsMaskedWhenSet() { Config.fe_meta_auth_token = "super-secret-token"; Map dumped = ConfigBase.dump(); - Assert.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, dumped.get("fe_meta_auth_token")); + Assertions.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, dumped.get("fe_meta_auth_token")); String value = configInfoValue("fe_meta_auth_token"); - Assert.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, value); + Assertions.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, value); } finally { Config.fe_meta_auth_token = old; } @@ -63,8 +63,8 @@ public void testAuthTokenIsMaskedWhenSet() { try { Config.auth_token = "super-secret-auth-token"; - Assert.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, ConfigBase.dump().get("auth_token")); - Assert.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, configInfoValue("auth_token")); + Assertions.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, ConfigBase.dump().get("auth_token")); + Assertions.assertEquals(ConfigBase.SENSITIVE_CONF_MASK, configInfoValue("auth_token")); } finally { Config.auth_token = old; } @@ -77,8 +77,8 @@ public void testEmptySensitiveConfigIsNotMasked() { try { Config.fe_meta_auth_token = ""; - Assert.assertEquals("", ConfigBase.dump().get("fe_meta_auth_token")); - Assert.assertEquals("", configInfoValue("fe_meta_auth_token")); + Assertions.assertEquals("", ConfigBase.dump().get("fe_meta_auth_token")); + Assertions.assertEquals("", configInfoValue("fe_meta_auth_token")); } finally { Config.fe_meta_auth_token = old; } @@ -97,7 +97,7 @@ private static String configInfoValue(String key) { public void testSetEmptyArray() throws ConfigException { ConfigBase.setMutableConfig("mysql_compat_var_whitelist", "a,b,c"); ConfigBase.setMutableConfig("mysql_compat_var_whitelist", ""); - Assert.assertEquals("array length should be 0", 0, Config.mysql_compat_var_whitelist.length); + Assertions.assertEquals(0, Config.mysql_compat_var_whitelist.length, "array length should be 0"); } @Test @@ -107,8 +107,7 @@ public void testConfFieldDescriptionsAreEnglishStrings() throws Exception { if (confField == null) { continue; } - Assert.assertFalse("Chinese description found in config: " + field.getName(), - confField.description().matches(".*[\\u4e00-\\u9fff].*")); + Assertions.assertFalse(confField.description().matches(".*[\\u4e00-\\u9fff].*"), "Chinese description found in config: " + field.getName()); } } @@ -126,9 +125,8 @@ public void testSecurityPathConfigsAreNotRuntimeMutable() { "force_sqlserver_jdbc_encrypt_false", }; for (String key : opsOnlyConfigs) { - ConfigException e = Assert.assertThrows(key + " should not be runtime-mutable", - ConfigException.class, () -> ConfigBase.setMutableConfig(key, "x")); - Assert.assertTrue(e.getMessage().contains("is not mutable")); + ConfigException e = Assertions.assertThrows(ConfigException.class, () -> ConfigBase.setMutableConfig(key, "x"), key + " should not be runtime-mutable"); + Assertions.assertTrue(e.getMessage().contains("is not mutable")); } } @@ -137,16 +135,16 @@ public void testRejectDeprecatedInvertedIndexV1WithWhitespace() throws Exception String originFormat = Config.inverted_index_storage_format; try { ConfigBase.setMutableConfig("inverted_index_storage_format", "V2"); - ConfigException dynamicException = Assert.assertThrows(ConfigException.class, + ConfigException dynamicException = Assertions.assertThrows(ConfigException.class, () -> ConfigBase.setMutableConfig("inverted_index_storage_format", " V1 ")); - Assert.assertTrue(dynamicException.getMessage().contains("Inverted index V1 is deprecated")); - Assert.assertEquals("V2", Config.inverted_index_storage_format); + Assertions.assertTrue(dynamicException.getMessage().contains("Inverted index V1 is deprecated")); + Assertions.assertEquals("V2", Config.inverted_index_storage_format); Config.inverted_index_storage_format = "V2"; - ConfigException startupException = Assert.assertThrows(ConfigException.class, + ConfigException startupException = Assertions.assertThrows(ConfigException.class, () -> InvertedIndexStorageFormatValidator.rejectStartupV1(" V1 ")); - Assert.assertTrue(startupException.getMessage().contains("inverted_index_storage_format=V1")); - Assert.assertEquals("V2", Config.inverted_index_storage_format); + Assertions.assertTrue(startupException.getMessage().contains("inverted_index_storage_format=V1")); + Assertions.assertEquals("V2", Config.inverted_index_storage_format); } finally { Config.inverted_index_storage_format = originFormat; } @@ -157,10 +155,10 @@ public void testSetWebSqlMaxResultBytes() throws ConfigException { long original = Config.web_sql_max_result_bytes; try { ConfigBase.setMutableConfig("web_sql_max_result_bytes", "32"); - Assert.assertEquals(32, Config.web_sql_max_result_bytes); - Assert.assertThrows(ConfigException.class, + Assertions.assertEquals(32, Config.web_sql_max_result_bytes); + Assertions.assertThrows(ConfigException.class, () -> ConfigBase.setMutableConfig("web_sql_max_result_bytes", "0")); - Assert.assertThrows(ConfigException.class, + Assertions.assertThrows(ConfigException.class, () -> ConfigBase.setMutableConfig("web_sql_max_result_bytes", "104857601")); } finally { Config.web_sql_max_result_bytes = original; @@ -176,15 +174,15 @@ public void testValidateWebSqlStartupConfig() throws ConfigException { Config.validateWebSqlConfig(); Config.web_sql_session_idle_timeout_seconds = 0; - Assert.assertThrows(ConfigException.class, Config::validateWebSqlConfig); + Assertions.assertThrows(ConfigException.class, Config::validateWebSqlConfig); Config.web_sql_session_idle_timeout_seconds = originalIdleTimeout; Config.web_sql_max_sessions = 0; - Assert.assertThrows(ConfigException.class, Config::validateWebSqlConfig); + Assertions.assertThrows(ConfigException.class, Config::validateWebSqlConfig); Config.web_sql_max_sessions = originalMaxSessions; Config.web_sql_max_result_bytes = Config.WEB_SQL_MAX_RESULT_BYTES_UPPER_BOUND + 1; - Assert.assertThrows(ConfigException.class, Config::validateWebSqlConfig); + Assertions.assertThrows(ConfigException.class, Config::validateWebSqlConfig); } finally { Config.web_sql_session_idle_timeout_seconds = originalIdleTimeout; Config.web_sql_max_sessions = originalMaxSessions; diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/FractionalFormatTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/FractionalFormatTest.java index c53b6e6dff6721..53a49087ee8dde 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/FractionalFormatTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/FractionalFormatTest.java @@ -18,8 +18,8 @@ package org.apache.doris.common; import com.fasterxml.jackson.core.io.schubfach.DoubleToDecimal; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.MathContext; @@ -34,30 +34,30 @@ public class FractionalFormatTest { @Test public void testBoundaryValues() { - Assert.assertEquals("0", FractionalFormat.getFormatStringValue(0.0)); - Assert.assertEquals("-0", FractionalFormat.getFormatStringValue(-0.0)); - Assert.assertEquals("NaN", FractionalFormat.getFormatStringValue(Double.NaN)); - Assert.assertEquals("Infinity", + Assertions.assertEquals("0", FractionalFormat.getFormatStringValue(0.0)); + Assertions.assertEquals("-0", FractionalFormat.getFormatStringValue(-0.0)); + Assertions.assertEquals("NaN", FractionalFormat.getFormatStringValue(Double.NaN)); + Assertions.assertEquals("Infinity", FractionalFormat.getFormatStringValue(Double.POSITIVE_INFINITY)); - Assert.assertEquals("-Infinity", + Assertions.assertEquals("-Infinity", FractionalFormat.getFormatStringValue(Double.NEGATIVE_INFINITY)); - Assert.assertEquals("0.0001", FractionalFormat.getFormatStringValue(1e-4)); - Assert.assertEquals("1e-05", FractionalFormat.getFormatStringValue(1e-5)); - Assert.assertEquals("1000000000000000", + Assertions.assertEquals("0.0001", FractionalFormat.getFormatStringValue(1e-4)); + Assertions.assertEquals("1e-05", FractionalFormat.getFormatStringValue(1e-5)); + Assertions.assertEquals("1000000000000000", FractionalFormat.getFormatStringValue(1e15)); - Assert.assertEquals("1e+16", FractionalFormat.getFormatStringValue(1e16)); - Assert.assertEquals("1e+23", FractionalFormat.getFormatStringValue(1e23)); - Assert.assertEquals("5.960464477539063e-08", + Assertions.assertEquals("1e+16", FractionalFormat.getFormatStringValue(1e16)); + Assertions.assertEquals("1e+23", FractionalFormat.getFormatStringValue(1e23)); + Assertions.assertEquals("5.960464477539063e-08", FractionalFormat.getFormatStringValue(Math.scalb(1.0, -24))); - Assert.assertEquals("5e-324", FractionalFormat.getFormatStringValue(Double.MIN_VALUE)); - Assert.assertEquals("1.7976931348623157e+308", + Assertions.assertEquals("5e-324", FractionalFormat.getFormatStringValue(Double.MIN_VALUE)); + Assertions.assertEquals("1.7976931348623157e+308", FractionalFormat.getFormatStringValue(Double.MAX_VALUE)); - Assert.assertEquals("10000000", FractionalFormat.getFormatStringValue(1e7f)); - Assert.assertEquals("1.2621775e-29", + Assertions.assertEquals("10000000", FractionalFormat.getFormatStringValue(1e7f)); + Assertions.assertEquals("1.2621775e-29", FractionalFormat.getFormatStringValue(Math.scalb(1.0f, -96))); - Assert.assertEquals("1e-45", FractionalFormat.getFormatStringValue(Float.MIN_VALUE)); - Assert.assertEquals("3.4028235e+38", + Assertions.assertEquals("1e-45", FractionalFormat.getFormatStringValue(Float.MIN_VALUE)); + Assertions.assertEquals("3.4028235e+38", FractionalFormat.getFormatStringValue(Float.MAX_VALUE)); } @@ -67,13 +67,13 @@ public void testRandomValuesRoundTrip() { for (int i = 0; i < 10_000; i++) { double value = nextFiniteDouble(random); String formatted = FractionalFormat.getFormatStringValue(value); - Assert.assertEquals(Double.doubleToRawLongBits(value), + Assertions.assertEquals(Double.doubleToRawLongBits(value), Double.doubleToRawLongBits(Double.parseDouble(formatted))); } for (int i = 0; i < 10_000; i++) { float value = nextFiniteFloat(random); String formatted = FractionalFormat.getFormatStringValue(value); - Assert.assertEquals(Float.floatToRawIntBits(value), + Assertions.assertEquals(Float.floatToRawIntBits(value), Float.floatToRawIntBits(Float.parseFloat(formatted))); } } diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/PairTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/PairTest.java index 11daa2075de32c..c98e60f28dbe6b 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/PairTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/PairTest.java @@ -17,18 +17,18 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PairTest { @Test public void testToString() { Pair pairFirstNull = Pair.of(null, "world"); - Assert.assertEquals(":world", pairFirstNull.toString()); + Assertions.assertEquals(":world", pairFirstNull.toString()); Pair pairSecondNull = Pair.of("hello", null); - Assert.assertEquals("hello:", pairSecondNull.toString()); + Assertions.assertEquals("hello:", pairSecondNull.toString()); } @Test @@ -36,20 +36,20 @@ public void testEquals() { Pair firstPair = Pair.of(null, "world"); Pair secondPair = null; - Assert.assertTrue(firstPair.equals(firstPair)); - Assert.assertFalse(firstPair.equals(secondPair)); + Assertions.assertTrue(firstPair.equals(firstPair)); + Assertions.assertFalse(firstPair.equals(secondPair)); secondPair = Pair.of(null, "world"); - Assert.assertTrue(firstPair.equals(secondPair)); + Assertions.assertTrue(firstPair.equals(secondPair)); secondPair = Pair.of("hello", null); - Assert.assertFalse(firstPair.equals(secondPair)); + Assertions.assertFalse(firstPair.equals(secondPair)); firstPair = Pair.of("hello", "world"); secondPair = Pair.of("hello", "world"); - Assert.assertTrue(firstPair.equals(secondPair)); + Assertions.assertTrue(firstPair.equals(secondPair)); secondPair = Pair.of("world", "hello"); - Assert.assertFalse(firstPair.equals(secondPair)); + Assertions.assertFalse(firstPair.equals(secondPair)); } } diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/io/BitmapValueTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/io/BitmapValueTest.java index 785574981dbb5c..08d293041a2e31 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/io/BitmapValueTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/io/BitmapValueTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.io; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -36,23 +36,23 @@ public void testVarint64IntEncode() throws IOException { ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); DataOutput output = new DataOutputStream(byteArrayOutput); Codec.encodeVarint64(value, output); - Assert.assertEquals(value, Codec.decodeVarint64(new DataInputStream(new ByteArrayInputStream(byteArrayOutput.toByteArray())))); + Assertions.assertEquals(value, Codec.decodeVarint64(new DataInputStream(new ByteArrayInputStream(byteArrayOutput.toByteArray())))); } } @Test public void testBitmapTypeTransfer() { BitmapValue bitmapValue = new BitmapValue(); - Assert.assertTrue(bitmapValue.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue.getBitmapType() == BitmapValue.EMPTY); bitmapValue.add(1); - Assert.assertTrue(bitmapValue.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue.getBitmapType() == BitmapValue.SINGLE_VALUE); bitmapValue.add(2); - Assert.assertTrue(bitmapValue.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue.getBitmapType() == BitmapValue.BITMAP_VALUE); bitmapValue.clear(); - Assert.assertTrue(bitmapValue.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue.getBitmapType() == BitmapValue.EMPTY); } @Test @@ -63,9 +63,9 @@ public void testBitmapValueAdd() { bitmapValue1.add(i); } for (int i = 0; i < 10; i++) { - Assert.assertTrue(bitmapValue1.contains(i)); + Assertions.assertTrue(bitmapValue1.contains(i)); } - Assert.assertFalse(bitmapValue1.contains(11)); + Assertions.assertFalse(bitmapValue1.contains(11)); // test add long BitmapValue bitmapValue2 = new BitmapValue(); @@ -73,9 +73,9 @@ public void testBitmapValueAdd() { bitmapValue2.add(i); } for (long i = Long.MAX_VALUE; i > Long.MAX_VALUE - 10; i--) { - Assert.assertTrue(bitmapValue2.contains(i)); + Assertions.assertTrue(bitmapValue2.contains(i)); } - Assert.assertFalse(bitmapValue2.contains(0)); + Assertions.assertFalse(bitmapValue2.contains(0)); // test add int and long for (int i = 0; i < 10; i++) { @@ -83,19 +83,19 @@ public void testBitmapValueAdd() { } for (long i = Long.MAX_VALUE; i > Long.MAX_VALUE - 10; i--) { - Assert.assertTrue(bitmapValue2.contains(i)); + Assertions.assertTrue(bitmapValue2.contains(i)); } for (int i = 0; i < 10; i++) { - Assert.assertTrue(bitmapValue2.contains(i)); + Assertions.assertTrue(bitmapValue2.contains(i)); } - Assert.assertFalse(bitmapValue2.contains(100)); + Assertions.assertFalse(bitmapValue2.contains(100)); // test distinct BitmapValue bitmapValue = new BitmapValue(); bitmapValue.add(1); bitmapValue.add(1); - Assert.assertTrue(bitmapValue.getBitmapType() == BitmapValue.SINGLE_VALUE); - Assert.assertTrue(bitmapValue.cardinality() == 1); + Assertions.assertTrue(bitmapValue.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue.cardinality() == 1); } @Test @@ -104,16 +104,16 @@ public void testBitmapValueAnd() { BitmapValue bitmapValue1 = new BitmapValue(); BitmapValue bitmapValue1Dot1 = new BitmapValue(); bitmapValue1.and(bitmapValue1Dot1); - Assert.assertTrue(bitmapValue1.getBitmapType() == BitmapValue.EMPTY); - Assert.assertTrue(bitmapValue1.cardinality() == 0); + Assertions.assertTrue(bitmapValue1.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue1.cardinality() == 0); // empty and single value BitmapValue bitmapValue2 = new BitmapValue(); BitmapValue bitmapValue2Dot1 = new BitmapValue(); bitmapValue2Dot1.add(1); bitmapValue2.and(bitmapValue2Dot1); - Assert.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.EMPTY); - Assert.assertTrue(bitmapValue2.cardinality() == 0); + Assertions.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue2.cardinality() == 0); // empty and bitmap BitmapValue bitmapValue3 = new BitmapValue(); @@ -121,16 +121,16 @@ public void testBitmapValueAnd() { bitmapValue3Dot1.add(1); bitmapValue3Dot1.add(2); bitmapValue3.and(bitmapValue3Dot1); - Assert.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.EMPTY); - Assert.assertTrue(bitmapValue3.cardinality() == 0); + Assertions.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue3.cardinality() == 0); // single value and empty BitmapValue bitmapValue4 = new BitmapValue(); bitmapValue4.add(1); BitmapValue bitmapValue4Dot1 = new BitmapValue(); bitmapValue4.and(bitmapValue4Dot1); - Assert.assertTrue(bitmapValue4.getBitmapType() == BitmapValue.EMPTY); - Assert.assertTrue(bitmapValue4.cardinality() == 0); + Assertions.assertTrue(bitmapValue4.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue4.cardinality() == 0); // single value and single value BitmapValue bitmapValue5 = new BitmapValue(); @@ -138,15 +138,15 @@ public void testBitmapValueAnd() { BitmapValue bitmapValue5Dot1 = new BitmapValue(); bitmapValue5Dot1.add(1); bitmapValue5.and(bitmapValue5Dot1); - Assert.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.SINGLE_VALUE); - Assert.assertTrue(bitmapValue5.contains(1)); + Assertions.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue5.contains(1)); bitmapValue5.clear(); bitmapValue5Dot1.clear(); bitmapValue5.add(1); bitmapValue5Dot1.add(2); bitmapValue5.and(bitmapValue5Dot1); - Assert.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.EMPTY); // single value and bitmap BitmapValue bitmapValue6 = new BitmapValue(); @@ -155,12 +155,12 @@ public void testBitmapValueAnd() { bitmapValue6Dot1.add(1); bitmapValue6Dot1.add(2); bitmapValue6.and(bitmapValue6Dot1); - Assert.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.SINGLE_VALUE); bitmapValue6.clear(); bitmapValue6.add(3); bitmapValue6.and(bitmapValue6Dot1); - Assert.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.EMPTY); // bitmap and empty BitmapValue bitmapValue7 = new BitmapValue(); @@ -168,7 +168,7 @@ public void testBitmapValueAnd() { bitmapValue7.add(2); BitmapValue bitmapValue7Dot1 = new BitmapValue(); bitmapValue7.and(bitmapValue7Dot1); - Assert.assertTrue(bitmapValue7.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue7.getBitmapType() == BitmapValue.EMPTY); // bitmap and single value BitmapValue bitmapValue8 = new BitmapValue(); @@ -177,13 +177,13 @@ public void testBitmapValueAnd() { BitmapValue bitmapValue8Dot1 = new BitmapValue(); bitmapValue8Dot1.add(1); bitmapValue8.and(bitmapValue8Dot1); - Assert.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.SINGLE_VALUE); bitmapValue8.clear(); bitmapValue8.add(2); bitmapValue8.add(3); bitmapValue8.and(bitmapValue8Dot1); - Assert.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.EMPTY); // bitmap and bitmap BitmapValue bitmapValue9 = new BitmapValue(); @@ -193,21 +193,21 @@ public void testBitmapValueAnd() { bitmapValue9Dot1.add(2); bitmapValue9Dot1.add(3); bitmapValue9.and(bitmapValue9Dot1); - Assert.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.SINGLE_VALUE); bitmapValue9.clear(); bitmapValue9.add(4); bitmapValue9.add(5); bitmapValue9.and(bitmapValue9Dot1); - Assert.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.EMPTY); bitmapValue9.clear(); bitmapValue9.add(2); bitmapValue9.add(3); bitmapValue9.add(4); bitmapValue9.and(bitmapValue9Dot1); - Assert.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.BITMAP_VALUE); - Assert.assertTrue(bitmapValue9.equals(bitmapValue9Dot1)); + Assertions.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue9.equals(bitmapValue9Dot1)); } @@ -217,14 +217,14 @@ public void testBitmapValueOr() { BitmapValue bitmapValue1 = new BitmapValue(); BitmapValue bitmapValue1Dot1 = new BitmapValue(); bitmapValue1.or(bitmapValue1Dot1); - Assert.assertTrue(bitmapValue1.getBitmapType() == BitmapValue.EMPTY); + Assertions.assertTrue(bitmapValue1.getBitmapType() == BitmapValue.EMPTY); // empty or single value BitmapValue bitmapValue2 = new BitmapValue(); BitmapValue bitmapValue2Dot1 = new BitmapValue(); bitmapValue2Dot1.add(1); bitmapValue2.or(bitmapValue2Dot1); - Assert.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue2.getBitmapType() == BitmapValue.SINGLE_VALUE); // empty or bitmap BitmapValue bitmapValue3 = new BitmapValue(); @@ -232,14 +232,14 @@ public void testBitmapValueOr() { bitmapValue3Dot1.add(1); bitmapValue3Dot1.add(2); bitmapValue3.or(bitmapValue3Dot1); - Assert.assertTrue(bitmapValue3.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue3.getBitmapType() == BitmapValue.BITMAP_VALUE); // single or and empty BitmapValue bitmapValue4 = new BitmapValue(); BitmapValue bitmapValue4Dot1 = new BitmapValue(); bitmapValue4.add(1); bitmapValue4.or(bitmapValue4Dot1); - Assert.assertTrue(bitmapValue4.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue4.getBitmapType() == BitmapValue.SINGLE_VALUE); // single or and single value BitmapValue bitmapValue5 = new BitmapValue(); @@ -247,12 +247,12 @@ public void testBitmapValueOr() { bitmapValue5.add(1); bitmapValue5Dot1.add(1); bitmapValue5.or(bitmapValue5Dot1); - Assert.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.SINGLE_VALUE); bitmapValue5.clear(); bitmapValue5.add(2); bitmapValue5.or(bitmapValue5Dot1); - Assert.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue5.getBitmapType() == BitmapValue.BITMAP_VALUE); // single or and bitmap BitmapValue bitmapValue6 = new BitmapValue(); @@ -261,7 +261,7 @@ public void testBitmapValueOr() { bitmapValue6Dot1.add(1); bitmapValue6Dot1.add(2); bitmapValue6.or(bitmapValue6Dot1); - Assert.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue6.getBitmapType() == BitmapValue.BITMAP_VALUE); // bitmap or empty BitmapValue bitmapValue7 = new BitmapValue(); @@ -269,7 +269,7 @@ public void testBitmapValueOr() { bitmapValue7.add(2); BitmapValue bitmapValue7Dot1 = new BitmapValue(); bitmapValue7.or(bitmapValue7Dot1); - Assert.assertTrue(bitmapValue7.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue7.getBitmapType() == BitmapValue.BITMAP_VALUE); // bitmap or single value BitmapValue bitmapValue8 = new BitmapValue(); @@ -278,7 +278,7 @@ public void testBitmapValueOr() { BitmapValue bitmapValue8Dot1 = new BitmapValue(); bitmapValue8Dot1.add(1); bitmapValue8.or(bitmapValue8Dot1); - Assert.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue8.getBitmapType() == BitmapValue.BITMAP_VALUE); // bitmap or bitmap BitmapValue bitmapValue9 = new BitmapValue(); @@ -286,7 +286,7 @@ public void testBitmapValueOr() { bitmapValue9.add(2); BitmapValue bitmapValue9Dot1 = new BitmapValue(); bitmapValue9.or(bitmapValue9Dot1); - Assert.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValue9.getBitmapType() == BitmapValue.BITMAP_VALUE); } @Test @@ -301,7 +301,7 @@ public void testBitmapValueSerializeAndDeserialize() throws IOException { BitmapValue deserializeBitmapValue = new BitmapValue(); deserializeBitmapValue.deserialize(emptyInputStream); - Assert.assertTrue(serializeBitmapValue.equals(deserializeBitmapValue)); + Assertions.assertTrue(serializeBitmapValue.equals(deserializeBitmapValue)); // single value BitmapValue serializeSingleValueBitmapValue = new BitmapValue(); @@ -316,7 +316,7 @@ public void testBitmapValueSerializeAndDeserialize() throws IOException { BitmapValue deserializeSingleValueBitmapValue = new BitmapValue(); deserializeSingleValueBitmapValue.deserialize(singleValueInputStream); - Assert.assertTrue(serializeSingleValueBitmapValue.equals(deserializeSingleValueBitmapValue)); + Assertions.assertTrue(serializeSingleValueBitmapValue.equals(deserializeSingleValueBitmapValue)); // bitmap // case 1 : 32-bit bitmap @@ -332,7 +332,7 @@ public void testBitmapValueSerializeAndDeserialize() throws IOException { BitmapValue deserializeBitmapBitmapValue = new BitmapValue(); deserializeBitmapBitmapValue.deserialize(bitmapInputStream); - Assert.assertTrue(serializeBitmapBitmapValue.equals(deserializeBitmapBitmapValue)); + Assertions.assertTrue(serializeBitmapBitmapValue.equals(deserializeBitmapBitmapValue)); // bitmap @@ -349,7 +349,7 @@ public void testBitmapValueSerializeAndDeserialize() throws IOException { BitmapValue deserializeBitmapBitmapValue64 = new BitmapValue(); deserializeBitmapBitmapValue64.deserialize(bitmapInputStream64); - Assert.assertTrue(serializeBitmapBitmapValue64.equals(deserializeBitmapBitmapValue64)); + Assertions.assertTrue(serializeBitmapBitmapValue64.equals(deserializeBitmapBitmapValue64)); } @Test @@ -362,17 +362,17 @@ public void testIs32BitsEnough() { long unsigned32bit = Integer.MAX_VALUE; bitmapValue.add(unsigned32bit + 1); - Assert.assertTrue(bitmapValue.is32BitsEnough()); + Assertions.assertTrue(bitmapValue.is32BitsEnough()); bitmapValue.add(Long.MAX_VALUE); - Assert.assertFalse(bitmapValue.is32BitsEnough()); + Assertions.assertFalse(bitmapValue.is32BitsEnough()); } @Test public void testCardinality() { BitmapValue bitmapValue = new BitmapValue(); - Assert.assertTrue(bitmapValue.cardinality() == 0); + Assertions.assertTrue(bitmapValue.cardinality() == 0); bitmapValue.add(0); bitmapValue.add(0); @@ -387,25 +387,25 @@ public void testCardinality() { bitmapValue.add(-Long.MAX_VALUE); bitmapValue.add(-Long.MAX_VALUE); - Assert.assertTrue(bitmapValue.cardinality() == 6); + Assertions.assertTrue(bitmapValue.cardinality() == 6); } @Test public void testContains() { // empty BitmapValue bitmapValue = new BitmapValue(); - Assert.assertFalse(bitmapValue.contains(1)); + Assertions.assertFalse(bitmapValue.contains(1)); // single value bitmapValue.add(1); - Assert.assertTrue(bitmapValue.contains(1)); - Assert.assertFalse(bitmapValue.contains(2)); + Assertions.assertTrue(bitmapValue.contains(1)); + Assertions.assertFalse(bitmapValue.contains(2)); // bitmap bitmapValue.add(2); - Assert.assertTrue(bitmapValue.contains(1)); - Assert.assertTrue(bitmapValue.contains(2)); - Assert.assertFalse(bitmapValue.contains(12)); + Assertions.assertTrue(bitmapValue.contains(1)); + Assertions.assertTrue(bitmapValue.contains(2)); + Assertions.assertFalse(bitmapValue.contains(12)); } @Test @@ -413,48 +413,48 @@ public void testEqual() { // empty == empty BitmapValue emp1 = new BitmapValue(); BitmapValue emp2 = new BitmapValue(); - Assert.assertTrue(emp1.equals(emp2)); + Assertions.assertTrue(emp1.equals(emp2)); // empty == single value emp2.add(1); - Assert.assertFalse(emp1.equals(emp2)); + Assertions.assertFalse(emp1.equals(emp2)); // empty == bitmap emp2.add(2); - Assert.assertFalse(emp1.equals(emp2)); + Assertions.assertFalse(emp1.equals(emp2)); // single value = empty BitmapValue sgv = new BitmapValue(); sgv.add(1); BitmapValue emp3 = new BitmapValue(); - Assert.assertFalse(sgv.equals(emp3)); + Assertions.assertFalse(sgv.equals(emp3)); // single value = single value BitmapValue sgv1 = new BitmapValue(); sgv1.add(1); BitmapValue sgv2 = new BitmapValue(); sgv2.add(2); - Assert.assertTrue(sgv.equals(sgv1)); - Assert.assertFalse(sgv.equals(sgv2)); + Assertions.assertTrue(sgv.equals(sgv1)); + Assertions.assertFalse(sgv.equals(sgv2)); // single value = bitmap sgv2.add(3); - Assert.assertFalse(sgv.equals(sgv2)); + Assertions.assertFalse(sgv.equals(sgv2)); // bitmap == empty BitmapValue bitmapValue = new BitmapValue(); bitmapValue.add(1); bitmapValue.add(2); BitmapValue emp4 = new BitmapValue(); - Assert.assertFalse(bitmapValue.equals(emp4)); + Assertions.assertFalse(bitmapValue.equals(emp4)); // bitmap == singlevalue BitmapValue sgv3 = new BitmapValue(); sgv3.add(1); - Assert.assertFalse(bitmapValue.equals(sgv3)); + Assertions.assertFalse(bitmapValue.equals(sgv3)); // bitmap == bitmap BitmapValue bitmapValue1 = new BitmapValue(); bitmapValue1.add(1); BitmapValue bitmapValue2 = new BitmapValue(); bitmapValue2.add(1); bitmapValue2.add(2); - Assert.assertTrue(bitmapValue.equals(bitmapValue2)); - Assert.assertFalse(bitmapValue.equals(bitmapValue1)); + Assertions.assertTrue(bitmapValue.equals(bitmapValue2)); + Assertions.assertFalse(bitmapValue.equals(bitmapValue1)); } @@ -469,16 +469,16 @@ public void testBitmapOrDeepCopy() { BitmapValue rollup1 = new BitmapValue(); rollup1.add(3L); rollup1.add(4L); - Assert.assertTrue(rollup1.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(rollup1.getBitmapType() == BitmapValue.BITMAP_VALUE); BitmapValue bitmapValMerge = new BitmapValue(); // or operator is supposed to deep copy Roaring64Map object bitmapValMerge.or(baseIndex1); bitmapValMerge.or(rollup1); - Assert.assertTrue(bitmapValMerge.getBitmapType() == BitmapValue.BITMAP_VALUE); + Assertions.assertTrue(bitmapValMerge.getBitmapType() == BitmapValue.BITMAP_VALUE); - Assert.assertTrue(baseIndex1.cardinality() == 2L); - Assert.assertTrue(rollup1.cardinality() == 2L); - Assert.assertTrue(bitmapValMerge.cardinality() == 4L); + Assertions.assertTrue(baseIndex1.cardinality() == 2L); + Assertions.assertTrue(rollup1.cardinality() == 2L); + Assertions.assertTrue(bitmapValMerge.cardinality() == 4L); //rollupIndex bitmap type == SINGLE_VALUE BitmapValue rollup2 = new BitmapValue(); @@ -486,31 +486,31 @@ public void testBitmapOrDeepCopy() { BitmapValue singleValMerge = new BitmapValue(); singleValMerge.or(rollup2); - Assert.assertTrue(singleValMerge.getBitmapType() == BitmapValue.SINGLE_VALUE); + Assertions.assertTrue(singleValMerge.getBitmapType() == BitmapValue.SINGLE_VALUE); singleValMerge.or(baseIndex1); // update merged bitmap and check whether the original bitmap changed singleValMerge.add(6L); singleValMerge.add(7L); - Assert.assertTrue(singleValMerge.cardinality() == 5L); - Assert.assertTrue(baseIndex1.cardinality() == 2L); - Assert.assertTrue(rollup2.cardinality() == 1L); + Assertions.assertTrue(singleValMerge.cardinality() == 5L); + Assertions.assertTrue(baseIndex1.cardinality() == 2L); + Assertions.assertTrue(rollup2.cardinality() == 1L); } @Test public void testToString() { BitmapValue empty = new BitmapValue(); - Assert.assertTrue(empty.toString().equals("{}")); + Assertions.assertTrue(empty.toString().equals("{}")); BitmapValue singleValue = new BitmapValue(); singleValue.add(1); - Assert.assertTrue(singleValue.toString().equals("{1}")); + Assertions.assertTrue(singleValue.toString().equals("{1}")); BitmapValue bitmap = new BitmapValue(); bitmap.add(1); bitmap.add(2); - Assert.assertTrue(bitmap.toString().equals("{1,2}")); + Assertions.assertTrue(bitmap.toString().equals("{1,2}")); } } diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/io/ByteBufferNetworkInputStreamTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/io/ByteBufferNetworkInputStreamTest.java index 1480cc31f562fc..5416d7d9978abd 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/io/ByteBufferNetworkInputStreamTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/io/ByteBufferNetworkInputStreamTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.io; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.IOException; @@ -35,9 +35,9 @@ public void testMultiByteBuffer() throws IOException, InterruptedException { inputStream.markFinished(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - Assert.assertEquals(bufferedReader.readLine(), "1\t2"); - Assert.assertEquals(bufferedReader.readLine(), "2\t3"); - Assert.assertNull(bufferedReader.readLine()); + Assertions.assertEquals(bufferedReader.readLine(), "1\t2"); + Assertions.assertEquals(bufferedReader.readLine(), "2\t3"); + Assertions.assertNull(bufferedReader.readLine()); bufferedReader.close(); } @@ -65,18 +65,18 @@ public void testMultiThreadByteBuffer() throws IOException, InterruptedException int count = 0; String line = bufferedReader.readLine(); while (line != null) { - Assert.assertEquals(line, String.format("%d\t%d", count, count + 1)); + Assertions.assertEquals(line, String.format("%d\t%d", count, count + 1)); count++; line = bufferedReader.readLine(); } - Assert.assertEquals(count, num); + Assertions.assertEquals(count, num); } catch (Exception e) { e.printStackTrace(); } }); thread2.start(); thread2.join(); - Assert.assertFalse(thread1.isAlive()); + Assertions.assertFalse(thread1.isAlive()); inputStream.close(); } @@ -104,19 +104,19 @@ public void testMultiThreadByteBuffer2() throws IOException, InterruptedExceptio int count = 0; String line = bufferedReader.readLine(); while (line != null) { - Assert.assertEquals(line, String.format("%d\t%d", count, count + 1)); + Assertions.assertEquals(line, String.format("%d\t%d", count, count + 1)); count++; Thread.sleep(500); line = bufferedReader.readLine(); } - Assert.assertEquals(count, num); + Assertions.assertEquals(count, num); } catch (Exception e) { e.printStackTrace(); } }); thread2.start(); thread2.join(); - Assert.assertFalse(thread1.isAlive()); + Assertions.assertFalse(thread1.isAlive()); inputStream.close(); } } diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/io/DiskUtilsTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/io/DiskUtilsTest.java index d0582efee27c36..984a7eb7e3e6b8 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/io/DiskUtilsTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/io/DiskUtilsTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.io; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class DiskUtilsTest { @Test @@ -44,13 +44,13 @@ public void testSiseFormat() { }; for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i], DiskUtils.sizeFormat(keys[i])); + Assertions.assertEquals(values[i], DiskUtils.sizeFormat(keys[i])); } } @Test public void testDf() { DiskUtils.Df d = DiskUtils.df("/"); - Assert.assertTrue(d.fileSystem.length() != 0); + Assertions.assertTrue(d.fileSystem.length() != 0); } } diff --git a/fe/fe-common/src/test/java/org/apache/doris/common/io/HllTest.java b/fe/fe-common/src/test/java/org/apache/doris/common/io/HllTest.java index 94333f255a657d..ced1b579070cf1 100644 --- a/fe/fe-common/src/test/java/org/apache/doris/common/io/HllTest.java +++ b/fe/fe-common/src/test/java/org/apache/doris/common/io/HllTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.io; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -31,10 +31,10 @@ public class HllTest { @Test public void testFindFirstNonZeroBitPosition() { - Assert.assertTrue(Hll.getLongTailZeroNum(0) == 0); - Assert.assertTrue(Hll.getLongTailZeroNum(1) == 0); - Assert.assertTrue(Hll.getLongTailZeroNum(1L << 30) == 30); - Assert.assertTrue(Hll.getLongTailZeroNum(1L << 62) == 62); + Assertions.assertTrue(Hll.getLongTailZeroNum(0) == 0); + Assertions.assertTrue(Hll.getLongTailZeroNum(1) == 0); + Assertions.assertTrue(Hll.getLongTailZeroNum(1L << 30) == 30); + Assertions.assertTrue(Hll.getLongTailZeroNum(1L << 62) == 62); } @Test @@ -42,8 +42,8 @@ public void hllBasicTest() throws IOException { // test empty Hll emptyHll = new Hll(); - Assert.assertTrue(emptyHll.getType() == Hll.HLL_DATA_EMPTY); - Assert.assertTrue(emptyHll.estimateCardinality() == 0); + Assertions.assertTrue(emptyHll.getType() == Hll.HLL_DATA_EMPTY); + Assertions.assertTrue(emptyHll.estimateCardinality() == 0); ByteArrayOutputStream emptyOutputStream = new ByteArrayOutputStream(); DataOutput output = new DataOutputStream(emptyOutputStream); @@ -51,15 +51,15 @@ public void hllBasicTest() throws IOException { DataInputStream emptyInputStream = new DataInputStream(new ByteArrayInputStream(emptyOutputStream.toByteArray())); Hll deserializedEmptyHll = new Hll(); deserializedEmptyHll.deserialize(emptyInputStream); - Assert.assertTrue(deserializedEmptyHll.getType() == Hll.HLL_DATA_EMPTY); + Assertions.assertTrue(deserializedEmptyHll.getType() == Hll.HLL_DATA_EMPTY); // test explicit Hll explicitHll = new Hll(); for (int i = 0; i < Hll.HLL_EXPLICIT_INT64_NUM; i++) { explicitHll.updateWithHash(i); } - Assert.assertTrue(explicitHll.getType() == Hll.HLL_DATA_EXPLICIT); - Assert.assertTrue(explicitHll.estimateCardinality() == Hll.HLL_EXPLICIT_INT64_NUM); + Assertions.assertTrue(explicitHll.getType() == Hll.HLL_DATA_EXPLICIT); + Assertions.assertTrue(explicitHll.estimateCardinality() == Hll.HLL_EXPLICIT_INT64_NUM); ByteArrayOutputStream explicitOutputStream = new ByteArrayOutputStream(); DataOutput explicitOutput = new DataOutputStream(explicitOutputStream); @@ -67,16 +67,16 @@ public void hllBasicTest() throws IOException { DataInputStream explicitInputStream = new DataInputStream(new ByteArrayInputStream(explicitOutputStream.toByteArray())); Hll deserializedExplicitHll = new Hll(); deserializedExplicitHll.deserialize(explicitInputStream); - Assert.assertTrue(deserializedExplicitHll.getType() == Hll.HLL_DATA_EXPLICIT); + Assertions.assertTrue(deserializedExplicitHll.getType() == Hll.HLL_DATA_EXPLICIT); // test sparse Hll sparseHll = new Hll(); for (int i = 0; i < Hll.HLL_SPARSE_THRESHOLD; i++) { sparseHll.updateWithHash(i); } - Assert.assertTrue(sparseHll.getType() == Hll.HLL_DATA_FULL); + Assertions.assertTrue(sparseHll.getType() == Hll.HLL_DATA_FULL); // 2% error rate - Assert.assertTrue(sparseHll.estimateCardinality() > Hll.HLL_SPARSE_THRESHOLD * (1 - 0.02) + Assertions.assertTrue(sparseHll.estimateCardinality() > Hll.HLL_SPARSE_THRESHOLD * (1 - 0.02) && sparseHll.estimateCardinality() < Hll.HLL_SPARSE_THRESHOLD * (1 + 0.02)); ByteArrayOutputStream sparseOutputStream = new ByteArrayOutputStream(); @@ -85,8 +85,8 @@ public void hllBasicTest() throws IOException { DataInputStream sparseInputStream = new DataInputStream(new ByteArrayInputStream(sparseOutputStream.toByteArray())); Hll deserializedSparseHll = new Hll(); deserializedSparseHll.deserialize(sparseInputStream); - Assert.assertTrue(deserializedSparseHll.getType() == Hll.HLL_DATA_SPARSE); - Assert.assertTrue(sparseHll.estimateCardinality() == deserializedSparseHll.estimateCardinality()); + Assertions.assertTrue(deserializedSparseHll.getType() == Hll.HLL_DATA_SPARSE); + Assertions.assertTrue(sparseHll.estimateCardinality() == deserializedSparseHll.estimateCardinality()); // test full @@ -94,10 +94,10 @@ public void hllBasicTest() throws IOException { for (int i = 1; i <= Short.MAX_VALUE; i++) { fullHll.updateWithHash(i); } - Assert.assertTrue(fullHll.getType() == Hll.HLL_DATA_FULL); + Assertions.assertTrue(fullHll.getType() == Hll.HLL_DATA_FULL); // the result 32748 is consistent with C++ 's implementation - Assert.assertTrue(fullHll.estimateCardinality() == 32748); - Assert.assertTrue(fullHll.estimateCardinality() > Short.MAX_VALUE * (1 - 0.02) + Assertions.assertTrue(fullHll.estimateCardinality() == 32748); + Assertions.assertTrue(fullHll.estimateCardinality() > Short.MAX_VALUE * (1 - 0.02) && fullHll.estimateCardinality() < Short.MAX_VALUE * (1 + 0.02)); ByteArrayOutputStream fullHllOutputStream = new ByteArrayOutputStream(); @@ -106,8 +106,8 @@ public void hllBasicTest() throws IOException { DataInputStream fullHllInputStream = new DataInputStream(new ByteArrayInputStream(fullHllOutputStream.toByteArray())); Hll deserializedFullHll = new Hll(); deserializedFullHll.deserialize(fullHllInputStream); - Assert.assertTrue(deserializedFullHll.getType() == Hll.HLL_DATA_FULL); - Assert.assertTrue(deserializedFullHll.estimateCardinality() == fullHll.estimateCardinality()); + Assertions.assertTrue(deserializedFullHll.getType() == Hll.HLL_DATA_FULL); + Assertions.assertTrue(deserializedFullHll.estimateCardinality() == fullHll.estimateCardinality()); } @@ -122,7 +122,7 @@ public void testCompareEstimateValueWithBe() throws IOException { byte[] serializedByte = serializeHll(hll); hll = deserializeHll(serializedByte); - Assert.assertTrue(estimateValue == hll.estimateCardinality()); + Assertions.assertTrue(estimateValue == hll.estimateCardinality()); } // CHECKSTYLE IGNORE THIS LINE // explicit [0. 100) @@ -131,11 +131,11 @@ public void testCompareEstimateValueWithBe() throws IOException { for (int i = 0; i < 100; i++) { explicitHll.updateWithHash(i); } - Assert.assertTrue(explicitHll.estimateCardinality() == 100); + Assertions.assertTrue(explicitHll.estimateCardinality() == 100); // check serialize byte[] serializeHll = serializeHll(explicitHll); explicitHll = deserializeHll(serializeHll); - Assert.assertTrue(explicitHll.estimateCardinality() == 100); + Assertions.assertTrue(explicitHll.estimateCardinality() == 100); Hll otherHll = new Hll(); for (int i = 0; i < 100; i++) { @@ -143,7 +143,7 @@ public void testCompareEstimateValueWithBe() throws IOException { } explicitHll.merge(otherHll); // compare with C++ version result - Assert.assertTrue(explicitHll.estimateCardinality() == 100); + Assertions.assertTrue(explicitHll.estimateCardinality() == 100); } // CHECKSTYLE IGNORE THIS LINE // sparse [1024, 2048) @@ -156,11 +156,11 @@ public void testCompareEstimateValueWithBe() throws IOException { long preValue = sparseHll.estimateCardinality(); // check serialize byte[] serializedHll = serializeHll(sparseHll); - Assert.assertTrue(serializedHll.length < Hll.HLL_REGISTERS_COUNT + 1); + Assertions.assertTrue(serializedHll.length < Hll.HLL_REGISTERS_COUNT + 1); sparseHll = deserializeHll(serializedHll); - Assert.assertTrue(sparseHll.estimateCardinality() == preValue); - Assert.assertTrue(sparseHll.getType() == Hll.HLL_DATA_SPARSE); + Assertions.assertTrue(sparseHll.estimateCardinality() == preValue); + Assertions.assertTrue(sparseHll.getType() == Hll.HLL_DATA_SPARSE); Hll otherHll = new Hll(); for (int i = 0; i < 1024; i++) { @@ -169,11 +169,11 @@ public void testCompareEstimateValueWithBe() throws IOException { sparseHll.updateWithHash(1024); sparseHll.merge(otherHll); long cardinality = sparseHll.estimateCardinality(); - Assert.assertTrue(preValue == cardinality); + Assertions.assertTrue(preValue == cardinality); // 2% error rate - Assert.assertTrue(cardinality > 1000 && cardinality < 1045); + Assertions.assertTrue(cardinality > 1000 && cardinality < 1045); // compare with C++ version result - Assert.assertTrue(cardinality == 1023); + Assertions.assertTrue(cardinality == 1023); } // CHECKSTYLE IGNORE THIS LINE // full [64 * 1024, 128 * 1024) @@ -187,21 +187,21 @@ public void testCompareEstimateValueWithBe() throws IOException { // check serialize byte[] serializedHll = serializeHll(fullHll); fullHll = deserializeHll(serializedHll); - Assert.assertTrue(fullHll.estimateCardinality() == preValue); - Assert.assertTrue(serializedHll.length == Hll.HLL_REGISTERS_COUNT + 1); + Assertions.assertTrue(fullHll.estimateCardinality() == preValue); + Assertions.assertTrue(serializedHll.length == Hll.HLL_REGISTERS_COUNT + 1); // 2% error rate - Assert.assertTrue(preValue > 62 * 1024 && preValue < 66 * 1024); + Assertions.assertTrue(preValue > 62 * 1024 && preValue < 66 * 1024); // compare with C++ version result - Assert.assertTrue(preValue == 66112); + Assertions.assertTrue(preValue == 66112); } // CHECKSTYLE IGNORE THIS LINE // merge explicit to empty_hll { // CHECKSTYLE IGNORE THIS LINE Hll newExplicit = new Hll(); newExplicit.merge(explicitHll); - Assert.assertTrue(newExplicit.estimateCardinality() == 100); + Assertions.assertTrue(newExplicit.estimateCardinality() == 100); // merge another explicit { // CHECKSTYLE IGNORE THIS LINE @@ -211,16 +211,16 @@ public void testCompareEstimateValueWithBe() throws IOException { } // this is converted to full otherHll.merge(newExplicit); - Assert.assertTrue(otherHll.estimateCardinality() > 190); + Assertions.assertTrue(otherHll.estimateCardinality() > 190); // compare with C++ version result - Assert.assertTrue(otherHll.estimateCardinality() == 201); + Assertions.assertTrue(otherHll.estimateCardinality() == 201); } // CHECKSTYLE IGNORE THIS LINE // merge full { // CHECKSTYLE IGNORE THIS LINE newExplicit.merge(fullHll); - Assert.assertTrue(newExplicit.estimateCardinality() > fullHll.estimateCardinality()); + Assertions.assertTrue(newExplicit.estimateCardinality() > fullHll.estimateCardinality()); // compare with C++ version result - Assert.assertTrue(newExplicit.estimateCardinality() == 66250); + Assertions.assertTrue(newExplicit.estimateCardinality() == 66250); } // CHECKSTYLE IGNORE THIS LINE } // CHECKSTYLE IGNORE THIS LINE @@ -228,21 +228,21 @@ public void testCompareEstimateValueWithBe() throws IOException { { // CHECKSTYLE IGNORE THIS LINE Hll newSparseHll = new Hll(); newSparseHll.merge(sparseHll); - Assert.assertTrue(sparseHll.estimateCardinality() == newSparseHll.estimateCardinality()); + Assertions.assertTrue(sparseHll.estimateCardinality() == newSparseHll.estimateCardinality()); // compare with C++ version result - Assert.assertTrue(newSparseHll.estimateCardinality() == 1023); + Assertions.assertTrue(newSparseHll.estimateCardinality() == 1023); // merge explicit newSparseHll.merge(explicitHll); - Assert.assertTrue(newSparseHll.estimateCardinality() > sparseHll.estimateCardinality()); + Assertions.assertTrue(newSparseHll.estimateCardinality() > sparseHll.estimateCardinality()); // compare with C++ version result - Assert.assertTrue(newSparseHll.estimateCardinality() == 1123); + Assertions.assertTrue(newSparseHll.estimateCardinality() == 1123); // merge full newSparseHll.merge(fullHll); - Assert.assertTrue(newSparseHll.estimateCardinality() > fullHll.estimateCardinality()); + Assertions.assertTrue(newSparseHll.estimateCardinality() > fullHll.estimateCardinality()); // compare with C++ version result - Assert.assertTrue(newSparseHll.estimateCardinality() == 67316); + Assertions.assertTrue(newSparseHll.estimateCardinality() == 67316); } // CHECKSTYLE IGNORE THIS LINE } diff --git a/fe/fe-core/kafka_datasource_properties b/fe/fe-core/kafka_datasource_properties new file mode 100644 index 00000000000000..2d32fb8bf39c02 Binary files /dev/null and b/fe/fe-core/kafka_datasource_properties differ diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java b/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java index b4263adaecc83e..caf04eddb495d6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/AlterJobV2RetryTest.java @@ -21,9 +21,9 @@ import org.apache.doris.task.AgentTask; import org.apache.doris.thrift.TStatusCode; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** @@ -34,7 +34,7 @@ public class AlterJobV2RetryTest { private SchemaChangeJobV2 job; - @Before + @BeforeEach public void setUp() { Config.enable_schema_change_retry = true; Config.schema_change_max_retry_time = 3; @@ -51,38 +51,38 @@ private AgentTask makeTask(TStatusCode errorCode) { @Test public void testScCompactionConflictIsRetryable() { AgentTask task = makeTask(TStatusCode.SC_COMPACTION_CONFLICT); - Assert.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); + Assertions.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); } @Test public void testDeleteBitmapLockErrorIsRetryable() { AgentTask task = makeTask(TStatusCode.DELETE_BITMAP_LOCK_ERROR); - Assert.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); + Assertions.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); } @Test public void testNetworkErrorIsRetryable() { AgentTask task = makeTask(TStatusCode.NETWORK_ERROR); - Assert.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); + Assertions.assertEquals(Config.schema_change_max_retry_time, job.getRetryTimes(task)); } @Test public void testInternalErrorIsNotRetryable() { AgentTask task = makeTask(TStatusCode.INTERNAL_ERROR); - Assert.assertEquals(0, job.getRetryTimes(task)); + Assertions.assertEquals(0, job.getRetryTimes(task)); } @Test public void testAnalysisErrorIsNotRetryable() { AgentTask task = makeTask(TStatusCode.ANALYSIS_ERROR); - Assert.assertEquals(0, job.getRetryTimes(task)); + Assertions.assertEquals(0, job.getRetryTimes(task)); } @Test public void testNullErrorCodeIsNotRetryable() { AgentTask task = Mockito.mock(AgentTask.class); Mockito.when(task.getErrorCode()).thenReturn(null); - Assert.assertEquals(0, job.getRetryTimes(task)); + Assertions.assertEquals(0, job.getRetryTimes(task)); } @Test @@ -90,10 +90,10 @@ public void testRetryDisabledReturnsZero() { Config.enable_schema_change_retry = false; try { AgentTask task = makeTask(TStatusCode.SC_COMPACTION_CONFLICT); - Assert.assertEquals(0, job.getRetryTimes(task)); + Assertions.assertEquals(0, job.getRetryTimes(task)); task = makeTask(TStatusCode.DELETE_BITMAP_LOCK_ERROR); - Assert.assertEquals(0, job.getRetryTimes(task)); + Assertions.assertEquals(0, job.getRetryTimes(task)); } finally { Config.enable_schema_change_retry = true; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/CloudIndexTest.java b/fe/fe-core/src/test/java/org/apache/doris/alter/CloudIndexTest.java index a8576b3e652cfb..029b3c1f1162dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/CloudIndexTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/CloudIndexTest.java @@ -73,10 +73,10 @@ import com.google.common.collect.Maps; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -113,7 +113,7 @@ private static void setField(Object target, Class clazz, String fieldName, Ob field.set(target, value); } - @After + @AfterEach public void tearDown() { if (mockedMetaServiceProxy != null) { mockedMetaServiceProxy.close(); @@ -126,7 +126,7 @@ public void tearDown() { } } - @Before + @BeforeEach public void setUp() throws Exception { FeConstants.runningUnitTest = true; // Setup for MetaServiceProxy mock @@ -253,8 +253,8 @@ public void setUp() throws Exception { ctx.setCurrentUserIdentity(rootUser); ctx.setThreadLocalInfo(); ctx.setCloudCluster("test_group"); - Assert.assertTrue(envFactory instanceof CloudEnvFactory); - Assert.assertTrue(masterEnv instanceof CloudEnv); + Assertions.assertTrue(envFactory instanceof CloudEnvFactory); + Assertions.assertTrue(masterEnv instanceof CloudEnv); // Replace MockUp with direct field injection on masterEnv setField(masterEnv, Env.class, "selfNode", @@ -292,7 +292,7 @@ public boolean checkCloudPriv(UserIdentity user, String cluster, PrivPredicate w // MockUp removed: checkCloudClusterPriv not called in test paths // MockUp removed: ctx already has correct values via setters - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); // Replace MockUp with spy CloudSystemInfoService sysInfo = (CloudSystemInfoService) Env.getCurrentSystemInfo(); CloudSystemInfoService sysInfoSpy = Mockito.spy(sysInfo); @@ -324,8 +324,8 @@ public boolean checkCloudPriv(UserIdentity user, String cluster, PrivPredicate w sysInfoSpy.addCloudCluster("test_group", ""); List backends = ((CloudSystemInfoService) Env.getCurrentSystemInfo()).getBackendsByClusterName("test_group"); - Assert.assertEquals(1, backends.size()); - Assert.assertEquals("host1", backends.get(0).getHost()); + Assertions.assertEquals(1, backends.size()); + Assertions.assertEquals("host1", backends.get(0).getHost()); backends.get(0).setAlive(true); ctx.setComputeGroup(masterEnv.getComputeGroupMgr().getAllBackendComputeGroup()); @@ -338,7 +338,7 @@ public boolean checkCloudPriv(UserIdentity user, String cluster, PrivPredicate w @Test public void testCreateNgramBfIndex() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -353,8 +353,8 @@ public void testCreateNgramBfIndex() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -379,21 +379,21 @@ public void testCreateNgramBfIndex() throws Exception { ctx.getSessionVariable().setEnableAddIndexForNewData(true); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); long createJobId = indexChangeJobMap.values().stream().findAny().get().jobId; // Finish the create index job first SchemaChangeJobV2 createJobV2 = (SchemaChangeJobV2) indexChangeJobMap.get(createJobId); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); } @Test public void testAlterBfIndexWithLightweightMode() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -424,12 +424,12 @@ public void testAlterBfIndexWithLightweightMode() throws Exception { addIndexOps.add(createIndexOp); schemaChangeHandler.process(addIndexOps, db, table); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); - Assert.assertEquals(1, schemaChangeHandler.getAlterJobsV2().size()); - Assert.assertEquals(0, schemaChangeHandler.getIndexChangeJobs().size()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals(IndexType.BLOOMFILTER, table.getIndexes().get(0).getIndexType()); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(1, schemaChangeHandler.getAlterJobsV2().size()); + Assertions.assertEquals(0, schemaChangeHandler.getIndexChangeJobs().size()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals(IndexType.BLOOMFILTER, table.getIndexes().get(0).getIndexType()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, schemaChangeHandler.getAlterJobsV2().values().iterator().next().getJobState()); DropIndexOp dropIndexOp = new DropIndexOp(indexName, false, tableName, false); @@ -437,10 +437,10 @@ public void testAlterBfIndexWithLightweightMode() throws Exception { dropIndexOps.add(dropIndexOp); schemaChangeHandler.process(dropIndexOps, db, table); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); - Assert.assertEquals(2, schemaChangeHandler.getAlterJobsV2().size()); - Assert.assertEquals(1, schemaChangeHandler.getIndexChangeJobs().size()); - Assert.assertTrue(table.getIndexes().isEmpty()); + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(2, schemaChangeHandler.getAlterJobsV2().size()); + Assertions.assertEquals(1, schemaChangeHandler.getIndexChangeJobs().size()); + Assertions.assertTrue(table.getIndexes().isEmpty()); } @Test @@ -460,13 +460,13 @@ public void testBuildBfIndexRejectedInCloud() throws Exception { schemaChangeHandler.process(Lists.newArrayList(createIndexOp), db, table); BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, null, null, false); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, () -> buildIndexOp.validate(ctx)); - Assert.assertTrue(exception.getMessage().contains("BLOOMFILTER index is not needed to build")); + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> buildIndexOp.validate(ctx)); + Assertions.assertTrue(exception.getMessage().contains("BLOOMFILTER index is not needed to build")); } @Test public void testNormalCreateNgramBfIndex() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -481,8 +481,8 @@ public void testNormalCreateNgramBfIndex() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -509,35 +509,35 @@ public void testNormalCreateNgramBfIndex() throws Exception { ctx.getSessionVariable().setEnableAddIndexForNewData(false); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); long createJobId = indexChangeJobMap.values().stream().findAny().get().jobId; // Finish the create index job first SchemaChangeJobV2 createJobV2 = (SchemaChangeJobV2) indexChangeJobMap.get(createJobId); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, createJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, createJobV2.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, createJobV2.getJobState()); - Assert.assertEquals(1, createJobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, createJobV2.getJobState()); + Assertions.assertEquals(1, createJobV2.schemaChangeBatchTask.getTaskNum()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(1, tasks.size()); + Assertions.assertEquals(1, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); } @Test public void testCreateInvertedIndex() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -552,8 +552,8 @@ public void testCreateInvertedIndex() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -576,36 +576,36 @@ public void testCreateInvertedIndex() throws Exception { ctx.getSessionVariable().setEnableAddIndexForNewData(false); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(1, indexChangeJobMap.size()); long createJobId = indexChangeJobMap.values().stream().findAny().get().jobId; - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); // Finish the create index job first SchemaChangeJobV2 createJobV2 = (SchemaChangeJobV2) indexChangeJobMap.get(createJobId); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, createJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, createJobV2.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, createJobV2.getJobState()); - Assert.assertEquals(1, createJobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, createJobV2.getJobState()); + Assertions.assertEquals(1, createJobV2.schemaChangeBatchTask.getTaskNum()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(1, tasks.size()); + Assertions.assertEquals(1, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("raw_inverted_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, createJobV2.getJobState()); + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("raw_inverted_index", table.getIndexes().get(0).getIndexName()); } @Test public void testCreateInvertedIndexWithLightweightMode() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -620,8 +620,8 @@ public void testCreateInvertedIndexWithLightweightMode() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -646,17 +646,17 @@ public void testCreateInvertedIndexWithLightweightMode() throws Exception { schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); // Lightweight mode should not create any schema change jobs - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("lightweight_raw_inverted_index", table.getIndexes().get(0).getIndexName()); - Assert.assertEquals(OlapTableState.NORMAL, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("lightweight_raw_inverted_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(OlapTableState.NORMAL, table.getState()); // Verify the index properties - Assert.assertEquals("none", table.getIndexes().get(0).getProperties().get("parser")); + Assertions.assertEquals("none", table.getIndexes().get(0).getProperties().get("parser")); } @Test public void testCreateTokenizedInvertedIndex() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -671,8 +671,8 @@ public void testCreateTokenizedInvertedIndex() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -701,44 +701,44 @@ public void testCreateTokenizedInvertedIndex() throws Exception { alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); SchemaChangeJobV2 jobV2 = (SchemaChangeJobV2) indexChangeJobMap.values().stream() .findFirst() .orElse(null); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); // This should be a heavyweight schema change for tokenized index schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); - Assert.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); + Assertions.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(1, tasks.size()); + Assertions.assertEquals(1, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("tokenized_inverted_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("tokenized_inverted_index", table.getIndexes().get(0).getIndexName()); // Verify that the index has the correct properties - Assert.assertEquals("english", table.getIndexes().get(0).getProperties().get("parser")); - Assert.assertEquals("true", table.getIndexes().get(0).getProperties().get("support_phrase")); - Assert.assertEquals("true", table.getIndexes().get(0).getProperties().get("lower_case")); + Assertions.assertEquals("english", table.getIndexes().get(0).getProperties().get("parser")); + Assertions.assertEquals("true", table.getIndexes().get(0).getProperties().get("support_phrase")); + Assertions.assertEquals("true", table.getIndexes().get(0).getProperties().get("lower_case")); } @Test public void testSchemaChangeWaitsWhenConflictTxnAbortFails() throws Exception { - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); SystemInfoService cloudSystemInfo = Env.getCurrentSystemInfo(); if (fakeEnv != null) { @@ -753,8 +753,8 @@ public void testSchemaChangeWaitsWhenConflictTxnAbortFails() throws Exception { FakeEnv.setSystemInfo(cloudSystemInfo); schemaChangeHandler = (SchemaChangeHandler) new Alter().getSchemaChangeHandler(); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(Env.getCurrentSystemInfo() instanceof CloudSystemInfoService); CatalogTestUtil.createDupTable(db); OlapTable table = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId2); DataSortInfo dataSortInfo = new DataSortInfo(); @@ -778,13 +778,13 @@ public void testSchemaChangeWaitsWhenConflictTxnAbortFails() throws Exception { alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(1, indexChangeJobMap.size()); SchemaChangeJobV2 jobV2 = (SchemaChangeJobV2) indexChangeJobMap.values().stream() .findFirst() .orElse(null); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); Mockito.doAnswer(invocation -> { Cloud.TxnCoordinatorPB coordinator = Cloud.TxnCoordinatorPB.newBuilder() @@ -814,8 +814,8 @@ public void testSchemaChangeWaitsWhenConflictTxnAbortFails() throws Exception { .build()).when(mockProxy).getTxn(Mockito.any()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); } @Test @@ -887,7 +887,7 @@ public void testCreateShadowIndexReplicaForPartitionCopiesBfIndexesOnlyForBaseSh // the original schema-change behavior and does not receive BfIndex metadata or folded // BfColumns flags from indexes. bfColumns is null so table-level bfFpp is not set; // BfIndexes carry their own per-index FPP. - Assert.assertEquals(2, capturedRequests.size()); + Assertions.assertEquals(2, capturedRequests.size()); Cloud.CreateTabletsRequest baseRequest = capturedRequests.stream() .filter(request -> request.getTabletMetas(0).getIndexId() == shadowBaseIndexId) .findFirst() @@ -897,20 +897,20 @@ public void testCreateShadowIndexReplicaForPartitionCopiesBfIndexesOnlyForBaseSh .findFirst() .orElseThrow(() -> new AssertionError("rollup shadow request not found")); - Assert.assertEquals(1, baseRequest.getTabletMetas(0).getSchema().getIndexCount()); - Assert.assertEquals(0, rollupRequest.getTabletMetas(0).getSchema().getIndexCount()); - Assert.assertFalse(baseRequest.getTabletMetas(0).getSchema().hasBfFpp()); - Assert.assertFalse(rollupRequest.getTabletMetas(0).getSchema().hasBfFpp()); - Assert.assertEquals("k1", baseRequest.getTabletMetas(0).getSchema().getColumn(0).getName()); - Assert.assertEquals("k2", baseRequest.getTabletMetas(0).getSchema().getColumn(1).getName()); - Assert.assertEquals("v1", baseRequest.getTabletMetas(0).getSchema().getColumn(2).getName()); - Assert.assertFalse(baseRequest.getTabletMetas(0).getSchema().getColumn(0).getIsBfColumn()); - Assert.assertFalse(baseRequest.getTabletMetas(0).getSchema().getColumn(1).getIsBfColumn()); - Assert.assertTrue(baseRequest.getTabletMetas(0).getSchema().getColumn(2).getIsBfColumn()); - Assert.assertEquals("k1", rollupRequest.getTabletMetas(0).getSchema().getColumn(0).getName()); - Assert.assertEquals("v1", rollupRequest.getTabletMetas(0).getSchema().getColumn(1).getName()); - Assert.assertFalse(rollupRequest.getTabletMetas(0).getSchema().getColumn(0).getIsBfColumn()); - Assert.assertFalse(rollupRequest.getTabletMetas(0).getSchema().getColumn(1).getIsBfColumn()); + Assertions.assertEquals(1, baseRequest.getTabletMetas(0).getSchema().getIndexCount()); + Assertions.assertEquals(0, rollupRequest.getTabletMetas(0).getSchema().getIndexCount()); + Assertions.assertFalse(baseRequest.getTabletMetas(0).getSchema().hasBfFpp()); + Assertions.assertFalse(rollupRequest.getTabletMetas(0).getSchema().hasBfFpp()); + Assertions.assertEquals("k1", baseRequest.getTabletMetas(0).getSchema().getColumn(0).getName()); + Assertions.assertEquals("k2", baseRequest.getTabletMetas(0).getSchema().getColumn(1).getName()); + Assertions.assertEquals("v1", baseRequest.getTabletMetas(0).getSchema().getColumn(2).getName()); + Assertions.assertFalse(baseRequest.getTabletMetas(0).getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(baseRequest.getTabletMetas(0).getSchema().getColumn(1).getIsBfColumn()); + Assertions.assertTrue(baseRequest.getTabletMetas(0).getSchema().getColumn(2).getIsBfColumn()); + Assertions.assertEquals("k1", rollupRequest.getTabletMetas(0).getSchema().getColumn(0).getName()); + Assertions.assertEquals("v1", rollupRequest.getTabletMetas(0).getSchema().getColumn(1).getName()); + Assertions.assertFalse(rollupRequest.getTabletMetas(0).getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(rollupRequest.getTabletMetas(0).getSchema().getColumn(1).getIsBfColumn()); } private MaterializedIndex createCloudIndex(long indexId, long tabletId, long replicaId, long backendId, diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/CloudSchemaChangeJobV2Test.java b/fe/fe-core/src/test/java/org/apache/doris/alter/CloudSchemaChangeJobV2Test.java index 64ebf383bf628c..a37ceb27b40deb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/CloudSchemaChangeJobV2Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/CloudSchemaChangeJobV2Test.java @@ -17,8 +17,8 @@ package org.apache.doris.alter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -38,7 +38,7 @@ public void testSchemaChangeJobDoesNotPersistFormatSpecificSchemaVersions() thro try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { CloudSchemaChangeJobV2 restored = (CloudSchemaChangeJobV2) AlterJobV2.read(input); - Assert.assertEquals(Long.valueOf(100L), restored.getIndexIdMap().get(101L)); + Assertions.assertEquals(Long.valueOf(100L), restored.getIndexIdMap().get(101L)); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/IndexChangeJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/alter/IndexChangeJobTest.java index 4ad2ff59e8d08c..22b3f16e2e3a2d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/IndexChangeJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/IndexChangeJobTest.java @@ -55,12 +55,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -84,10 +82,7 @@ public class IndexChangeJobTest { private static ConnectContext ctx; private MockedStatic mockedConnectContext; - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, UserException { @@ -109,7 +104,7 @@ public void setUp() AgentTaskQueue.clearAllTasks(); } - @After + @AfterEach public void tearDown() { if (mockedConnectContext != null) { mockedConnectContext.close(); @@ -152,10 +147,10 @@ public void testCreateIndexIndexChange() throws UserException { alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(0, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(0, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); } @Test @@ -185,16 +180,16 @@ public void testBuildIndexIndexChange() throws UserException { createIndexClause.validate(connectContext); alterOps.add(createIndexClause); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); BuildIndexOp buildIndexClause = new BuildIndexOp(tableNameInfo, indexName, null, false); buildIndexClause.validate(connectContext); alterOps.add(buildIndexClause); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); } // Creates a fresh db holding the dup table (which owns VARCHAR columns) and puts one @@ -228,7 +223,7 @@ private OlapTable createDupTableWithInvertedIndex(String indexName, String parse ArrayList alterOps = new ArrayList<>(); alterOps.add(createIndexOp); Env.getCurrentEnv().getSchemaChangeHandler().process(alterOps, db, olapTable); - Assert.assertEquals(1, olapTable.getIndexes().size()); + Assertions.assertEquals(1, olapTable.getIndexes().size()); return olapTable; } @@ -245,11 +240,11 @@ public void testBuildIndexAdmittedForSniiNamedIndex() throws UserException { olapTable.setInvertedIndexFileStorageFormat(TInvertedIndexFileStorageFormat.SNII); BuildIndexOp buildIndexOp = new BuildIndexOp(tableNameInfo, indexName, null, false); buildIndexOp.validate(new ConnectContext()); - Assert.assertEquals(indexName, buildIndexOp.getIndex().getIndexName()); + Assertions.assertEquals(indexName, buildIndexOp.getIndex().getIndexName()); ArrayList alterOps = new ArrayList<>(); alterOps.add(buildIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(1, schemaChangeHandler.getIndexChangeJobs().size()); + Assertions.assertEquals(1, schemaChangeHandler.getIndexChangeJobs().size()); } finally { olapTable.setInvertedIndexFileStorageFormat(originalFormat); } @@ -270,7 +265,7 @@ public void testBuildIndexAdmittedForSniiParsedIndexInCloudMode() throws UserExc // Cloud mode takes no index name: it builds every index of the table. BuildIndexOp buildIndexOp = new BuildIndexOp(tableNameInfo, null, null, false); buildIndexOp.validate(new ConnectContext()); - Assert.assertEquals(indexName, buildIndexOp.getIndex().getIndexName()); + Assertions.assertEquals(indexName, buildIndexOp.getIndex().getIndexName()); } finally { Config.cloud_unique_id = originalCloudUniqueId; olapTable.setInvertedIndexFileStorageFormat(originalFormat); @@ -291,9 +286,9 @@ public void testBuildIndexStillRejectedForParsedIndexInCloudModeWithoutSnii() th Config.cloud_unique_id = "test_cloud_v3_build_index"; BuildIndexOp buildIndexOp = new BuildIndexOp(tableNameInfo, null, null, false); buildIndexOp.validate(new ConnectContext()); - Assert.fail("a parsed non-SNII inverted index still needs no explicit build in cloud mode"); + Assertions.fail("a parsed non-SNII inverted index still needs no explicit build in cloud mode"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("index is not needed to build")); + Assertions.assertTrue(e.getMessage().contains("index is not needed to build")); } finally { Config.cloud_unique_id = originalCloudUniqueId; olapTable.setInvertedIndexFileStorageFormat(originalFormat); @@ -314,9 +309,9 @@ public void testBuildIndexForSniiReachesGenericPartitionValidation() throws User Lists.newArrayList(CatalogTestUtil.testPartition2)); BuildIndexOp buildIndexOp = new BuildIndexOp(tableNameInfo, indexName, partitionNamesInfo, false); buildIndexOp.validate(new ConnectContext()); - Assert.fail("partitions on a non-partitioned table must be rejected"); + Assertions.fail("partitions on a non-partitioned table must be rejected"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("is not partitioned, cannot build index with partitions")); + Assertions.assertTrue(e.getMessage().contains("is not partitioned, cannot build index with partitions")); } finally { olapTable.setInvertedIndexFileStorageFormat(originalFormat); } @@ -349,17 +344,17 @@ public void testDropIndexIndexChange() throws UserException { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); DropIndexOp dropIndexOp = new DropIndexOp(indexName, false, tableName, false); dropIndexOp.validate(connectContext); alterOps.add(dropIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - Assert.assertEquals(olapTable.getIndexes().size(), 0); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(olapTable.getIndexes().size(), 0); } @Test @@ -390,41 +385,41 @@ public void testBuildIndexIndexChangeNormal() throws UserException { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); BuildIndexOp buildIndexOp = new BuildIndexOp(tableNameInfo, indexName, null, false); buildIndexOp.validate(new ConnectContext()); alterOps.add(buildIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); // run waiting txn job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); // run running job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); // finish alter tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); } @Test @@ -455,41 +450,41 @@ public void testDropIndexIndexChangeNormal() throws UserException { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); DropIndexOp dropIndexOp = new DropIndexOp(indexName, false, tableName, false); dropIndexOp.validate(connectContext); alterOps.add(dropIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); // run waiting txn job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); // run running job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); // finish alter tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); } @Test @@ -519,31 +514,31 @@ public void testCancelBuildIndexIndexChangeNormal() throws UserException { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, indexName, null, false); buildIndexOp.validate(connectContext); alterOps.add(buildIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); // run waiting txn job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); // run running job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); } @Test @@ -573,64 +568,66 @@ public void testBuildIndexIndexChangeWhileTableNotStable() throws Exception { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); olapTable.setState(OlapTableState.SCHEMA_CHANGE); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2, detailMessage = Table[testTable1]'s state(SCHEMA_CHANGE) is not NORMAL. Do not allow doing ALTER ops"); - schemaChangeHandler.process(alterOps, db, olapTable); - - olapTable.setState(OlapTableState.NORMAL); - schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); - alterOps.clear(); - BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, indexName, null, false); - buildIndexOp.validate(connectContext); - alterOps.add(buildIndexOp); - schemaChangeHandler.process(alterOps, db, olapTable); - Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - - IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - - Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); - MaterializedIndex baseIndex = testPartition.getBaseIndex(); - Assert.assertEquals(IndexState.NORMAL, baseIndex.getState()); - Assert.assertEquals(PartitionState.NORMAL, testPartition.getState()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - - Tablet baseTablet = baseIndex.getTablets().get(0); - List replicas = baseTablet.getReplicas(); - Replica replica2 = replicas.get(1); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); - // run waiting txn job, set replica2 to clone - replica2.setState(Replica.ReplicaState.CLONE); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + olapTable.setState(OlapTableState.NORMAL); + schemaChangeHandler.process(alterOps, db, olapTable); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + alterOps.clear(); + BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, indexName, null, false); + buildIndexOp.validate(connectContext); + alterOps.add(buildIndexOp); + schemaChangeHandler.process(alterOps, db, olapTable); + Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + + IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + + Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); + MaterializedIndex baseIndex = testPartition.getBaseIndex(); + Assertions.assertEquals(IndexState.NORMAL, baseIndex.getState()); + Assertions.assertEquals(PartitionState.NORMAL, testPartition.getState()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + + Tablet baseTablet = baseIndex.getTablets().get(0); + List replicas = baseTablet.getReplicas(); + Replica replica2 = replicas.get(1); + + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + // run waiting txn job, set replica2 to clone + replica2.setState(Replica.ReplicaState.CLONE); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); - // rerun waiting txn job, set replica2 to normal - replica2.setState(Replica.ReplicaState.NORMAL); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + // rerun waiting txn job, set replica2 to normal + replica2.setState(Replica.ReplicaState.NORMAL); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); - // run running job - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + // run running job + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - // finish alter tasks - List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); - for (AgentTask agentTask : tasks) { - agentTask.setFinished(true); - } + // finish alter tasks + List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); + Assertions.assertEquals(3, tasks.size()); + for (AgentTask agentTask : tasks) { + agentTask.setFinished(true); + } - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2, detailMessage = Table[testTable1]'s state(SCHEMA_CHANGE) is not NORMAL. Do not allow doing ALTER ops"), + "unexpected message: " + e.getMessage()); } @Test @@ -660,64 +657,66 @@ public void testDropIndexIndexChangeWhileTableNotStable() throws Exception { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); olapTable.setState(OlapTableState.SCHEMA_CHANGE); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2, detailMessage = Table[testTable1]'s state(SCHEMA_CHANGE) is not NORMAL. Do not allow doing ALTER ops"); - schemaChangeHandler.process(alterOps, db, olapTable); - - olapTable.setState(OlapTableState.NORMAL); - schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); - alterOps.clear(); - DropIndexOp dropIndexOp = new DropIndexOp(indexName, false, tableName, false); - dropIndexOp.validate(connectContext); - alterOps.add(dropIndexOp); - schemaChangeHandler.process(alterOps, db, olapTable); - Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - - IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - - Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); - MaterializedIndex baseIndex = testPartition.getBaseIndex(); - Assert.assertEquals(IndexState.NORMAL, baseIndex.getState()); - Assert.assertEquals(PartitionState.NORMAL, testPartition.getState()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); - - Tablet baseTablet = baseIndex.getTablets().get(0); - List replicas = baseTablet.getReplicas(); - Replica replica2 = replicas.get(1); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); - // run waiting txn job, set replica2 to clone - replica2.setState(Replica.ReplicaState.CLONE); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + olapTable.setState(OlapTableState.NORMAL); + schemaChangeHandler.process(alterOps, db, olapTable); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + alterOps.clear(); + DropIndexOp dropIndexOp = new DropIndexOp(indexName, false, tableName, false); + dropIndexOp.validate(connectContext); + alterOps.add(dropIndexOp); + schemaChangeHandler.process(alterOps, db, olapTable); + Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + + IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + + Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); + MaterializedIndex baseIndex = testPartition.getBaseIndex(); + Assertions.assertEquals(IndexState.NORMAL, baseIndex.getState()); + Assertions.assertEquals(PartitionState.NORMAL, testPartition.getState()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + + Tablet baseTablet = baseIndex.getTablets().get(0); + List replicas = baseTablet.getReplicas(); + Replica replica2 = replicas.get(1); + + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + // run waiting txn job, set replica2 to clone + replica2.setState(Replica.ReplicaState.CLONE); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); - // rerun waiting txn job, set replica2 to normal - replica2.setState(Replica.ReplicaState.NORMAL); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + // rerun waiting txn job, set replica2 to normal + replica2.setState(Replica.ReplicaState.NORMAL); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); - // run running job - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + // run running job + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - // finish alter tasks - List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); - for (AgentTask agentTask : tasks) { - agentTask.setFinished(true); - } + // finish alter tasks + List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); + Assertions.assertEquals(3, tasks.size()); + for (AgentTask agentTask : tasks) { + agentTask.setFinished(true); + } - schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + schemaChangeHandler.runAfterCatalogReady(); + Assertions.assertEquals(IndexChangeJob.JobState.FINISHED, indexChangejob.getJobState()); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2, detailMessage = Table[testTable1]'s state(SCHEMA_CHANGE) is not NORMAL. Do not allow doing ALTER ops"), + "unexpected message: " + e.getMessage()); } @Test @@ -747,49 +746,49 @@ public void testBuildIndexFailedWithMinFailedNum() throws Exception { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, indexName, null, false); buildIndexOp.validate(connectContext); alterOps.add(buildIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 0); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); // run waiting txn job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(indexChangejob.invertedIndexBatchTask.getTaskNum(), 3); // run running job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); // if one task failed, the job should be failed // if task error is not OBTAIN_LOCK_FAILED, the job should be failed after // MIN_FAILED_NUM = 3 times AgentTask agentTask = tasks.get(0); agentTask.setErrorCode(TStatusCode.IO_ERROR); - Assert.assertEquals(agentTask.getFailedTimes(), 0); + Assertions.assertEquals(agentTask.getFailedTimes(), 0); for (int i = 0; i < IndexChangeJob.MIN_FAILED_NUM; i++) { agentTask.failed(); schemaChangeHandler.runAfterCatalogReady(); if (i < IndexChangeJob.MIN_FAILED_NUM - 1) { - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); } } - Assert.assertEquals(IndexChangeJob.JobState.CANCELLED, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.CANCELLED, indexChangejob.getJobState()); } @Test @@ -819,49 +818,49 @@ public void testBuildIndexFailedWithMaxFailedNum() throws Exception { createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(olapTable.getIndexes().size(), 1); - Assert.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); + Assertions.assertEquals(olapTable.getIndexes().size(), 1); + Assertions.assertEquals(olapTable.getIndexes().get(0).getIndexName(), "index1"); alterOps.clear(); BuildIndexOp buildIndexOp = new BuildIndexOp(tableName, indexName, null, false); buildIndexOp.validate(connectContext); alterOps.add(buildIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); Map indexChangeJobMap = schemaChangeHandler.getIndexChangeJobs(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.NORMAL, olapTable.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.NORMAL, olapTable.getState()); IndexChangeJob indexChangejob = indexChangeJobMap.values().stream().findAny().get(); - Assert.assertEquals(0, indexChangejob.invertedIndexBatchTask.getTaskNum()); + Assertions.assertEquals(0, indexChangejob.invertedIndexBatchTask.getTaskNum()); - Assert.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.WAITING_TXN, indexChangejob.getJobState()); // run waiting txn job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); - Assert.assertEquals(3, indexChangejob.invertedIndexBatchTask.getTaskNum()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(3, indexChangejob.invertedIndexBatchTask.getTaskNum()); // run running job schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER_INVERTED_INDEX); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); // if one task failed, the job should be failed // if task error is OBTAIN_LOCK_FAILED, the job should be failed after // MAX_FAILED_NUM = 10 times AgentTask agentTask = tasks.get(0); agentTask.setErrorCode(TStatusCode.OBTAIN_LOCK_FAILED); - Assert.assertEquals(agentTask.getFailedTimes(), 0); + Assertions.assertEquals(agentTask.getFailedTimes(), 0); for (int i = 0; i < IndexChangeJob.MAX_FAILED_NUM; i++) { agentTask.failed(); schemaChangeHandler.runAfterCatalogReady(); if (i < IndexChangeJob.MAX_FAILED_NUM - 1) { - Assert.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.RUNNING, indexChangejob.getJobState()); } } - Assert.assertEquals(IndexChangeJob.JobState.CANCELLED, indexChangejob.getJobState()); + Assertions.assertEquals(IndexChangeJob.JobState.CANCELLED, indexChangejob.getJobState()); } @Test @@ -898,15 +897,15 @@ public void testNgramBfBuildIndex() throws UserException { context.getSessionVariable().setEnableAddIndexForNewData(true); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("ngram_bf_index", table.getIndexes().get(0).getIndexName()); SchemaChangeJobV2 jobV2 = (SchemaChangeJobV2) indexChangeJobMap.values().stream() .findFirst() .orElse(null); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); // Clean up for next test table.setIndexes(Lists.newArrayList()); @@ -926,36 +925,36 @@ public void testNgramBfBuildIndex() throws UserException { alterOps2.add(createIndexOp); schemaChangeHandler.process(alterOps2, db, table); indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); jobV2 = (SchemaChangeJobV2) indexChangeJobMap.values().stream() .findFirst() .orElse(null); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); - Assert.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); + Assertions.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); - Assert.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); + Assertions.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(1, tasks.size()); + Assertions.assertEquals(1, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); - Assert.assertEquals(1, table.getIndexes().size()); - Assert.assertEquals("ngram_bf_index2", table.getIndexes().get(0).getIndexName()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, jobV2.getJobState()); + Assertions.assertEquals(1, table.getIndexes().size()); + Assertions.assertEquals("ngram_bf_index2", table.getIndexes().get(0).getIndexName()); } @Test @@ -991,25 +990,25 @@ public void testCancelNgramBfBuildIndex() throws UserException { ctx.getSessionVariable().setEnableAddIndexForNewData(false); schemaChangeHandler.process(alterOps, db, table); Map indexChangeJobMap = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, indexChangeJobMap.size()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); + Assertions.assertEquals(1, indexChangeJobMap.size()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, table.getState()); SchemaChangeJobV2 jobV2 = (SchemaChangeJobV2) indexChangeJobMap.values().stream() .findFirst() .orElse(null); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); - Assert.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.WAITING_TXN, jobV2.getJobState()); + Assertions.assertEquals(0, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); - Assert.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); + Assertions.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); - Assert.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); + Assertions.assertEquals(AlterJobV2.JobState.RUNNING, jobV2.getJobState()); + Assertions.assertEquals(1, jobV2.schemaChangeBatchTask.getTaskNum()); TableNameInfo tableNameInfo = new TableNameInfo(db.getName(), table.getName()); CancelAlterTableCommand cancelAlterTableCommand = new CancelAlterTableCommand( @@ -1019,7 +1018,7 @@ public void testCancelNgramBfBuildIndex() throws UserException { schemaChangeHandler.cancel(cancelAlterTableCommand); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(AlterJobV2.JobState.CANCELLED, jobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.CANCELLED, jobV2.getJobState()); } @Test @@ -1029,9 +1028,9 @@ public void testDropIndexOnPartitionValidateRejectsStarPartition() throws Except DropIndexOp dropIndexOp = new DropIndexOp("index1", false, null, true, starPartition); try { dropIndexOp.validate(new ConnectContext()); - Assert.fail("Should throw AnalysisException for PARTITIONS (*)"); + Assertions.fail("Should throw AnalysisException for PARTITIONS (*)"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("PARTITIONS (*) is not supported")); + Assertions.assertTrue(e.getMessage().contains("PARTITIONS (*) is not supported")); } } @@ -1042,9 +1041,9 @@ public void testDropIndexOnPartitionValidateRejectsTempPartition() throws Except DropIndexOp dropIndexOp = new DropIndexOp("index1", false, null, true, tempPartition); try { dropIndexOp.validate(new ConnectContext()); - Assert.fail("Should throw AnalysisException for TEMPORARY PARTITION"); + Assertions.fail("Should throw AnalysisException for TEMPORARY PARTITION"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("does not support temporary partitions")); + Assertions.assertTrue(e.getMessage().contains("does not support temporary partitions")); } } @@ -1055,8 +1054,8 @@ public void testDropIndexOnPartitionValidateAcceptsNormalPartition() throws Exce DropIndexOp dropIndexOp = new DropIndexOp("index1", false, null, true, normalPartition); // Should not throw dropIndexOp.validate(new ConnectContext()); - Assert.assertTrue(dropIndexOp.hasPartitionSpec()); - Assert.assertEquals(2, dropIndexOp.getPartitionNames().size()); + Assertions.assertTrue(dropIndexOp.hasPartitionSpec()); + Assertions.assertEquals(2, dropIndexOp.getPartitionNames().size()); } @Test @@ -1088,7 +1087,7 @@ public void testDropIndexOnPartitionRejectsNonPartitionedTable() throws UserExce createIndexOp.validate(connectContext); alterOps.add(createIndexOp); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertEquals(1, olapTable.getIndexes().size()); + Assertions.assertEquals(1, olapTable.getIndexes().size()); alterOps.clear(); // Now try DROP INDEX ON PARTITION on this non-partitioned table @@ -1098,12 +1097,12 @@ public void testDropIndexOnPartitionRejectsNonPartitionedTable() throws UserExce alterOps.add(dropIndexOp); try { schemaChangeHandler.process(alterOps, db, olapTable); - Assert.fail("Should throw DdlException for non-partitioned table"); + Assertions.fail("Should throw DdlException for non-partitioned table"); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("is not partitioned")); + Assertions.assertTrue(e.getMessage().contains("is not partitioned")); } // Index definition should still exist - Assert.assertEquals(1, olapTable.getIndexes().size()); + Assertions.assertEquals(1, olapTable.getIndexes().size()); } @Test @@ -1130,9 +1129,9 @@ public void testDropIndexOnPartitionRejectsNonExistentIndex() throws UserExcepti alterOps.add(dropIndexOp); try { schemaChangeHandler.process(alterOps, db, olapTable); - Assert.fail("Should throw DdlException for non-existent index"); + Assertions.fail("Should throw DdlException for non-existent index"); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("does not exist")); + Assertions.assertTrue(e.getMessage().contains("does not exist")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/MaterializedViewHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/alter/MaterializedViewHandlerTest.java index a80da7a2547bec..80c13f683bf792 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/MaterializedViewHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/MaterializedViewHandlerTest.java @@ -34,9 +34,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.HashMap; @@ -55,7 +55,7 @@ public void testDifferentBaseTable() { try { Deencapsulation.invoke(materializedViewHandler, "processCreateMaterializedView", createMaterializedViewCommand, db, olapTable); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -74,7 +74,7 @@ public void testNotNormalTable() { try { Deencapsulation.invoke(materializedViewHandler, "processCreateMaterializedView", createMaterializedViewCommand, db, olapTable); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -94,7 +94,7 @@ public void testErrorBaseIndexName() { try { Deencapsulation.invoke(materializedViewHandler, "processCreateMaterializedView", createMaterializedViewCommand, db, olapTable); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -120,7 +120,7 @@ public void testRollupReplica() { try { Deencapsulation.invoke(materializedViewHandler, "processCreateMaterializedView", createMaterializedViewCommand, db, olapTable); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -137,7 +137,7 @@ public void testDuplicateMVName() { try { Deencapsulation.invoke(materializedViewHandler, "checkAndPrepareMaterializedView", createMaterializedViewCommand, olapTable, new HashMap()); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -154,7 +154,7 @@ public void testInvalidKeysType() { try { Deencapsulation.invoke(materializedViewHandler, "checkAndPrepareMaterializedView", createMaterializedViewCommand, olapTable, new HashMap()); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -174,7 +174,7 @@ public void testDuplicateTable() { try { mvColumnItem = new MVColumnItem(slot); } catch (AnalysisException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } mvColumnItem.setIsKey(true); mvColumnItem.setAggregationType(null, false); @@ -191,16 +191,16 @@ public void testDuplicateTable() { List mvColumns = Deencapsulation.invoke(materializedViewHandler, "checkAndPrepareMaterializedView", createMaterializedViewCommand, olapTable, new HashMap()); - Assert.assertEquals(1, mvColumns.size()); + Assertions.assertEquals(1, mvColumns.size()); Column newMVColumn = mvColumns.get(0); - Assert.assertEquals(columnName1, newMVColumn.getName()); - Assert.assertTrue(newMVColumn.isKey()); - Assert.assertEquals(null, newMVColumn.getAggregationType()); - Assert.assertEquals(false, newMVColumn.isAggregationTypeImplicit()); - Assert.assertEquals(Type.VARCHAR.getPrimitiveType(), newMVColumn.getType().getPrimitiveType()); + Assertions.assertEquals(columnName1, newMVColumn.getName()); + Assertions.assertTrue(newMVColumn.isKey()); + Assertions.assertEquals(null, newMVColumn.getAggregationType()); + Assertions.assertEquals(false, newMVColumn.isAggregationTypeImplicit()); + Assertions.assertEquals(Type.VARCHAR.getPrimitiveType(), newMVColumn.getType().getPrimitiveType()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -219,7 +219,7 @@ public void checkInvalidPartitionKeyMV() throws DdlException { try { mvColumnItem = new MVColumnItem(slot); } catch (AnalysisException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } mvColumnItem.setIsKey(false); @@ -236,7 +236,7 @@ public void checkInvalidPartitionKeyMV() throws DdlException { try { Deencapsulation.invoke(materializedViewHandler, "checkAndPrepareMaterializedView", createMaterializedViewCommand, olapTable); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } @@ -258,7 +258,7 @@ public void testCheckDropMaterializedView() { try { Deencapsulation.invoke(materializedViewHandler, "checkDropMaterializedView", mvName, olapTable); } catch (Exception e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/RollupJobV2Test.java b/fe/fe-core/src/test/java/org/apache/doris/alter/RollupJobV2Test.java index 4265e267b7e244..c525ea2d4a48cd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/RollupJobV2Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/RollupJobV2Test.java @@ -58,10 +58,10 @@ import org.apache.doris.transaction.GlobalTransactionMgrIface; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -93,7 +93,7 @@ public class RollupJobV2Test { private FakeEditLog fakeEditLog; private MockedStatic agentTaskExecutorMock; - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, UserException { fakeEnv = new FakeEnv(); @@ -126,7 +126,7 @@ public void setUp() throws InstantiationException, IllegalAccessException, Illeg .thenAnswer(invocation -> null); } - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -166,9 +166,9 @@ public void testRunRollupJobConcurrentLimit() throws UserException { materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(Config.max_running_rollup_job_num_per_table, materializedViewHandler.getTableRunningJobMap().get(CatalogTestUtil.testTableId1).size()); - Assert.assertEquals(2, alterJobsV2.size()); - Assert.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); + Assertions.assertEquals(Config.max_running_rollup_job_num_per_table, materializedViewHandler.getTableRunningJobMap().get(CatalogTestUtil.testTableId1).size()); + Assertions.assertEquals(2, alterJobsV2.size()); + Assertions.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); } @Test @@ -189,8 +189,8 @@ public void testAddSchemaChange() throws UserException { OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId1); materializedViewHandler.process(alterOps, db, olapTable); Map alterJobsV2 = materializedViewHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); - Assert.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); + Assertions.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); } @Test @@ -212,7 +212,7 @@ public void testCancelRollupWithEmptyJobIdList() throws Exception { OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId1); materializedViewHandler.process(alterOps, db, olapTable); Map alterJobsV2 = materializedViewHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); RollupJobV2 rollupJob = (RollupJobV2) alterJobsV2.values().stream().findAny().get(); CancelAlterTableCommand cancelAlterTableCommand = new CancelAlterTableCommand( @@ -221,7 +221,7 @@ public void testCancelRollupWithEmptyJobIdList() throws Exception { Lists.newArrayList()); materializedViewHandler.cancel(cancelAlterTableCommand); - Assert.assertEquals(JobState.CANCELLED, rollupJob.getJobState()); + Assertions.assertEquals(JobState.CANCELLED, rollupJob.getJobState()); } // start a schema change, then finished @@ -246,27 +246,27 @@ public void testSchemaChange1() throws Exception { Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); materializedViewHandler.process(alterOps, db, olapTable); Map alterJobsV2 = materializedViewHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); RollupJobV2 rollupJob = (RollupJobV2) alterJobsV2.values().stream().findAny().get(); // runPendingJob materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); - Assert.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); + Assertions.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); + Assertions.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); // runWaitingTxnJob materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, rollupJob.getJobState()); // runWaitingTxnJob, task not finished materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, rollupJob.getJobState()); // finish all tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } @@ -278,7 +278,7 @@ public void testSchemaChange1() throws Exception { } materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.FINISHED, rollupJob.getJobState()); + Assertions.assertEquals(JobState.FINISHED, rollupJob.getJobState()); } @Test @@ -300,17 +300,17 @@ public void testSchemaChangeCancelWhenRollupTasksFailed() throws Exception { OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId1); materializedViewHandler.process(alterOps, db, olapTable); Map alterJobsV2 = materializedViewHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); RollupJobV2 rollupJob = (RollupJobV2) alterJobsV2.values().stream().findAny().get(); materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); + Assertions.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, rollupJob.getJobState()); List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); long failedTabletId = tasks.get(0).getTabletId(); int failedTaskCount = 0; for (AgentTask agentTask : tasks) { @@ -322,10 +322,10 @@ public void testSchemaChangeCancelWhenRollupTasksFailed() throws Exception { break; } } - Assert.assertEquals(2, failedTaskCount); + Assertions.assertEquals(2, failedTaskCount); materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.CANCELLED, rollupJob.getJobState()); + Assertions.assertEquals(JobState.CANCELLED, rollupJob.getJobState()); } @Test @@ -349,13 +349,13 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); materializedViewHandler.process(alterOps, db, olapTable); Map alterJobsV2 = materializedViewHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); RollupJobV2 rollupJob = (RollupJobV2) alterJobsV2.values().stream().findAny().get(); MaterializedIndex baseIndex = testPartition.getBaseIndex(); - Assert.assertEquals(MaterializedIndex.IndexState.NORMAL, baseIndex.getState()); - Assert.assertEquals(Partition.PartitionState.NORMAL, testPartition.getState()); - Assert.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); + Assertions.assertEquals(MaterializedIndex.IndexState.NORMAL, baseIndex.getState()); + Assertions.assertEquals(Partition.PartitionState.NORMAL, testPartition.getState()); + Assertions.assertEquals(OlapTableState.ROLLUP, olapTable.getState()); Tablet baseTablet = baseIndex.getTablets().get(0); List replicas = baseTablet.getReplicas(); @@ -363,40 +363,40 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { Replica replica2 = replicas.get(1); Replica replica3 = replicas.get(2); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); - Assert.assertEquals(-1, replica1.getLastFailedVersion()); - Assert.assertEquals(-1, replica2.getLastFailedVersion()); - Assert.assertEquals(-1, replica3.getLastFailedVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); + Assertions.assertEquals(-1, replica1.getLastFailedVersion()); + Assertions.assertEquals(-1, replica2.getLastFailedVersion()); + Assertions.assertEquals(-1, replica3.getLastFailedVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); // runPendingJob replica1.setState(Replica.ReplicaState.DECOMMISSION); materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.PENDING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.PENDING, rollupJob.getJobState()); // table is stable, runPendingJob again replica1.setState(Replica.ReplicaState.NORMAL); materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); - Assert.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); + Assertions.assertEquals(JobState.WAITING_TXN, rollupJob.getJobState()); + Assertions.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); // runWaitingTxnJob materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, rollupJob.getJobState()); // runWaitingTxnJob, task not finished materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, rollupJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, rollupJob.getJobState()); // finish all tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } @@ -408,7 +408,7 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { } materializedViewHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.FINISHED, rollupJob.getJobState()); + Assertions.assertEquals(JobState.FINISHED, rollupJob.getJobState()); } @@ -445,11 +445,11 @@ public void testSerializeOfRollupJob() DataInputStream in = new DataInputStream(new FileInputStream(file)); RollupJobV2 result = (RollupJobV2) AlterJobV2.read(in); - Assert.assertEquals(TStorageFormat.V2, Deencapsulation.getField(result, "storageFormat")); + Assertions.assertEquals(TStorageFormat.V2, Deencapsulation.getField(result, "storageFormat")); List resultColumns = Deencapsulation.getField(result, "rollupSchema"); - Assert.assertEquals(1, resultColumns.size()); + Assertions.assertEquals(1, resultColumns.size()); Column resultColumn1 = resultColumns.get(0); - Assert.assertEquals(mvColumnName, + Assertions.assertEquals(mvColumnName, resultColumn1.getName()); } @@ -486,7 +486,7 @@ public void testDeserializeOldRollupJobWithoutOrigStmt() { + "}"; RollupJobV2 result = (RollupJobV2) GsonUtils.GSON.fromJson(oldJson, AlterJobV2.class); - Assert.assertEquals(JobState.FINISHED, Deencapsulation.getField(result, "showJobState")); + Assertions.assertEquals(JobState.FINISHED, Deencapsulation.getField(result, "showJobState")); } @Test @@ -509,7 +509,7 @@ public void testAddRollupForDupTable() throws UserException { List columns = materializedViewHandler.checkAndPrepareMaterializedView(addRollupOp, olapTable, CatalogTestUtil.testIndexId2, false); for (Column column : columns) { if (column.nameEquals("v1", true)) { - Assert.assertNull(column.getAggregationType()); + Assertions.assertNull(column.getAggregationType()); break; } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeHandlerTest.java index 8839fca5a54e1e..4b3962b91421b4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeHandlerTest.java @@ -46,7 +46,6 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -131,7 +130,7 @@ private void waitAlterJobDone(Map alterJobs) throws Exception Thread.sleep(1000); } LOG.info("alter job {} is done. state: {}", alterJobV2.getJobId(), alterJobV2.getJobState()); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); Database db = Env.getCurrentInternalCatalog().getDbOrMetaException(alterJobV2.getDbId()); OlapTable tbl = (OlapTable) db.getTableOrMetaException(alterJobV2.getTableId(), Table.TableType.OLAP); @@ -193,7 +192,7 @@ public void testWithRowBinlogSchemaChangeNoHistoricalValue() throws Exception { List cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName) .collect(Collectors.toList()); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v1"))); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v1"))); // single add column alterTable("ALTER TABLE test." + tableName + " ADD COLUMN v2 INT AFTER v1", connectContext); @@ -201,10 +200,10 @@ public void testWithRowBinlogSchemaChangeNoHistoricalValue() throws Exception { waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(2, cols.indexOf("v2")); - Assert.assertEquals(3, cols.indexOf(Column.BINLOG_TSO_COL)); - Assert.assertEquals(4, cols.indexOf(Column.BINLOG_LSN_COL)); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v2"))); + Assertions.assertEquals(2, cols.indexOf("v2")); + Assertions.assertEquals(3, cols.indexOf(Column.BINLOG_TSO_COL)); + Assertions.assertEquals(4, cols.indexOf(Column.BINLOG_LSN_COL)); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v2"))); // multiple add column clauses in one ALTER alterTable("ALTER TABLE test." + tableName @@ -213,12 +212,12 @@ public void testWithRowBinlogSchemaChangeNoHistoricalValue() throws Exception { waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(3, cols.indexOf("v3")); - Assert.assertEquals(4, cols.indexOf("v4")); - Assert.assertEquals(5, cols.indexOf(Column.BINLOG_TSO_COL)); - Assert.assertEquals(6, cols.indexOf(Column.BINLOG_LSN_COL)); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v3"))); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v4"))); + Assertions.assertEquals(3, cols.indexOf("v3")); + Assertions.assertEquals(4, cols.indexOf("v4")); + Assertions.assertEquals(5, cols.indexOf(Column.BINLOG_TSO_COL)); + Assertions.assertEquals(6, cols.indexOf(Column.BINLOG_LSN_COL)); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v3"))); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v4"))); // AddColumnsOp: ADD COLUMN (colDef1, colDef2) alterTable("ALTER TABLE test." + tableName + " ADD COLUMN (v5 INT, v6 INT)", connectContext); @@ -226,12 +225,12 @@ public void testWithRowBinlogSchemaChangeNoHistoricalValue() throws Exception { waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(5, cols.indexOf("v5")); - Assert.assertEquals(6, cols.indexOf("v6")); - Assert.assertEquals(7, cols.indexOf(Column.BINLOG_TSO_COL)); - Assert.assertEquals(8, cols.indexOf(Column.BINLOG_LSN_COL)); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v5"))); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v6"))); + Assertions.assertEquals(5, cols.indexOf("v5")); + Assertions.assertEquals(6, cols.indexOf("v6")); + Assertions.assertEquals(7, cols.indexOf(Column.BINLOG_TSO_COL)); + Assertions.assertEquals(8, cols.indexOf(Column.BINLOG_LSN_COL)); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v5"))); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v6"))); // drop column alterTable("ALTER TABLE test." + tableName + " DROP COLUMN v6", connectContext); @@ -239,9 +238,9 @@ public void testWithRowBinlogSchemaChangeNoHistoricalValue() throws Exception { waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertFalse(cols.contains("v6")); - Assert.assertEquals(6, cols.indexOf(Column.BINLOG_TSO_COL)); - Assert.assertEquals(7, cols.indexOf(Column.BINLOG_LSN_COL)); + Assertions.assertFalse(cols.contains("v6")); + Assertions.assertEquals(6, cols.indexOf(Column.BINLOG_TSO_COL)); + Assertions.assertEquals(7, cols.indexOf(Column.BINLOG_LSN_COL)); } @Test @@ -263,7 +262,7 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception List cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName) .collect(Collectors.toList()); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v1"))); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v1"))); // single add column alterTable("ALTER TABLE test." + tableName + " ADD COLUMN v2 INT AFTER v1", connectContext); @@ -271,9 +270,9 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(2, cols.indexOf("v2")); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v2"))); - Assert.assertEquals(cols.indexOf(Column.generateBeforeColName("v1")) + 1, + Assertions.assertEquals(2, cols.indexOf("v2")); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v2"))); + Assertions.assertEquals(cols.indexOf(Column.generateBeforeColName("v1")) + 1, cols.indexOf(Column.generateBeforeColName("v2"))); // multiple add column clauses in one ALTER @@ -283,13 +282,13 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(3, cols.indexOf("v3")); - Assert.assertEquals(4, cols.indexOf("v4")); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v3"))); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v4"))); - Assert.assertEquals(cols.indexOf(Column.generateBeforeColName("v2")) + 1, + Assertions.assertEquals(3, cols.indexOf("v3")); + Assertions.assertEquals(4, cols.indexOf("v4")); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v3"))); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v4"))); + Assertions.assertEquals(cols.indexOf(Column.generateBeforeColName("v2")) + 1, cols.indexOf(Column.generateBeforeColName("v3"))); - Assert.assertEquals(cols.indexOf(Column.generateBeforeColName("v3")) + 1, + Assertions.assertEquals(cols.indexOf(Column.generateBeforeColName("v3")) + 1, cols.indexOf(Column.generateBeforeColName("v4"))); // AddColumnsOp: ADD COLUMN (colDef1, colDef2) @@ -298,13 +297,13 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertEquals(5, cols.indexOf("v5")); - Assert.assertEquals(6, cols.indexOf("v6")); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v5"))); - Assert.assertTrue(cols.contains(Column.generateBeforeColName("v6"))); - Assert.assertEquals(cols.indexOf(Column.generateBeforeColName("v4")) + 1, + Assertions.assertEquals(5, cols.indexOf("v5")); + Assertions.assertEquals(6, cols.indexOf("v6")); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v5"))); + Assertions.assertTrue(cols.contains(Column.generateBeforeColName("v6"))); + Assertions.assertEquals(cols.indexOf(Column.generateBeforeColName("v4")) + 1, cols.indexOf(Column.generateBeforeColName("v5"))); - Assert.assertEquals(cols.indexOf(Column.generateBeforeColName("v5")) + 1, + Assertions.assertEquals(cols.indexOf(Column.generateBeforeColName("v5")) + 1, cols.indexOf(Column.generateBeforeColName("v6"))); // drop column @@ -312,8 +311,8 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception jobSize++; waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertFalse(cols.contains("v6")); - Assert.assertFalse(cols.contains(Column.generateBeforeColName("v6"))); + Assertions.assertFalse(cols.contains("v6")); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName("v6"))); // enable hidden sequence column should not pollute row binlog schema alterTable("ALTER TABLE test." + tableName @@ -322,10 +321,10 @@ public void testWithRowBinlogSchemaChangeWithHistoricalValue() throws Exception jobSize++; waitAlterJobDone(Env.getCurrentEnv().getSchemaChangeHandler().getAlterJobsV2()); - Assert.assertTrue(tbl.getBaseSchema(true).stream().anyMatch(Column::isSequenceColumn)); + Assertions.assertTrue(tbl.getBaseSchema(true).stream().anyMatch(Column::isSequenceColumn)); cols = tbl.getRowBinlogMeta().getSchema(true).stream().map(Column::getName).collect(Collectors.toList()); - Assert.assertFalse(cols.contains(Column.SEQUENCE_COL)); - Assert.assertFalse(cols.contains(Column.generateBeforeColName(Column.SEQUENCE_COL))); + Assertions.assertFalse(cols.contains(Column.SEQUENCE_COL)); + Assertions.assertFalse(cols.contains(Column.generateBeforeColName(Column.SEQUENCE_COL))); } @Test @@ -433,7 +432,7 @@ public void testWithRowBinlogOpNotSupported() throws Exception { createTable(createVariant); Assertions.fail("Expected exception for VARIANT column"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().toLowerCase().contains("variant")); + Assertions.assertTrue(e.getMessage().toLowerCase().contains("variant")); } String tableName2 = "binlog_add_variant"; @@ -455,7 +454,7 @@ public void testWithRowBinlogOpNotSupported() throws Exception { createTable(createAutoinc); Assertions.fail("Expected exception for AUTO_INCREMENT column"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().toLowerCase().contains("auto")); + Assertions.assertTrue(e.getMessage().toLowerCase().contains("auto")); } } @@ -782,7 +781,7 @@ public void testAggAddOrDropColumn() throws Exception { // process agg drop key column with replace schema change, expect exception. String dropKeyColStmtStr = "alter table test.sc_agg drop column new_k1"; alterTable(dropKeyColStmtStr, connectContext); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { LOG.info(e.getMessage()); } @@ -969,7 +968,7 @@ public void testAddValueColumnOnAggMV() { try { Deencapsulation.invoke(schemaChangeHandler, "addColumnInternal", olapTable, newColumn, columnPosition, Long.valueOf(2), Long.valueOf(1), Maps.newHashMap(), Sets.newHashSet(), false, Maps.newHashMap()); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.println(e.getMessage()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeJobV2Test.java b/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeJobV2Test.java index f184c73d62bfeb..ce03ab8663b6e6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeJobV2Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/alter/SchemaChangeJobV2Test.java @@ -75,12 +75,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -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.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -114,10 +112,7 @@ public class SchemaChangeJobV2Test { false, AggregateType.MAX, false, Optional.of(new DefaultValue("1")), ""); private static AddColumnOp addColumnOp = new AddColumnOp(newCol, new ColumnPosition("v"), null, null); - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, UserException { @@ -138,7 +133,7 @@ public void setUp() mockedAgentTaskExecutor = Mockito.mockStatic(AgentTaskExecutor.class); } - @After + @AfterEach public void tearDown() { if (mockedAgentTaskExecutor != null) { mockedAgentTaskExecutor.close(); @@ -173,8 +168,8 @@ public void testAddSchemaChange() throws UserException { OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogTestUtil.testTableId1); schemaChangeHandler.process(alterOps, db, olapTable); Map alterJobsV2 = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); + Assertions.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); } @Test @@ -197,11 +192,11 @@ public void testDropColumnUpdatesBfColumnsBeforeJobFinalized() throws UserExcept alterOps.add(new DropColumnOp(bfColumn.getName(), null, Maps.newHashMap())); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertNull(olapTable.getCopiedBfColumns()); + Assertions.assertNull(olapTable.getCopiedBfColumns()); SchemaChangeJobV2 schemaChangeJob = (SchemaChangeJobV2) schemaChangeHandler .getAlterJobsV2().values().stream().findFirst().orElseThrow(); - Assert.assertNull(Deencapsulation.getField(schemaChangeJob, "bfColumns")); - Assert.assertFalse((Boolean) Deencapsulation.getField(schemaChangeJob, "hasBfChange")); + Assertions.assertNull(Deencapsulation.getField(schemaChangeJob, "bfColumns")); + Assertions.assertFalse((Boolean) Deencapsulation.getField(schemaChangeJob, "hasBfChange")); } // start a schema change, then finished @@ -226,13 +221,13 @@ public void testSchemaChange1() throws Exception { Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); schemaChangeHandler.process(alterOps, db, olapTable); Map alterJobsV2 = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); SchemaChangeJobV2 schemaChangeJob = (SchemaChangeJobV2) alterJobsV2.values().stream().findAny().get(); MaterializedIndex baseIndex = testPartition.getBaseIndex(); - Assert.assertEquals(IndexState.NORMAL, baseIndex.getState()); - Assert.assertEquals(PartitionState.NORMAL, testPartition.getState()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); + Assertions.assertEquals(IndexState.NORMAL, baseIndex.getState()); + Assertions.assertEquals(PartitionState.NORMAL, testPartition.getState()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); Tablet baseTablet = baseIndex.getTablets().get(0); List replicas = baseTablet.getReplicas(); @@ -240,39 +235,39 @@ public void testSchemaChange1() throws Exception { Replica replica2 = replicas.get(1); Replica replica3 = replicas.get(2); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); - Assert.assertEquals(-1, replica1.getLastFailedVersion()); - Assert.assertEquals(-1, replica2.getLastFailedVersion()); - Assert.assertEquals(-1, replica3.getLastFailedVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); + Assertions.assertEquals(-1, replica1.getLastFailedVersion()); + Assertions.assertEquals(-1, replica2.getLastFailedVersion()); + Assertions.assertEquals(-1, replica3.getLastFailedVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); // runPendingJob schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.WAITING_TXN, schemaChangeJob.getJobState()); - Assert.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); + Assertions.assertEquals(JobState.WAITING_TXN, schemaChangeJob.getJobState()); + Assertions.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); // runWaitingTxnJob schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // runRunningJob, task not finished schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // runRunningJob schemaChangeHandler.runAfterCatalogReady(); // task not finished, still running - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // finish alter tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } @@ -284,7 +279,7 @@ public void testSchemaChange1() throws Exception { } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.FINISHED, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.FINISHED, schemaChangeJob.getJobState()); } @Test @@ -308,13 +303,13 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { Partition testPartition = olapTable.getPartition(CatalogTestUtil.testPartitionId1); schemaChangeHandler.process(alterOps, db, olapTable); Map alterJobsV2 = schemaChangeHandler.getAlterJobsV2(); - Assert.assertEquals(1, alterJobsV2.size()); + Assertions.assertEquals(1, alterJobsV2.size()); SchemaChangeJobV2 schemaChangeJob = (SchemaChangeJobV2) alterJobsV2.values().stream().findAny().get(); MaterializedIndex baseIndex = testPartition.getBaseIndex(); - Assert.assertEquals(IndexState.NORMAL, baseIndex.getState()); - Assert.assertEquals(PartitionState.NORMAL, testPartition.getState()); - Assert.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); + Assertions.assertEquals(IndexState.NORMAL, baseIndex.getState()); + Assertions.assertEquals(PartitionState.NORMAL, testPartition.getState()); + Assertions.assertEquals(OlapTableState.SCHEMA_CHANGE, olapTable.getState()); Tablet baseTablet = baseIndex.getTablets().get(0); List replicas = baseTablet.getReplicas(); @@ -322,45 +317,45 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { Replica replica2 = replicas.get(1); Replica replica3 = replicas.get(2); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); - Assert.assertEquals(-1, replica1.getLastFailedVersion()); - Assert.assertEquals(-1, replica2.getLastFailedVersion()); - Assert.assertEquals(-1, replica3.getLastFailedVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getVersion()); + Assertions.assertEquals(-1, replica1.getLastFailedVersion()); + Assertions.assertEquals(-1, replica2.getLastFailedVersion()); + Assertions.assertEquals(-1, replica3.getLastFailedVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica1.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica2.getLastSuccessVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica3.getLastSuccessVersion()); // runPendingJob replica1.setState(Replica.ReplicaState.DECOMMISSION); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.PENDING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.PENDING, schemaChangeJob.getJobState()); // table is stable runPendingJob again replica1.setState(Replica.ReplicaState.NORMAL); schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.WAITING_TXN, schemaChangeJob.getJobState()); - Assert.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); - Assert.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); + Assertions.assertEquals(JobState.WAITING_TXN, schemaChangeJob.getJobState()); + Assertions.assertEquals(2, testPartition.getMaterializedIndices(IndexExtState.ALL).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.VISIBLE).size()); + Assertions.assertEquals(1, testPartition.getMaterializedIndices(IndexExtState.SHADOW).size()); // runWaitingTxnJob schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // runWaitingTxnJob, task not finished schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // runRunningJob schemaChangeHandler.runAfterCatalogReady(); // task not finished, still running - Assert.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.RUNNING, schemaChangeJob.getJobState()); // finish alter tasks List tasks = AgentTaskQueue.getTask(TTaskType.ALTER); - Assert.assertEquals(3, tasks.size()); + Assertions.assertEquals(3, tasks.size()); for (AgentTask agentTask : tasks) { agentTask.setFinished(true); } @@ -372,7 +367,7 @@ public void testSchemaChangeWhileTabletNotStable() throws Exception { } schemaChangeHandler.runAfterCatalogReady(); - Assert.assertEquals(JobState.FINISHED, schemaChangeJob.getJobState()); + Assertions.assertEquals(JobState.FINISHED, schemaChangeJob.getJobState()); } @Test @@ -398,43 +393,43 @@ public void testModifyDynamicPartitionNormal() throws UserException { Database db = CatalogMocker.mockDb(); OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogMocker.TEST_TBL2_ID); schemaChangeHandler.process(alterOps, db, olapTable); - Assert.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().isExist()); - Assert.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); - Assert.assertEquals("day", olapTable.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); - Assert.assertEquals(3, olapTable.getTableProperty().getDynamicPartitionProperty().getEnd()); - Assert.assertEquals("p", olapTable.getTableProperty().getDynamicPartitionProperty().getPrefix()); - Assert.assertEquals(30, olapTable.getTableProperty().getDynamicPartitionProperty().getBuckets()); + Assertions.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertEquals("day", olapTable.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); + Assertions.assertEquals(3, olapTable.getTableProperty().getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals("p", olapTable.getTableProperty().getDynamicPartitionProperty().getPrefix()); + Assertions.assertEquals(30, olapTable.getTableProperty().getDynamicPartitionProperty().getBuckets()); // set dynamic_partition.enable = false ArrayList tmpAlterOps = new ArrayList<>(); properties.put(DynamicPartitionProperty.ENABLE, "false"); tmpAlterOps.add(new ModifyTablePropertiesOp(properties)); schemaChangeHandler.process(tmpAlterOps, db, olapTable); - Assert.assertFalse(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertFalse(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); // set dynamic_partition.time_unit = week tmpAlterOps = new ArrayList<>(); properties.put(DynamicPartitionProperty.TIME_UNIT, "week"); tmpAlterOps.add(new ModifyTablePropertiesOp(properties)); schemaChangeHandler.process(tmpAlterOps, db, olapTable); - Assert.assertEquals("week", olapTable.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); + Assertions.assertEquals("week", olapTable.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); // set dynamic_partition.end = 10 tmpAlterOps = new ArrayList<>(); properties.put(DynamicPartitionProperty.END, "10"); tmpAlterOps.add(new ModifyTablePropertiesOp(properties)); schemaChangeHandler.process(tmpAlterOps, db, olapTable); - Assert.assertEquals(10, olapTable.getTableProperty().getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals(10, olapTable.getTableProperty().getDynamicPartitionProperty().getEnd()); // set dynamic_partition.prefix = p1 tmpAlterOps = new ArrayList<>(); properties.put(DynamicPartitionProperty.PREFIX, "p1"); tmpAlterOps.add(new ModifyTablePropertiesOp(properties)); schemaChangeHandler.process(tmpAlterOps, db, olapTable); - Assert.assertEquals("p1", olapTable.getTableProperty().getDynamicPartitionProperty().getPrefix()); + Assertions.assertEquals("p1", olapTable.getTableProperty().getDynamicPartitionProperty().getPrefix()); // set dynamic_partition.buckets = 3 tmpAlterOps = new ArrayList<>(); properties.put(DynamicPartitionProperty.BUCKETS, "3"); tmpAlterOps.add(new ModifyTablePropertiesOp(properties)); schemaChangeHandler.process(tmpAlterOps, db, olapTable); - Assert.assertEquals(3, olapTable.getTableProperty().getDynamicPartitionProperty().getBuckets()); + Assertions.assertEquals(3, olapTable.getTableProperty().getDynamicPartitionProperty().getBuckets()); } public void modifyDynamicPartitionWithoutTableProperty(String propertyKey, String propertyValue) @@ -453,11 +448,13 @@ public void modifyDynamicPartitionWithoutTableProperty(String propertyKey, Strin Database db = CatalogMocker.mockDb(); OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogMocker.TEST_TBL2_ID); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2," + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + schemaChangeHandler.process(alterOps, db, olapTable); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2," + " detailMessage = Table test_db.test_tbl2 is not a dynamic partition table. " - + "Use command `HELP ALTER TABLE` to see how to change a normal table to a dynamic partition table."); - schemaChangeHandler.process(alterOps, db, olapTable); + + "Use command `HELP ALTER TABLE` to see how to change a normal table to a dynamic partition table."), + "unexpected message: " + e.getMessage()); } @Test @@ -493,10 +490,12 @@ public void testModifyDynamicPartitionWithInvalidProperty() throws UserException Database db = CatalogMocker.mockDb(); OlapTable olapTable = (OlapTable) db.getTableOrDdlException(CatalogMocker.TEST_TBL2_ID); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2," - + " detailMessage = Invalid dynamic partition properties: dynamic_partition.time_uint, dynamic_partition.edn"); - schemaChangeHandler.process(alterOps, db, olapTable); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + schemaChangeHandler.process(alterOps, db, olapTable); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2," + + " detailMessage = Invalid dynamic partition properties: dynamic_partition.time_uint, dynamic_partition.edn"), + "unexpected message: " + e.getMessage()); } @Test @@ -527,16 +526,16 @@ public void testSerializeOfSchemaChangeJob() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); SchemaChangeJobV2 result = (SchemaChangeJobV2) AlterJobV2.read(in); - Assert.assertEquals(1, result.getJobId()); - Assert.assertEquals(JobState.FINISHED, result.getJobState()); - Assert.assertEquals(TStorageFormat.V2, Deencapsulation.getField(result, "storageFormat")); + Assertions.assertEquals(1, result.getJobId()); + Assertions.assertEquals(JobState.FINISHED, result.getJobState()); + Assertions.assertEquals(TStorageFormat.V2, Deencapsulation.getField(result, "storageFormat")); - Assert.assertNotNull(Deencapsulation.getField(result, "partitionIndexMap")); - Assert.assertNotNull(Deencapsulation.getField(result, "partitionIndexTabletMap")); + Assertions.assertNotNull(Deencapsulation.getField(result, "partitionIndexMap")); + Assertions.assertNotNull(Deencapsulation.getField(result, "partitionIndexTabletMap")); Map map = Deencapsulation.getField(result, "indexSchemaVersionAndHashMap"); - Assert.assertEquals(10, map.get(1000L).schemaVersion); - Assert.assertEquals(20, map.get(1000L).schemaHash); + Assertions.assertEquals(10, map.get(1000L).schemaVersion); + Assertions.assertEquals(20, map.get(1000L).schemaHash); } @Test @@ -553,9 +552,9 @@ public void testModifyTableDistributionType() throws DdlException { Database db = masterEnv.getInternalCatalog().getDb(CatalogTestUtil.testDbId1).get(); OlapTable olapTable = (OlapTable) db.getTable(CatalogTestUtil.testTableId1).get(); Env.getCurrentEnv().convertDistributionType(db, olapTable); - Assert.assertTrue(olapTable.getDefaultDistributionInfo().getType() == DistributionInfo.DistributionInfoType.RANDOM); + Assertions.assertTrue(olapTable.getDefaultDistributionInfo().getType() == DistributionInfo.DistributionInfoType.RANDOM); Partition partition1 = olapTable.getPartition(CatalogTestUtil.testPartitionId1); - Assert.assertTrue(partition1.getDistributionInfo().getType() == DistributionInfo.DistributionInfoType.RANDOM); + Assertions.assertTrue(partition1.getDistributionInfo().getType() == DistributionInfo.DistributionInfoType.RANDOM); } @Test @@ -572,9 +571,11 @@ public void testAbnormalModifyTableDistributionType1() throws UserException { FakeEnv.setEnv(masterEnv); Database db = masterEnv.getInternalCatalog().getDb(CatalogTestUtil.testDbId1).get(); Mockito.when(table.isColocateTable()).thenReturn(true); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2, detailMessage = Cannot change distribution type of colocate table."); - Env.getCurrentEnv().convertDistributionType(db, table); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + Env.getCurrentEnv().convertDistributionType(db, table); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2, detailMessage = Cannot change distribution type of colocate table."), + "unexpected message: " + e.getMessage()); } @Test @@ -592,9 +593,11 @@ public void testAbnormalModifyTableDistributionType2() throws UserException { Database db = masterEnv.getInternalCatalog().getDb(CatalogTestUtil.testDbId1).get(); Mockito.when(table.isColocateTable()).thenReturn(false); Mockito.when(table.getKeysType()).thenReturn(KeysType.UNIQUE_KEYS); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2, detailMessage = Cannot change distribution type of unique keys table."); - Env.getCurrentEnv().convertDistributionType(db, table); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + Env.getCurrentEnv().convertDistributionType(db, table); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2, detailMessage = Cannot change distribution type of unique keys table."), + "unexpected message: " + e.getMessage()); } @Test @@ -615,10 +618,12 @@ public void testAbnormalModifyTableDistributionType3() throws UserException { Mockito.when(table.getBaseSchema()).thenReturn(Lists.newArrayList( new Column("k1", Type.INT, true, null, "0", ""), new Column("v1", Type.INT, false, AggregateType.REPLACE, "0", ""))); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("errCode = 2, detailMessage = Cannot change " - + "distribution type of aggregate keys table which has value columns with REPLACE type."); - Env.getCurrentEnv().convertDistributionType(db, table); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + Env.getCurrentEnv().convertDistributionType(db, table); + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 2, detailMessage = Cannot change " + + "distribution type of aggregate keys table which has value columns with REPLACE type."), + "unexpected message: " + e.getMessage()); } @Test @@ -706,7 +711,7 @@ public void testCreateShadowIndexReplicaCopiesBfIndexesOnlyForBaseShadowReplica( // Only base shadow indexes copy BfIndex metadata. BfColumns are carried separately, // so BfIndex metadata does not get folded // into the rollup shadow replica. - Assert.assertEquals(2, submittedTasks.size()); + Assertions.assertEquals(2, submittedTasks.size()); CreateReplicaTask baseTask = (CreateReplicaTask) submittedTasks.stream() .filter(task -> task.getIndexId() == shadowBaseIndexId) .findFirst() @@ -725,10 +730,10 @@ public void testCreateShadowIndexReplicaCopiesBfIndexesOnlyForBaseShadowReplica( @SuppressWarnings("unchecked") Set rollupTaskBfColumns = Deencapsulation.getField(rollupTask, "bfColumns"); - Assert.assertEquals(bfIndexes, baseTaskIndexes); - Assert.assertNull(rollupTaskIndexes); - Assert.assertNull(baseTaskBfColumns); - Assert.assertNull(rollupTaskBfColumns); + Assertions.assertEquals(bfIndexes, baseTaskIndexes); + Assertions.assertNull(rollupTaskIndexes); + Assertions.assertNull(baseTaskBfColumns); + Assertions.assertNull(rollupTaskBfColumns); } private MaterializedIndex createLocalIndex(long indexId, long tabletId, long replicaId, long backendId, diff --git a/fe/fe-core/src/test/java/org/apache/doris/analysis/AlterUserStmtTest.java b/fe/fe-core/src/test/java/org/apache/doris/analysis/AlterUserStmtTest.java index d16b9e0638d9ce..1ccedb59b36db5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/analysis/AlterUserStmtTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/AlterUserStmtTest.java @@ -26,9 +26,9 @@ import org.apache.doris.nereids.trees.plans.commands.info.AlterUserInfo; import org.apache.doris.qe.ConnectContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -36,7 +36,7 @@ public class AlterUserStmtTest { - @Before + @BeforeEach public void setUp() { ConnectContext ctx = new ConnectContext(); ctx.setRemoteIP("192.168.1.1"); @@ -64,8 +64,8 @@ public void testTlsRequireNoneOnly() throws UserException { PasswordOptions.UNSET_OPTION, null, TlsOptions.requireNone()); info.validate(); - Assert.assertEquals(org.apache.doris.alter.AlterUserOpType.SET_TLS_REQUIRE, info.getOpType()); - Assert.assertFalse(info.getUserIdent().hasTlsRequirements()); + Assertions.assertEquals(org.apache.doris.alter.AlterUserOpType.SET_TLS_REQUIRE, info.getOpType()); + Assertions.assertFalse(info.getUserIdent().hasTlsRequirements()); } } @@ -79,68 +79,78 @@ public void testTlsRequireSanOnly() throws UserException { PasswordOptions.UNSET_OPTION, null, tlsOptions); info.validate(); - Assert.assertEquals(org.apache.doris.alter.AlterUserOpType.SET_TLS_REQUIRE, info.getOpType()); - Assert.assertEquals("DNS:example.com", info.getUserIdent().getSan()); + Assertions.assertEquals(org.apache.doris.alter.AlterUserOpType.SET_TLS_REQUIRE, info.getOpType()); + Assertions.assertEquals("DNS:example.com", info.getUserIdent().getSan()); } } - @Test(expected = AnalysisException.class) + @Test public void testTlsWithPasswordChangeNotAllowed() throws UserException { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { - TlsOptions tlsOptions = TlsOptions.of(Collections.singletonList(Pair.of("SAN", "DNS:example.com"))); - AlterUserInfo info = new AlterUserInfo(false, - new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), - PasswordOptions.UNSET_OPTION, null, tlsOptions); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { + TlsOptions tlsOptions = TlsOptions.of(Collections.singletonList(Pair.of("SAN", "DNS:example.com"))); + AlterUserInfo info = new AlterUserInfo(false, + new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), + PasswordOptions.UNSET_OPTION, null, tlsOptions); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testTlsRequireSanEmptyValue() throws UserException { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { - AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), - PasswordOptions.UNSET_OPTION, null, - TlsOptions.of(Collections.singletonList(Pair.of("SAN", "")))); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { + AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), + PasswordOptions.UNSET_OPTION, null, + TlsOptions.of(Collections.singletonList(Pair.of("SAN", "")))); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testTlsUnsupportedOption() throws UserException { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { - AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), - PasswordOptions.UNSET_OPTION, null, - TlsOptions.of(Collections.singletonList(Pair.of("ISSUER", "ca")))); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { + AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), + PasswordOptions.UNSET_OPTION, null, + TlsOptions.of(Collections.singletonList(Pair.of("ISSUER", "ca")))); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testMultipleNonTlsOpsAreRejected() throws UserException { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { - AlterUserInfo info = new AlterUserInfo(false, - new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), PasswordOptions.UNSET_OPTION, - "new comment", TlsOptions.notSpecified()); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { + AlterUserInfo info = new AlterUserInfo(false, + new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), PasswordOptions.UNSET_OPTION, + "new comment", TlsOptions.notSpecified()); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testNoOpsAreRejected() throws UserException { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { - AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), - PasswordOptions.UNSET_OPTION, null, TlsOptions.notSpecified()); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, accessManager)) { + AlterUserInfo info = new AlterUserInfo(false, new UserDesc(new UserIdentity("tls_user", "%")), + PasswordOptions.UNSET_OPTION, null, TlsOptions.notSpecified()); + info.validate(); + } + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/analysis/CreateUserStmtTest.java b/fe/fe-core/src/test/java/org/apache/doris/analysis/CreateUserStmtTest.java index 25c53ef1b5a934..b805bb95018699 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/analysis/CreateUserStmtTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/CreateUserStmtTest.java @@ -26,9 +26,9 @@ import org.apache.doris.nereids.trees.plans.commands.info.CreateUserInfo; import org.apache.doris.qe.ConnectContext; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -36,7 +36,7 @@ public class CreateUserStmtTest { - @Before + @BeforeEach public void setUp() { ConnectContext ctx = new ConnectContext(); ctx.setRemoteIP("192.168.1.1"); @@ -66,18 +66,18 @@ public void testPasswordNormalize() throws AnalysisException { try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { CreateUserInfo info = new CreateUserInfo(new UserDesc(new UserIdentity("user", "%"), "passwd", true)); info.validate(); - Assert.assertEquals("user", info.getUserIdent().getQualifiedUser()); - Assert.assertEquals("*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0", new String(info.getPassword())); + Assertions.assertEquals("user", info.getUserIdent().getQualifiedUser()); + Assertions.assertEquals("*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0", new String(info.getPassword())); info = new CreateUserInfo( new UserDesc(new UserIdentity("user", "%"), "*59c70da2f3e3a5bdf46b68f5c8b8f25762bccef0", false)); info.validate(); - Assert.assertEquals("*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0", new String(info.getPassword())); + Assertions.assertEquals("*59C70DA2F3E3A5BDF46B68F5C8B8F25762BCCEF0", new String(info.getPassword())); info = new CreateUserInfo(new UserDesc(new UserIdentity("user", "%"), "", false)); info.validate(); - Assert.assertEquals("", new String(info.getPassword())); + Assertions.assertEquals("", new String(info.getPassword())); } } @@ -93,8 +93,8 @@ public void testTlsRequireNone() throws AnalysisException { info.validate(); UserIdentity userIdent = info.getUserIdent(); - Assert.assertFalse(userIdent.hasTlsRequirements()); - Assert.assertNull(userIdent.getSan()); + Assertions.assertFalse(userIdent.hasTlsRequirements()); + Assertions.assertNull(userIdent.getSan()); } } @@ -111,55 +111,63 @@ public void testTlsRequireSan() throws AnalysisException { info.validate(); UserIdentity userIdent = info.getUserIdent(); - Assert.assertEquals("DNS:example.com", userIdent.getSan()); + Assertions.assertEquals("DNS:example.com", userIdent.getSan()); } } - @Test(expected = AnalysisException.class) + @Test public void testTlsRequireSanEmptyValue() throws AnalysisException { - Env env = Mockito.mock(Env.class); - Auth auth = Mockito.mock(Auth.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { - CreateUserInfo info = new CreateUserInfo(false, - new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), - null, null, null, TlsOptions.of(Collections.singletonList(Pair.of("SAN", "")))); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + Auth auth = Mockito.mock(Auth.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { + CreateUserInfo info = new CreateUserInfo(false, + new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), + null, null, null, TlsOptions.of(Collections.singletonList(Pair.of("SAN", "")))); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testTlsUnsupportedOption() throws AnalysisException { - Env env = Mockito.mock(Env.class); - Auth auth = Mockito.mock(Auth.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { - CreateUserInfo info = new CreateUserInfo(false, - new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), - null, null, null, TlsOptions.of(Collections.singletonList(Pair.of("ISSUER", "ca")))); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + Auth auth = Mockito.mock(Auth.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { + CreateUserInfo info = new CreateUserInfo(false, + new UserDesc(new UserIdentity("tls_user", "%"), "passwd", true), + null, null, null, TlsOptions.of(Collections.singletonList(Pair.of("ISSUER", "ca")))); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testEmptyUser() throws AnalysisException { - Env env = Mockito.mock(Env.class); - Auth auth = Mockito.mock(Auth.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { - CreateUserInfo info = new CreateUserInfo(new UserDesc(new UserIdentity("", "%"), "passwd", true)); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + Auth auth = Mockito.mock(Auth.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { + CreateUserInfo info = new CreateUserInfo(new UserDesc(new UserIdentity("", "%"), "passwd", true)); + info.validate(); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testBadPass() throws AnalysisException { - Env env = Mockito.mock(Env.class); - Auth auth = Mockito.mock(Auth.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { - CreateUserInfo info = new CreateUserInfo(new UserDesc(new UserIdentity("", "%"), "passwd", false)); - info.validate(); - } + Assertions.assertThrows(AnalysisException.class, () -> { + Env env = Mockito.mock(Env.class); + Auth auth = Mockito.mock(Auth.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + try (MockedStatic ignored = mockValidateEnv(env, auth, accessManager)) { + CreateUserInfo info = new CreateUserInfo(new UserDesc(new UserIdentity("", "%"), "passwd", false)); + info.validate(); + } + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/analysis/StorageDescPersistTest.java b/fe/fe-core/src/test/java/org/apache/doris/analysis/StorageDescPersistTest.java index f26fc09a915f9f..b029e9695099a5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/analysis/StorageDescPersistTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/StorageDescPersistTest.java @@ -23,8 +23,8 @@ import org.apache.doris.persist.gson.GsonUtils; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Map; @@ -40,10 +40,10 @@ public void testBrokerDescRestoreStoragePropertiesAfterGsonRoundTrip() { BrokerDesc restored = GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(brokerDesc), BrokerDesc.class); - Assert.assertNotNull(restored.getStorageAdapter()); - Assert.assertEquals("BROKER", restored.getStorageAdapter().getStorageName()); - Assert.assertEquals("test_broker", restored.getStorageAdapter().getBrokerName()); - Assert.assertEquals("user", restored.getStorageAdapter().getBackendConfigProperties() + Assertions.assertNotNull(restored.getStorageAdapter()); + Assertions.assertEquals("BROKER", restored.getStorageAdapter().getStorageName()); + Assertions.assertEquals("test_broker", restored.getStorageAdapter().getBrokerName()); + Assertions.assertEquals("user", restored.getStorageAdapter().getBackendConfigProperties() .get("broker.username")); } @@ -64,14 +64,14 @@ public void testBrokerLoadJobRestoreS3StoragePropertiesAfterGsonRoundTrip() thro (BrokerDesc) getField(BrokerLoadJob.class.getSuperclass(), restored, "brokerDesc"); StorageAdapter restoredStorageProperties = restoredBrokerDesc.getStorageAdapter(); - Assert.assertNotNull(restoredStorageProperties); - Assert.assertEquals("S3", restoredStorageProperties.getStorageName()); - Assert.assertEquals(EtlJobType.BROKER, restored.getJobType()); - Assert.assertEquals(StorageBackend.StorageType.S3, restoredBrokerDesc.getStorageType()); - Assert.assertEquals("test-bucket", restoredStorageProperties.getOrigProps().get("s3.bucket")); - Assert.assertNotNull(restoredBrokerDesc.getStorageAdapter()); - Assert.assertEquals("S3", restoredBrokerDesc.getStorageAdapter().getStorageName()); - Assert.assertEquals("test-bucket", + Assertions.assertNotNull(restoredStorageProperties); + Assertions.assertEquals("S3", restoredStorageProperties.getStorageName()); + Assertions.assertEquals(EtlJobType.BROKER, restored.getJobType()); + Assertions.assertEquals(StorageBackend.StorageType.S3, restoredBrokerDesc.getStorageType()); + Assertions.assertEquals("test-bucket", restoredStorageProperties.getOrigProps().get("s3.bucket")); + Assertions.assertNotNull(restoredBrokerDesc.getStorageAdapter()); + Assertions.assertEquals("S3", restoredBrokerDesc.getStorageAdapter().getStorageName()); + Assertions.assertEquals("test-bucket", restoredBrokerDesc.getStorageAdapter().getOrigProps().get("s3.bucket")); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/analysis/TableScanParamsTest.java b/fe/fe-core/src/test/java/org/apache/doris/analysis/TableScanParamsTest.java index 6a37a91e1e7f9a..5adfa5f0ea241e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/analysis/TableScanParamsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/TableScanParamsTest.java @@ -19,8 +19,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -40,31 +40,31 @@ public void testConstructAcceptsValidParamTypes() { @Test public void testConstructRejectsInvalidParamType() { - IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class, + IllegalArgumentException e = Assertions.assertThrows(IllegalArgumentException.class, () -> new TableScanParams("unknown", EMPTY_MAP, EMPTY_LIST)); - Assert.assertTrue(e.getMessage().contains("Invalid param type")); + Assertions.assertTrue(e.getMessage().contains("Invalid param type")); } @Test public void testParamTypeLowerCased() { TableScanParams params = new TableScanParams("BRANCH", EMPTY_MAP, EMPTY_LIST); - Assert.assertEquals(TableScanParams.BRANCH, params.getParamType()); - Assert.assertTrue(params.isBranch()); + Assertions.assertEquals(TableScanParams.BRANCH, params.getParamType()); + Assertions.assertTrue(params.isBranch()); } @Test public void testNullMapParamsBecomesEmpty() { TableScanParams params = new TableScanParams(TableScanParams.TAG, null, EMPTY_LIST); - Assert.assertTrue(params.getMapParams().isEmpty()); + Assertions.assertTrue(params.getMapParams().isEmpty()); } @Test public void testTypePredicates() { - Assert.assertTrue(new TableScanParams(TableScanParams.INCREMENTAL_READ, EMPTY_MAP, EMPTY_LIST) + Assertions.assertTrue(new TableScanParams(TableScanParams.INCREMENTAL_READ, EMPTY_MAP, EMPTY_LIST) .incrementalRead()); - Assert.assertTrue(new TableScanParams(TableScanParams.SNAPSHOT, EMPTY_MAP, EMPTY_LIST).isSnapshot()); - Assert.assertTrue(new TableScanParams(TableScanParams.RESET, EMPTY_MAP, EMPTY_LIST).isReset()); - Assert.assertTrue(new TableScanParams(TableScanParams.TAG, EMPTY_MAP, EMPTY_LIST).isTag()); + Assertions.assertTrue(new TableScanParams(TableScanParams.SNAPSHOT, EMPTY_MAP, EMPTY_LIST).isSnapshot()); + Assertions.assertTrue(new TableScanParams(TableScanParams.RESET, EMPTY_MAP, EMPTY_LIST).isReset()); + Assertions.assertTrue(new TableScanParams(TableScanParams.TAG, EMPTY_MAP, EMPTY_LIST).isTag()); } @Test @@ -74,9 +74,9 @@ public void testValidateOlapTableAcceptsIncr() { @Test public void testValidateOlapTableRejectsOthers() { - IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class, + IllegalArgumentException e = Assertions.assertThrows(IllegalArgumentException.class, () -> new TableScanParams(TableScanParams.BRANCH, EMPTY_MAP, EMPTY_LIST).validateOlapTable()); - Assert.assertTrue(e.getMessage().contains("Invalid param type for olap table")); + Assertions.assertTrue(e.getMessage().contains("Invalid param type for olap table")); } @Test @@ -87,9 +87,9 @@ public void testValidateOlapTableStreamAcceptsSnapshotAndReset() { @Test public void testValidateOlapTableStreamRejectsOthers() { - IllegalArgumentException e = Assert.assertThrows(IllegalArgumentException.class, + IllegalArgumentException e = Assertions.assertThrows(IllegalArgumentException.class, () -> new TableScanParams(TableScanParams.INCREMENTAL_READ, EMPTY_MAP, EMPTY_LIST) .validateOlapTableStream()); - Assert.assertTrue(e.getMessage().contains("Invalid param type for olap table stream")); + Assertions.assertTrue(e.getMessage().contains("Invalid param type for olap table stream")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/analysis/TlsOptionsTest.java b/fe/fe-core/src/test/java/org/apache/doris/analysis/TlsOptionsTest.java index da06ec0487eb11..79cf943a765dbd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/analysis/TlsOptionsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/analysis/TlsOptionsTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.AnalysisException; import org.apache.doris.common.Pair; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; @@ -31,24 +31,24 @@ public class TlsOptionsTest { public void testAnalyzeRejectsSanEntryWithoutValue() { TlsOptions tlsOptions = TlsOptions.of(Collections.singletonList(Pair.of("SAN", "DNS:"))); - AnalysisException e = Assert.assertThrows(AnalysisException.class, tlsOptions::analyze); - Assert.assertTrue(e.getMessage().contains("Invalid SAN entry format")); + AnalysisException e = Assertions.assertThrows(AnalysisException.class, tlsOptions::analyze); + Assertions.assertTrue(e.getMessage().contains("Invalid SAN entry format")); } @Test public void testAnalyzeRejectsUnsupportedSanType() { TlsOptions tlsOptions = TlsOptions.of(Collections.singletonList(Pair.of("SAN", "FOO:bar"))); - AnalysisException e = Assert.assertThrows(AnalysisException.class, tlsOptions::analyze); - Assert.assertTrue(e.getMessage().contains("Unsupported SAN entry type")); + AnalysisException e = Assertions.assertThrows(AnalysisException.class, tlsOptions::analyze); + Assertions.assertTrue(e.getMessage().contains("Unsupported SAN entry type")); } @Test public void testAnalyzeRejectsEmptyEntryInList() { TlsOptions tlsOptions = TlsOptions.of(Collections.singletonList(Pair.of("SAN", "DNS:example.com, "))); - AnalysisException e = Assert.assertThrows(AnalysisException.class, tlsOptions::analyze); - Assert.assertTrue(e.getMessage().contains("empty entry")); + AnalysisException e = Assertions.assertThrows(AnalysisException.class, tlsOptions::analyze); + Assertions.assertTrue(e.getMessage().contains("empty entry")); } @Test @@ -58,7 +58,7 @@ public void testAnalyzeNormalizesValidEntries() throws AnalysisException { )); tlsOptions.analyze(); - Assert.assertEquals( + Assertions.assertEquals( "email:alice@example.com, DNS:Example.com, URI:spiffe://Example.com/workload, IP Address:192.168.1.1", tlsOptions.getSan()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/auth/certificate/SanEntryCodecTest.java b/fe/fe-core/src/test/java/org/apache/doris/auth/certificate/SanEntryCodecTest.java index e91512478ae55f..f966db38e7fc5c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/auth/certificate/SanEntryCodecTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/auth/certificate/SanEntryCodecTest.java @@ -17,8 +17,8 @@ package org.apache.doris.auth.certificate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; @@ -30,7 +30,7 @@ public void testParseAndNormalizeCanonicalizesEntries() { List entries = SanEntryCodec.parseAndNormalize( "email:Alice@Example.com, DNS:Example.com., IP:10.0.0.1"); - Assert.assertEquals(Arrays.asList( + Assertions.assertEquals(Arrays.asList( "email:Alice@Example.com", "DNS:Example.com", "IP Address:10.0.0.1"), entries); @@ -38,14 +38,14 @@ public void testParseAndNormalizeCanonicalizesEntries() { @Test public void testContainsAllMatchesNormalizedEntries() { - Assert.assertTrue(SanEntryCodec.containsAll( + Assertions.assertTrue(SanEntryCodec.containsAll( Arrays.asList("DNS:example.com", "email:Alice@Example.com"), Arrays.asList("email:Alice@Example.com", "DNS:example.com.", "URI:spiffe://foo"))); } @Test public void testContainsAllRejectsMissingEntry() { - Assert.assertFalse(SanEntryCodec.containsAll( + Assertions.assertFalse(SanEntryCodec.containsAll( Arrays.asList("DNS:example.com", "URI:spiffe://example.com/workload"), Arrays.asList("DNS:example.com"))); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupHandlerTest.java index 48e65ae6293b3a..e055cdb37f7e72 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupHandlerTest.java @@ -51,10 +51,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -90,7 +90,7 @@ public class BackupHandlerTest { private TabletInvertedIndex invertedIndex = new LocalTabletInvertedIndex(); - @Before + @BeforeEach public void setUp() throws Exception { Config.tmp_dir = tmpPath; rootDir = new File(Config.tmp_dir); @@ -113,7 +113,7 @@ public void setUp() throws Exception { Mockito.doReturn(db).when(catalog).getDbOrDdlException(Mockito.anyString()); } - @After + @AfterEach public void done() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -135,7 +135,7 @@ public void testInit() { handler.runAfterCatalogReady(); File backupDir = new File(BackupHandler.BACKUP_ROOT_DIR.toString()); - Assert.assertTrue(backupDir.exists()); + Assertions.assertTrue(backupDir.exists()); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobInfoTest.java index 9132f157a395ee..31661bc78bc2ce 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobInfoTest.java @@ -17,10 +17,10 @@ package org.apache.doris.backup; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileNotFoundException; @@ -31,7 +31,7 @@ public class BackupJobInfoTest { private static String fileName = "job_info.txt"; - @BeforeClass + @BeforeAll public static void createFile() { String json = "{\n" + " \"backup_time\": 1522231864000,\n" @@ -124,11 +124,11 @@ public static void createFile() { out.print(json); } catch (FileNotFoundException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } - @AfterClass + @AfterAll public static void deleteFile() { File file = new File(fileName); if (file.exists()) { @@ -143,23 +143,23 @@ public void testReadWrite() { jobInfo = BackupJobInfo.fromFile(fileName); } catch (IOException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } - Assert.assertNotNull(jobInfo); + Assertions.assertNotNull(jobInfo); - Assert.assertEquals(1522231864000L, jobInfo.backupTime); - Assert.assertEquals("snapshot1", jobInfo.name); - Assert.assertEquals(2, jobInfo.backupOlapTableObjects.size()); + Assertions.assertEquals(1522231864000L, jobInfo.backupTime); + Assertions.assertEquals("snapshot1", jobInfo.name); + Assertions.assertEquals(2, jobInfo.backupOlapTableObjects.size()); - Assert.assertEquals(2, jobInfo.getOlapTableInfo("table1").partitions.size()); - Assert.assertEquals(2, jobInfo.getOlapTableInfo("table1").getPartInfo("partition1").indexes.size()); - Assert.assertEquals(2, + Assertions.assertEquals(2, jobInfo.getOlapTableInfo("table1").partitions.size()); + Assertions.assertEquals(2, jobInfo.getOlapTableInfo("table1").getPartInfo("partition1").indexes.size()); + Assertions.assertEquals(2, jobInfo.getOlapTableInfo("table1").getPartInfo("partition1").getIdx("rollup1").tablets.size()); - Assert.assertEquals(2, + Assertions.assertEquals(2, jobInfo.getOlapTableInfo("table1").getPartInfo("partition1") .getIdx("rollup1").getTabletFiles(10007L).size()); - Assert.assertEquals(1, jobInfo.newBackupObjects.views.size()); - Assert.assertEquals("view1", jobInfo.newBackupObjects.views.get(0).name); + Assertions.assertEquals(1, jobInfo.newBackupObjects.views.size()); + Assertions.assertEquals("view1", jobInfo.newBackupObjects.views.get(0).name); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobTest.java index e1e79f5bbe0dba..daafadc9d35b12 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/BackupJobTest.java @@ -51,12 +51,12 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +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.mockito.ArgumentMatchers; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; @@ -117,14 +117,14 @@ public BackupJobTest() throws UserException { private MockedStatic mockedAgentTaskExecutor; private MockedConstruction mockedFsDescriptor; - @BeforeClass + @BeforeAll public static void start() { Config.tmp_dir = "./"; File backupDir = new File(BackupHandler.BACKUP_ROOT_DIR.toString()); backupDir.mkdirs(); } - @AfterClass + @AfterAll public static void end() throws IOException { Config.tmp_dir = "./"; File backupDir = new File(BackupHandler.BACKUP_ROOT_DIR.toString()); @@ -134,7 +134,7 @@ public static void end() throws IOException { } } - @Before + @BeforeEach public void setUp() { repoMgr = Mockito.mock(RepositoryMgr.class); backupHandler = Mockito.mock(BackupHandler.class); @@ -208,7 +208,7 @@ public void setUp() { env, repo.getId(), 0); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -235,27 +235,27 @@ public void tearDown() { @Test public void testRunNormal() { // 1. pending - Assert.assertEquals(BackupJobState.PENDING, job.getState()); + Assertions.assertEquals(BackupJobState.PENDING, job.getState()); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); BackupMeta backupMeta = job.getBackupMeta(); - Assert.assertEquals(1, backupMeta.getTables().size()); + Assertions.assertEquals(1, backupMeta.getTables().size()); OlapTable backupTbl = (OlapTable) backupMeta.getTable(UnitTestUtil.TABLE_NAME); List partNames = Lists.newArrayList(backupTbl.getPartitionNames()); - Assert.assertNotNull(backupTbl); - Assert.assertEquals(backupTbl.getSignature(BackupHandler.SIGNATURE_VERSION, partNames), + Assertions.assertNotNull(backupTbl); + Assertions.assertEquals(backupTbl.getSignature(BackupHandler.SIGNATURE_VERSION, partNames), ((OlapTable) db.getTableNullable(tblId)).getSignature(BackupHandler.SIGNATURE_VERSION, partNames)); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); AgentTask task = AgentTaskQueue.getTask(backendId, TTaskType.MAKE_SNAPSHOT, id.get() - 1); - Assert.assertTrue(task instanceof SnapshotTask); + Assertions.assertTrue(task instanceof SnapshotTask); SnapshotTask snapshotTask = (SnapshotTask) task; // 2. snapshoting job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); // 3. snapshot finished String snapshotPath = "/path/to/snapshot"; @@ -269,90 +269,90 @@ public void testRunNormal() { snapshotTask.getSignature(), taskStatus); request.setSnapshotFiles(snapshotFiles); request.setSnapshotPath(snapshotPath); - Assert.assertTrue(job.finishTabletSnapshotTask(snapshotTask, request)); + Assertions.assertTrue(job.finishTabletSnapshotTask(snapshotTask, request)); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.UPLOAD_SNAPSHOT, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.UPLOAD_SNAPSHOT, job.getState()); // 4. upload snapshots AgentTaskQueue.clearAllTasks(); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.UPLOADING, job.getState()); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.UPLOADING, job.getState()); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); task = AgentTaskQueue.getTask(backendId, TTaskType.UPLOAD, id.get() - 1); - Assert.assertTrue(task instanceof UploadTask); + Assertions.assertTrue(task instanceof UploadTask); UploadTask upTask = (UploadTask) task; - Assert.assertEquals(job.getJobId(), upTask.getJobId()); + Assertions.assertEquals(job.getJobId(), upTask.getJobId()); Map srcToDest = upTask.getSrcToDestPath(); - Assert.assertEquals(1, srcToDest.size()); + Assertions.assertEquals(1, srcToDest.size()); String dest = srcToDest.get(snapshotPath + "/" + tabletId + "/" + 0); - Assert.assertNotNull(dest); + Assertions.assertNotNull(dest); // 5. uploading job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.UPLOADING, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.UPLOADING, job.getState()); Map> tabletFileMap = Maps.newHashMap(); request = new TFinishTaskRequest(tBackend, TTaskType.UPLOAD, upTask.getSignature(), taskStatus); request.setTabletFiles(tabletFileMap); - Assert.assertFalse(job.finishSnapshotUploadTask(upTask, request)); + Assertions.assertFalse(job.finishSnapshotUploadTask(upTask, request)); List tabletFiles = Lists.newArrayList(); tabletFileMap.put(tabletId, tabletFiles); - Assert.assertFalse(job.finishSnapshotUploadTask(upTask, request)); + Assertions.assertFalse(job.finishSnapshotUploadTask(upTask, request)); tabletFiles.add("1.dat.4f158689243a3d6030352fec3cfd3798"); tabletFiles.add("wrong_files.idx.4f158689243a3d6030352fec3cfd3798"); tabletFiles.add("wrong_files.hdr.4f158689243a3d6030352fec3cfd3798"); - Assert.assertFalse(job.finishSnapshotUploadTask(upTask, request)); + Assertions.assertFalse(job.finishSnapshotUploadTask(upTask, request)); tabletFiles.clear(); tabletFiles.add("1.dat.4f158689243a3d6030352fec3cfd3798"); tabletFiles.add("1.idx.4f158689243a3d6030352fec3cfd3798"); tabletFiles.add("1.hdr.4f158689243a3d6030352fec3cfd3798"); - Assert.assertTrue(job.finishSnapshotUploadTask(upTask, request)); + Assertions.assertTrue(job.finishSnapshotUploadTask(upTask, request)); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.SAVE_META, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.SAVE_META, job.getState()); // 6. save meta job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.UPLOAD_INFO, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.UPLOAD_INFO, job.getState()); File metaInfo = new File(job.getLocalMetaInfoFilePath()); - Assert.assertTrue(metaInfo.exists()); + Assertions.assertTrue(metaInfo.exists()); File jobInfo = new File(job.getLocalJobInfoFilePath()); - Assert.assertTrue(jobInfo.exists()); + Assertions.assertTrue(jobInfo.exists()); BackupMeta restoreMetaInfo = null; BackupJobInfo restoreJobInfo = null; try { restoreMetaInfo = BackupMeta.fromFile(job.getLocalMetaInfoFilePath(), FeConstants.meta_version); - Assert.assertEquals(1, restoreMetaInfo.getTables().size()); + Assertions.assertEquals(1, restoreMetaInfo.getTables().size()); OlapTable olapTable = (OlapTable) restoreMetaInfo.getTable(tblId); - Assert.assertNotNull(olapTable); - Assert.assertNotNull(restoreMetaInfo.getTable(UnitTestUtil.TABLE_NAME)); + Assertions.assertNotNull(olapTable); + Assertions.assertNotNull(restoreMetaInfo.getTable(UnitTestUtil.TABLE_NAME)); List names = Lists.newArrayList(olapTable.getPartitionNames()); - Assert.assertEquals(((OlapTable) db.getTableNullable(tblId)).getSignature(BackupHandler.SIGNATURE_VERSION, names), + Assertions.assertEquals(((OlapTable) db.getTableNullable(tblId)).getSignature(BackupHandler.SIGNATURE_VERSION, names), olapTable.getSignature(BackupHandler.SIGNATURE_VERSION, names)); restoreJobInfo = BackupJobInfo.fromFile(job.getLocalJobInfoFilePath()); - Assert.assertEquals(UnitTestUtil.DB_NAME, restoreJobInfo.dbName); - Assert.assertEquals(job.getLabel(), restoreJobInfo.name); - Assert.assertEquals(1, restoreJobInfo.backupOlapTableObjects.values().size()); + Assertions.assertEquals(UnitTestUtil.DB_NAME, restoreJobInfo.dbName); + Assertions.assertEquals(job.getLabel(), restoreJobInfo.name); + Assertions.assertEquals(1, restoreJobInfo.backupOlapTableObjects.values().size()); } catch (IOException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } - Assert.assertNull(job.getBackupMeta()); - Assert.assertNull(job.getJobInfo()); + Assertions.assertNull(job.getBackupMeta()); + Assertions.assertNull(job.getJobInfo()); // 7. upload_info job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.FINISHED, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.FINISHED, job.getState()); } @Test @@ -361,11 +361,11 @@ public void testBackupCopyTableWithDirtyDynamicPartitionStorageMedium() { dirtyProperties.put(DynamicPartitionProperty.STORAGE_MEDIUM, "hdd"); table2.setTableProperty(new TableProperty(dirtyProperties)); - Assert.assertFalse(table2.dynamicPartitionExists()); + Assertions.assertFalse(table2.dynamicPartitionExists()); OlapTable copied = table2.selectiveCopy(null, IndexExtState.VISIBLE, true); - Assert.assertNotNull(copied); - Assert.assertFalse(copied.dynamicPartitionExists()); - Assert.assertTrue(copied.getTableProperty().hasInvalidDynamicPartition()); + Assertions.assertNotNull(copied); + Assertions.assertFalse(copied.dynamicPartitionExists()); + Assertions.assertTrue(copied.getTableProperty().hasInvalidDynamicPartition()); } @Test @@ -374,11 +374,11 @@ public void testBackupCopyTableWithDirtyDynamicPartitionStoragePolicy() { dirtyProperties.put(DynamicPartitionProperty.STORAGE_POLICY, "test_policy"); table2.setTableProperty(new TableProperty(dirtyProperties)); - Assert.assertFalse(table2.dynamicPartitionExists()); + Assertions.assertFalse(table2.dynamicPartitionExists()); OlapTable copied = table2.selectiveCopy(null, IndexExtState.VISIBLE, true); - Assert.assertNotNull(copied); - Assert.assertFalse(copied.dynamicPartitionExists()); - Assert.assertTrue(copied.getTableProperty().hasInvalidDynamicPartition()); + Assertions.assertNotNull(copied); + Assertions.assertFalse(copied.dynamicPartitionExists()); + Assertions.assertTrue(copied.getTableProperty().hasInvalidDynamicPartition()); } /** @@ -408,8 +408,8 @@ public void testRunAbnormal() { job = new BackupJob("label", dbId, UnitTestUtil.DB_NAME, tableRefs, 13600 * 1000, BackupCommand.BackupContent.ALL, env, repo.getId(), 0); job.run(); - Assert.assertEquals(Status.ErrCode.NOT_FOUND, job.getStatus().getErrCode()); - Assert.assertEquals(BackupJobState.CANCELLED, job.getState()); + Assertions.assertEquals(Status.ErrCode.NOT_FOUND, job.getStatus().getErrCode()); + Assertions.assertEquals(BackupJobState.CANCELLED, job.getState()); } /** @@ -454,28 +454,28 @@ public void testRunAbnormalWithMixedTables() { env, repo.getId(), 0); // 1. pending - Assert.assertEquals(BackupJobState.PENDING, job.getState()); + Assertions.assertEquals(BackupJobState.PENDING, job.getState()); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); // Verify backup meta only contains the normal table BackupMeta backupMeta = job.getBackupMeta(); - Assert.assertEquals(1, backupMeta.getTables().size()); + Assertions.assertEquals(1, backupMeta.getTables().size()); OlapTable backupTbl = (OlapTable) backupMeta.getTable(UnitTestUtil.TABLE_NAME); - Assert.assertNotNull(backupTbl); - Assert.assertNull(backupMeta.getTable("unknown_tbl")); + Assertions.assertNotNull(backupTbl); + Assertions.assertNull(backupMeta.getTable("unknown_tbl")); // Verify only snapshot tasks for the normal table are created - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); AgentTask task = AgentTaskQueue.getTask(backendId, TTaskType.MAKE_SNAPSHOT, id.get() - 1); - Assert.assertTrue(task instanceof SnapshotTask); + Assertions.assertTrue(task instanceof SnapshotTask); SnapshotTask snapshotTask = (SnapshotTask) task; - Assert.assertEquals(tblId, snapshotTask.getTableId()); - Assert.assertEquals(dbId, snapshotTask.getDbId()); - Assert.assertEquals(partId, snapshotTask.getPartitionId()); - Assert.assertEquals(idxId, snapshotTask.getIndexId()); - Assert.assertEquals(tabletId, snapshotTask.getTabletId()); + Assertions.assertEquals(tblId, snapshotTask.getTableId()); + Assertions.assertEquals(dbId, snapshotTask.getDbId()); + Assertions.assertEquals(partId, snapshotTask.getPartitionId()); + Assertions.assertEquals(idxId, snapshotTask.getIndexId()); + Assertions.assertEquals(tabletId, snapshotTask.getTabletId()); } /** @@ -518,19 +518,19 @@ public void testRunWithTableDroppedDuringSnapshoting() { env, repo.getId(), 0); // 1. pending - should create snapshot tasks for both tables - Assert.assertEquals(BackupJobState.PENDING, job.getState()); + Assertions.assertEquals(BackupJobState.PENDING, job.getState()); job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.SNAPSHOTING, job.getState()); // Verify backup meta contains both tables initially BackupMeta backupMeta = job.getBackupMeta(); - Assert.assertEquals(2, backupMeta.getTables().size()); - Assert.assertNotNull(backupMeta.getTable(UnitTestUtil.TABLE_NAME)); - Assert.assertNotNull(backupMeta.getTable(table2Name)); + Assertions.assertEquals(2, backupMeta.getTables().size()); + Assertions.assertNotNull(backupMeta.getTable(UnitTestUtil.TABLE_NAME)); + Assertions.assertNotNull(backupMeta.getTable(table2Name)); // Verify snapshot tasks are created for both tables - Assert.assertEquals(2, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(2, AgentTaskQueue.getTaskNum()); // 2. Simulate dropping the second table during SNAPSHOTING phase db.unregisterTable(table2Name); @@ -554,7 +554,7 @@ public void testRunWithTableDroppedDuringSnapshoting() { taskStatusMissing.setErrorMsgs(Lists.newArrayList("Tablet missing")); TFinishTaskRequest requestMissing = new TFinishTaskRequest(tBackend, TTaskType.MAKE_SNAPSHOT, taskForDroppedTable.getSignature(), taskStatusMissing); - Assert.assertTrue(job.finishTabletSnapshotTask(taskForDroppedTable, requestMissing)); + Assertions.assertTrue(job.finishTabletSnapshotTask(taskForDroppedTable, requestMissing)); // Finish task for existing table String snapshotPath = "/path/to/snapshot"; @@ -564,16 +564,16 @@ public void testRunWithTableDroppedDuringSnapshoting() { taskForExistingTable.getSignature(), taskStatusOK); requestOK.setSnapshotFiles(snapshotFiles); requestOK.setSnapshotPath(snapshotPath); - Assert.assertTrue(job.finishTabletSnapshotTask(taskForExistingTable, requestOK)); + Assertions.assertTrue(job.finishTabletSnapshotTask(taskForExistingTable, requestOK)); // 4. Continue the backup process job.run(); - Assert.assertEquals(Status.OK, job.getStatus()); - Assert.assertEquals(BackupJobState.UPLOAD_SNAPSHOT, job.getState()); + Assertions.assertEquals(Status.OK, job.getStatus()); + Assertions.assertEquals(BackupJobState.UPLOAD_SNAPSHOT, job.getState()); AgentTaskQueue.clearAllTasks(); job.run(); // UPLOAD_SNAPSHOT -> UPLOADING - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); UploadTask upTask = (UploadTask) AgentTaskQueue.getTask(backendId, TTaskType.UPLOAD, id.get() - 1); // Finish upload task @@ -586,20 +586,20 @@ public void testRunWithTableDroppedDuringSnapshoting() { TFinishTaskRequest requestUpload = new TFinishTaskRequest(tBackend, TTaskType.UPLOAD, upTask.getSignature(), taskStatusOK); requestUpload.setTabletFiles(tabletFileMap); - Assert.assertTrue(job.finishSnapshotUploadTask(upTask, requestUpload)); + Assertions.assertTrue(job.finishSnapshotUploadTask(upTask, requestUpload)); job.run(); // UPLOADING -> SAVE_META - Assert.assertEquals(BackupJobState.SAVE_META, job.getState()); + Assertions.assertEquals(BackupJobState.SAVE_META, job.getState()); job.run(); // SAVE_META -> UPLOAD_INFO - Assert.assertEquals(BackupJobState.UPLOAD_INFO, job.getState()); + Assertions.assertEquals(BackupJobState.UPLOAD_INFO, job.getState()); job.run(); // UPLOAD_INFO -> FINISHED - Assert.assertEquals(BackupJobState.FINISHED, job.getState()); + Assertions.assertEquals(BackupJobState.FINISHED, job.getState()); } catch (Throwable e) { e.printStackTrace(); - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } finally { // Clean up: re-register the second table if it was removed if (db.getTableNullable(table2Name) == null && table2 != null) { @@ -647,11 +647,11 @@ public void testSerialization() throws IOException, AnalysisException { BackupJob job2 = BackupJob.read(in); - Assert.assertEquals(job.getJobId(), job2.getJobId()); - Assert.assertEquals(job.getDbId(), job2.getDbId()); - Assert.assertEquals(job.getCreateTime(), job2.getCreateTime()); - Assert.assertEquals(job.getType(), job2.getType()); - Assert.assertEquals(job.getCommitSeq(), job2.getCommitSeq()); + Assertions.assertEquals(job.getJobId(), job2.getJobId()); + Assertions.assertEquals(job.getDbId(), job2.getDbId()); + Assertions.assertEquals(job.getCreateTime(), job2.getCreateTime()); + Assertions.assertEquals(job.getType(), job2.getType()); + Assertions.assertEquals(job.getCommitSeq(), job2.getCommitSeq()); // 3. delete files in.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/PathMakerTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/PathMakerTest.java index de9ff4f0b3f26a..07f0e51fe5e69d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/PathMakerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/PathMakerTest.java @@ -17,7 +17,7 @@ package org.apache.doris.backup; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class PathMakerTest { diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/RepositoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/RepositoryTest.java index 109c9816b981a4..83c24ff34f9e47 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/RepositoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/RepositoryTest.java @@ -38,11 +38,11 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -83,7 +83,7 @@ public class RepositoryTest { private final StorageAdapter testProps = StorageAdapter.ofBroker("broker", Maps.newHashMap()); - @Before + @BeforeEach public void setUp() throws Exception { List files = Lists.newArrayList(); files.add("1.dat"); @@ -112,7 +112,7 @@ public void setUp() throws Exception { FeConstants.runningUnitTest = true; } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -129,12 +129,12 @@ public void tearDown() { public void testGet() { repo = new Repository(10000, "repo", false, location, testProps); - Assert.assertEquals(repoId, repo.getId()); - Assert.assertEquals(name, repo.getName()); - Assert.assertEquals(false, repo.isReadOnly()); - Assert.assertEquals(location, repo.getLocation()); - Assert.assertEquals(null, repo.getErrorMsg()); - Assert.assertTrue(System.currentTimeMillis() - repo.getCreateTime() < 1000); + Assertions.assertEquals(repoId, repo.getId()); + Assertions.assertEquals(name, repo.getName()); + Assertions.assertEquals(false, repo.isReadOnly()); + Assertions.assertEquals(location, repo.getLocation()); + Assertions.assertEquals(null, repo.getErrorMsg()); + Assertions.assertTrue(System.currentTimeMillis() - repo.getCreateTime() < 1000); } @Test @@ -144,7 +144,7 @@ public void testInit() throws UserException { // initRepository() short-circuits with OK when FeConstants.runningUnitTest == true Status st = repo.initRepository(); System.out.println(st); - Assert.assertTrue(st.ok()); + Assertions.assertTrue(st.ok()); } @Test @@ -161,22 +161,22 @@ public void testassemnblePath() throws MalformedURLException, URISyntaxException // "location/__palo_repository_repo_name/__ss_my_sp1/__info_2018-01-01-08-00-00" String expected = location + "/" + Repository.PREFIX_REPO + name + "/" + Repository.PREFIX_SNAPSHOT_DIR + label + "/" + Repository.PREFIX_JOB_INFO + createTime2; - Assert.assertEquals(expected, repo.assembleJobInfoFilePath(label, creastTs)); + Assertions.assertEquals(expected, repo.assembleJobInfoFilePath(label, creastTs)); // meta info expected = location + "/" + Repository.PREFIX_REPO + name + "/" + Repository.PREFIX_SNAPSHOT_DIR + label + "/" + Repository.FILE_META_INFO; - Assert.assertEquals(expected, repo.assembleMetaInfoFilePath(label)); + Assertions.assertEquals(expected, repo.assembleMetaInfoFilePath(label)); // snapshot path // /location/__palo_repository_repo_name/__ss_my_ss1/__ss_content/__db_10001/__tbl_10020/__part_10031/__idx_10032/__10023/__3481721 expected = location + "/" + Repository.PREFIX_REPO + name + "/" + Repository.PREFIX_SNAPSHOT_DIR + label + "/" + "__ss_content/__db_1/__tbl_2/__part_3/__idx_4/__5/__7"; - Assert.assertEquals(expected, repo.assembleRemoteSnapshotPath(label, info)); + Assertions.assertEquals(expected, repo.assembleRemoteSnapshotPath(label, info)); String rootTabletPath = "/__db_10000/__tbl_10001/__part_10002/_idx_10001/__10003"; String path = repo.getRepoPath(label, rootTabletPath); - Assert.assertEquals("bos://backup-cmy/__palo_repository_repo/__ss_label/__ss_content/__db_10000/__tbl_10001/__part_10002/_idx_10001/__10003", + Assertions.assertEquals("bos://backup-cmy/__palo_repository_repo/__ss_label/__ss_content/__db_10000/__tbl_10001/__part_10002/_idx_10001/__10003", path); } @@ -184,8 +184,8 @@ public void testassemnblePath() throws MalformedURLException, URISyntaxException public void testPing() { repo = new Repository(10000, "repo", false, location, testProps); // ping() short-circuits with true when FeConstants.runningUnitTest == true - Assert.assertTrue(repo.ping()); - Assert.assertTrue(repo.getErrorMsg() == null); + Assertions.assertTrue(repo.ping()); + Assertions.assertTrue(repo.getErrorMsg() == null); } @Test @@ -223,9 +223,9 @@ public void close() { repo = new Repository(10000, "repo", false, location, testProps); List snapshotNames = Lists.newArrayList(); Status st = repo.listSnapshots(snapshotNames); - Assert.assertTrue(st.ok()); - Assert.assertEquals(1, snapshotNames.size()); - Assert.assertEquals("a", snapshotNames.get(0)); + Assertions.assertTrue(st.ok()); + Assertions.assertEquals(1, snapshotNames.size()); + Assertions.assertEquals("a", snapshotNames.get(0)); } /** @@ -278,12 +278,12 @@ public void close() { repo = new Repository(10000, "repo", false, location, testProps); List snapshotNames = Lists.newArrayList(); Status st = repo.listSnapshots(snapshotNames); - Assert.assertTrue(st.ok()); - Assert.assertEquals(2, snapshotNames.size()); - Assert.assertTrue(snapshotNames.contains("snap1")); - Assert.assertTrue(snapshotNames.contains("snap2")); + Assertions.assertTrue(st.ok()); + Assertions.assertEquals(2, snapshotNames.size()); + Assertions.assertTrue(snapshotNames.contains("snap1")); + Assertions.assertTrue(snapshotNames.contains("snap2")); // "content" must NOT appear — it is a nested directory, not a snapshot - Assert.assertFalse(snapshotNames.contains("content")); + Assertions.assertFalse(snapshotNames.contains("content")); } @Test @@ -300,12 +300,12 @@ public void testUpload() throws IOException { out.print("a"); } catch (FileNotFoundException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } try { String remoteFilePath = location + "/remote_file"; Status st = repo.upload(localFilePath, remoteFilePath); - Assert.assertTrue(st.ok()); + Assertions.assertTrue(st.ok()); } finally { File file = new File(localFilePath); file.delete(); @@ -321,7 +321,7 @@ public void testDownload() throws Exception { out.print("a"); } catch (FileNotFoundException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // The remote file has an md5 checksum suffix matching content "a" @@ -367,7 +367,7 @@ public void seek(long newPos) throws IOException { repo = new Repository(10000, "repo", false, location, testProps); String remoteFilePath = location + "/remote_file"; Status st = repo.download(remoteFilePath, localFilePath); - Assert.assertTrue(st.ok()); + Assertions.assertTrue(st.ok()); } finally { localFile.delete(); } @@ -419,15 +419,15 @@ public void close() { String timestamp = ""; try { List> infos = repo.getSnapshotInfos(snapshotName, timestamp); - Assert.assertEquals(2, infos.size()); + Assertions.assertEquals(2, infos.size()); } catch (AnalysisException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } - @Ignore("wait support") + @Disabled("wait support") @Test public void testPersist() throws UserException { Map properties = Maps.newHashMap(); @@ -447,14 +447,14 @@ public void testPersist() throws UserException { Repository newRepo = Repository.read(in); in.close(); - Assert.assertEquals(repo.getName(), newRepo.getName()); - Assert.assertEquals(repo.getId(), newRepo.getId()); - Assert.assertEquals(repo.getLocation(), newRepo.getLocation()); + Assertions.assertEquals(repo.getName(), newRepo.getName()); + Assertions.assertEquals(repo.getId(), newRepo.getId()); + Assertions.assertEquals(repo.getLocation(), newRepo.getLocation()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } finally { file.delete(); } @@ -466,16 +466,16 @@ public void testPathNormalize() { String newLoc = "bos://cmy_bucket/bos_repo/"; repo = new Repository(10000, "repo", false, newLoc, testProps); String path = repo.getRepoPath("label1", "/_ss_my_ss/_ss_content/__db_10000/"); - Assert.assertEquals("bos://cmy_bucket/bos_repo/__palo_repository_repo/__ss_label1/__ss_content/_ss_my_ss/_ss_content/__db_10000/", path); + Assertions.assertEquals("bos://cmy_bucket/bos_repo/__palo_repository_repo/__ss_label1/__ss_content/_ss_my_ss/_ss_content/__db_10000/", path); path = repo.getRepoPath("label1", "/_ss_my_ss/_ss_content///__db_10000"); - Assert.assertEquals("bos://cmy_bucket/bos_repo/__palo_repository_repo/__ss_label1/__ss_content/_ss_my_ss/_ss_content/__db_10000", path); + Assertions.assertEquals("bos://cmy_bucket/bos_repo/__palo_repository_repo/__ss_label1/__ss_content/_ss_my_ss/_ss_content/__db_10000", path); newLoc = "hdfs://path/to/repo"; repo = new Repository(10000, "repo", false, newLoc, testProps); SnapshotInfo snapshotInfo = new SnapshotInfo(1, 2, 3, 4, 5, 6, 7, "/path", Lists.newArrayList()); path = repo.getRepoTabletPathBySnapshotInfo("label1", snapshotInfo); - Assert.assertEquals("hdfs://path/to/repo/__palo_repository_repo/__ss_label1/__ss_content/__db_1/__tbl_2/__part_3/__idx_4/__5", path); + Assertions.assertEquals("hdfs://path/to/repo/__palo_repository_repo/__ss_label1/__ss_content/__db_1/__tbl_2/__part_3/__idx_4/__5", path); } /** @@ -505,10 +505,10 @@ public void testGsonPostProcessLegacyBrokerFormat() { // The migration must produce a non-null FileSystemDescriptor. FileSystemDescriptor fd = deserialized.getFileSystemDescriptor(); - Assert.assertNotNull("fileSystemDescriptor must be migrated from legacy 'fs' field", fd); + Assertions.assertNotNull(fd, "fileSystemDescriptor must be migrated from legacy 'fs' field"); // Broker fallback is expected: props are empty so no primary storage type matches. - Assert.assertEquals(FsStorageType.BROKER, fd.getStorageType()); - Assert.assertEquals("broker", fd.getName()); + Assertions.assertEquals(FsStorageType.BROKER, fd.getStorageType()); + Assertions.assertEquals("broker", fd.getName()); } /** @@ -531,8 +531,8 @@ public void testGsonPostProcessLegacyHdfsFormat() { Repository deserialized = GsonUtils.GSON.fromJson(legacyJson, Repository.class); FileSystemDescriptor fd = deserialized.getFileSystemDescriptor(); - Assert.assertNotNull("fileSystemDescriptor must be migrated from legacy HDFS 'fs' field", fd); - Assert.assertEquals(FsStorageType.HDFS, fd.getStorageType()); + Assertions.assertNotNull(fd, "fileSystemDescriptor must be migrated from legacy HDFS 'fs' field"); + Assertions.assertEquals(FsStorageType.HDFS, fd.getStorageType()); } /** @@ -581,11 +581,8 @@ public void close() { List snapshotNames = Lists.newArrayList(); repo.listSnapshots(snapshotNames); // triggers acquireSpiFs() → getBroker(name, host) - Assert.assertNotNull( - "getBroker() must have been called during listSnapshots()", capturedHost.get()); - Assert.assertEquals( - "acquireSpiFs() must pass FrontendOptions.getLocalHostAddress() to getBroker()", - "127.0.0.1", capturedHost.get()); + Assertions.assertNotNull(capturedHost.get(), "getBroker() must have been called during listSnapshots()"); + Assertions.assertEquals("127.0.0.1", capturedHost.get(), "acquireSpiFs() must pass FrontendOptions.getLocalHostAddress() to getBroker()"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreFileMappingTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreFileMappingTest.java index 85de627fa447b4..c27385b25e608e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreFileMappingTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreFileMappingTest.java @@ -19,9 +19,9 @@ import org.apache.doris.backup.RestoreFileMapping.IdChain; -import junit.framework.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class RestoreFileMappingTest { @@ -29,7 +29,7 @@ public class RestoreFileMappingTest { private IdChain src; private IdChain dest; - @Before + @BeforeEach public void setUp() { src = new IdChain(10005L, 10006L, 10005L, 10007L, 10008L, -1L); dest = new IdChain(10004L, 10003L, 10004L, 10007L, -1L, -1L); @@ -39,21 +39,21 @@ public void setUp() { @Test public void test() { IdChain key = new IdChain(10005L, 10006L, 10005L, 10007L, 10008L, -1L); - Assert.assertEquals(key, src); - Assert.assertEquals(src, key); + Assertions.assertEquals(key, src); + Assertions.assertEquals(src, key); IdChain val = fileMapping.get(key); - Assert.assertNotNull(val); - Assert.assertEquals(dest, val); + Assertions.assertNotNull(val); + Assertions.assertEquals(dest, val); Long l1 = new Long(10005L); Long l2 = new Long(10005L); - Assert.assertFalse(l1 == l2); - Assert.assertEquals(l1, l2); + Assertions.assertFalse(l1 == l2); + Assertions.assertEquals(l1, l2); Long l3 = new Long(1L); Long l4 = new Long(1L); - Assert.assertFalse(l3 == l4); - Assert.assertEquals(l3, l4); + Assertions.assertFalse(l3 == l4); + Assertions.assertEquals(l3, l4); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreJobTest.java index 40a6f72b2db2c2..00d49f6489b464 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/backup/RestoreJobTest.java @@ -47,10 +47,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -124,7 +124,7 @@ public Repository getRepo(long repoId) { @SuppressWarnings("rawtypes") private MockedConstruction mockedMarkedCountDownLatch; - @Before + @BeforeEach public void setUp() throws Exception { db = CatalogMocker.mockDb(); backupHandler = new MockBackupHandler(env); @@ -219,7 +219,7 @@ public void setUp() throws Exception { backupMeta = new BackupMeta(tbls, resources); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -265,10 +265,10 @@ public void testSerialization() throws IOException, AnalysisException { RestoreJob job2 = RestoreJob.read(in); - Assert.assertEquals(job.getJobId(), job2.getJobId()); - Assert.assertEquals(job.getDbId(), job2.getDbId()); - Assert.assertEquals(job.getCreateTime(), job2.getCreateTime()); - Assert.assertEquals(job.getType(), job2.getType()); + Assertions.assertEquals(job.getJobId(), job2.getJobId()); + Assertions.assertEquals(job.getDbId(), job2.getDbId()); + Assertions.assertEquals(job.getCreateTime(), job2.getCreateTime()); + Assertions.assertEquals(job.getType(), job2.getType()); // 3. delete files in.close(); @@ -295,7 +295,7 @@ public void testResetPartitionVisibleAndNextVersionForRestore() throws Exception job.resetPartitionForRestore(localTbl, remoteTbl, partName, alloc); Partition localPart = remoteTbl.getPartition(partName); - Assert.assertEquals(localPart.getVisibleVersion(), visibleVersion); - Assert.assertEquals(localPart.getNextVersion(), visibleVersion + 1); + Assertions.assertEquals(localPart.getVisibleVersion(), visibleVersion); + Assertions.assertEquals(localPart.getNextVersion(), visibleVersion + 1); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/binlog/BinlogManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/binlog/BinlogManagerTest.java index 0e0b0d0ce231a4..8a357aa20596f9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/binlog/BinlogManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/binlog/BinlogManagerTest.java @@ -33,11 +33,11 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -73,14 +73,14 @@ public class BinlogManagerTest { private MockedConstruction mockedInternalCatalogConstruction; private MockedConstruction mockedDatabaseConstruction; - @BeforeClass + @BeforeAll public static void beforeClass() { Config.enable_feature_binlog = true; } - @Before + @BeforeEach public void setUp() { - Assert.assertTrue(tableNumPerDb < 100); + Assertions.assertTrue(tableNumPerDb < 100); frameWork = Maps.newHashMap(); for (int dbOff = 1; dbOff <= dbNum; ++dbOff) { long dbId = dbOff * dbBaseId; @@ -136,7 +136,7 @@ public void setUp() { .thenAnswer(inv -> EnvFactory.getInstance().createInternalCatalog()); } - @After + @AfterEach public void tearDown() { if (mockedBinlogConfigCacheConstruction != null) { mockedBinlogConfigCacheConstruction.close(); @@ -163,9 +163,9 @@ public void testBinlogConfigEquals() { BinlogConfig c2 = new BinlogConfig(true, 10L, 20L, 30L, BinlogConfig.BinlogFormat.ROW, true); BinlogConfig c3 = new BinlogConfig(true, 10L, 20L, 30L, BinlogConfig.BinlogFormat.ROW, false); - Assert.assertEquals(c1, c2); - Assert.assertNotEquals(c1, c3); - Assert.assertNotEquals(c1, "not_binlog"); + Assertions.assertEquals(c1, c2); + Assertions.assertNotEquals(c1, c3); + Assertions.assertNotEquals(c1, "not_binlog"); } @Test @@ -176,22 +176,22 @@ public void testBinlogConfigShowDDL() { StringBuilder sb = new StringBuilder(); rowCfg.appendToShowCreateTable(sb); String out = sb.toString(); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_ENABLE + "\" = \"true\"")); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_TTL_SECONDS + "\" = \"11\"")); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_MAX_BYTES + "\" = \"22\"")); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_MAX_HISTORY_NUMS + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_ENABLE + "\" = \"true\"")); + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_TTL_SECONDS + "\" = \"11\"")); + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_MAX_BYTES + "\" = \"22\"")); + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_MAX_HISTORY_NUMS + "\" = \"33\"")); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_FORMAT + "\" = \"ROW\"")); - Assert.assertTrue(out.contains(PropertyAnalyzer.PROPERTIES_BINLOG_NEED_HISTORICAL_VALUE)); + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_FORMAT + "\" = \"ROW\"")); + Assertions.assertTrue(out.contains(PropertyAnalyzer.PROPERTIES_BINLOG_NEED_HISTORICAL_VALUE)); BinlogConfig stmtCfg = new BinlogConfig(true, 11L, 22L, 33L, BinlogConfig.BinlogFormat.STATEMENT_AND_SNAPSHOT, true); sb = new StringBuilder(); stmtCfg.appendToShowCreateTable(sb); out = sb.toString(); - Assert.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_FORMAT + Assertions.assertTrue(out.contains("\"" + PropertyAnalyzer.PROPERTIES_BINLOG_FORMAT + "\" = \"STATEMENT_AND_SNAPSHOT\"")); - Assert.assertFalse(out.contains(PropertyAnalyzer.PROPERTIES_BINLOG_NEED_HISTORICAL_VALUE)); + Assertions.assertFalse(out.contains(PropertyAnalyzer.PROPERTIES_BINLOG_NEED_HISTORICAL_VALUE)); } @Test @@ -220,33 +220,33 @@ public void testGetBinlog() // get too old pair = manager.getBinlog(dbBaseId, tableBaseId, -99); - Assert.assertEquals(TStatusCode.BINLOG_TOO_OLD_COMMIT_SEQ, pair.first.getStatusCode()); - Assert.assertEquals(TBinlogType.DUMMY, pair.second.getType()); + Assertions.assertEquals(TStatusCode.BINLOG_TOO_OLD_COMMIT_SEQ, pair.first.getStatusCode()); + Assertions.assertEquals(TBinlogType.DUMMY, pair.second.getType()); // get odd commit seq in table level ok pair = manager.getBinlog(dbBaseId, tableBaseId, 5); - Assert.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); - Assert.assertEquals(5 + 2, pair.second.getCommitSeq()); + Assertions.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); + Assertions.assertEquals(5 + 2, pair.second.getCommitSeq()); // get even commit seq in table level ok pair = manager.getBinlog(dbBaseId, tableBaseId, 6); - Assert.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); - Assert.assertEquals(6 + 1, pair.second.getCommitSeq()); + Assertions.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); + Assertions.assertEquals(6 + 1, pair.second.getCommitSeq()); // get odd commit seq in db level ok pair = manager.getBinlog(dbBaseId, -1, 5); - Assert.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); - Assert.assertEquals(5 + 1, pair.second.getCommitSeq()); + Assertions.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); + Assertions.assertEquals(5 + 1, pair.second.getCommitSeq()); // get even commit seq in db level ok pair = manager.getBinlog(dbBaseId, -1, 6); - Assert.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); - Assert.assertEquals(6 + 1, pair.second.getCommitSeq()); + Assertions.assertEquals(TStatusCode.OK, pair.first.getStatusCode()); + Assertions.assertEquals(6 + 1, pair.second.getCommitSeq()); // get too new pair = manager.getBinlog(dbBaseId, tableBaseId, 999); - Assert.assertEquals(TStatusCode.BINLOG_TOO_NEW_COMMIT_SEQ, pair.first.getStatusCode()); - Assert.assertNull(pair.second); + Assertions.assertEquals(TStatusCode.BINLOG_TOO_NEW_COMMIT_SEQ, pair.first.getStatusCode()); + Assertions.assertNull(pair.second); } @Test @@ -291,15 +291,15 @@ public void testPersist() throws NoSuchMethodException, InvocationTargetExceptio // get origin & new dbbinlog's allbinlogs Map originDbBinlogMap = (Map) dbBinlogMapField.get(originManager); Map newDbBinlogMap = (Map) dbBinlogMapField.get(newManager); - Assert.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); + Assertions.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); for (long dbId : frameWork.keySet()) { List originBinlogList = Lists.newArrayList(); List newBinlogList = Lists.newArrayList(); originDbBinlogMap.get(dbId).getAllBinlogs(originBinlogList); newDbBinlogMap.get(dbId).getAllBinlogs(newBinlogList); - Assert.assertEquals(originBinlogList.size(), newBinlogList.size()); + Assertions.assertEquals(originBinlogList.size(), newBinlogList.size()); for (int i = 0; i < originBinlogList.size(); ++i) { - Assert.assertEquals(originBinlogList.get(i).getCommitSeq(), + Assertions.assertEquals(originBinlogList.get(i).getCommitSeq(), newBinlogList.get(i).getCommitSeq()); } } @@ -346,19 +346,19 @@ public void testReplayGcFromTableLevel() throws NoSuchMethodException, Invocatio // get origin & new dbbinlog's allbinlogs Map originDbBinlogMap = (Map) dbBinlogMapField.get(originManager); Map newDbBinlogMap = (Map) dbBinlogMapField.get(newManager); - Assert.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); + Assertions.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); for (long dbId : frameWork.keySet()) { List originBinlogList = Lists.newArrayList(); List newBinlogList = Lists.newArrayList(); originDbBinlogMap.get(dbId).getAllBinlogs(originBinlogList); newDbBinlogMap.get(dbId).getAllBinlogs(newBinlogList); - Assert.assertEquals(originBinlogList.size(), newBinlogList.size()); + Assertions.assertEquals(originBinlogList.size(), newBinlogList.size()); for (int i = 0; i < originBinlogList.size(); ++i) { TBinlog originBinlog = originBinlogList.get(i); TBinlog newBinlog = newBinlogList.get(i); - Assert.assertEquals(originBinlog.getCommitSeq(), newBinlog.getCommitSeq()); + Assertions.assertEquals(originBinlog.getCommitSeq(), newBinlog.getCommitSeq()); if (newBinlog.getType() != TBinlogType.DUMMY) { - Assert.assertTrue(newBinlog.getTimestamp() > timeNow - ttl); + Assertions.assertTrue(newBinlog.getTimestamp() > timeNow - ttl); } } } @@ -411,20 +411,20 @@ public void testReplayGcFromDbLevel() throws NoSuchMethodException, InvocationTa // get origin & new dbbinlog's allbinlogs Map originDbBinlogMap = (Map) dbBinlogMapField.get(originManager); Map newDbBinlogMap = (Map) dbBinlogMapField.get(newManager); - Assert.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); + Assertions.assertEquals(originDbBinlogMap.size(), newDbBinlogMap.size()); for (Map.Entry> dbEntry : frameWork.entrySet()) { long dbId = dbEntry.getKey(); List originBinlogList = Lists.newArrayList(); List newBinlogList = Lists.newArrayList(); originDbBinlogMap.get(dbId).getAllBinlogs(originBinlogList); newDbBinlogMap.get(dbId).getAllBinlogs(newBinlogList); - Assert.assertEquals(originBinlogList.size(), newBinlogList.size()); + Assertions.assertEquals(originBinlogList.size(), newBinlogList.size()); for (int i = 0; i < originBinlogList.size(); ++i) { TBinlog originBinlog = originBinlogList.get(i); TBinlog newBinlog = newBinlogList.get(i); - Assert.assertEquals(originBinlog.getCommitSeq(), newBinlog.getCommitSeq()); + Assertions.assertEquals(originBinlog.getCommitSeq(), newBinlog.getCommitSeq()); if (newBinlog.getType() != TBinlogType.DUMMY) { - Assert.assertTrue(newBinlog.getCommitSeq() > timeNow - ttl); + Assertions.assertTrue(newBinlog.getCommitSeq() > timeNow - ttl); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/binlog/DbBinlogTest.java b/fe/fe-core/src/test/java/org/apache/doris/binlog/DbBinlogTest.java index 08c831b1e2c34f..ff08b91b2d3c90 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/binlog/DbBinlogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/binlog/DbBinlogTest.java @@ -22,10 +22,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -46,12 +46,12 @@ public class DbBinlogTest { private int expiredBinlogNum = 3; private long baseNum = 30000L; - @Before + @BeforeEach public void setUp() { // check args valid - Assert.assertTrue(totalBinlogNum > 0); - Assert.assertTrue(gcTableNum <= tableNum); - Assert.assertTrue(expiredBinlogNum <= totalBinlogNum); + Assertions.assertTrue(totalBinlogNum > 0); + Assertions.assertTrue(gcTableNum <= tableNum); + Assertions.assertTrue(expiredBinlogNum <= totalBinlogNum); // gen tableIds tableIds = Lists.newArrayList(); @@ -64,7 +64,7 @@ public void setUp() { .thenAnswer(invocation -> (long) invocation.getArgument(0)); } - @After + @AfterEach public void tearDown() { if (mockedBinlogUtils != null) { mockedBinlogUtils.close(); @@ -120,9 +120,9 @@ public void testTableTtlGcCommonCase() { // check binlog status for (TBinlog binlog : testBinlogs) { if (binlog.getTableIds().get(0) <= baseTableId + gcTableNum) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } @@ -135,18 +135,18 @@ public void testTableTtlGcCommonCase() { } long belong = binlog.getBelong(); if (belong < 0) { - Assert.assertEquals(expiredCommitSeq, binlog.getCommitSeq()); + Assertions.assertEquals(expiredCommitSeq, binlog.getCommitSeq()); } else if (belong <= maxGcTableId) { int offset = (int) (belong - baseTableId); - Assert.assertEquals((long) tableLastCommitInfo[offset], binlog.getCommitSeq()); + Assertions.assertEquals((long) tableLastCommitInfo[offset], binlog.getCommitSeq()); } else { - Assert.assertEquals(-1, binlog.getCommitSeq()); + Assertions.assertEquals(-1, binlog.getCommitSeq()); } } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(expiredCommitSeq, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(expiredCommitSeq, tombstone.getCommitSeq()); } @Test @@ -201,9 +201,9 @@ public void testTableTtlGcBinlogMultiRefCase() { long unGcTableId = baseTableId + tableNum - 1; for (TBinlog binlog : testBinlogs) { if (binlog.getTableIds().contains(unGcTableId)) { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } else { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } } } @@ -251,9 +251,9 @@ public void testTableCommitSeqGc() { // check binlog status for (TBinlog binlog : testBinlogs) { if (binlog.getTimestamp() <= expiredTime) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertTrue(binlog.getTableRef() != 0); + Assertions.assertTrue(binlog.getTableRef() != 0); } } } @@ -288,15 +288,15 @@ public void testAddBinlog() throws NoSuchFieldException, IllegalAccessException TreeSet allbinlogs = (TreeSet) allBinlogsField.get(dbBinlog); Map tableBinlogMap = (Map) tableBinlogMapField.get(dbBinlog); - Assert.assertTrue(allbinlogs.contains(binlog)); + Assertions.assertTrue(allbinlogs.contains(binlog)); switch (type) { case CREATE_TABLE: case DROP_TABLE: { - Assert.assertTrue(tableBinlogMap.isEmpty()); + Assertions.assertTrue(tableBinlogMap.isEmpty()); break; } default: { - Assert.assertTrue(tableBinlogMap.containsKey(baseTableId)); + Assertions.assertTrue(tableBinlogMap.containsKey(baseTableId)); break; } } @@ -351,20 +351,20 @@ public void testDbAndTableGcWithDisable() { long tableId = binlog.getTableIds().get(0); if (tableId <= maxGcTableId) { // For disabled tables, all binlogs should be cleared - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { // For enabled tables, only expired binlogs should be cleared if (binlog.getTimestamp() <= expiredTime) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(baseNum + totalBinlogNum - 1, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(baseNum + totalBinlogNum - 1, tombstone.getCommitSeq()); } @Test @@ -410,14 +410,14 @@ public void testDbAndTableGcWithEnable() { // check binlog status - only expired binlogs should be cleared for (TBinlog binlog : testBinlogs) { if (binlog.getTimestamp() <= expiredTime) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } // check tombstone - Assert.assertTrue(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(expiredTime, tombstone.getCommitSeq()); + Assertions.assertTrue(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(expiredTime, tombstone.getCommitSeq()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/binlog/TableBinlogTest.java b/fe/fe-core/src/test/java/org/apache/doris/binlog/TableBinlogTest.java index 7546d6c952dd94..3a8b8e927bed6e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/binlog/TableBinlogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/binlog/TableBinlogTest.java @@ -21,9 +21,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -38,10 +38,10 @@ public class TableBinlogTest { private int expiredBinlogNum = 3; private long baseNum = 30000L; - @Before + @BeforeEach public void setUp() { // check args valid - Assert.assertTrue(expiredBinlogNum <= totalBinlogNum); + Assertions.assertTrue(expiredBinlogNum <= totalBinlogNum); } @Test @@ -80,19 +80,19 @@ public void testTtlGc() { // check binlog status for (TBinlog binlog : testBinlogs) { if (binlog.getTimestamp() <= expiredTime) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(expiredTime, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(expiredTime, tombstone.getCommitSeq()); // check dummy TBinlog dummy = tableBinlog.getDummyBinlog(); - Assert.assertEquals(expiredTime, dummy.getCommitSeq()); + Assertions.assertEquals(expiredTime, dummy.getCommitSeq()); } } @@ -126,19 +126,19 @@ public void testCommitSeqGc() { // check binlog status for (TBinlog binlog : testBinlogs) { if (binlog.getTimestamp() <= expiredCommitSeq) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(expiredCommitSeq, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(expiredCommitSeq, tombstone.getCommitSeq()); // check dummy TBinlog dummy = tableBinlog.getDummyBinlog(); - Assert.assertEquals(expiredCommitSeq, dummy.getCommitSeq()); + Assertions.assertEquals(expiredCommitSeq, dummy.getCommitSeq()); } @Test @@ -182,16 +182,16 @@ public void testTableGcBinlogWithDisable() { // check binlog status - all binlogs should be cleared when table binlog is disabled for (TBinlog binlog : testBinlogs) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(baseNum + totalBinlogNum - 1, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(baseNum + totalBinlogNum - 1, tombstone.getCommitSeq()); // check dummy - should have the last commitSeq TBinlog dummy = tableBinlog.getDummyBinlog(); - Assert.assertEquals(baseNum + totalBinlogNum - 1, dummy.getCommitSeq()); + Assertions.assertEquals(baseNum + totalBinlogNum - 1, dummy.getCommitSeq()); } } @@ -237,19 +237,19 @@ public void testTableGcBinlogWithEnable() { // check binlog status - only expired binlogs should be cleared for (TBinlog binlog : testBinlogs) { if (binlog.getTimestamp() <= expiredTime) { - Assert.assertEquals(0, binlog.getTableRef()); + Assertions.assertEquals(0, binlog.getTableRef()); } else { - Assert.assertEquals(1, binlog.getTableRef()); + Assertions.assertEquals(1, binlog.getTableRef()); } } // check tombstone - Assert.assertFalse(tombstone.isDbBinlogTomstone()); - Assert.assertEquals(expiredTime, tombstone.getCommitSeq()); + Assertions.assertFalse(tombstone.isDbBinlogTomstone()); + Assertions.assertEquals(expiredTime, tombstone.getCommitSeq()); // check dummy - should have the expiredTime as commitSeq TBinlog dummy = tableBinlog.getDummyBinlog(); - Assert.assertEquals(expiredTime, dummy.getCommitSeq()); + Assertions.assertEquals(expiredTime, dummy.getCommitSeq()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/blockrule/SqlBlockRuleMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/blockrule/SqlBlockRuleMgrTest.java index a87fcf1a84bdda..cb66b2a52f33ce 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/blockrule/SqlBlockRuleMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/blockrule/SqlBlockRuleMgrTest.java @@ -21,16 +21,16 @@ import org.apache.doris.metric.MetricRepo; import org.apache.doris.persist.gson.GsonUtils; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class SqlBlockRuleMgrTest { - @BeforeClass + @BeforeAll public static void setUp() { MetricRepo.init(); } @@ -38,14 +38,14 @@ public static void setUp() { @Test public void testToInfoString() { SqlBlockRuleMgr mgr = new SqlBlockRuleMgr(); - Assert.assertTrue(mgr.getNameToSqlBlockRuleMap() instanceof ConcurrentHashMap); + Assertions.assertTrue(mgr.getNameToSqlBlockRuleMap() instanceof ConcurrentHashMap); SqlBlockRule rule = new SqlBlockRule(); mgr.getNameToSqlBlockRuleMap().put("r1", rule); String mgrJson = GsonUtils.GSON.toJson(mgr); SqlBlockRuleMgr mgrNew = GsonUtils.GSON.fromJson(mgrJson, SqlBlockRuleMgr.class); Map nameToSqlBlockRuleMap = mgrNew.getNameToSqlBlockRuleMap(); - Assert.assertTrue(nameToSqlBlockRuleMap instanceof ConcurrentHashMap); - Assert.assertTrue(nameToSqlBlockRuleMap.containsKey("r1")); + Assertions.assertTrue(nameToSqlBlockRuleMap instanceof ConcurrentHashMap); + Assertions.assertTrue(nameToSqlBlockRuleMap.containsKey("r1")); } @Test @@ -54,7 +54,7 @@ public void testRuleSerializeRequirePartitionFilter() { true, true, true); String json = GsonUtils.GSON.toJson(rule); SqlBlockRule roundTrip = GsonUtils.GSON.fromJson(json, SqlBlockRule.class); - Assert.assertTrue(roundTrip.getRequirePartitionFilter()); + Assertions.assertTrue(roundTrip.getRequirePartitionFilter()); } @Test @@ -62,22 +62,22 @@ public void testShowInfoUseNumericBooleanForRequirePartitionFilter() { SqlBlockRule enabledRule = new SqlBlockRule("r1", "NULL", "NULL", 0L, 0L, 0L, true, true, true); List enabledShowInfo = enabledRule.getShowInfo(); - Assert.assertEquals(9, enabledShowInfo.size()); - Assert.assertEquals("1", enabledShowInfo.get(8)); + Assertions.assertEquals(9, enabledShowInfo.size()); + Assertions.assertEquals("1", enabledShowInfo.get(8)); SqlBlockRule disabledRule = new SqlBlockRule("r2", "NULL", "NULL", 0L, 0L, 0L, false, true, true); List disabledShowInfo = disabledRule.getShowInfo(); - Assert.assertEquals("0", disabledShowInfo.get(8)); + Assertions.assertEquals("0", disabledShowInfo.get(8)); } @Test public void testConstructorPlaceRequirePartitionFilterBeforeGlobal() { SqlBlockRule rule = new SqlBlockRule("r1", "NULL", "NULL", 0L, 0L, 0L, true, false, true); - Assert.assertTrue(rule.getRequirePartitionFilter()); - Assert.assertFalse(rule.getGlobal()); - Assert.assertTrue(rule.getEnable()); + Assertions.assertTrue(rule.getRequirePartitionFilter()); + Assertions.assertFalse(rule.getGlobal()); + Assertions.assertTrue(rule.getEnable()); } @Test @@ -86,9 +86,9 @@ public void testRequirePartitionFilterBlocksPartitionedScanWithoutFilter() { SqlBlockRule rule = new SqlBlockRule("r1", "NULL", "NULL", 0L, 0L, 0L, true, true, true); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> mgr.checkLimitations(rule, 2L, 3L, 4L, true, false)); - Assert.assertTrue(exception.getMessage().contains("sql hits sql block rule: r1, missing partition filter")); + Assertions.assertTrue(exception.getMessage().contains("sql hits sql block rule: r1, missing partition filter")); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/AIResourceTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/AIResourceTest.java index 467a0953926e4b..70d37bf5ebf740 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/AIResourceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/AIResourceTest.java @@ -33,9 +33,9 @@ import com.google.common.collect.ImmutableMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -62,7 +62,7 @@ public class AIResourceTest { private String retryDelaySecond; private Map aiProperties; - @Before + @BeforeEach public void setUp() { name = "openai-gpt"; type = "ai"; @@ -102,20 +102,20 @@ public void testFromCommand() throws UserException { createResourceCommand.getInfo().validate(); AIResource aiResource = (AIResource) Resource.fromCommand(createResourceCommand); - Assert.assertEquals(name, aiResource.getName()); - Assert.assertEquals(type, aiResource.getType().name().toLowerCase()); - Assert.assertEquals(endpoint, aiResource.getProperty(AIProperties.ENDPOINT)); - Assert.assertEquals(providerType.toUpperCase(), aiResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals(apiKey, aiResource.getProperty(AIProperties.API_KEY)); - Assert.assertEquals(modelName, aiResource.getProperty(AIProperties.MODEL_NAME)); - - Assert.assertEquals(AIProperties.DEFAULT_TEMPERATURE, + Assertions.assertEquals(name, aiResource.getName()); + Assertions.assertEquals(type, aiResource.getType().name().toLowerCase()); + Assertions.assertEquals(endpoint, aiResource.getProperty(AIProperties.ENDPOINT)); + Assertions.assertEquals(providerType.toUpperCase(), aiResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals(apiKey, aiResource.getProperty(AIProperties.API_KEY)); + Assertions.assertEquals(modelName, aiResource.getProperty(AIProperties.MODEL_NAME)); + + Assertions.assertEquals(AIProperties.DEFAULT_TEMPERATURE, aiResource.getProperty(AIProperties.TEMPERATURE)); - Assert.assertEquals(AIProperties.DEFAULT_MAX_TOKEN, + Assertions.assertEquals(AIProperties.DEFAULT_MAX_TOKEN, aiResource.getProperty(AIProperties.MAX_TOKEN)); - Assert.assertEquals(AIProperties.DEFAULT_MAX_RETRIES, + Assertions.assertEquals(AIProperties.DEFAULT_MAX_RETRIES, aiResource.getProperty(AIProperties.MAX_RETRIES)); - Assert.assertEquals(AIProperties.DEFAULT_RETRY_DELAY_SECOND, + Assertions.assertEquals(AIProperties.DEFAULT_RETRY_DELAY_SECOND, aiResource.getProperty(AIProperties.RETRY_DELAY_SECOND)); // with no default settings @@ -129,16 +129,16 @@ public void testFromCommand() throws UserException { createResourceCommand.getInfo().validate(); aiResource = (AIResource) Resource.fromCommand(createResourceCommand); - Assert.assertEquals(name, aiResource.getName()); - Assert.assertEquals(type, aiResource.getType().name().toLowerCase()); - Assert.assertEquals(endpoint, aiResource.getProperty(AIProperties.ENDPOINT)); - Assert.assertEquals(providerType.toUpperCase(), aiResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals(apiKey, aiResource.getProperty(AIProperties.API_KEY)); - Assert.assertEquals(modelName, aiResource.getProperty(AIProperties.MODEL_NAME)); - Assert.assertEquals(temperature, aiResource.getProperty(AIProperties.TEMPERATURE)); - Assert.assertEquals(maxToken, aiResource.getProperty(AIProperties.MAX_TOKEN)); - Assert.assertEquals(maxRetries, aiResource.getProperty(AIProperties.MAX_RETRIES)); - Assert.assertEquals(retryDelaySecond, aiResource.getProperty(AIProperties.RETRY_DELAY_SECOND)); + Assertions.assertEquals(name, aiResource.getName()); + Assertions.assertEquals(type, aiResource.getType().name().toLowerCase()); + Assertions.assertEquals(endpoint, aiResource.getProperty(AIProperties.ENDPOINT)); + Assertions.assertEquals(providerType.toUpperCase(), aiResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals(apiKey, aiResource.getProperty(AIProperties.API_KEY)); + Assertions.assertEquals(modelName, aiResource.getProperty(AIProperties.MODEL_NAME)); + Assertions.assertEquals(temperature, aiResource.getProperty(AIProperties.TEMPERATURE)); + Assertions.assertEquals(maxToken, aiResource.getProperty(AIProperties.MAX_TOKEN)); + Assertions.assertEquals(maxRetries, aiResource.getProperty(AIProperties.MAX_RETRIES)); + Assertions.assertEquals(retryDelaySecond, aiResource.getProperty(AIProperties.RETRY_DELAY_SECOND)); } } @@ -165,57 +165,61 @@ public void testAnthropic() throws UserException { createResourceCommand.getInfo().validate(); AIResource aiResource = (AIResource) Resource.fromCommand(createResourceCommand); - Assert.assertEquals("anthropic-claude", aiResource.getName()); - Assert.assertEquals("ANTHROPIC", aiResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals("https://api.anthropic.com/v1/messages", + Assertions.assertEquals("anthropic-claude", aiResource.getName()); + Assertions.assertEquals("ANTHROPIC", aiResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals("https://api.anthropic.com/v1/messages", aiResource.getProperty(AIProperties.ENDPOINT)); - Assert.assertEquals("claude-opus-4-20250514", aiResource.getProperty(AIProperties.MODEL_NAME)); - Assert.assertEquals("2023-06-01", aiResource.getProperty(AIProperties.ANTHROPIC_VERSION)); + Assertions.assertEquals("claude-opus-4-20250514", aiResource.getProperty(AIProperties.MODEL_NAME)); + Assertions.assertEquals("2023-06-01", aiResource.getProperty(AIProperties.ANTHROPIC_VERSION)); } } - @Test(expected = DdlException.class) + @Test public void testAbnormalResource() throws UserException { - try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { - Env env = Mockito.mock(Env.class); - EditLog editLog = Mockito.mock(EditLog.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - Mockito.when(env.getEditLog()).thenReturn(editLog); - Mockito.when(env.getAccessManager()).thenReturn(accessManager); - Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) - .thenReturn(true); - - aiProperties.remove("ai.endpoint"); - CreateResourceCommand createResourceCommand = new CreateResourceCommand( - new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(aiProperties))); - createResourceCommand.getInfo().validate(); - - Resource.fromCommand(createResourceCommand); - } + Assertions.assertThrows(DdlException.class, () -> { + try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { + Env env = Mockito.mock(Env.class); + EditLog editLog = Mockito.mock(EditLog.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + mockedEnv.when(Env::getCurrentEnv).thenReturn(env); + Mockito.when(env.getEditLog()).thenReturn(editLog); + Mockito.when(env.getAccessManager()).thenReturn(accessManager); + Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) + .thenReturn(true); + + aiProperties.remove("ai.endpoint"); + CreateResourceCommand createResourceCommand = new CreateResourceCommand( + new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(aiProperties))); + createResourceCommand.getInfo().validate(); + + Resource.fromCommand(createResourceCommand); + } + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidProvider() throws UserException { - try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { - Env env = Mockito.mock(Env.class); - EditLog editLog = Mockito.mock(EditLog.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - Mockito.when(env.getEditLog()).thenReturn(editLog); - Mockito.when(env.getAccessManager()).thenReturn(accessManager); - Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) - .thenReturn(true); - - // Invalid provider type - aiProperties.put("ai.provider_type", "invalid_provider"); - - CreateResourceCommand createResourceCommand = new CreateResourceCommand( - new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(aiProperties))); - createResourceCommand.getInfo().validate(); - - Resource.fromCommand(createResourceCommand); - } + Assertions.assertThrows(DdlException.class, () -> { + try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { + Env env = Mockito.mock(Env.class); + EditLog editLog = Mockito.mock(EditLog.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + mockedEnv.when(Env::getCurrentEnv).thenReturn(env); + Mockito.when(env.getEditLog()).thenReturn(editLog); + Mockito.when(env.getAccessManager()).thenReturn(accessManager); + Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) + .thenReturn(true); + + // Invalid provider type + aiProperties.put("ai.provider_type", "invalid_provider"); + + CreateResourceCommand createResourceCommand = new CreateResourceCommand( + new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(aiProperties))); + createResourceCommand.getInfo().validate(); + + Resource.fromCommand(createResourceCommand); + } + }); } @Test @@ -250,17 +254,17 @@ public void testSerialization() throws Exception { AIResource rAiResource1 = (AIResource) Resource.read(aiDis); AIResource rAiResource2 = (AIResource) Resource.read(aiDis); - Assert.assertEquals("ai_1", rAiResource1.getName()); - Assert.assertEquals("ai_2", rAiResource2.getName()); - - Assert.assertEquals(rAiResource2.getProperty(AIProperties.ENDPOINT), endpoint); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.PROVIDER_TYPE), providerType.toUpperCase()); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.API_KEY), apiKey); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.MODEL_NAME), modelName); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.TEMPERATURE), AIProperties.DEFAULT_TEMPERATURE); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.MAX_TOKEN), AIProperties.DEFAULT_MAX_TOKEN); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.MAX_RETRIES), AIProperties.DEFAULT_MAX_RETRIES); - Assert.assertEquals(rAiResource2.getProperty(AIProperties.RETRY_DELAY_SECOND), + Assertions.assertEquals("ai_1", rAiResource1.getName()); + Assertions.assertEquals("ai_2", rAiResource2.getName()); + + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.ENDPOINT), endpoint); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.PROVIDER_TYPE), providerType.toUpperCase()); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.API_KEY), apiKey); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.MODEL_NAME), modelName); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.TEMPERATURE), AIProperties.DEFAULT_TEMPERATURE); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.MAX_TOKEN), AIProperties.DEFAULT_MAX_TOKEN); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.MAX_RETRIES), AIProperties.DEFAULT_MAX_RETRIES); + Assertions.assertEquals(rAiResource2.getProperty(AIProperties.RETRY_DELAY_SECOND), AIProperties.DEFAULT_RETRY_DELAY_SECOND); // 3. delete @@ -286,8 +290,8 @@ public void testModifyProperties() throws Exception { modify.put("ai.temperature", "0.9"); aiResource.modifyProperties(modify); - Assert.assertEquals("new_api_key", aiResource.getProperty(AIProperties.API_KEY)); - Assert.assertEquals("0.9", aiResource.getProperty(AIProperties.TEMPERATURE)); + Assertions.assertEquals("new_api_key", aiResource.getProperty(AIProperties.API_KEY)); + Assertions.assertEquals("0.9", aiResource.getProperty(AIProperties.TEMPERATURE)); } @Test @@ -337,9 +341,9 @@ public void testDifferentProviders() throws DdlException { AIResource localResource = new AIResource("local-resource"); localResource.setProperties(ImmutableMap.copyOf(localProps)); - Assert.assertEquals("OPENAI", openaiResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals("GEMINI", geminiResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals("ANTHROPIC", anthropicResource.getProperty(AIProperties.PROVIDER_TYPE)); - Assert.assertEquals("LOCAL", localResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals("OPENAI", openaiResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals("GEMINI", geminiResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals("ANTHROPIC", anthropicResource.getProperty(AIProperties.PROVIDER_TYPE)); + Assertions.assertEquals("LOCAL", localResource.getProperty(AIProperties.PROVIDER_TYPE)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/BackendTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/BackendTest.java index a2f4b769ebd0a4..7a036063410692 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/BackendTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/BackendTest.java @@ -26,10 +26,10 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -57,7 +57,7 @@ public class BackendTest { private FakeEnv fakeEnv; private FakeEditLog fakeEditLog; - @Before + @BeforeEach public void setUp() { env = AccessTestUtil.fetchAdminCatalog(); @@ -72,7 +72,7 @@ public void setUp() { backend.updateOnce(bePort, httpPort, beRpcPort); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -84,24 +84,24 @@ public void tearDown() { @Test public void getMethodTest() { - Assert.assertEquals(backendId, backend.getId()); - Assert.assertEquals(host, backend.getHost()); - Assert.assertEquals(heartbeatPort, backend.getHeartbeatPort()); - Assert.assertEquals(bePort, backend.getBePort()); + Assertions.assertEquals(backendId, backend.getId()); + Assertions.assertEquals(host, backend.getHost()); + Assertions.assertEquals(heartbeatPort, backend.getHeartbeatPort()); + Assertions.assertEquals(bePort, backend.getBePort()); // set new port int newBePort = 31235; int newHttpPort = 31237; backend.updateOnce(newBePort, newHttpPort, beRpcPort); - Assert.assertEquals(newBePort, backend.getBePort()); + Assertions.assertEquals(newBePort, backend.getBePort()); // check alive - Assert.assertTrue(backend.isAlive()); + Assertions.assertTrue(backend.isAlive()); } @Test public void testLocationTagIsSafelyPublished() throws NoSuchFieldException { - Assert.assertTrue(Modifier.isVolatile(Backend.class.getDeclaredField("locationTag").getModifiers())); + Assertions.assertTrue(Modifier.isVolatile(Backend.class.getDeclaredField("locationTag").getModifiers())); } @Test @@ -118,17 +118,17 @@ public void diskInfoTest() { // first update backend.updateDisks(diskInfos); - Assert.assertEquals(disk1.getDiskTotalCapacity() + disk2.getDiskTotalCapacity(), + Assertions.assertEquals(disk1.getDiskTotalCapacity() + disk2.getDiskTotalCapacity(), backend.getTotalCapacityB()); - Assert.assertEquals(1, backend.getAvailableCapacityB()); + Assertions.assertEquals(1, backend.getAvailableCapacityB()); // second update diskInfos.remove(disk1.getRootPath()); backend.updateDisks(diskInfos); - Assert.assertEquals(disk2.getDiskTotalCapacity(), backend.getTotalCapacityB()); - Assert.assertEquals(disk2.getDiskAvailableCapacity() + 1, backend.getAvailableCapacityB()); - Assert.assertFalse(backend.hasSpecifiedStorageMedium(TStorageMedium.SSD)); - Assert.assertTrue(backend.hasSpecifiedStorageMedium(TStorageMedium.HDD)); + Assertions.assertEquals(disk2.getDiskTotalCapacity(), backend.getTotalCapacityB()); + Assertions.assertEquals(disk2.getDiskAvailableCapacity() + 1, backend.getAvailableCapacityB()); + Assertions.assertFalse(backend.hasSpecifiedStorageMedium(TStorageMedium.SSD)); + Assertions.assertTrue(backend.hasSpecifiedStorageMedium(TStorageMedium.HDD)); } @Test @@ -169,44 +169,44 @@ public void testSerialization() throws Exception { for (int count = 0; count < 200; ++count) { Backend backend = Backend.read(dis); list2.add(backend); - Assert.assertEquals(count, backend.getId()); - Assert.assertEquals("10.120.22.32" + count, backend.getHost()); + Assertions.assertEquals(count, backend.getId()); + Assertions.assertEquals("10.120.22.32" + count, backend.getHost()); } // check isAlive Backend backend100 = list2.get(100); - Assert.assertTrue(backend100.isAlive()); + Assertions.assertTrue(backend100.isAlive()); // check disksRef ImmutableMap backend100DiskRef = backend100.getDisks(); - Assert.assertEquals(2, backend100DiskRef.size()); - Assert.assertTrue(backend100DiskRef.containsKey("disk1")); - Assert.assertTrue(backend100DiskRef.containsKey("disk2")); + Assertions.assertEquals(2, backend100DiskRef.size()); + Assertions.assertTrue(backend100DiskRef.containsKey("disk1")); + Assertions.assertTrue(backend100DiskRef.containsKey("disk2")); DiskInfo backend100DiskInfo1 = backend100DiskRef.get("disk1"); - Assert.assertEquals("/disk1", backend100DiskInfo1.getRootPath()); + Assertions.assertEquals("/disk1", backend100DiskInfo1.getRootPath()); DiskInfo backend100DiskInfo2 = backend100DiskRef.get("disk2"); - Assert.assertEquals("/disk2", backend100DiskInfo2.getRootPath()); + Assertions.assertEquals("/disk2", backend100DiskInfo2.getRootPath()); // check backend status Backend.BackendStatus backend100BackendStatus = backend100.getBackendStatus(); - Assert.assertEquals(100, backend100BackendStatus.lastStreamLoadTime); + Assertions.assertEquals(100, backend100BackendStatus.lastStreamLoadTime); for (int count = 0; count < 200; count++) { - Assert.assertEquals(list1.get(count), list2.get(count)); + Assertions.assertEquals(list1.get(count), list2.get(count)); } - Assert.assertNotEquals(list1.get(1), list1.get(2)); - Assert.assertNotEquals(list1.get(1), this); - Assert.assertEquals(list1.get(1), list1.get(1)); + Assertions.assertNotEquals(list1.get(1), list1.get(2)); + Assertions.assertNotEquals(list1.get(1), this); + Assertions.assertEquals(list1.get(1), list1.get(1)); Backend back1 = new Backend(1, "a", 1); back1.updateOnce(1, 1, 1); Backend back2 = new Backend(2, "a", 1); back2.updateOnce(1, 1, 1); - Assert.assertNotEquals(back1, back2); + Assertions.assertNotEquals(back1, back2); back1 = new Backend(1, "a", 1); back1.updateOnce(1, 1, 1); back2 = new Backend(1, "b", 1); back2.updateOnce(1, 1, 1); - Assert.assertNotEquals(back1, back2); + Assertions.assertNotEquals(back1, back2); back1 = new Backend(1, "a", 1); back1.updateOnce(1, 1, 1); @@ -216,10 +216,10 @@ public void testSerialization() throws Exception { tagMap.put(Tag.TYPE_LOCATION, "l1"); tagMap.put("compute", "c1"); back2.setTagMap(tagMap); - Assert.assertNotEquals(back1, back2); + Assertions.assertNotEquals(back1, back2); - Assert.assertTrue(back1.toString().contains("tags: {location=default}")); - Assert.assertEquals("{\"compute\" : \"c1\", \"location\" : \"l1\"}", back2.getTagMapString()); + Assertions.assertTrue(back1.toString().contains("tags: {location=default}")); + Assertions.assertEquals("{\"compute\" : \"c1\", \"location\" : \"l1\"}", back2.getTagMapString()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableIndexTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableIndexTest.java index 5b78103f71e85c..017e84981f9cba 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableIndexTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableIndexTest.java @@ -22,8 +22,8 @@ import org.apache.doris.meta.MetaContext; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -41,16 +41,16 @@ public void testGroupId() { GroupId groupId1 = new GroupId(1000, 2000); GroupId groupId2 = new GroupId(1000, 2000); Map map = Maps.newHashMap(); - Assert.assertEquals(groupId1, groupId2); - Assert.assertTrue(groupId1.hashCode() == groupId2.hashCode()); + Assertions.assertEquals(groupId1, groupId2); + Assertions.assertTrue(groupId1.hashCode() == groupId2.hashCode()); map.put(groupId1, 1000L); - Assert.assertTrue(map.containsKey(groupId2)); + Assertions.assertTrue(map.containsKey(groupId2)); Set balancingGroups = new CopyOnWriteArraySet(); balancingGroups.add(groupId1); - Assert.assertTrue(balancingGroups.size() == 1); + Assertions.assertTrue(balancingGroups.size() == 1); balancingGroups.remove(groupId2); - Assert.assertTrue(balancingGroups.isEmpty()); + Assertions.assertTrue(balancingGroups.isEmpty()); } @Test @@ -73,7 +73,7 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(path)); ColocateTableIndex.GroupId rGroupId = ColocateTableIndex.GroupId.read(dis); - Assert.assertEquals(groupId, rGroupId); + Assertions.assertEquals(groupId, rGroupId); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableTest.java index ef96012d64ef5d..f03ffec9111fda 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColocateTableTest.java @@ -37,14 +37,12 @@ import com.google.common.collect.Multimap; import com.google.common.collect.Table; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterAll; +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.mockito.Mockito; import java.io.File; @@ -64,23 +62,20 @@ public class ColocateTableTest { private static String tableName2 = "t2"; private static String groupName = "group1"; - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { UtFrameUtils.createDorisCluster(runningDir); connectContext = UtFrameUtils.createDefaultCtx(); } - @AfterClass + @AfterAll public static void tearDown() { File file = new File(runningDir); file.delete(); } - @Before + @BeforeEach public void createDb() throws Exception { String createDbStmtStr = "create database " + dbName; NereidsParser nereidsParser = new NereidsParser(); @@ -92,7 +87,7 @@ public void createDb() throws Exception { Env.getCurrentEnv().setColocateTableIndex(new ColocateTableIndex()); } - @After + @AfterEach public void dropDb() throws Exception { String dropDbStmtStr = "drop database " + dbName; NereidsParser nereidsParser = new NereidsParser(); @@ -131,7 +126,7 @@ private static void alterColocateGroup(String sql) throws Exception { if (parsed instanceof AlterColocateGroupCommand) { ((AlterColocateGroupCommand) parsed).run(connectContext, stmtExecutor); } else { - Assert.fail("Expected AlterColocateGroupCommand, but parsed: " + parsed.getClass().getSimpleName()); + Assertions.fail("Expected AlterColocateGroupCommand, but parsed: " + parsed.getClass().getSimpleName()); } } @@ -180,29 +175,29 @@ public void testCreateOneTable() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrMetaException(fullDbName); long tableId = db.getTableOrMetaException(tableName1).getId(); - Assert.assertEquals(1, Deencapsulation.>getField(index, "group2Tables").size()); - Assert.assertEquals(1, index.getAllGroupIds().size()); - Assert.assertEquals(1, Deencapsulation.>getField(index, "table2Group").size()); - Assert.assertEquals(1, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); - Assert.assertEquals(1, Deencapsulation.>getField(index, "group2Schema").size()); - Assert.assertEquals(0, index.getUnstableGroupIds().size()); + Assertions.assertEquals(1, Deencapsulation.>getField(index, "group2Tables").size()); + Assertions.assertEquals(1, index.getAllGroupIds().size()); + Assertions.assertEquals(1, Deencapsulation.>getField(index, "table2Group").size()); + Assertions.assertEquals(1, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); + Assertions.assertEquals(1, Deencapsulation.>getField(index, "group2Schema").size()); + Assertions.assertEquals(0, index.getUnstableGroupIds().size()); - Assert.assertTrue(index.isColocateTable(tableId)); + Assertions.assertTrue(index.isColocateTable(tableId)); Long dbId = db.getId(); - Assert.assertEquals(dbId, index.getGroup(tableId).dbId); + Assertions.assertEquals(dbId, index.getGroup(tableId).dbId); GroupId groupId = index.getGroup(tableId); Map>> backendIds = index.getBackendsPerBucketSeq(groupId); - Assert.assertEquals(1, backendIds.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); + Assertions.assertEquals(1, backendIds.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); String fullGroupName = GroupId.getFullGroupName(dbId, groupName); - Assert.assertEquals(tableId, index.getTableIdByGroup(fullGroupName)); + Assertions.assertEquals(tableId, index.getTableIdByGroup(fullGroupName)); ColocateGroupSchema groupSchema = index.getGroupSchema(fullGroupName); - Assert.assertNotNull(groupSchema); - Assert.assertEquals(dbId, groupSchema.getGroupId().dbId); - Assert.assertEquals(1, groupSchema.getBucketsNum()); - Assert.assertEquals((short) 1, groupSchema.getReplicaAlloc().getTotalReplicaNum()); + Assertions.assertNotNull(groupSchema); + Assertions.assertEquals(dbId, groupSchema.getGroupId().dbId); + Assertions.assertEquals(1, groupSchema.getBucketsNum()); + Assertions.assertEquals((short) 1, groupSchema.getReplicaAlloc().getTotalReplicaNum()); } @Test @@ -223,7 +218,7 @@ public void testAlterColocateGroupReplicaAllocationLogsEditLog() throws Exceptio ColocateTableIndex index = Env.getCurrentColocateIndex(); Database db = Env.getCurrentInternalCatalog().getDbOrMetaException(fullDbName); String fullGroupName = GroupId.getFullGroupName(db.getId(), groupName); - Assert.assertEquals((short) 1, + Assertions.assertEquals((short) 1, index.getGroupSchema(fullGroupName).getReplicaAlloc().getTotalReplicaNum()); } finally { env.setEditLog(originalEditLog); @@ -287,42 +282,42 @@ public void testCreateTwoTableWithSameGroup() throws Exception { long firstTblId = db.getTableOrMetaException(tableName1).getId(); long secondTblId = db.getTableOrMetaException(tableName2).getId(); - Assert.assertEquals(2, Deencapsulation.>getField(index, "group2Tables").size()); - Assert.assertEquals(1, index.getAllGroupIds().size()); - Assert.assertEquals(2, Deencapsulation.>getField(index, "table2Group").size()); - Assert.assertEquals(1, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); - Assert.assertEquals(1, Deencapsulation.>getField(index, "group2Schema").size()); - Assert.assertEquals(0, index.getUnstableGroupIds().size()); + Assertions.assertEquals(2, Deencapsulation.>getField(index, "group2Tables").size()); + Assertions.assertEquals(1, index.getAllGroupIds().size()); + Assertions.assertEquals(2, Deencapsulation.>getField(index, "table2Group").size()); + Assertions.assertEquals(1, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); + Assertions.assertEquals(1, Deencapsulation.>getField(index, "group2Schema").size()); + Assertions.assertEquals(0, index.getUnstableGroupIds().size()); - Assert.assertTrue(index.isColocateTable(firstTblId)); - Assert.assertTrue(index.isColocateTable(secondTblId)); + Assertions.assertTrue(index.isColocateTable(firstTblId)); + Assertions.assertTrue(index.isColocateTable(secondTblId)); - Assert.assertTrue(index.isSameGroup(firstTblId, secondTblId)); + Assertions.assertTrue(index.isSameGroup(firstTblId, secondTblId)); // drop first index.removeTable(firstTblId); - Assert.assertEquals(1, Deencapsulation.>getField(index, "group2Tables").size()); - Assert.assertEquals(1, index.getAllGroupIds().size()); - Assert.assertEquals(1, Deencapsulation.>getField(index, "table2Group").size()); - Assert.assertEquals(1, + Assertions.assertEquals(1, Deencapsulation.>getField(index, "group2Tables").size()); + Assertions.assertEquals(1, index.getAllGroupIds().size()); + Assertions.assertEquals(1, Deencapsulation.>getField(index, "table2Group").size()); + Assertions.assertEquals(1, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); - Assert.assertEquals(0, index.getUnstableGroupIds().size()); + Assertions.assertEquals(0, index.getUnstableGroupIds().size()); - Assert.assertFalse(index.isColocateTable(firstTblId)); - Assert.assertTrue(index.isColocateTable(secondTblId)); - Assert.assertFalse(index.isSameGroup(firstTblId, secondTblId)); + Assertions.assertFalse(index.isColocateTable(firstTblId)); + Assertions.assertTrue(index.isColocateTable(secondTblId)); + Assertions.assertFalse(index.isSameGroup(firstTblId, secondTblId)); // drop second index.removeTable(secondTblId); - Assert.assertEquals(0, Deencapsulation.>getField(index, "group2Tables").size()); - Assert.assertEquals(0, index.getAllGroupIds().size()); - Assert.assertEquals(0, Deencapsulation.>getField(index, "table2Group").size()); - Assert.assertEquals(0, + Assertions.assertEquals(0, Deencapsulation.>getField(index, "group2Tables").size()); + Assertions.assertEquals(0, index.getAllGroupIds().size()); + Assertions.assertEquals(0, Deencapsulation.>getField(index, "table2Group").size()); + Assertions.assertEquals(0, Deencapsulation.>>>getField(index, "group2BackendsPerBucketSeq").size()); - Assert.assertEquals(0, index.getUnstableGroupIds().size()); + Assertions.assertEquals(0, index.getUnstableGroupIds().size()); - Assert.assertFalse(index.isColocateTable(firstTblId)); - Assert.assertFalse(index.isColocateTable(secondTblId)); + Assertions.assertFalse(index.isColocateTable(firstTblId)); + Assertions.assertFalse(index.isColocateTable(secondTblId)); } @Test @@ -339,20 +334,21 @@ public void testBucketNum() throws Exception { + " \"colocate_with\" = \"" + groupName + "\"\n" + ");"); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("Colocate tables must have same bucket num: 2 should be 1"); - createTable("create table " + dbName + "." + tableName2 + " (\n" - + " `k1` int NULL COMMENT \"\",\n" - + " `k2` varchar(10) NULL COMMENT \"\"\n" - + ") ENGINE=OLAP\n" - + "DUPLICATE KEY(`k1`, `k2`)\n" - + "COMMENT \"OLAP\"\n" - + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 2\n" - + "PROPERTIES (\n" - + " \"replication_num\" = \"1\",\n" - + " \"colocate_with\" = \"" + groupName + "\"\n" - + ");"); - + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + createTable("create table " + dbName + "." + tableName2 + " (\n" + + " `k1` int NULL COMMENT \"\",\n" + + " `k2` varchar(10) NULL COMMENT \"\"\n" + + ") ENGINE=OLAP\n" + + "DUPLICATE KEY(`k1`, `k2`)\n" + + "COMMENT \"OLAP\"\n" + + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 2\n" + + "PROPERTIES (\n" + + " \"replication_num\" = \"1\",\n" + + " \"colocate_with\" = \"" + groupName + "\"\n" + + ");"); + }); + Assertions.assertTrue(e.getMessage().contains("Colocate tables must have same bucket num: 2 should be 1"), + "unexpected message: " + e.getMessage()); } @Test @@ -369,20 +365,22 @@ public void testReplicationNum() throws Exception { + " \"colocate_with\" = \"" + groupName + "\"\n" + ");"); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("Colocate tables must have same replication allocation: { tag.location.default: 2 }" - + " should be { tag.location.default: 1 }"); - createTable("create table " + dbName + "." + tableName2 + " (\n" - + " `k1` int NULL COMMENT \"\",\n" - + " `k2` varchar(10) NULL COMMENT \"\"\n" - + ") ENGINE=OLAP\n" - + "DUPLICATE KEY(`k1`, `k2`)\n" - + "COMMENT \"OLAP\"\n" - + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 1\n" - + "PROPERTIES (\n" - + " \"replication_num\" = \"2\",\n" - + " \"colocate_with\" = \"" + groupName + "\"\n" - + ");"); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + createTable("create table " + dbName + "." + tableName2 + " (\n" + + " `k1` int NULL COMMENT \"\",\n" + + " `k2` varchar(10) NULL COMMENT \"\"\n" + + ") ENGINE=OLAP\n" + + "DUPLICATE KEY(`k1`, `k2`)\n" + + "COMMENT \"OLAP\"\n" + + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 1\n" + + "PROPERTIES (\n" + + " \"replication_num\" = \"2\",\n" + + " \"colocate_with\" = \"" + groupName + "\"\n" + + ");"); + }); + Assertions.assertTrue(e.getMessage().contains("Colocate tables must have same replication allocation: { tag.location.default: 2 }" + + " should be { tag.location.default: 1 }"), + "unexpected message: " + e.getMessage()); } @Test @@ -399,19 +397,21 @@ public void testDistributionColumnsSize() throws Exception { + " \"colocate_with\" = \"" + groupName + "\"\n" + ");"); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("Colocate tables distribution columns size must be same: 1 should be 2"); - createTable("create table " + dbName + "." + tableName2 + " (\n" - + " `k1` int NULL COMMENT \"\",\n" - + " `k2` varchar(10) NULL COMMENT \"\"\n" - + ") ENGINE=OLAP\n" - + "DUPLICATE KEY(`k1`, `k2`)\n" - + "COMMENT \"OLAP\"\n" - + "DISTRIBUTED BY HASH(`k1`) BUCKETS 1\n" - + "PROPERTIES (\n" - + " \"replication_num\" = \"1\",\n" - + " \"colocate_with\" = \"" + groupName + "\"\n" - + ");"); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + createTable("create table " + dbName + "." + tableName2 + " (\n" + + " `k1` int NULL COMMENT \"\",\n" + + " `k2` varchar(10) NULL COMMENT \"\"\n" + + ") ENGINE=OLAP\n" + + "DUPLICATE KEY(`k1`, `k2`)\n" + + "COMMENT \"OLAP\"\n" + + "DISTRIBUTED BY HASH(`k1`) BUCKETS 1\n" + + "PROPERTIES (\n" + + " \"replication_num\" = \"1\",\n" + + " \"colocate_with\" = \"" + groupName + "\"\n" + + ");"); + }); + Assertions.assertTrue(e.getMessage().contains("Colocate tables distribution columns size must be same: 1 should be 2"), + "unexpected message: " + e.getMessage()); } @Test @@ -428,19 +428,21 @@ public void testDistributionColumnsType() throws Exception { + " \"colocate_with\" = \"" + groupName + "\"\n" + ");"); - expectedEx.expect(DdlException.class); - expectedEx.expectMessage("Colocate tables distribution columns must have the same data type: k2(varchar(10)) should be int"); - createTable("create table " + dbName + "." + tableName2 + " (\n" - + " `k1` int NULL COMMENT \"\",\n" - + " `k2` varchar(10) NULL COMMENT \"\"\n" - + ") ENGINE=OLAP\n" - + "DUPLICATE KEY(`k1`, `k2`)\n" - + "COMMENT \"OLAP\"\n" - + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 1\n" - + "PROPERTIES (\n" - + " \"replication_num\" = \"1\",\n" - + " \"colocate_with\" = \"" + groupName + "\"\n" - + ");"); + DdlException e = Assertions.assertThrows(DdlException.class, () -> { + createTable("create table " + dbName + "." + tableName2 + " (\n" + + " `k1` int NULL COMMENT \"\",\n" + + " `k2` varchar(10) NULL COMMENT \"\"\n" + + ") ENGINE=OLAP\n" + + "DUPLICATE KEY(`k1`, `k2`)\n" + + "COMMENT \"OLAP\"\n" + + "DISTRIBUTED BY HASH(`k1`, `k2`) BUCKETS 1\n" + + "PROPERTIES (\n" + + " \"replication_num\" = \"1\",\n" + + " \"colocate_with\" = \"" + groupName + "\"\n" + + ");"); + }); + Assertions.assertTrue(e.getMessage().contains("Colocate tables distribution columns must have the same data type: k2(varchar(10)) should be int"), + "unexpected message: " + e.getMessage()); } @@ -464,7 +466,7 @@ public void testModifyGroupNameForBucketSeqInconsistent() throws Exception { GroupId groupId1 = index.getGroup(tableId); Map>> backendIds1 = index.getBackendsPerBucketSeq(groupId1); - Assert.assertEquals(1, backendIds1.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); + Assertions.assertEquals(1, backendIds1.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); // set same group name alterTable("ALTER TABLE " + dbName + "." + tableName1 @@ -473,8 +475,8 @@ public void testModifyGroupNameForBucketSeqInconsistent() throws Exception { // verify groupId group2BackendsPerBucketSeq Map>> backendIds2 = index.getBackendsPerBucketSeq(groupId2); - Assert.assertEquals(1, backendIds2.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); - Assert.assertEquals(groupId1, groupId2); - Assert.assertEquals(backendIds1, backendIds2); + Assertions.assertEquals(1, backendIds2.get(Tag.DEFAULT_BACKEND_TAG).get(0).size()); + Assertions.assertEquals(groupId1, groupId2); + Assertions.assertEquals(backendIds1, backendIds2); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnBloomFilterMaterializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnBloomFilterMaterializationTest.java index 3d9d6613f16e8d..58c21d88c439a1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnBloomFilterMaterializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnBloomFilterMaterializationTest.java @@ -24,8 +24,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Set; @@ -43,8 +43,8 @@ public void testSetIndexFlagMarksBfIndexOnShadowColumn() { TColumn tColumn = ColumnToThrift.toThrift(shadowColumn); ColumnToThrift.setIndexFlag(tColumn, olapTable); - Assert.assertEquals("k1", tColumn.getColumnName()); - Assert.assertTrue(tColumn.isIsBloomFilterColumn()); + Assertions.assertEquals("k1", tColumn.getColumnName()); + Assertions.assertTrue(tColumn.isIsBloomFilterColumn()); } @Test @@ -59,8 +59,8 @@ public void testSetIndexFlagFallsBackToBfIndexMetadataWhenCopiedBfColumnsUnavail TColumn tColumn = ColumnToThrift.toThrift(shadowColumn); ColumnToThrift.setIndexFlag(tColumn, olapTable); - Assert.assertEquals("k1", tColumn.getColumnName()); - Assert.assertTrue(tColumn.isIsBloomFilterColumn()); + Assertions.assertEquals("k1", tColumn.getColumnName()); + Assertions.assertTrue(tColumn.isIsBloomFilterColumn()); } @Test @@ -72,8 +72,8 @@ public void testColumnToProtobufMarksBfIndexOnShadowColumn() throws DdlException Lists.newArrayList(new Index(1L, "bf_k1", Lists.newArrayList("k1"), IndexType.BLOOMFILTER, null, ""))); - Assert.assertEquals("k1", columnPb.getName()); - Assert.assertTrue(columnPb.getIsBfColumn()); + Assertions.assertEquals("k1", columnPb.getName()); + Assertions.assertTrue(columnPb.getIsBfColumn()); } @Test @@ -86,8 +86,8 @@ public void testColumnToProtobufMarksBfColumnsWithoutBfIndexes() throws DdlExcep OlapFile.ColumnPB columnPb = ColumnToProtobuf.toPb(shadowColumn, Sets.newHashSet("k1"), Lists.newArrayList()); - Assert.assertEquals("k1", columnPb.getName()); - Assert.assertTrue(columnPb.getIsBfColumn()); + Assertions.assertEquals("k1", columnPb.getName()); + Assertions.assertTrue(columnPb.getIsBfColumn()); } @Test @@ -100,24 +100,24 @@ public void testOlapTableBloomFilterColumnGetters() { Set bfColumns = olapTable.getCopiedBfColumns(); Set bfIndexColumns = Index.getBfIndexColumns(olapTable.getIndexes()); - Assert.assertEquals(Sets.newHashSet("k1"), bfColumns); - Assert.assertEquals(Sets.newHashSet("v1"), bfIndexColumns); + Assertions.assertEquals(Sets.newHashSet("k1"), bfColumns); + Assertions.assertEquals(Sets.newHashSet("v1"), bfIndexColumns); } @Test public void testIndexBloomFilterHelpersIgnoreNonBloomFilterIndexesAndHandleNulls() { Set emptyBfIndexColumns = Index.getBfIndexColumns(null); - Assert.assertTrue(emptyBfIndexColumns.isEmpty()); + Assertions.assertTrue(emptyBfIndexColumns.isEmpty()); Set bfIndexColumns = Index.getBfIndexColumns(Lists.newArrayList( new Index(1L, "bf_v1", Lists.newArrayList("v1"), IndexType.BLOOMFILTER, null, ""), new Index(2L, "bitmap_k1", Lists.newArrayList("k1"), IndexType.BITMAP, null, ""), new Index(3L, "bf_v2", Lists.newArrayList("V2"), IndexType.BLOOMFILTER, null, ""))); - Assert.assertEquals(Sets.newHashSet("v1", "V2"), bfIndexColumns); - Assert.assertTrue(Index.getBfIndexColumns(Lists.newArrayList( + Assertions.assertEquals(Sets.newHashSet("v1", "V2"), bfIndexColumns); + Assertions.assertTrue(Index.getBfIndexColumns(Lists.newArrayList( new Index(1L, "bf_v2", Lists.newArrayList("V2"), IndexType.BLOOMFILTER, null, ""))).contains("v2")); - Assert.assertFalse(Index.getBfIndexColumns(Lists.newArrayList( + Assertions.assertFalse(Index.getBfIndexColumns(Lists.newArrayList( new Index(1L, "bitmap_k1", Lists.newArrayList("k1"), IndexType.BITMAP, null, ""))).contains("k1")); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnGsonSerializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnGsonSerializationTest.java index 6e81121ca04366..6d52675c316208 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnGsonSerializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnGsonSerializationTest.java @@ -24,9 +24,9 @@ import com.google.common.collect.Lists; import com.google.gson.annotations.SerializedName; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInput; import java.io.DataInputStream; @@ -43,7 +43,7 @@ public class ColumnGsonSerializationTest { private static String fileName = "./ColumnGsonSerializationTest"; private static Path path = Paths.get(fileName); - @After + @AfterEach public void tearDown() throws IOException { Files.deleteIfExists(path); } @@ -83,7 +83,7 @@ public void testSerializeColumn() throws IOException, AnalysisException { String readJson = Text.readString(in); Column readC1 = GsonUtils.GSON.fromJson(readJson, Column.class); - Assert.assertEquals(c1, readC1); + Assertions.assertEquals(c1, readC1); // 3.close in.close(); } @@ -113,10 +113,10 @@ public void testSerializeColumnList() throws IOException, AnalysisException { ColumnList readList = ColumnList.read(in); List columns = readList.columns; - Assert.assertEquals(3, columns.size()); - Assert.assertEquals(c1, columns.get(0)); - Assert.assertEquals(c2, columns.get(1)); - Assert.assertEquals(c3, columns.get(2)); + Assertions.assertEquals(3, columns.size()); + Assertions.assertEquals(c1, columns.get(0)); + Assertions.assertEquals(c2, columns.get(1)); + Assertions.assertEquals(c3, columns.get(2)); // 3.close in.close(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTest.java index 2ced7a567bfc72..730cf91c49c342 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTest.java @@ -29,10 +29,10 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.persist.gson.GsonUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -45,7 +45,7 @@ public class ColumnTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { fakeEnv = new FakeEnv(); env = Deencapsulation.newInstance(Env.class); @@ -54,7 +54,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -89,74 +89,84 @@ public void testSerialization() throws Exception { // 2. Read objects from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); Column rColumn1 = GsonUtils.GSON.fromJson(Text.readString(dis), Column.class); - Assert.assertEquals("user", rColumn1.getName()); - Assert.assertEquals(PrimitiveType.CHAR, rColumn1.getDataType()); - Assert.assertEquals(AggregateType.SUM, rColumn1.getAggregationType()); - Assert.assertEquals("", rColumn1.getDefaultValue()); - Assert.assertEquals(0, rColumn1.getScale()); - Assert.assertEquals(0, rColumn1.getPrecision()); - Assert.assertEquals(20, rColumn1.getStrLen()); - Assert.assertFalse(rColumn1.isAllowNull()); + Assertions.assertEquals("user", rColumn1.getName()); + Assertions.assertEquals(PrimitiveType.CHAR, rColumn1.getDataType()); + Assertions.assertEquals(AggregateType.SUM, rColumn1.getAggregationType()); + Assertions.assertEquals("", rColumn1.getDefaultValue()); + Assertions.assertEquals(0, rColumn1.getScale()); + Assertions.assertEquals(0, rColumn1.getPrecision()); + Assertions.assertEquals(20, rColumn1.getStrLen()); + Assertions.assertFalse(rColumn1.isAllowNull()); // 3. Test read() Column rColumn2 = GsonUtils.GSON.fromJson(Text.readString(dis), Column.class); - Assert.assertEquals("age", rColumn2.getName()); - Assert.assertEquals(PrimitiveType.INT, rColumn2.getDataType()); - Assert.assertEquals(AggregateType.REPLACE, rColumn2.getAggregationType()); - Assert.assertEquals("20", rColumn2.getDefaultValue()); + Assertions.assertEquals("age", rColumn2.getName()); + Assertions.assertEquals(PrimitiveType.INT, rColumn2.getDataType()); + Assertions.assertEquals(AggregateType.REPLACE, rColumn2.getAggregationType()); + Assertions.assertEquals("20", rColumn2.getDefaultValue()); Column rColumn3 = GsonUtils.GSON.fromJson(Text.readString(dis), Column.class); - Assert.assertEquals(rColumn3, column3); + Assertions.assertEquals(rColumn3, column3); Column rColumn4 = GsonUtils.GSON.fromJson(Text.readString(dis), Column.class); - Assert.assertEquals(rColumn4, column4); + Assertions.assertEquals(rColumn4, column4); - Assert.assertEquals(rColumn2.toString(), column2.toString()); - Assert.assertEquals(column1, column1); + Assertions.assertEquals(rColumn2.toString(), column2.toString()); + Assertions.assertEquals(column1, column1); // 4. delete files dis.close(); Files.delete(path); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeAllowed() throws DdlException { - Column oldColumn = new Column("user", ScalarType.createType(PrimitiveType.INT), true, null, true, "0", ""); - Column newColumn = new Column("user", ScalarType.createType(PrimitiveType.INT), true, null, false, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("user", ScalarType.createType(PrimitiveType.INT), true, null, true, "0", ""); + Column newColumn = new Column("user", ScalarType.createType(PrimitiveType.INT), true, null, false, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeIntToVarchar() throws DdlException { - Column oldColumn = new Column("a", ScalarType.createType(PrimitiveType.INT), false, null, true, "0", ""); - Column newColumn = new Column("a", ScalarType.createType(PrimitiveType.VARCHAR, 1, 0, 0), false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ScalarType.createType(PrimitiveType.INT), false, null, true, "0", ""); + Column newColumn = new Column("a", ScalarType.createType(PrimitiveType.VARCHAR, 1, 0, 0), false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeFloatToVarchar() throws DdlException { - Column oldColumn = new Column("b", ScalarType.createType(PrimitiveType.FLOAT), false, null, true, "0", ""); - Column newColumn = new Column("b", ScalarType.createType(PrimitiveType.VARCHAR, 23, 0, 0), false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("b", ScalarType.createType(PrimitiveType.FLOAT), false, null, true, "0", ""); + Column newColumn = new Column("b", ScalarType.createType(PrimitiveType.VARCHAR, 23, 0, 0), false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeDecimalToVarchar() throws DdlException { - Column oldColumn = new Column("a", ScalarType.createType(PrimitiveType.DECIMALV2, 13, 13, 3), false, null, true, "0", ""); - Column newColumn = new Column("a", ScalarType.createType(PrimitiveType.VARCHAR, 14, 0, 0), false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ScalarType.createType(PrimitiveType.DECIMALV2, 13, 13, 3), false, null, true, "0", ""); + Column newColumn = new Column("a", ScalarType.createType(PrimitiveType.VARCHAR, 14, 0, 0), false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeDoubleToVarchar() throws DdlException { - Column oldColumn = new Column("c", ScalarType.createType(PrimitiveType.DOUBLE), false, null, true, "0", ""); - Column newColumn = new Column("c", ScalarType.createType(PrimitiveType.VARCHAR, 31, 0, 0), false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("c", ScalarType.createType(PrimitiveType.DOUBLE), false, null, true, "0", ""); + Column newColumn = new Column("c", ScalarType.createType(PrimitiveType.VARCHAR, 31, 0, 0), false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } @Test @@ -168,89 +178,101 @@ public void testSchemaChangeArrayToArray() throws DdlException { @Test public void testStrictNestedPrimitivePromotionRules() { - Assert.assertTrue(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.TINYINT, Type.INT)); - Assert.assertTrue(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.FLOAT, Type.DOUBLE)); + Assertions.assertTrue(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.TINYINT, Type.INT)); + Assertions.assertTrue(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.FLOAT, Type.DOUBLE)); - Assert.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.INT, Type.FLOAT)); - Assert.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.VARCHAR, Type.INT)); - Assert.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( + Assertions.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.INT, Type.FLOAT)); + Assertions.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion(Type.VARCHAR, Type.INT)); + Assertions.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( ScalarType.createDecimalV3Type(5, 2), ScalarType.createDecimalV3Type(10, 2))); - Assert.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( + Assertions.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( ScalarType.createDecimalV3Type(10, 2), ScalarType.createDecimalV3Type(5, 2))); - Assert.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( + Assertions.assertFalse(ColumnType.isSupportedStrictNestedPrimitivePromotion( ScalarType.createDecimalV3Type(5, 2), ScalarType.createDecimalV3Type(10, 3))); } @Test public void testIcebergNestedDecimalPromotionRules() { - Assert.assertTrue(ColumnType.isSupportedIcebergNestedDecimalPromotion( + Assertions.assertTrue(ColumnType.isSupportedIcebergNestedDecimalPromotion( ScalarType.createDecimalV3Type(5, 2), ScalarType.createDecimalV3Type(10, 2))); - Assert.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion(Type.INT, Type.BIGINT)); - Assert.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion( + Assertions.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion(Type.INT, Type.BIGINT)); + Assertions.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion( ScalarType.createDecimalV3Type(10, 2), ScalarType.createDecimalV3Type(5, 2))); - Assert.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion( + Assertions.assertFalse(ColumnType.isSupportedIcebergNestedDecimalPromotion( ScalarType.createDecimalV3Type(5, 2), ScalarType.createDecimalV3Type(10, 3))); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeArrayDecimalPrecisionPromotionRejectedForInternalTable() throws DdlException { - Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), - false, null, true, "0", ""); - Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 2), true), - false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), + false, null, true, "0", ""); + Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 2), true), + false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeMapDecimalValuePrecisionPromotionRejectedForInternalTable() throws DdlException { - Column oldColumn = new Column("a", new MapType(Type.INT, ScalarType.createDecimalV3Type(5, 2)), - false, null, true, "0", ""); - Column newColumn = new Column("a", new MapType(Type.INT, ScalarType.createDecimalV3Type(10, 2)), - false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", new MapType(Type.INT, ScalarType.createDecimalV3Type(5, 2)), + false, null, true, "0", ""); + Column newColumn = new Column("a", new MapType(Type.INT, ScalarType.createDecimalV3Type(10, 2)), + false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeStructDecimalFieldPrecisionPromotionRejectedForInternalTable() throws DdlException { - Column oldColumn = new Column("a", - new StructType(new StructField("d", ScalarType.createDecimalV3Type(5, 2))), - false, null, true, "0", ""); - Column newColumn = new Column("a", - new StructType(new StructField("d", ScalarType.createDecimalV3Type(10, 2))), - false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", + new StructType(new StructField("d", ScalarType.createDecimalV3Type(5, 2))), + false, null, true, "0", ""); + Column newColumn = new Column("a", + new StructType(new StructField("d", ScalarType.createDecimalV3Type(10, 2))), + false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeArrayDecimalPrecisionNarrowing() throws DdlException { - Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 2), true), - false, null, true, "0", ""); - Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), - false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 2), true), + false, null, true, "0", ""); + Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), + false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeArrayDecimalScaleChange() throws DdlException { - Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), - false, null, true, "0", ""); - Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 3), true), - false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(5, 2), true), + false, null, true, "0", ""); + Column newColumn = new Column("a", ArrayType.create(ScalarType.createDecimalV3Type(10, 3), true), + false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testSchemaChangeArrayToArrayDowngrade() throws DdlException { - Column oldColumn = new Column("a", ArrayType.create(Type.INT, true), false, null, true, "0", ""); - Column newColumn = new Column("a", ArrayType.create(Type.TINYINT, true), false, null, true, "0", ""); - oldColumn.checkSchemaChangeAllowed(newColumn); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + Column oldColumn = new Column("a", ArrayType.create(Type.INT, true), false, null, true, "0", ""); + Column newColumn = new Column("a", ArrayType.create(Type.TINYINT, true), false, null, true, "0", ""); + oldColumn.checkSchemaChangeAllowed(newColumn); + Assertions.fail("No exception throws."); + }); } @Test @@ -261,10 +283,10 @@ public void testBaseColumn() { SlotRef baseSlot = new SlotRef(baseDescriptor); Column mvColumnSimple = new Column("mv_a", ArrayType.create(Type.INT, true), false, null, true, "0", ""); mvColumnSimple.setDefineExpr(baseSlot); - Assert.assertTrue(mvColumnSimple.tryGetBaseColumnName().equalsIgnoreCase("base_a")); + Assertions.assertTrue(mvColumnSimple.tryGetBaseColumnName().equalsIgnoreCase("base_a")); Expr add = new ArithmeticExpr(ArithmeticExpr.Operator.ADD, baseSlot, baseSlot, ScalarType.BOOLEAN, NullableMode.DEPEND_ON_ARGUMENT, true); Column mvColumnComplex = new Column("mv_b", ArrayType.create(Type.INT, true), false, null, true, "0", ""); mvColumnComplex.setDefineExpr(add); - Assert.assertTrue(mvColumnComplex.tryGetBaseColumnName().equalsIgnoreCase("mv_b")); + Assertions.assertTrue(mvColumnComplex.tryGetBaseColumnName().equalsIgnoreCase("mv_b")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTypeTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTypeTest.java index b6d1e72c4ffa5d..200862046e359e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTypeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ColumnTypeTest.java @@ -20,10 +20,10 @@ import org.apache.doris.common.Config; import org.apache.doris.common.FeConstants; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -34,13 +34,13 @@ public class ColumnTypeTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { fakeEnv = new FakeEnv(); FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -50,126 +50,126 @@ public void tearDown() { @Test public void testPrimitiveType() { Type type = ScalarType.createType(PrimitiveType.INT); - Assert.assertEquals(PrimitiveType.INT, type.getPrimitiveType()); - Assert.assertEquals("int", type.toSql()); + Assertions.assertEquals(PrimitiveType.INT, type.getPrimitiveType()); + Assertions.assertEquals("int", type.toSql()); // equal type Type type2 = ScalarType.createType(PrimitiveType.INT); - Assert.assertEquals(type, type2); + Assertions.assertEquals(type, type2); // not equal type Type type3 = ScalarType.createType(PrimitiveType.BIGINT); - Assert.assertNotSame(type, type3); + Assertions.assertNotSame(type, type3); } @Test public void testCharType() { Type type = ScalarType.createVarchar(10); - Assert.assertEquals("varchar(10)", type.toSql()); - Assert.assertEquals(PrimitiveType.VARCHAR, type.getPrimitiveType()); - Assert.assertEquals(10, type.getLength()); + Assertions.assertEquals("varchar(10)", type.toSql()); + Assertions.assertEquals(PrimitiveType.VARCHAR, type.getPrimitiveType()); + Assertions.assertEquals(10, type.getLength()); // equal type Type type2 = ScalarType.createVarchar(10); - Assert.assertEquals(type, type2); + Assertions.assertEquals(type, type2); // different type Type type3 = ScalarType.createVarchar(3); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); // different type Type type4 = ScalarType.createType(PrimitiveType.BIGINT); - Assert.assertNotEquals(type, type4); + Assertions.assertNotEquals(type, type4); } @Test public void testDecimal() { Type type = ScalarType.createDecimalType(12, 5); if (Config.enable_decimal_conversion) { - Assert.assertEquals("decimalv3(12,5)", type.toSql()); - Assert.assertEquals(PrimitiveType.DECIMAL64, type.getPrimitiveType()); + Assertions.assertEquals("decimalv3(12,5)", type.toSql()); + Assertions.assertEquals(PrimitiveType.DECIMAL64, type.getPrimitiveType()); } else { - Assert.assertEquals("decimalv2(12,5)", type.toSql()); - Assert.assertEquals(PrimitiveType.DECIMALV2, type.getPrimitiveType()); + Assertions.assertEquals("decimalv2(12,5)", type.toSql()); + Assertions.assertEquals(PrimitiveType.DECIMALV2, type.getPrimitiveType()); } - Assert.assertEquals(12, ((ScalarType) type).getScalarPrecision()); - Assert.assertEquals(5, ((ScalarType) type).getScalarScale()); + Assertions.assertEquals(12, ((ScalarType) type).getScalarPrecision()); + Assertions.assertEquals(5, ((ScalarType) type).getScalarScale()); // equal type Type type2 = ScalarType.createDecimalType(12, 5); - Assert.assertEquals(type, type2); + Assertions.assertEquals(type, type2); // different type Type type3 = ScalarType.createDecimalType(11, 5); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); type3 = ScalarType.createDecimalType(12, 4); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); // different type Type type4 = ScalarType.createType(PrimitiveType.BIGINT); - Assert.assertNotEquals(type, type4); + Assertions.assertNotEquals(type, type4); } @Test public void testDatetimeV2() { Type type = ScalarType.createDatetimeV2Type(3); - Assert.assertEquals("datetimev2(3)", type.toSql()); - Assert.assertEquals(PrimitiveType.DATETIMEV2, type.getPrimitiveType()); - Assert.assertEquals(ScalarType.DATETIME_PRECISION, ((ScalarType) type).getScalarPrecision()); - Assert.assertEquals(3, ((ScalarType) type).getScalarScale()); + Assertions.assertEquals("datetimev2(3)", type.toSql()); + Assertions.assertEquals(PrimitiveType.DATETIMEV2, type.getPrimitiveType()); + Assertions.assertEquals(ScalarType.DATETIME_PRECISION, ((ScalarType) type).getScalarPrecision()); + Assertions.assertEquals(3, ((ScalarType) type).getScalarScale()); // equal type Type type2 = ScalarType.createDatetimeV2Type(3); - Assert.assertEquals(type, type2); + Assertions.assertEquals(type, type2); // different type Type type3 = ScalarType.createDatetimeV2Type(6); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); type3 = ScalarType.createDatetimeV2Type(0); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); // different type Type type4 = ScalarType.createType(PrimitiveType.BIGINT); - Assert.assertNotEquals(type, type4); + Assertions.assertNotEquals(type, type4); Type type5 = ScalarType.createDatetimeV2Type(0); Type type6 = ScalarType.createType(PrimitiveType.DATETIME); - Assert.assertNotEquals(type5, type6); - Assert.assertNotEquals(type, type6); + Assertions.assertNotEquals(type5, type6); + Assertions.assertNotEquals(type, type6); } @Test public void testDateV2() { Type type = ScalarType.createType(PrimitiveType.DATE); Type type2 = ScalarType.createType(PrimitiveType.DATEV2); - Assert.assertNotEquals(type, type2); + Assertions.assertNotEquals(type, type2); // different type Type type3 = ScalarType.createDatetimeV2Type(6); - Assert.assertNotEquals(type2, type3); + Assertions.assertNotEquals(type2, type3); } @Test public void testTimeV2() { Type type = ScalarType.createTimeV2Type(3); - Assert.assertEquals("time(3)", type.toSql()); - Assert.assertEquals(PrimitiveType.TIMEV2, type.getPrimitiveType()); - Assert.assertEquals(ScalarType.DATETIME_PRECISION, ((ScalarType) type).getScalarPrecision()); - Assert.assertEquals(3, ((ScalarType) type).getScalarScale()); + Assertions.assertEquals("time(3)", type.toSql()); + Assertions.assertEquals(PrimitiveType.TIMEV2, type.getPrimitiveType()); + Assertions.assertEquals(ScalarType.DATETIME_PRECISION, ((ScalarType) type).getScalarPrecision()); + Assertions.assertEquals(3, ((ScalarType) type).getScalarScale()); // equal type Type type2 = ScalarType.createTimeV2Type(3); - Assert.assertEquals(type, type2); + Assertions.assertEquals(type, type2); // different type Type type3 = ScalarType.createTimeV2Type(6); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); type3 = ScalarType.createTimeV2Type(0); - Assert.assertNotEquals(type, type3); + Assertions.assertNotEquals(type, type3); // different type Type type4 = ScalarType.createType(PrimitiveType.BIGINT); - Assert.assertNotEquals(type, type4); + Assertions.assertNotEquals(type, type4); } @Test @@ -193,17 +193,17 @@ public void testSerialization() throws Exception { // 2. Read objects from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); Type rType1 = ColumnType.read(dis); - Assert.assertEquals(rType1, type1); + Assertions.assertEquals(rType1, type1); Type rType2 = ColumnType.read(dis); - Assert.assertEquals(rType2, type2); + Assertions.assertEquals(rType2, type2); Type rType3 = ColumnType.read(dis); // Change it when remove DecimalV2 - Assert.assertTrue(rType3.equals(type3) || rType3.equals(type4)); + Assertions.assertTrue(rType3.equals(type3) || rType3.equals(type4)); - Assert.assertNotEquals(type1, this); + Assertions.assertNotEquals(type1, this); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/CreateTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/CreateTableTest.java index 584a2c44d5bb01..5cc2899958cf57 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/CreateTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/CreateTableTest.java @@ -30,7 +30,7 @@ import org.apache.doris.utframe.TestWithFeService; import com.google.common.collect.Maps; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Map; @@ -61,8 +61,8 @@ public void testDuplicateCreateTable() throws Exception { createTable(sql); Set tabletIdSetAfterCreateFirstTable = env.getTabletInvertedIndex().getReplicaMetaTable().rowKeySet(); Set colocateTableIdBeforeCreateFirstTable = env.getColocateTableIndex().getTable2Group().keySet(); - Assert.assertTrue(colocateTableIdBeforeCreateFirstTable.size() > 0); - Assert.assertTrue(tabletIdSetAfterCreateFirstTable.size() > 0); + Assertions.assertTrue(colocateTableIdBeforeCreateFirstTable.size() > 0); + Assertions.assertTrue(tabletIdSetAfterCreateFirstTable.size() > 0); createTable(sql); // check whether tablet is cleared after duplicate create table @@ -70,13 +70,13 @@ public void testDuplicateCreateTable() throws Exception { Set tabletIdSetAfterDuplicateCreateTable2 = env.getTabletInvertedIndex().getBackingReplicaMetaTable().columnKeySet(); Set tabletIdSetAfterDuplicateCreateTable3 = env.getTabletInvertedIndex().getTabletMetaMap().keySet(); - Assert.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable1); - Assert.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable2); - Assert.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable3); + Assertions.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable1); + Assertions.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable2); + Assertions.assertEquals(tabletIdSetAfterCreateFirstTable, tabletIdSetAfterDuplicateCreateTable3); // check whether table id is cleared from colocate group after duplicate create table Set colocateTableIdAfterCreateFirstTable = env.getColocateTableIndex().getTable2Group().keySet(); - Assert.assertEquals(colocateTableIdBeforeCreateFirstTable, colocateTableIdAfterCreateFirstTable); + Assertions.assertEquals(colocateTableIdBeforeCreateFirstTable, colocateTableIdAfterCreateFirstTable); } @Test @@ -227,9 +227,9 @@ public void testNormal() throws DdlException, ConfigException { Database db = Env.getCurrentInternalCatalog().getDbOrDdlException("test"); OlapTable rowBinlogNormal = (OlapTable) db.getTableOrDdlException("row_binlog_normal"); - Assert.assertTrue(rowBinlogNormal.needRowBinlog()); - Assert.assertNotNull(rowBinlogNormal.getAutoIncrementGenerator()); - Assert.assertEquals((long) Column.BINLOG_LSN_AUTO_INC_ID, + Assertions.assertTrue(rowBinlogNormal.needRowBinlog()); + Assertions.assertNotNull(rowBinlogNormal.getAutoIncrementGenerator()); + Assertions.assertEquals((long) Column.BINLOG_LSN_AUTO_INC_ID, rowBinlogNormal.getAutoIncrementGenerator().getColumnId()); boolean foundRowBinlogIndex = false; for (Partition partition : rowBinlogNormal.getPartitions()) { @@ -238,39 +238,39 @@ public void testNormal() throws DdlException, ConfigException { foundRowBinlogIndex |= index.isRowBinlog(); for (Tablet tablet : index.getTablets()) { TabletMeta tabletMeta = Env.getCurrentInvertedIndex().getTabletMeta(tablet.getId()); - Assert.assertNotNull(tabletMeta); - Assert.assertEquals(index.isRowBinlog(), tabletMeta.isRowBinlog()); + Assertions.assertNotNull(tabletMeta); + Assertions.assertEquals(index.isRowBinlog(), tabletMeta.isRowBinlog()); } } } - Assert.assertTrue(foundRowBinlogIndex); + Assertions.assertTrue(foundRowBinlogIndex); OlapTable rowBinlogUnique = (OlapTable) db.getTableOrDdlException("row_binlog_unique"); - Assert.assertTrue(rowBinlogUnique.needRowBinlog()); - Assert.assertNotNull(rowBinlogUnique.getAutoIncrementGenerator()); - Assert.assertEquals((long) Column.BINLOG_LSN_AUTO_INC_ID, + Assertions.assertTrue(rowBinlogUnique.needRowBinlog()); + Assertions.assertNotNull(rowBinlogUnique.getAutoIncrementGenerator()); + Assertions.assertEquals((long) Column.BINLOG_LSN_AUTO_INC_ID, rowBinlogUnique.getAutoIncrementGenerator().getColumnId()); OlapTable tbl6 = (OlapTable) db.getTableOrDdlException("tbl6"); - Assert.assertTrue(tbl6.getColumn("k1").isKey()); - Assert.assertTrue(tbl6.getColumn("k2").isKey()); - Assert.assertTrue(tbl6.getColumn("k3").isKey()); + Assertions.assertTrue(tbl6.getColumn("k1").isKey()); + Assertions.assertTrue(tbl6.getColumn("k2").isKey()); + Assertions.assertTrue(tbl6.getColumn("k3").isKey()); OlapTable tbl7 = (OlapTable) db.getTableOrDdlException("tbl7"); - Assert.assertTrue(tbl7.getColumn("k1").isKey()); - Assert.assertFalse(tbl7.getColumn("k2").isKey()); - Assert.assertTrue(tbl7.getColumn("k2").getAggregationType() == AggregateType.NONE); + Assertions.assertTrue(tbl7.getColumn("k1").isKey()); + Assertions.assertFalse(tbl7.getColumn("k2").isKey()); + Assertions.assertTrue(tbl7.getColumn("k2").getAggregationType() == AggregateType.NONE); OlapTable tbl8 = (OlapTable) db.getTableOrDdlException("tbl8"); - Assert.assertTrue(tbl8.getColumn("k1").isKey()); - Assert.assertTrue(tbl8.getColumn("k2").isKey()); - Assert.assertFalse(tbl8.getColumn("v1").isKey()); - Assert.assertTrue(tbl8.getColumn(Column.SEQUENCE_COL).getAggregationType() == AggregateType.NONE); + Assertions.assertTrue(tbl8.getColumn("k1").isKey()); + Assertions.assertTrue(tbl8.getColumn("k2").isKey()); + Assertions.assertFalse(tbl8.getColumn("v1").isKey()); + Assertions.assertTrue(tbl8.getColumn(Column.SEQUENCE_COL).getAggregationType() == AggregateType.NONE); OlapTable tbl13 = (OlapTable) db.getTableOrDdlException("tbl13"); - Assert.assertTrue(tbl13.getColumn(Column.SEQUENCE_COL).getAggregationType() == AggregateType.NONE); - Assert.assertTrue(tbl13.getColumn(Column.SEQUENCE_COL).getType() == Type.INT); - Assert.assertEquals(tbl13.getSequenceMapCol(), "v1"); + Assertions.assertTrue(tbl13.getColumn(Column.SEQUENCE_COL).getAggregationType() == AggregateType.NONE); + Assertions.assertTrue(tbl13.getColumn(Column.SEQUENCE_COL).getType() == Type.INT); + Assertions.assertEquals(tbl13.getSequenceMapCol(), "v1"); ExceptionChecker.expectThrowsNoException( () -> createTable("create table test.tbl14\n" + "(k1 int, k2 int default 10)\n" + "duplicate key(k1)\n" @@ -296,9 +296,9 @@ public void testPartitionsStoreTableInvertedIndexStorageFormat() throws Exceptio Database db = Env.getCurrentInternalCatalog().getDbOrDdlException("test"); OlapTable table = (OlapTable) db.getTableOrDdlException("partition_inverted_index_format"); - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getPartitionInfo() + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getPartitionInfo() .getInvertedIndexFileStorageFormat(table.getPartition("p1").getId())); - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getPartitionInfo() + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getPartitionInfo() .getInvertedIndexFileStorageFormat(table.getPartition("p2").getId())); } @@ -817,10 +817,10 @@ public void testCreateTableWithStringLen() throws DdlException { }); Database db = Env.getCurrentInternalCatalog().getDbOrDdlException("test"); OlapTable tb = (OlapTable) db.getTableOrDdlException("test_strLen"); - Assert.assertEquals(1, tb.getColumn("k1").getStrLen()); - Assert.assertEquals(10, tb.getColumn("k2").getStrLen()); - Assert.assertEquals(ScalarType.MAX_VARCHAR_LENGTH, tb.getColumn("k3").getStrLen()); - Assert.assertEquals(10, tb.getColumn("k4").getStrLen()); + Assertions.assertEquals(1, tb.getColumn("k1").getStrLen()); + Assertions.assertEquals(10, tb.getColumn("k2").getStrLen()); + Assertions.assertEquals(ScalarType.MAX_VARCHAR_LENGTH, tb.getColumn("k3").getStrLen()); + Assertions.assertEquals(10, tb.getColumn("k4").getStrLen()); } @Test @@ -843,8 +843,8 @@ public void testCreateTableWithForceReplica() throws DdlException { Database db = Env.getCurrentInternalCatalog().getDbOrDdlException("test"); OlapTable tb = (OlapTable) db.getTableOrDdlException("test_replica"); Partition p1 = tb.getPartition("p1"); - Assert.assertEquals(1, tb.getPartitionInfo().getReplicaAllocation(p1.getId()).getTotalReplicaNum()); - Assert.assertEquals(1, tb.getTableProperty().getReplicaAllocation().getTotalReplicaNum()); + Assertions.assertEquals(1, tb.getPartitionInfo().getReplicaAllocation(p1.getId()).getTotalReplicaNum()); + Assertions.assertEquals(1, tb.getTableProperty().getReplicaAllocation().getTotalReplicaNum()); } finally { Config.force_olap_table_replication_num = -1; } @@ -854,14 +854,14 @@ public void testCreateTableWithForceReplica() throws DdlException { public void testCreateTableDetailMsg() throws Exception { Map allocMap = Maps.newHashMap(); allocMap.put(Tag.create(Tag.TYPE_LOCATION, "group_a"), (short) 6); - Assert.assertEquals(" Backends details: backends with tag {\"location\" : \"group_a\"} is [], ", + Assertions.assertEquals(" Backends details: backends with tag {\"location\" : \"group_a\"} is [], ", Env.getCurrentSystemInfo().getDetailsForCreateReplica(new ReplicaAllocation(allocMap))); allocMap.clear(); allocMap.put(Tag.create(Tag.TYPE_LOCATION, new String(Tag.VALUE_DEFAULT_TAG)), (short) 6); String msg = Env.getCurrentSystemInfo().getDetailsForCreateReplica(new ReplicaAllocation(allocMap)); - Assert.assertTrue("msg: " + msg, msg.contains("Backends details: backends with tag {\"location\" : \"default\"} is [[backendId=") - && msg.contains("hdd disks count={ok=1,}, ssd disk count={}], [backendId=")); + Assertions.assertTrue(msg.contains("Backends details: backends with tag {\"location\" : \"default\"} is [[backendId=") + && msg.contains("hdd disks count={ok=1,}, ssd disk count={}], [backendId="), "msg: " + msg); } @Test @@ -878,18 +878,18 @@ public void testCreateTableWithMinLoadReplicaNum() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrDdlException("test"); OlapTable tbl1 = (OlapTable) db.getTableOrDdlException("tbl_min_load_replica_num_1"); - Assert.assertEquals(1, tbl1.getMinLoadReplicaNum()); - Assert.assertEquals(2, (int) tbl1.getDefaultReplicaAllocation().getTotalReplicaNum()); + Assertions.assertEquals(1, tbl1.getMinLoadReplicaNum()); + Assertions.assertEquals(2, (int) tbl1.getDefaultReplicaAllocation().getTotalReplicaNum()); ExceptionChecker.expectThrowsNoException( () -> alterTableSync("alter table test.tbl_min_load_replica_num_1\n" + " set ( 'min_load_replica_num' = '2');")); - Assert.assertEquals(2, tbl1.getMinLoadReplicaNum()); + Assertions.assertEquals(2, tbl1.getMinLoadReplicaNum()); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "Failed to check min load replica num", () -> alterTableSync("alter table test.tbl_min_load_replica_num_1\n" + " set ( 'min_load_replica_num' = '3');")); - Assert.assertEquals(2, tbl1.getMinLoadReplicaNum()); + Assertions.assertEquals(2, tbl1.getMinLoadReplicaNum()); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "min_load_replica_num should > 0 or =-1", () -> alterTableSync("alter table test.tbl_min_load_replica_num_1\n" @@ -922,7 +922,7 @@ public void testCreateTableWithMinLoadReplicaNum() throws Exception { + ");")); OlapTable tbl3 = (OlapTable) db.getTableOrDdlException("tbl_min_load_replica_num_3"); - Assert.assertEquals(1, tbl3.getMinLoadReplicaNum()); + Assertions.assertEquals(1, tbl3.getMinLoadReplicaNum()); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "Failed to check min load replica num", () -> createTable("create table test.tbl_min_load_replica_num_4\n" @@ -1071,10 +1071,10 @@ public void testCreateTableTrimPropertyKey() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("tbl_trim_property_key"); - Assert.assertEquals(1, table.getMinLoadReplicaNum()); - Assert.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getEnable()); - Assert.assertEquals("DAY", table.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); - Assert.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals(1, table.getMinLoadReplicaNum()); + Assertions.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertEquals("DAY", table.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); + Assertions.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "Invalid dynamic partition properties: dynamic_partition. enable", @@ -1117,10 +1117,10 @@ public void testCreateTableTrimPropertyKeyWithNereids() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("tbl_trim_property_key_with_nereids"); - Assert.assertEquals(1, table.getMinLoadReplicaNum()); - Assert.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getEnable()); - Assert.assertEquals("DAY", table.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); - Assert.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals(1, table.getMinLoadReplicaNum()); + Assertions.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertEquals("DAY", table.getTableProperty().getDynamicPartitionProperty().getTimeUnit()); + Assertions.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); ExceptionChecker.expectThrowsWithMsg(DdlException.class, "Invalid dynamic partition properties: dynamic_partition. enable", diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/DataPropertyTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/DataPropertyTest.java index a53c18680af97a..03d5b106a3b390 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/DataPropertyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/DataPropertyTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.Config; import org.apache.doris.thrift.TStorageMedium; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class DataPropertyTest { @@ -29,16 +29,16 @@ public class DataPropertyTest { public void testCooldownTimeMs() throws Exception { Config.default_storage_medium = "ssd"; DataProperty dataProperty = new DataProperty(DataProperty.DEFAULT_STORAGE_MEDIUM); - Assert.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); dataProperty = new DataProperty(TStorageMedium.SSD); - Assert.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); long storageCooldownTimeMs = System.currentTimeMillis() + 24 * 3600 * 1000L; dataProperty = new DataProperty(TStorageMedium.SSD, storageCooldownTimeMs, ""); - Assert.assertEquals(storageCooldownTimeMs, dataProperty.getCooldownTimeMs()); + Assertions.assertEquals(storageCooldownTimeMs, dataProperty.getCooldownTimeMs()); dataProperty = new DataProperty(TStorageMedium.HDD); - Assert.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dataProperty.getCooldownTimeMs()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/DataSizeDisplayUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/DataSizeDisplayUtilTest.java index d88397e977a5c0..069391b5f7d514 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/DataSizeDisplayUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/DataSizeDisplayUtilTest.java @@ -23,16 +23,16 @@ import org.apache.doris.common.Config; import org.apache.doris.common.Pair; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DataSizeDisplayUtilTest { private String originDeployMode; private String originCloudUniqueId; - @Before + @BeforeEach public void setUp() { originDeployMode = Config.deploy_mode; originCloudUniqueId = Config.cloud_unique_id; @@ -40,7 +40,7 @@ public void setUp() { Config.cloud_unique_id = ""; } - @After + @AfterEach public void tearDown() { Config.deploy_mode = originDeployMode; Config.cloud_unique_id = originCloudUniqueId; @@ -61,8 +61,8 @@ public void testPartitionDisplaySizeFallbackToReplicaIndexAndSegmentSize() { Partition partition = new Partition(300L, "p1", baseIndex, new RandomDistributionInfo(1)); Pair displayDataSize = DataSizeDisplayUtil.getDisplayDataSize(partition); - Assert.assertEquals(0L, displayDataSize.first.longValue()); - Assert.assertEquals(333L, displayDataSize.second.longValue()); + Assertions.assertEquals(0L, displayDataSize.first.longValue()); + Assertions.assertEquals(333L, displayDataSize.second.longValue()); } @Test @@ -78,8 +78,8 @@ public void testPartitionDisplaySizeMapsCloudDataSizeToRemoteSize() { Partition partition = new Partition(300L, "p1", baseIndex, new RandomDistributionInfo(1)); Pair displayDataSize = DataSizeDisplayUtil.getDisplayDataSize(partition); - Assert.assertEquals(0L, displayDataSize.first.longValue()); - Assert.assertEquals(123L, displayDataSize.second.longValue()); + Assertions.assertEquals(0L, displayDataSize.first.longValue()); + Assertions.assertEquals(123L, displayDataSize.second.longValue()); } @Test @@ -105,8 +105,8 @@ public void testPartitionDisplaySizeAggregatesMixedReplicaDisplaySize() { Partition partition = new Partition(300L, "p1", baseIndex, new RandomDistributionInfo(2)); Pair displayDataSize = DataSizeDisplayUtil.getDisplayDataSize(partition); - Assert.assertEquals(0L, displayDataSize.first.longValue()); - Assert.assertEquals(456L, displayDataSize.second.longValue()); + Assertions.assertEquals(0L, displayDataSize.first.longValue()); + Assertions.assertEquals(456L, displayDataSize.second.longValue()); } @Test @@ -118,7 +118,7 @@ public void testReplicaDisplaySizeFallbackToReplicaIndexAndSegmentSize() { replica.setLocalSegmentSize(222L); Pair displayDataSize = DataSizeDisplayUtil.getDisplayDataSize(replica); - Assert.assertEquals(0L, displayDataSize.first.longValue()); - Assert.assertEquals(333L, displayDataSize.second.longValue()); + Assertions.assertEquals(0L, displayDataSize.first.longValue()); + Assertions.assertEquals(333L, displayDataSize.second.longValue()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/DatabaseTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/DatabaseTest.java index b3c845c7ca2411..37c5472951285e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/DatabaseTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/DatabaseTest.java @@ -28,10 +28,10 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -53,7 +53,7 @@ public class DatabaseTest { private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setup() { FeConstants.runningUnitTest = true; db = new Database(dbId, "dbTest"); @@ -65,7 +65,7 @@ public void setup() { mockedEnvStatic.when(Env::getCurrentEnvJournalVersion).thenReturn(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -74,25 +74,25 @@ public void tearDown() { public void lockTest() { db.readLock(); try { - Assert.assertFalse(db.tryWriteLock(0, TimeUnit.SECONDS)); + Assertions.assertFalse(db.tryWriteLock(0, TimeUnit.SECONDS)); } finally { db.readUnlock(); } db.writeLock(); try { - Assert.assertTrue(db.tryWriteLock(1000, TimeUnit.SECONDS)); + Assertions.assertTrue(db.tryWriteLock(1000, TimeUnit.SECONDS)); db.writeUnlock(); } finally { db.writeUnlock(); } db.markDropped(); - Assert.assertFalse(db.writeLockIfExist()); - Assert.assertFalse(db.isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(db.writeLockIfExist()); + Assertions.assertFalse(db.isWriteLockHeldByCurrentThread()); db.unmarkDropped(); - Assert.assertTrue(db.writeLockIfExist()); - Assert.assertTrue(db.isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(db.writeLockIfExist()); + Assertions.assertTrue(db.isWriteLockHeldByCurrentThread()); db.writeUnlock(); } @@ -116,9 +116,9 @@ public void getTablesOnIdOrderOrThrowExceptionTest() throws MetaNotFoundExceptio db.registerTable(table2); List tableIdList = Lists.newArrayList(2001L, 2000L); List tableList = db.getTablesOnIdOrderOrThrowException(tableIdList); - Assert.assertEquals(2, tableList.size()); - Assert.assertEquals(2000L, tableList.get(0).getId()); - Assert.assertEquals(2001L, tableList.get(1).getId()); + Assertions.assertEquals(2, tableList.size()); + Assertions.assertEquals(2000L, tableList.get(0).getId()); + Assertions.assertEquals(2001L, tableList.get(1).getId()); ExceptionChecker.expectThrowsWithMsg(MetaNotFoundException.class, "table not found, tableId=3000", () -> db.getTablesOnIdOrderOrThrowException(Lists.newArrayList(3000L))); } @@ -131,8 +131,8 @@ public void getTableOrThrowExceptionTest() throws MetaNotFoundException { db.registerTable(table); Table resultTable1 = db.getTableOrMetaException(2000L, Table.TableType.OLAP); Table resultTable2 = db.getTableOrMetaException("baseTable", Table.TableType.OLAP); - Assert.assertEquals(table, resultTable1); - Assert.assertEquals(table, resultTable2); + Assertions.assertEquals(table, resultTable1); + Assertions.assertEquals(table, resultTable2); ExceptionChecker.expectThrowsWithMsg(MetaNotFoundException.class, "table not found, tableId=3000", () -> db.getTableOrMetaException(3000L, Table.TableType.OLAP)); ExceptionChecker.expectThrowsWithMsg(MetaNotFoundException.class, "table not found, tableName=baseTable1", @@ -147,8 +147,8 @@ public void getTableOrThrowExceptionTest() throws MetaNotFoundException { @Test public void createAndDropPartitionTest() { - Assert.assertEquals("dbTest", db.getFullName()); - Assert.assertEquals(dbId, db.getId()); + Assertions.assertEquals("dbTest", db.getFullName()); + Assertions.assertEquals(dbId, db.getId()); MaterializedIndex baseIndex = new MaterializedIndex(10001, IndexState.NORMAL); Partition partition = new Partition(20000L, "baseTable", baseIndex, new RandomDistributionInfo(10)); @@ -158,29 +158,29 @@ public void createAndDropPartitionTest() { table.addPartition(partition); // create - Assert.assertTrue(db.registerTable(table)); + Assertions.assertTrue(db.registerTable(table)); // duplicate - Assert.assertFalse(db.registerTable(table)); + Assertions.assertFalse(db.registerTable(table)); - Assert.assertEquals(table, db.getTableNullable(table.getId())); - Assert.assertEquals(table, db.getTableNullable(table.getName())); + Assertions.assertEquals(table, db.getTableNullable(table.getId())); + Assertions.assertEquals(table, db.getTableNullable(table.getName())); - Assert.assertEquals(1, db.getTables().size()); - Assert.assertEquals(table, db.getTables().get(0)); + Assertions.assertEquals(1, db.getTables().size()); + Assertions.assertEquals(table, db.getTables().get(0)); - Assert.assertEquals(1, db.getTableNamesWithLock().size()); + Assertions.assertEquals(1, db.getTableNamesWithLock().size()); for (String tableFamilyGroupName : db.getTableNamesWithLock()) { - Assert.assertEquals(table.getName(), tableFamilyGroupName); + Assertions.assertEquals(table.getName(), tableFamilyGroupName); } // drop // drop not exist tableFamily db.unregisterTable("invalid"); - Assert.assertEquals(1, db.getTables().size()); + Assertions.assertEquals(1, db.getTables().size()); db.registerTable(table); db.unregisterTable(table.getName()); - Assert.assertEquals(0, db.getTables().size()); + Assertions.assertEquals(0, db.getTables().size()); } @Test @@ -234,10 +234,10 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(path)); Database rDb1 = Database.read(dis); - Assert.assertEquals(rDb1, db1); + Assertions.assertEquals(rDb1, db1); Database rDb2 = Database.read(dis); - Assert.assertEquals(rDb2, db2); + Assertions.assertEquals(rDb2, db2); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/DynamicPartitionTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/DynamicPartitionTableTest.java index 5c0df7c47ad892..eee11b90fbfbe8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/DynamicPartitionTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/DynamicPartitionTableTest.java @@ -42,7 +42,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Range; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -128,7 +127,7 @@ public void testNormal() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("dynamic_partition_normal"); - Assert.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getReplicaAllocation().isNotSet()); + Assertions.assertTrue(table.getTableProperty().getDynamicPartitionProperty().getReplicaAllocation().isNotSet()); // test only set dynamic_partition.replication_num createOlapTblStmt = "CREATE TABLE test.`dynamic_partition_normal2` (\n" @@ -304,8 +303,7 @@ public void testMissBuckets() throws Exception { createTableStmt(createOlapTblStmt); Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("dynamic_partition_miss_buckets"); - Assert.assertEquals("Default buckets should come from table distribution (BUCKETS 32)", - 32, table.getTableProperty().getDynamicPartitionProperty().getBuckets()); + Assertions.assertEquals(32, table.getTableProperty().getDynamicPartitionProperty().getBuckets(), "Default buckets should come from table distribution (BUCKETS 32)"); } @Test @@ -397,9 +395,7 @@ public void testMissTimeZone() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("dynamic_partition_miss_time_zone"); String expectedTz = TimeUtils.getSystemTimeZone().getID(); - Assert.assertEquals("Default timezone should be system timezone", - expectedTz, - table.getTableProperty().getDynamicPartitionProperty().getTimeZone().getID()); + Assertions.assertEquals(expectedTz, table.getTableProperty().getDynamicPartitionProperty().getTimeZone().getID(), "Default timezone should be system timezone"); } @Test @@ -487,13 +483,13 @@ public void testSetDynamicPartitionReplicationNum() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException(tableName); - Assert.assertEquals(1, + Assertions.assertEquals(1, table.getTableProperty().getDynamicPartitionProperty().getReplicaAllocation().getTotalReplicaNum()); String alter1 = "alter table test.dynamic_partition_replication_num set ('dynamic_partition.replication_num' = '0')"; ExceptionChecker.expectThrows(AnalysisException.class, () -> alterTable(alter1)); - Assert.assertEquals(1, + Assertions.assertEquals(1, table.getTableProperty().getDynamicPartitionProperty().getReplicaAllocation().getTotalReplicaNum()); } @@ -524,7 +520,7 @@ public void testCreateDynamicPartitionImmediately() throws Exception { OlapTable emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("empty_dynamic_partition"); - Assert.assertTrue(emptyDynamicTable.getAllPartitions().size() == 4); + Assertions.assertTrue(emptyDynamicTable.getAllPartitions().size() == 4); Iterator partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); List partNames = Lists.newArrayList(); @@ -545,9 +541,9 @@ public void testCreateDynamicPartitionImmediately() throws Exception { calendar.add(calendar.DATE, partitionCount); date = calendar.getTime(); - Assert.assertEquals(partitionDate.getYear(), date.getYear()); - Assert.assertEquals(partitionDate.getMonth(), date.getMonth()); - Assert.assertEquals(partitionDate.getDay(), date.getDay()); + Assertions.assertEquals(partitionDate.getYear(), date.getYear()); + Assertions.assertEquals(partitionDate.getMonth(), date.getMonth()); + Assertions.assertEquals(partitionDate.getDay(), date.getDay()); partitionCount++; } @@ -581,7 +577,7 @@ public void testFillHistoryDynamicPartition() throws Exception { OlapTable emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("histo_dynamic_partition"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); Iterator partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); List partNames = Lists.newArrayList(); @@ -602,9 +598,9 @@ public void testFillHistoryDynamicPartition() throws Exception { calendar.add(calendar.DATE, partitionCount); date = calendar.getTime(); - Assert.assertEquals(partitionDate.getYear(), date.getYear()); - Assert.assertEquals(partitionDate.getMonth(), date.getMonth()); - Assert.assertEquals(partitionDate.getDay(), date.getDay()); + Assertions.assertEquals(partitionDate.getYear(), date.getYear()); + Assertions.assertEquals(partitionDate.getMonth(), date.getMonth()); + Assertions.assertEquals(partitionDate.getDay(), date.getDay()); partitionCount++; } @@ -714,7 +710,7 @@ public void testFillHistoryDynamicPartition3() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable tbl = (OlapTable) db.getTableOrAnalysisException("dynamic_partition3"); - Assert.assertEquals(9, tbl.getPartitionNames().size()); + Assertions.assertEquals(9, tbl.getPartitionNames().size()); // alter dynamic partition property of table dynamic_partition3 // start too small @@ -732,13 +728,13 @@ public void testFillHistoryDynamicPartition3() throws Exception { String alter3 = "alter table test.dynamic_partition3 set ('dynamic_partition.history_partition_num' = '1000')"; ExceptionChecker.expectThrowsNoException(() -> alterTable(alter3)); Env.getCurrentEnv().getDynamicPartitionScheduler().executeDynamicPartitionFirstTime(db.getId(), tbl.getId()); - Assert.assertEquals(14, tbl.getPartitionNames().size()); + Assertions.assertEquals(14, tbl.getPartitionNames().size()); // set start and history_partition_num properly. String alter4 = "alter table test.dynamic_partition3 set ('dynamic_partition.history_partition_num' = '100', 'dynamic_partition.start' = '-20')"; ExceptionChecker.expectThrowsNoException(() -> alterTable(alter4)); Env.getCurrentEnv().getDynamicPartitionScheduler().executeDynamicPartitionFirstTime(db.getId(), tbl.getId()); - Assert.assertEquals(24, tbl.getPartitionNames().size()); + Assertions.assertEquals(24, tbl.getPartitionNames().size()); String createOlapTblStmt5 = "CREATE TABLE test.`dynamic_partition4` (\n" + " `k1` datetime NULL COMMENT \"\"\n" + ")\n" @@ -752,15 +748,15 @@ public void testFillHistoryDynamicPartition3() throws Exception { // start and history_partition_num are set, create ok ExceptionChecker.expectThrowsNoException(() -> createTableStmt(createOlapTblStmt5)); OlapTable tbl4 = (OlapTable) db.getTableOrAnalysisException("dynamic_partition4"); - Assert.assertEquals(9, tbl4.getPartitionNames().size()); + Assertions.assertEquals(9, tbl4.getPartitionNames().size()); String alter5 = "alter table test.dynamic_partition4 set ('dynamic_partition.history_partition_num' = '3')"; ExceptionChecker.expectThrowsNoException(() -> alterTable(alter5)); Env.getCurrentEnv().getDynamicPartitionScheduler().executeDynamicPartitionFirstTime(db.getId(), tbl4.getId()); - Assert.assertEquals(9, tbl4.getPartitionNames().size()); + Assertions.assertEquals(9, tbl4.getPartitionNames().size()); String dropPartitionErr = Env.getCurrentEnv().getDynamicPartitionScheduler() .getRuntimeInfo(tbl4.getId(), DynamicPartitionScheduler.DROP_PARTITION_MSG); - Assert.assertTrue(dropPartitionErr.contains("'dynamic_partition.start' = -99999999, maybe it's too small, " + Assertions.assertTrue(dropPartitionErr.contains("'dynamic_partition.start' = -99999999, maybe it's too small, " + "can use alter table sql to increase it.")); } @@ -788,9 +784,9 @@ public void testFillHistoryDynamicPartitionWithHistoryPartitionNum() throws Exce .getDbOrAnalysisException("test") .getTableOrAnalysisException("history_dynamic_partition_day"); Map tableProperties = emptyDynamicTable.getTableProperty().getProperties(); - Assert.assertEquals(14, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(14, emptyDynamicTable.getAllPartitions().size()); // never delete the old partitions - Assert.assertEquals(Integer.parseInt(tableProperties.get("dynamic_partition.start")), Integer.MIN_VALUE); + Assertions.assertEquals(Integer.parseInt(tableProperties.get("dynamic_partition.start")), Integer.MIN_VALUE); } @Test @@ -811,16 +807,16 @@ public void testAutoPartitionRetentionCountTableRegisteredAfterSchedulerInit() t OlapTable tbl = (OlapTable) db.getTableOrAnalysisException("auto_partition_retention_init"); DynamicPartitionScheduler scheduler = Env.getCurrentEnv().getDynamicPartitionScheduler(); - Assert.assertTrue(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); + Assertions.assertTrue(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); scheduler.removeDynamicPartitionTable(db.getId(), tbl.getId()); - Assert.assertFalse(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); + Assertions.assertFalse(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); Method initDynamicPartitionTable = DynamicPartitionScheduler.class .getDeclaredMethod("initDynamicPartitionTable"); initDynamicPartitionTable.setAccessible(true); initDynamicPartitionTable.invoke(scheduler); - Assert.assertTrue(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); + Assertions.assertTrue(scheduler.containsDynamicPartitionTable(db.getId(), tbl.getId())); } @Test @@ -845,12 +841,12 @@ public void testAllTypeDynamicPartition() throws Exception { createTableStmt(createOlapTblStmt); OlapTable emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test").getTableOrAnalysisException("hour_dynamic_partition"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); Iterator partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(11, partitionName.length()); + Assertions.assertEquals(11, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`week_dynamic_partition` (\n" @@ -873,12 +869,12 @@ public void testAllTypeDynamicPartition() throws Exception { createTableStmt(createOlapTblStmt); emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test").getTableOrAnalysisException("week_dynamic_partition"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(8, partitionName.length()); + Assertions.assertEquals(8, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`month_dynamic_partition` (\n" @@ -902,12 +898,12 @@ public void testAllTypeDynamicPartition() throws Exception { emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("month_dynamic_partition"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(7, partitionName.length()); + Assertions.assertEquals(7, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`year_dynamic_partition` (\n" @@ -931,12 +927,12 @@ public void testAllTypeDynamicPartition() throws Exception { emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("year_dynamic_partition"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(5, partitionName.length()); + Assertions.assertEquals(5, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`int_dynamic_partition_day` (\n" @@ -960,12 +956,12 @@ public void testAllTypeDynamicPartition() throws Exception { emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("int_dynamic_partition_day"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(9, partitionName.length()); + Assertions.assertEquals(9, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`int_dynamic_partition_week` (\n" @@ -989,12 +985,12 @@ public void testAllTypeDynamicPartition() throws Exception { emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("int_dynamic_partition_week"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(8, partitionName.length()); + Assertions.assertEquals(8, partitionName.length()); } createOlapTblStmt = "CREATE TABLE test.`int_dynamic_partition_month` (\n" @@ -1018,12 +1014,12 @@ public void testAllTypeDynamicPartition() throws Exception { emptyDynamicTable = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("int_dynamic_partition_month"); - Assert.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); + Assertions.assertEquals(7, emptyDynamicTable.getAllPartitions().size()); partitionIterator = emptyDynamicTable.getAllPartitions().iterator(); while (partitionIterator.hasNext()) { String partitionName = partitionIterator.next().getName(); - Assert.assertEquals(7, partitionName.length()); + Assertions.assertEquals(7, partitionName.length()); } } @@ -1078,13 +1074,13 @@ public void testHotPartitionNum() throws Exception { OlapTable tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_hour_tbl1"); RangePartitionInfo partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); Map idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(7, idToDataProperty.size()); + Assertions.assertEquals(7, idToDataProperty.size()); int count = 0; for (DataProperty dataProperty : idToDataProperty.values()) { if (count < 3) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } else { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } ++count; } @@ -1111,9 +1107,9 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_hour_tbl2"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(7, idToDataProperty.size()); + Assertions.assertEquals(7, idToDataProperty.size()); for (DataProperty dataProperty : idToDataProperty.values()) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } createOlapTblStmt = "CREATE TABLE test.`hot_partition_hour_tbl3` (\n" @@ -1138,13 +1134,13 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_hour_tbl3"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(7, idToDataProperty.size()); + Assertions.assertEquals(7, idToDataProperty.size()); count = 0; for (DataProperty dataProperty : idToDataProperty.values()) { if (count < 1) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } else { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } ++count; } @@ -1172,13 +1168,13 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_day_tbl1"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(7, idToDataProperty.size()); + Assertions.assertEquals(7, idToDataProperty.size()); int dayCount = 0; for (DataProperty dataProperty : idToDataProperty.values()) { if (dayCount < 2) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } else { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } ++dayCount; } @@ -1205,13 +1201,13 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_day_tbl2"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(8, idToDataProperty.size()); + Assertions.assertEquals(8, idToDataProperty.size()); count = 0; for (DataProperty dataProperty : idToDataProperty.values()) { if (count < 2) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } else { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } ++count; } @@ -1238,13 +1234,13 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_week_tbl1"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(8, idToDataProperty.size()); + Assertions.assertEquals(8, idToDataProperty.size()); count = 0; for (DataProperty dataProperty : idToDataProperty.values()) { if (count < 3) { - Assert.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dataProperty.getStorageMedium()); } else { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } ++count; } @@ -1271,9 +1267,9 @@ public void testHotPartitionNum() throws Exception { tbl = (OlapTable) testDb.getTableOrAnalysisException("hot_partition_month_tbl1"); partitionInfo = (RangePartitionInfo) tbl.getPartitionInfo(); idToDataProperty = new TreeMap<>(partitionInfo.idToDataProperty); - Assert.assertEquals(8, idToDataProperty.size()); + Assertions.assertEquals(8, idToDataProperty.size()); for (DataProperty dataProperty : idToDataProperty.values()) { - Assert.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dataProperty.getStorageMedium()); } } @@ -1340,16 +1336,16 @@ public void testRuntimeInfo() throws Exception { // add scheduler.createOrUpdateRuntimeInfo(tableId, key1, value1); scheduler.createOrUpdateRuntimeInfo(tableId, key2, value2); - Assert.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == value1); + Assertions.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == value1); // modify String value3 = "value2"; scheduler.createOrUpdateRuntimeInfo(tableId, key1, value3); - Assert.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == value3); + Assertions.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == value3); // remove scheduler.removeRuntimeInfo(tableId); - Assert.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == FeConstants.null_string); + Assertions.assertTrue(scheduler.getRuntimeInfo(tableId, key1) == FeConstants.null_string); } @Test @@ -1383,7 +1379,7 @@ public void testMissReservedHistoryPeriods() throws Exception { OlapTable table = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("dynamic_partition_miss_reserved_history_periods"); - Assert.assertEquals("NULL", table.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); + Assertions.assertEquals("NULL", table.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); } @Test @@ -1426,8 +1422,8 @@ public void testNormalReservedHisrotyPeriods() throws Exception { OlapTable table = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("dynamic_partition_normal_reserved_history_periods"); - Assert.assertEquals("[2020-06-01,2020-06-20],[2020-10-25,2020-11-15],[2021-06-01,2021-06-20]", table.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); - Assert.assertEquals(table.getAllPartitions().size(), 9); + Assertions.assertEquals("[2020-06-01,2020-06-20],[2020-10-25,2020-11-15],[2021-06-01,2021-06-20]", table.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); + Assertions.assertEquals(table.getAllPartitions().size(), 9); String createOlapTblStmt2 = "CREATE TABLE test.`dynamic_partition_normal_reserved_history_periods2` (\n" + " `k1` datetime NULL COMMENT \"\",\n" @@ -1461,8 +1457,8 @@ public void testNormalReservedHisrotyPeriods() throws Exception { OlapTable table2 = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("dynamic_partition_normal_reserved_history_periods2"); - Assert.assertEquals("[2014-01-01 00:00:00,2014-01-01 03:00:00]", table2.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); - Assert.assertEquals(table2.getAllPartitions().size(), 6); + Assertions.assertEquals("[2014-01-01 00:00:00,2014-01-01 03:00:00]", table2.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); + Assertions.assertEquals(table2.getAllPartitions().size(), 6); String createOlapTblStmt3 = "CREATE TABLE test.`dynamic_partition_normal_reserved_history_periods3` (\n" + " `k1` int NULL COMMENT \"\",\n" @@ -1492,8 +1488,8 @@ public void testNormalReservedHisrotyPeriods() throws Exception { OlapTable table3 = (OlapTable) Env.getCurrentInternalCatalog() .getDbOrAnalysisException("test") .getTableOrAnalysisException("dynamic_partition_normal_reserved_history_periods3"); - Assert.assertEquals("[2020-06-01,2020-06-30]", table3.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); - Assert.assertEquals(table3.getAllPartitions().size(), 5); + Assertions.assertEquals("[2020-06-01,2020-06-30]", table3.getTableProperty().getDynamicPartitionProperty().getReservedHistoryPeriods()); + Assertions.assertEquals(table3.getAllPartitions().size(), 5); } @Test @@ -1718,10 +1714,10 @@ public void testNoPartition() throws AnalysisException { .getDbOrAnalysisException("test") .getTableOrAnalysisException("no_partition"); Collection partitions = table.getPartitions(); - Assert.assertTrue(partitions.isEmpty()); + Assertions.assertTrue(partitions.isEmpty()); OlapTable copiedTable = table.selectiveCopy(Collections.emptyList(), IndexExtState.VISIBLE, true); partitions = copiedTable.getPartitions(); - Assert.assertTrue(partitions.isEmpty()); + Assertions.assertTrue(partitions.isEmpty()); } @Test @@ -1750,10 +1746,10 @@ public void testRejectDynamicPartitionStorageMediumOnNonDynamicTable() throws Ex Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("non_dynamic_storage_medium"); - Assert.assertFalse(table.dynamicPartitionExists()); - Assert.assertFalse(table.getTableProperty().getProperties() + Assertions.assertFalse(table.dynamicPartitionExists()); + Assertions.assertFalse(table.getTableProperty().getProperties() .containsKey(DynamicPartitionProperty.STORAGE_MEDIUM)); - Assert.assertNotNull(table.selectiveCopy(null, IndexExtState.VISIBLE, true)); + Assertions.assertNotNull(table.selectiveCopy(null, IndexExtState.VISIBLE, true)); } @Test @@ -1782,10 +1778,10 @@ public void testRejectDynamicPartitionStoragePolicyOnNonDynamicTable() throws Ex Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("non_dynamic_storage_policy"); - Assert.assertFalse(table.dynamicPartitionExists()); - Assert.assertFalse(table.getTableProperty().getProperties() + Assertions.assertFalse(table.dynamicPartitionExists()); + Assertions.assertFalse(table.getTableProperty().getProperties() .containsKey(DynamicPartitionProperty.STORAGE_POLICY)); - Assert.assertNotNull(table.selectiveCopy(null, IndexExtState.VISIBLE, true)); + Assertions.assertNotNull(table.selectiveCopy(null, IndexExtState.VISIBLE, true)); } @Test @@ -1814,10 +1810,10 @@ public void testAlterDynamicPartitionStorageMediumOnDynamicTable() throws Except Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("dynamic_storage_medium"); - Assert.assertTrue(table.dynamicPartitionExists()); - Assert.assertEquals("hdd", table.getTableProperty().getDynamicPartitionProperty().getStorageMedium()); - Assert.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); - Assert.assertEquals(1, table.getTableProperty().getDynamicPartitionProperty().getBuckets()); + Assertions.assertTrue(table.dynamicPartitionExists()); + Assertions.assertEquals("hdd", table.getTableProperty().getDynamicPartitionProperty().getStorageMedium()); + Assertions.assertEquals(3, table.getTableProperty().getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals(1, table.getTableProperty().getDynamicPartitionProperty().getBuckets()); } @Test @@ -1917,9 +1913,9 @@ public void testAutoBuckets() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("test_autobucket_dynamic_partition"); List partitions = Lists.newArrayList(table.getAllPartitions()); - Assert.assertEquals(52, partitions.size()); + Assertions.assertEquals(52, partitions.size()); for (Partition partition : partitions) { - Assert.assertEquals(FeConstants.default_bucket_num, partition.getDistributionInfo().getBucketNum()); + Assertions.assertEquals(FeConstants.default_bucket_num, partition.getDistributionInfo().getBucketNum()); partition.setVisibleVersionAndTime(2L, System.currentTimeMillis()); } RebalancerTestUtil.updateReplicaDataSize(1, 1, 1); @@ -1933,8 +1929,8 @@ public void testAutoBuckets() throws Exception { partitions = Lists.newArrayList(table.getAllPartitions()); partitions.sort(Comparator.comparing(Partition::getId)); - Assert.assertEquals(53, partitions.size()); - Assert.assertEquals(3, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); + Assertions.assertEquals(53, partitions.size()); + Assertions.assertEquals(3, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); Config.autobucket_out_of_bounds_percent_threshold = 0.5; table.readLock(); @@ -1945,7 +1941,7 @@ public void testAutoBuckets() throws Exception { partition.updateVisibleVersion(2L); for (MaterializedIndex idx : partition.getMaterializedIndices( MaterializedIndex.IndexExtState.VISIBLE)) { - Assert.assertEquals(10, idx.getTablets().size()); + Assertions.assertEquals(10, idx.getTablets().size()); for (Tablet tablet : idx.getTablets()) { for (Replica replica : tablet.getReplicas()) { replica.updateVersion(2L); @@ -1956,7 +1952,7 @@ public void testAutoBuckets() throws Exception { } if (i >= 40) { // first 52 partitions are 10 buckets(FeConstants.default_bucket_num) - Assert.assertEquals(10 * (10L << 30), partition.getAllDataSize(true)); + Assertions.assertEquals(10 * (10L << 30), partition.getAllDataSize(true)); } } } finally { @@ -1970,9 +1966,9 @@ public void testAutoBuckets() throws Exception { partitions = Lists.newArrayList(table.getAllPartitions()); partitions.sort(Comparator.comparing(Partition::getId)); - Assert.assertEquals(54, partitions.size()); + Assertions.assertEquals(54, partitions.size()); // 100GB total, 5GB per bucket, should 20 buckets. - Assert.assertEquals(20, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); + Assertions.assertEquals(20, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); // mock partition size eq 0, use back-to-back logic table.readLock(); @@ -1984,11 +1980,11 @@ public void testAutoBuckets() throws Exception { for (MaterializedIndex idx : partition.getMaterializedIndices( MaterializedIndex.IndexExtState.VISIBLE)) { if (i < 52) { - Assert.assertEquals(10, idx.getTablets().size()); + Assertions.assertEquals(10, idx.getTablets().size()); } else if (i == 52) { - Assert.assertEquals(3, idx.getTablets().size()); + Assertions.assertEquals(3, idx.getTablets().size()); } else if (i == 53) { - Assert.assertEquals(20, idx.getTablets().size()); + Assertions.assertEquals(20, idx.getTablets().size()); } for (Tablet tablet : idx.getTablets()) { for (Replica replica : tablet.getReplicas()) { @@ -1999,7 +1995,7 @@ public void testAutoBuckets() throws Exception { } } } - Assert.assertEquals(0, partition.getAllDataSize(true)); + Assertions.assertEquals(0, partition.getAllDataSize(true)); } } finally { table.readUnlock(); @@ -2013,9 +2009,9 @@ public void testAutoBuckets() throws Exception { partitions = Lists.newArrayList(table.getAllPartitions()); partitions.sort(Comparator.comparing(Partition::getId)); - Assert.assertEquals(55, partitions.size()); + Assertions.assertEquals(55, partitions.size()); // due to partition size eq 0, use previous partition's(54th) bucket num - Assert.assertEquals(53, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); + Assertions.assertEquals(53, partitions.get(partitions.size() - 1).getDistributionInfo().getBucketNum()); } @Test @@ -2049,7 +2045,7 @@ public void testTimeStampTzDynamicPartition() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("timestamptz_dynamic_partition"); - Assert.assertTrue(table.dynamicPartitionExists()); + Assertions.assertTrue(table.dynamicPartitionExists()); // Execute dynamic partition scheduling Env.getCurrentEnv().getDynamicPartitionScheduler() @@ -2057,7 +2053,7 @@ public void testTimeStampTzDynamicPartition() throws Exception { // Verify total partitions (7 = start(-3) to end(3), inclusive) int partitionCount = table.getPartitionNames().size(); - Assert.assertEquals(7, partitionCount); + Assertions.assertEquals(7, partitionCount); // Verify partition names use configured timezone, boundaries are UTC RangePartitionInfo partitionInfo = (RangePartitionInfo) table.getPartitionInfo(); @@ -2066,39 +2062,32 @@ public void testTimeStampTzDynamicPartition() throws Exception { // Verify the partition name is clean String partitionName = table.getPartition(entry.getKey()).getName(); - Assert.assertTrue("Partition name should start with 'p': " + partitionName, - partitionName.startsWith("p")); - Assert.assertEquals("Partition name should be exactly 9 chars (p + yyyyMMdd): " + partitionName, - 9, partitionName.length()); + Assertions.assertTrue(partitionName.startsWith("p"), "Partition name should start with 'p': " + partitionName); + Assertions.assertEquals(9, partitionName.length(), "Partition name should be exactly 9 chars (p + yyyyMMdd): " + partitionName); // Verify the range endpoints are valid and correctly ordered Range range = item.getItems(); PartitionKey lower = range.lowerEndpoint(); PartitionKey upper = range.upperEndpoint(); - Assert.assertTrue("lower must be < upper: " + range, - lower.compareTo(upper) < 0); + Assertions.assertTrue(lower.compareTo(upper) < 0, "lower must be < upper: " + range); // Verify partition keys are UTC timestamps (with +00:00 suffix) List lowerKeys = lower.getKeys(); - Assert.assertEquals(1, lowerKeys.size()); + Assertions.assertEquals(1, lowerKeys.size()); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC with +00:00 suffix: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC with +00:00 suffix: " + lowerStr); List upperKeys = upper.getKeys(); - Assert.assertEquals(1, upperKeys.size()); + Assertions.assertEquals(1, upperKeys.size()); String upperStr = upperKeys.get(0).getStringValue(); - Assert.assertTrue("Upper key must be UTC with +00:00 suffix: " + upperStr, - upperStr.contains("+00:00")); + Assertions.assertTrue(upperStr.contains("+00:00"), "Upper key must be UTC with +00:00 suffix: " + upperStr); // Partition boundaries must be at UTC midnight (hour=00) // regardless of time_zone. String lowerHour = lowerStr.substring(11, 13); - Assert.assertEquals("Lower bound must be UTC midnight (00): " + lowerStr, - "00", lowerHour); + Assertions.assertEquals("00", lowerHour, "Lower bound must be UTC midnight (00): " + lowerStr); String upperHour = upperStr.substring(11, 13); - Assert.assertEquals("Upper bound must be UTC midnight (00): " + upperStr, - "00", upperHour); + Assertions.assertEquals("00", upperHour, "Upper bound must be UTC midnight (00): " + upperStr); } // Identify the current partition (idx=0) by its stored range @@ -2112,7 +2101,7 @@ public void testTimeStampTzDynamicPartition() throws Exception { RangePartitionItem bi = (RangePartitionItem) b.getValue(); return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sorted.size()); + Assertions.assertEquals(7, sorted.size()); // idx=0 is the 4th partition (index 3) for start=-3,end=3. RangePartitionItem currentItem = (RangePartitionItem) sorted.get(3).getValue(); String currentLowerStr = currentItem.getItems().lowerEndpoint().getKeys().get(0) @@ -2122,14 +2111,12 @@ public void testTimeStampTzDynamicPartition() throws Exception { String expectedCurrentName = "p" + DateTimeFormatter.ofPattern("yyyyMMdd").format(currentLower); String actualCurrentName = table.getPartition(sorted.get(3).getKey()).getName(); - Assert.assertEquals("Current partition (idx=0) name must match its UTC lower bound", - expectedCurrentName, actualCurrentName); - Assert.assertEquals("Current partition lower bound must be UTC midnight", - "00", currentLowerStr.substring(11, 13)); + Assertions.assertEquals(expectedCurrentName, actualCurrentName, "Current partition (idx=0) name must match its UTC lower bound"); + Assertions.assertEquals("00", currentLowerStr.substring(11, 13), "Current partition lower bound must be UTC midnight"); for (Partition partition : table.getPartitions()) { RangePartitionItem item = (RangePartitionItem) partitionInfo.getItem(partition.getId()); - Assert.assertNotNull("Each partition should have a range item", item); + Assertions.assertNotNull(item, "Each partition should have a range item"); } } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); @@ -2167,13 +2154,13 @@ public void testTimeStampTzDynamicPartitionWeekUnit() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("timestamptz_dynamic_week"); - Assert.assertTrue(table.dynamicPartitionExists()); + Assertions.assertTrue(table.dynamicPartitionExists()); Env.getCurrentEnv().getDynamicPartitionScheduler() .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int partitionCount = table.getPartitionNames().size(); - Assert.assertEquals(7, partitionCount); + Assertions.assertEquals(7, partitionCount); // Verify partition boundaries are UTC midnight and names use // configured timezone (Asia/Tokyo). @@ -2181,38 +2168,31 @@ public void testTimeStampTzDynamicPartitionWeekUnit() throws Exception { for (Map.Entry entry : partitionInfo.getIdToItem(false).entrySet()) { RangePartitionItem item = (RangePartitionItem) entry.getValue(); String partitionName = table.getPartition(entry.getKey()).getName(); - Assert.assertTrue("Partition name should start with 'p': " + partitionName, - partitionName.startsWith("p")); + Assertions.assertTrue(partitionName.startsWith("p"), "Partition name should start with 'p': " + partitionName); // Week partition name should be like "p2026_26" (year_week) - Assert.assertFalse("Partition name must not contain timezone: " + partitionName, - partitionName.contains("Asia") || partitionName.contains("Tokyo")); + Assertions.assertFalse(partitionName.contains("Asia") || partitionName.contains("Tokyo"), "Partition name must not contain timezone: " + partitionName); // Verify range validity Range range = item.getItems(); - Assert.assertTrue("lower must be < upper", - range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0); + Assertions.assertTrue(range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0, "lower must be < upper"); // Partition boundaries must be at UTC midnight (hour=00) // regardless of time_zone. List lowerKeys = range.lowerEndpoint().getKeys(); - Assert.assertEquals(1, lowerKeys.size()); + Assertions.assertEquals(1, lowerKeys.size()); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC with +00:00 suffix: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC with +00:00 suffix: " + lowerStr); List upperKeys = range.upperEndpoint().getKeys(); - Assert.assertEquals(1, upperKeys.size()); + Assertions.assertEquals(1, upperKeys.size()); String upperStr = upperKeys.get(0).getStringValue(); - Assert.assertTrue("Upper key must be UTC with +00:00 suffix: " + upperStr, - upperStr.contains("+00:00")); + Assertions.assertTrue(upperStr.contains("+00:00"), "Upper key must be UTC with +00:00 suffix: " + upperStr); // UTC midnight (00:00), regardless of time_zone. String lowerHour = lowerStr.substring(11, 13); - Assert.assertEquals("Lower bound must be UTC midnight (00): " + lowerStr, - "00", lowerHour); + Assertions.assertEquals("00", lowerHour, "Lower bound must be UTC midnight (00): " + lowerStr); String upperHour = upperStr.substring(11, 13); - Assert.assertEquals("Upper bound must be UTC midnight (00): " + upperStr, - "00", upperHour); + Assertions.assertEquals("00", upperHour, "Upper bound must be UTC midnight (00): " + upperStr); } // Identify the current partition (idx=0) by its stored range. @@ -2223,7 +2203,7 @@ public void testTimeStampTzDynamicPartitionWeekUnit() throws Exception { RangePartitionItem bi = (RangePartitionItem) b.getValue(); return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sorted.size()); + Assertions.assertEquals(7, sorted.size()); RangePartitionItem currentItem = (RangePartitionItem) sorted.get(3).getValue(); String currentLowerStr = currentItem.getItems().lowerEndpoint().getKeys().get(0) .getStringValue(); @@ -2240,8 +2220,7 @@ public void testTimeStampTzDynamicPartitionWeekUnit() throws Exception { String expectedWeekName = "p" + DynamicPartitionUtil.getFormattedPartitionName( utcTz, border, prop.getTimeUnit()); String actualCurrentName = table.getPartition(sorted.get(3).getKey()).getName(); - Assert.assertEquals("Current partition (idx=0) week name must match its UTC lower bound", - expectedWeekName, actualCurrentName); + Assertions.assertEquals(expectedWeekName, actualCurrentName, "Current partition (idx=0) week name must match its UTC lower bound"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -2284,13 +2263,13 @@ public void testTimeStampTzDynamicPartitionHourUnit() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("timestamptz_dynamic_hour"); - Assert.assertTrue(table.dynamicPartitionExists()); + Assertions.assertTrue(table.dynamicPartitionExists()); Env.getCurrentEnv().getDynamicPartitionScheduler() .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int partitionCount = table.getPartitionNames().size(); - Assert.assertEquals(7, partitionCount); + Assertions.assertEquals(7, partitionCount); // Hour partition boundaries must be at whole UTC hours // regardless of time_zone. Names use configured timezone. @@ -2308,28 +2287,23 @@ public void testTimeStampTzDynamicPartitionHourUnit() throws Exception { for (Map.Entry entry : sortedEntries) { RangePartitionItem item = (RangePartitionItem) entry.getValue(); String partitionName = table.getPartition(entry.getKey()).getName(); - Assert.assertTrue("Partition name should start with 'p': " + partitionName, - partitionName.startsWith("p")); + Assertions.assertTrue(partitionName.startsWith("p"), "Partition name should start with 'p': " + partitionName); // Hour partition names: p + yyyyMMddHH → length 11 (p + 10 digits) - Assert.assertEquals("Hour partition name length: " + partitionName, - 11, partitionName.length()); + Assertions.assertEquals(11, partitionName.length(), "Hour partition name length: " + partitionName); // Verify range validity Range range = item.getItems(); - Assert.assertTrue("lower must be < upper", - range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0); + Assertions.assertTrue(range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0, "lower must be < upper"); List lowerKeys = range.lowerEndpoint().getKeys(); - Assert.assertEquals(1, lowerKeys.size()); + Assertions.assertEquals(1, lowerKeys.size()); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must have +00:00 suffix: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must have +00:00 suffix: " + lowerStr); List upperKeys = range.upperEndpoint().getKeys(); - Assert.assertEquals(1, upperKeys.size()); + Assertions.assertEquals(1, upperKeys.size()); String upperStr = upperKeys.get(0).getStringValue(); - Assert.assertTrue("Upper key must have +00:00 suffix: " + upperStr, - upperStr.contains("+00:00")); + Assertions.assertTrue(upperStr.contains("+00:00"), "Upper key must have +00:00 suffix: " + upperStr); // Partition boundaries must be at whole UTC hours (minute=second=00). // A configured timezone with a fractional offset (Asia/Kathmandu, @@ -2337,29 +2311,23 @@ public void testTimeStampTzDynamicPartitionHourUnit() throws Exception { // old configured-timezone flooring were used instead of UTC-first. String lowerMinutes = lowerStr.substring(14, 16); String lowerSeconds = lowerStr.substring(17, 19); - Assert.assertEquals("Lower bound minutes must be 00: " + lowerStr, - "00", lowerMinutes); - Assert.assertEquals("Lower bound seconds must be 00: " + lowerStr, - "00", lowerSeconds); + Assertions.assertEquals("00", lowerMinutes, "Lower bound minutes must be 00: " + lowerStr); + Assertions.assertEquals("00", lowerSeconds, "Lower bound seconds must be 00: " + lowerStr); String upperMinutes = upperStr.substring(14, 16); String upperSeconds = upperStr.substring(17, 19); - Assert.assertEquals("Upper bound minutes must be 00: " + upperStr, - "00", upperMinutes); - Assert.assertEquals("Upper bound seconds must be 00: " + upperStr, - "00", upperSeconds); + Assertions.assertEquals("00", upperMinutes, "Upper bound minutes must be 00: " + upperStr); + Assertions.assertEquals("00", upperSeconds, "Upper bound seconds must be 00: " + upperStr); // Verify adjacency using full timestamps (handles midnight crossing) if (prevLower != null) { ZonedDateTime expectedNext = prevLower.plusHours(1); ZonedDateTime actual = ZonedDateTime.parse(lowerStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX")); - Assert.assertEquals("Adjacent partitions' lower bounds must differ by 1 hour", - expectedNext, actual); + Assertions.assertEquals(expectedNext, actual, "Adjacent partitions' lower bounds must differ by 1 hour"); ZonedDateTime expectedUpper = prevUpper.plusHours(1); ZonedDateTime actualUpper = ZonedDateTime.parse(upperStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX")); - Assert.assertEquals("Adjacent partitions' upper bounds must differ by 1 hour", - expectedUpper, actualUpper); + Assertions.assertEquals(expectedUpper, actualUpper, "Adjacent partitions' upper bounds must differ by 1 hour"); } prevLower = ZonedDateTime.parse(lowerStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX")); @@ -2377,14 +2345,11 @@ public void testTimeStampTzDynamicPartitionHourUnit() throws Exception { String expectedCurrentName = "p" + DateTimeFormatter.ofPattern("yyyyMMddHH").format(currentLower); String actualCurrentName = table.getPartition(sortedEntries.get(3).getKey()).getName(); - Assert.assertEquals("Current partition (idx=0) hour name must match its UTC lower bound", - expectedCurrentName, actualCurrentName); + Assertions.assertEquals(expectedCurrentName, actualCurrentName, "Current partition (idx=0) hour name must match its UTC lower bound"); // With a fractional-offset timezone, only the UTC-first approach // guarantees minute=second=00 on every bound. - Assert.assertEquals("Current partition lower bound must end :00:00: " + currentLowerStr, - "00", currentLowerStr.substring(14, 16)); // minutes - Assert.assertEquals("Current partition lower bound must end :00:00: " + currentLowerStr, - "00", currentLowerStr.substring(17, 19)); // seconds + Assertions.assertEquals("00", currentLowerStr.substring(14, 16), "Current partition lower bound must end :00:00: " + currentLowerStr); // minutes + Assertions.assertEquals("00", currentLowerStr.substring(17, 19), "Current partition lower bound must end :00:00: " + currentLowerStr); // seconds } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -2461,7 +2426,7 @@ public void testTimeStampTzDynamicPartitionDropCutoffAligned() throws Exception + "('dynamic_partition.enable' = 'false')"); alterTable("ALTER TABLE test.tstz_drop_cutoff ADD PARTITION p_old VALUES " + "[('" + oldLower + "'), ('" + oldUpper + "'))"); - Assert.assertTrue("p_old should be added", table.getPartitionNames().contains("p_old")); + Assertions.assertTrue(table.getPartitionNames().contains("p_old"), "p_old should be added"); alterTable("ALTER TABLE test.tstz_drop_cutoff SET " + "('dynamic_partition.enable' = 'true')"); @@ -2471,14 +2436,12 @@ public void testTimeStampTzDynamicPartitionDropCutoffAligned() throws Exception // p_old must be dropped by the start=-1 cutoff. // With the fix, the cutoff is at UTC midnight of the previous day, // and p_old (two days ago) is entirely before it. - Assert.assertFalse("p_old should be dropped — drop cutoff must be at UTC midnight," - + " not timezone-offset midnight", - table.getPartitionNames().contains("p_old")); + Assertions.assertFalse(table.getPartitionNames().contains("p_old"), "p_old should be dropped — drop cutoff must be at UTC midnight," + + " not timezone-offset midnight"); // idx=0 (today) and idx=1 (tomorrow) should remain (start=-1, end=1, // create_history_partition=false only creates idx>=0) - Assert.assertEquals("Should have idx=0 and idx=1 partitions after drop", - 2, table.getPartitionNames().size()); + Assertions.assertEquals(2, table.getPartitionNames().size(), "Should have idx=0 and idx=1 partitions after drop"); // Verify remaining partitions have UTC midnight boundaries RangePartitionInfo partitionInfo = (RangePartitionInfo) table.getPartitionInfo(); @@ -2486,10 +2449,8 @@ public void testTimeStampTzDynamicPartitionDropCutoffAligned() throws Exception RangePartitionItem item = (RangePartitionItem) entry.getValue(); List lowerKeys = item.getItems().lowerEndpoint().getKeys(); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC: " + lowerStr, - lowerStr.contains("+00:00")); - Assert.assertEquals("Boundary must be at UTC midnight: " + lowerStr, - "00", lowerStr.substring(11, 13)); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC: " + lowerStr); + Assertions.assertEquals("00", lowerStr.substring(11, 13), "Boundary must be at UTC midnight: " + lowerStr); } } finally { schedulerField.set(Env.getCurrentEnv(), scheduler); @@ -2540,7 +2501,7 @@ public void testAutoPartitionRetentionTimestampTzCutoffNormalized() throws Excep String recentUpper = utcNow.plusHours(4).format(fmt) + "+00:00"; alterTable("ALTER TABLE test.auto_retention_tstz ADD PARTITION p_recent VALUES " + "[('" + recentLower + "'), ('" + recentUpper + "'))"); - Assert.assertEquals(3, tbl.getPartitionNames().size()); + Assertions.assertEquals(3, tbl.getPartitionNames().size()); // Simulate the scheduler thread: remove ConnectContext and set // JVM default to a non-UTC zone. DateUtils.getTimeZone() now @@ -2563,12 +2524,9 @@ public void testAutoPartitionRetentionTimestampTzCutoffNormalized() throws Excep // p_old (2000, oldest history) → dropped by retention_count=1. // p_mid (2020, latest history) → kept. // Total: 2 partitions survive. - Assert.assertEquals("After retention, 2 partitions should remain", 2, - tbl.getPartitionNames().size()); - Assert.assertTrue("p_mid should be kept as the latest history partition", - tbl.getPartitionNames().contains("p_mid")); - Assert.assertTrue("p_recent should survive (not history)", - tbl.getPartitionNames().contains("p_recent")); + Assertions.assertEquals(2, tbl.getPartitionNames().size(), "After retention, 2 partitions should remain"); + Assertions.assertTrue(tbl.getPartitionNames().contains("p_mid"), "p_mid should be kept as the latest history partition"); + Assertions.assertTrue(tbl.getPartitionNames().contains("p_recent"), "p_recent should survive (not history)"); } finally { TimeZone.setDefault(originalJvmTz); connectContext.getSessionVariable().setTimeZone(originalSessionTz); @@ -2614,7 +2572,7 @@ public void testTimeStampTzGetHistoricalPartitionsRangeBased() throws Exception .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int totalPartitions = table.getPartitionNames().size(); - Assert.assertEquals(7, totalPartitions); + Assertions.assertEquals(7, totalPartitions); RangePartitionInfo info = (RangePartitionInfo) table.getPartitionInfo(); DynamicPartitionProperty prop = table.getTableProperty().getDynamicPartitionProperty(); @@ -2641,9 +2599,8 @@ public void testTimeStampTzGetHistoricalPartitionsRangeBased() throws Exception break; } } - Assert.assertTrue("Name-based should fail to exclude current partition: " - + "nowPartitionName='" + wrongNowPartitionName + "' does not match any partition", - currentFoundByName); + Assertions.assertTrue(currentFoundByName, "Name-based should fail to exclude current partition: " + + "nowPartitionName='" + wrongNowPartitionName + "' does not match any partition"); // 2. With the correct nowPartitionName matching the current partition's // actual name, name-based exclusion correctly removes it. @@ -2656,7 +2613,7 @@ public void testTimeStampTzGetHistoricalPartitionsRangeBased() throws Exception break; } } - Assert.assertNotNull("Should find the current partition", currentPartitionName); + Assertions.assertNotNull(currentPartitionName, "Should find the current partition"); List historicalWithName = DynamicPartitionScheduler.getHistoricalPartitions( table, currentPartitionName); boolean currentFoundByName2 = false; @@ -2668,10 +2625,8 @@ public void testTimeStampTzGetHistoricalPartitionsRangeBased() throws Exception break; } } - Assert.assertFalse("Name-based should exclude the current partition when name matches", - currentFoundByName2); - Assert.assertEquals("Should exclude exactly the current partition", - totalPartitions - 1, historicalWithName.size()); + Assertions.assertFalse(currentFoundByName2, "Name-based should exclude the current partition when name matches"); + Assertions.assertEquals(totalPartitions - 1, historicalWithName.size(), "Should exclude exactly the current partition"); } @Test @@ -2706,13 +2661,13 @@ public void testTimeStampTzDynamicPartitionMonthUnit() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("timestamptz_dynamic_month"); - Assert.assertTrue(table.dynamicPartitionExists()); + Assertions.assertTrue(table.dynamicPartitionExists()); Env.getCurrentEnv().getDynamicPartitionScheduler() .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int partitionCount = table.getPartitionNames().size(); - Assert.assertEquals(7, partitionCount); + Assertions.assertEquals(7, partitionCount); // Verify partition boundaries are UTC midnight and names use // configured timezone (Asia/Shanghai). @@ -2720,41 +2675,33 @@ public void testTimeStampTzDynamicPartitionMonthUnit() throws Exception { for (Map.Entry entry : partitionInfo.getIdToItem(false).entrySet()) { RangePartitionItem item = (RangePartitionItem) entry.getValue(); String partitionName = table.getPartition(entry.getKey()).getName(); - Assert.assertTrue("Partition name should start with 'p': " + partitionName, - partitionName.startsWith("p")); + Assertions.assertTrue(partitionName.startsWith("p"), "Partition name should start with 'p': " + partitionName); // Month partition names: p + yyyyMM → length 7 - Assert.assertEquals("Month partition name length: " + partitionName, - 7, partitionName.length()); + Assertions.assertEquals(7, partitionName.length(), "Month partition name length: " + partitionName); // Verify range validity Range range = item.getItems(); - Assert.assertTrue("lower must be < upper", - range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0); + Assertions.assertTrue(range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0, "lower must be < upper"); // Partition boundaries must be UTC timestamps with +00:00 suffix. List lowerKeys = range.lowerEndpoint().getKeys(); - Assert.assertEquals(1, lowerKeys.size()); + Assertions.assertEquals(1, lowerKeys.size()); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC with +00:00 suffix: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC with +00:00 suffix: " + lowerStr); List upperKeys = range.upperEndpoint().getKeys(); - Assert.assertEquals(1, upperKeys.size()); + Assertions.assertEquals(1, upperKeys.size()); String upperStr = upperKeys.get(0).getStringValue(); - Assert.assertTrue("Upper key must be UTC with +00:00 suffix: " + upperStr, - upperStr.contains("+00:00")); + Assertions.assertTrue(upperStr.contains("+00:00"), "Upper key must be UTC with +00:00 suffix: " + upperStr); // Partition boundaries must be at UTC midnight (hour=00) // regardless of time_zone. Day should be 01 (first of month). String lowerDay = lowerStr.substring(8, 10); - Assert.assertEquals("Lower bound must be day 01 for month unit: " + lowerStr, - "01", lowerDay); + Assertions.assertEquals("01", lowerDay, "Lower bound must be day 01 for month unit: " + lowerStr); String lowerHour = lowerStr.substring(11, 13); - Assert.assertEquals("Lower bound must be UTC midnight (00): " + lowerStr, - "00", lowerHour); + Assertions.assertEquals("00", lowerHour, "Lower bound must be UTC midnight (00): " + lowerStr); String upperHour = upperStr.substring(11, 13); - Assert.assertEquals("Upper bound must be UTC midnight (00): " + upperStr, - "00", upperHour); + Assertions.assertEquals("00", upperHour, "Upper bound must be UTC midnight (00): " + upperStr); } // Identify the current partition (idx=0) by its stored range. @@ -2765,7 +2712,7 @@ public void testTimeStampTzDynamicPartitionMonthUnit() throws Exception { RangePartitionItem bi = (RangePartitionItem) b.getValue(); return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sorted.size()); + Assertions.assertEquals(7, sorted.size()); RangePartitionItem currentItem = (RangePartitionItem) sorted.get(3).getValue(); String currentLowerStr = currentItem.getItems().lowerEndpoint().getKeys().get(0) .getStringValue(); @@ -2774,12 +2721,9 @@ public void testTimeStampTzDynamicPartitionMonthUnit() throws Exception { String expectedCurrentName = "p" + DateTimeFormatter.ofPattern("yyyyMM").format(currentLower); String actualCurrentName = table.getPartition(sorted.get(3).getKey()).getName(); - Assert.assertEquals("Current partition (idx=0) month name must match its UTC lower bound", - expectedCurrentName, actualCurrentName); - Assert.assertEquals("Current partition lower bound must be UTC midnight", - "00", currentLowerStr.substring(11, 13)); - Assert.assertEquals("Current partition lower bound day must be 01", - "01", currentLowerStr.substring(8, 10)); + Assertions.assertEquals(expectedCurrentName, actualCurrentName, "Current partition (idx=0) month name must match its UTC lower bound"); + Assertions.assertEquals("00", currentLowerStr.substring(11, 13), "Current partition lower bound must be UTC midnight"); + Assertions.assertEquals("01", currentLowerStr.substring(8, 10), "Current partition lower bound day must be 01"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -2817,13 +2761,13 @@ public void testTimeStampTzDynamicPartitionYearUnit() throws Exception { Database db = Env.getCurrentInternalCatalog().getDbOrAnalysisException("test"); OlapTable table = (OlapTable) db.getTableOrAnalysisException("timestamptz_dynamic_year"); - Assert.assertTrue(table.dynamicPartitionExists()); + Assertions.assertTrue(table.dynamicPartitionExists()); Env.getCurrentEnv().getDynamicPartitionScheduler() .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int partitionCount = table.getPartitionNames().size(); - Assert.assertEquals(7, partitionCount); + Assertions.assertEquals(7, partitionCount); // Verify partition boundaries are UTC midnight and names use // configured timezone (Asia/Shanghai). @@ -2831,44 +2775,35 @@ public void testTimeStampTzDynamicPartitionYearUnit() throws Exception { for (Map.Entry entry : partitionInfo.getIdToItem(false).entrySet()) { RangePartitionItem item = (RangePartitionItem) entry.getValue(); String partitionName = table.getPartition(entry.getKey()).getName(); - Assert.assertTrue("Partition name should start with 'p': " + partitionName, - partitionName.startsWith("p")); + Assertions.assertTrue(partitionName.startsWith("p"), "Partition name should start with 'p': " + partitionName); // Year partition names: p + yyyy → length 5 - Assert.assertEquals("Year partition name length: " + partitionName, - 5, partitionName.length()); + Assertions.assertEquals(5, partitionName.length(), "Year partition name length: " + partitionName); // Verify range validity Range range = item.getItems(); - Assert.assertTrue("lower must be < upper", - range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0); + Assertions.assertTrue(range.lowerEndpoint().compareTo(range.upperEndpoint()) < 0, "lower must be < upper"); // Partition boundaries must be UTC timestamps with +00:00 suffix. List lowerKeys = range.lowerEndpoint().getKeys(); - Assert.assertEquals(1, lowerKeys.size()); + Assertions.assertEquals(1, lowerKeys.size()); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC with +00:00 suffix: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC with +00:00 suffix: " + lowerStr); List upperKeys = range.upperEndpoint().getKeys(); - Assert.assertEquals(1, upperKeys.size()); + Assertions.assertEquals(1, upperKeys.size()); String upperStr = upperKeys.get(0).getStringValue(); - Assert.assertTrue("Upper key must be UTC with +00:00 suffix: " + upperStr, - upperStr.contains("+00:00")); + Assertions.assertTrue(upperStr.contains("+00:00"), "Upper key must be UTC with +00:00 suffix: " + upperStr); // Partition boundaries must be at UTC midnight (hour=00) // regardless of time_zone. Month should be 01, day should be 01. String lowerMonth = lowerStr.substring(5, 7); - Assert.assertEquals("Lower bound must be month 01 for year unit: " + lowerStr, - "01", lowerMonth); + Assertions.assertEquals("01", lowerMonth, "Lower bound must be month 01 for year unit: " + lowerStr); String lowerDay = lowerStr.substring(8, 10); - Assert.assertEquals("Lower bound must be day 01 for year unit: " + lowerStr, - "01", lowerDay); + Assertions.assertEquals("01", lowerDay, "Lower bound must be day 01 for year unit: " + lowerStr); String lowerHour = lowerStr.substring(11, 13); - Assert.assertEquals("Lower bound must be UTC midnight (00): " + lowerStr, - "00", lowerHour); + Assertions.assertEquals("00", lowerHour, "Lower bound must be UTC midnight (00): " + lowerStr); String upperHour = upperStr.substring(11, 13); - Assert.assertEquals("Upper bound must be UTC midnight (00): " + upperStr, - "00", upperHour); + Assertions.assertEquals("00", upperHour, "Upper bound must be UTC midnight (00): " + upperStr); } // Identify the current partition (idx=0) by its stored range. @@ -2879,7 +2814,7 @@ public void testTimeStampTzDynamicPartitionYearUnit() throws Exception { RangePartitionItem bi = (RangePartitionItem) b.getValue(); return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sorted.size()); + Assertions.assertEquals(7, sorted.size()); RangePartitionItem currentItem = (RangePartitionItem) sorted.get(3).getValue(); String currentLowerStr = currentItem.getItems().lowerEndpoint().getKeys().get(0) .getStringValue(); @@ -2888,14 +2823,10 @@ public void testTimeStampTzDynamicPartitionYearUnit() throws Exception { String expectedCurrentName = "p" + DateTimeFormatter.ofPattern("yyyy").format(currentLower); String actualCurrentName = table.getPartition(sorted.get(3).getKey()).getName(); - Assert.assertEquals("Current partition (idx=0) year name must match its UTC lower bound", - expectedCurrentName, actualCurrentName); - Assert.assertEquals("Current partition lower bound must be UTC midnight", - "00", currentLowerStr.substring(11, 13)); - Assert.assertEquals("Current partition lower bound month must be 01", - "01", currentLowerStr.substring(5, 7)); - Assert.assertEquals("Current partition lower bound day must be 01", - "01", currentLowerStr.substring(8, 10)); + Assertions.assertEquals(expectedCurrentName, actualCurrentName, "Current partition (idx=0) year name must match its UTC lower bound"); + Assertions.assertEquals("00", currentLowerStr.substring(11, 13), "Current partition lower bound must be UTC midnight"); + Assertions.assertEquals("01", currentLowerStr.substring(5, 7), "Current partition lower bound month must be 01"); + Assertions.assertEquals("01", currentLowerStr.substring(8, 10), "Current partition lower bound day must be 01"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -2958,12 +2889,9 @@ public void testTimeStampTzReservedHistoryPeriodsUtcAligned() throws Exception { alterTable("ALTER TABLE test.tstz_reserved_hist ADD PARTITION p_boundary VALUES " + "[('2020-07-31 17:00:00+00:00'), ('2020-07-31 18:00:00+00:00'))"); - Assert.assertTrue("p_202001 should exist before scheduling", - table.getPartitionNames().contains("p_202001")); - Assert.assertTrue("p_old should exist before scheduling", - table.getPartitionNames().contains("p_old")); - Assert.assertTrue("p_boundary should exist before scheduling", - table.getPartitionNames().contains("p_boundary")); + Assertions.assertTrue(table.getPartitionNames().contains("p_202001"), "p_202001 should exist before scheduling"); + Assertions.assertTrue(table.getPartitionNames().contains("p_old"), "p_old should exist before scheduling"); + Assertions.assertTrue(table.getPartitionNames().contains("p_boundary"), "p_boundary should exist before scheduling"); // Re-enable dynamic partition and run the scheduler. alterTable("ALTER TABLE test.tstz_reserved_hist SET " @@ -2974,18 +2902,15 @@ public void testTimeStampTzReservedHistoryPeriodsUtcAligned() throws Exception { // p_202001 falls within the reserved period in both old and new // interpretations — kept regardless. - Assert.assertTrue("p_202001 should be kept", - table.getPartitionNames().contains("p_202001")); + Assertions.assertTrue(table.getPartitionNames().contains("p_202001"), "p_202001 should be kept"); // p_old is before the start=-3 cutoff and outside the reserved // period — dropped regardless. - Assert.assertFalse("p_old should be dropped", - table.getPartitionNames().contains("p_old")); + Assertions.assertFalse(table.getPartitionNames().contains("p_old"), "p_old should be dropped"); // p_boundary is the discriminating case: only kept when the // reserved period is interpreted in UTC rather than shifted by // the configured timezone (Asia/Shanghai, UTC+8). - Assert.assertTrue("p_boundary should be kept — reserved period is UTC-aligned," - + " not shifted by the configured timezone", - table.getPartitionNames().contains("p_boundary")); + Assertions.assertTrue(table.getPartitionNames().contains("p_boundary"), "p_boundary should be kept — reserved period is UTC-aligned," + + " not shifted by the configured timezone"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -3041,7 +2966,7 @@ public void testTimeStampTzHotPartitionCooldownUtcAligned() throws Exception { return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sortedEntries.size()); + Assertions.assertEquals(7, sortedEntries.size()); // Partitions idx=-3,-2,-1 are before the hot range → HDD. // Partitions idx=0..3 (4 partitions) are within hot_partition_num=1: @@ -3061,19 +2986,16 @@ public void testTimeStampTzHotPartitionCooldownUtcAligned() throws Exception { if (i < 3) { // Historical partitions: HDD - Assert.assertEquals("Historical partition should be HDD: idx=" + (i - 3), - TStorageMedium.HDD, dp.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dp.getStorageMedium(), "Historical partition should be HDD: idx=" + (i - 3)); } else { // Hot partitions: SSD - Assert.assertEquals("Hot partition should be SSD: idx=" + (i - 3), - TStorageMedium.SSD, dp.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.SSD, dp.getStorageMedium(), "Hot partition should be SSD: idx=" + (i - 3)); // Every hot partition must have a finite cooldown equal to // that partition's upper endpoint (offset + hotPartitionNum). // Assert it is NOT the MAX fallback, which would indicate // the TIMESTAMPTZ lifecycle string was rejected during parse. - Assert.assertNotEquals("Hot partition must have a finite cooldown: idx=" + (i - 3), - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertNotEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "Hot partition must have a finite cooldown: idx=" + (i - 3)); ZonedDateTime cooldownUtc = ZonedDateTime.ofInstant( java.time.Instant.ofEpochMilli(dp.getCooldownTimeMs()), @@ -3084,18 +3006,15 @@ public void testTimeStampTzHotPartitionCooldownUtcAligned() throws Exception { ZonedDateTime upperUtc = ZonedDateTime.parse(upperStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX")); - Assert.assertEquals("Cooldown must equal the partition upper bound (" - + upperUtc + "): idx=" + (i - 3), - upperUtc.toInstant(), cooldownUtc.toInstant()); + Assertions.assertEquals(upperUtc.toInstant(), cooldownUtc.toInstant(), "Cooldown must equal the partition upper bound (" + + upperUtc + "): idx=" + (i - 3)); } // Verify partition boundaries are UTC midnight. List lowerKeys = item.getItems().lowerEndpoint().getKeys(); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC: " + lowerStr, - lowerStr.contains("+00:00")); - Assert.assertEquals("Lower bound must be at UTC midnight: " + lowerStr, - "00", lowerStr.substring(11, 13)); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC: " + lowerStr); + Assertions.assertEquals("00", lowerStr.substring(11, 13), "Lower bound must be at UTC midnight: " + lowerStr); } } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); @@ -3158,7 +3077,7 @@ public void testTimeStampTzHotPartitionCooldownDstMonth() throws Exception { return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sortedEntries.size()); + Assertions.assertEquals(7, sortedEntries.size()); // idx=-3,-2,-1: offset+6=3,2,1 >0 → SSD (hot) // idx=0..3: offset+6=6,7,8,9 >0 → SSD (hot) @@ -3179,10 +3098,8 @@ public void testTimeStampTzHotPartitionCooldownDstMonth() throws Exception { RangePartitionItem item = (RangePartitionItem) entry.getValue(); DataProperty dp = partitionInfo.getDataProperty(entry.getKey()); - Assert.assertEquals("All partitions should be SSD with hot_partition_num=6", - TStorageMedium.SSD, dp.getStorageMedium()); - Assert.assertNotEquals("Hot partition must have a finite cooldown", - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertEquals(TStorageMedium.SSD, dp.getStorageMedium(), "All partitions should be SSD with hot_partition_num=6"); + Assertions.assertNotEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "Hot partition must have a finite cooldown"); // Cooldown is the lower bound of the (idx + hotPartitionNum)-th // partition. Derive it from the current partition's lower bound @@ -3191,20 +3108,16 @@ public void testTimeStampTzHotPartitionCooldownDstMonth() throws Exception { java.time.Instant.ofEpochMilli(dp.getCooldownTimeMs()), ZoneOffset.UTC); ZonedDateTime expectedUtc = currentLower.plusMonths(idx + 6); - Assert.assertEquals("Cooldown must equal lower bound of partition at offset " - + (idx + 6) + " (" + expectedUtc + "): idx=" + idx, - expectedUtc.toInstant(), cooldownUtc.toInstant()); + Assertions.assertEquals(expectedUtc.toInstant(), cooldownUtc.toInstant(), "Cooldown must equal lower bound of partition at offset " + + (idx + 6) + " (" + expectedUtc + "): idx=" + idx); // Verify partition boundaries are UTC midnight, day=01. List lowerKeys = item.getItems().lowerEndpoint().getKeys(); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC: " + lowerStr, - lowerStr.contains("+00:00")); - Assert.assertEquals("Lower bound must be at UTC midnight: " + lowerStr, - "00", lowerStr.substring(11, 13)); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC: " + lowerStr); + Assertions.assertEquals("00", lowerStr.substring(11, 13), "Lower bound must be at UTC midnight: " + lowerStr); // Month boundaries must fall on the first day of the month. - Assert.assertEquals("Month lower bound day must be 01: " + lowerStr, - "01", lowerStr.substring(8, 10)); + Assertions.assertEquals("01", lowerStr.substring(8, 10), "Month lower bound day must be 01: " + lowerStr); } } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); @@ -3264,7 +3177,7 @@ public void testTimeStampTzHotPartitionCooldownDstFallback() throws Exception { return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals(7, sortedEntries.size()); + Assertions.assertEquals(7, sortedEntries.size()); // Derive the expected cooldown from the current partition's // stored lower bound rather than sampling ZonedDateTime.now(), @@ -3284,15 +3197,12 @@ public void testTimeStampTzHotPartitionCooldownDstFallback() throws Exception { // idx=-3,-2,-1: offset+1 ≤ 0 → HDD (MAX_COOLDOWN_TIME_MS) // idx=0,1,2,3: offset+1 > 0 → SSD (finite cooldown) if (idx + 1 <= 0) { - Assert.assertEquals("Historical partition should be HDD: idx=" + idx, - TStorageMedium.HDD, dp.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dp.getStorageMedium(), "Historical partition should be HDD: idx=" + idx); continue; } - Assert.assertEquals("Hot partition should be SSD: idx=" + idx, - TStorageMedium.SSD, dp.getStorageMedium()); - Assert.assertNotEquals("Hot partition must have a finite cooldown: idx=" + idx, - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertEquals(TStorageMedium.SSD, dp.getStorageMedium(), "Hot partition should be SSD: idx=" + idx); + Assertions.assertNotEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "Hot partition must have a finite cooldown: idx=" + idx); // Cooldown is the lower bound of the (idx + hotPartitionNum)-th // partition. Derive it from the current partition's lower bound @@ -3301,18 +3211,15 @@ public void testTimeStampTzHotPartitionCooldownDstFallback() throws Exception { java.time.Instant.ofEpochMilli(dp.getCooldownTimeMs()), ZoneOffset.UTC); ZonedDateTime expectedUtc = currentLower.plusHours(idx + 1); - Assert.assertEquals("Cooldown must equal lower bound of partition at offset " - + (idx + 1) + " (" + expectedUtc + "): idx=" + idx, - expectedUtc.toInstant(), cooldownUtc.toInstant()); + Assertions.assertEquals(expectedUtc.toInstant(), cooldownUtc.toInstant(), "Cooldown must equal lower bound of partition at offset " + + (idx + 1) + " (" + expectedUtc + "): idx=" + idx); // Hour boundaries must be at whole UTC hours. List lowerKeys = item.getItems().lowerEndpoint().getKeys(); String lowerStr = lowerKeys.get(0).getStringValue(); - Assert.assertTrue("Lower key must be UTC: " + lowerStr, - lowerStr.contains("+00:00")); + Assertions.assertTrue(lowerStr.contains("+00:00"), "Lower key must be UTC: " + lowerStr); int lowerHour = Integer.parseInt(lowerStr.substring(11, 13)); - Assert.assertTrue("Lower bound hour must be 0-23: " + lowerStr, - lowerHour >= 0 && lowerHour <= 23); + Assertions.assertTrue(lowerHour >= 0 && lowerHour <= 23, "Lower bound hour must be 0-23: " + lowerStr); } } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); @@ -3376,8 +3283,7 @@ public void testTimeStampTzHotPartitionCooldownFractionalSeconds() throws Except return ai.getItems().lowerEndpoint().compareTo(bi.getItems().lowerEndpoint()); }); - Assert.assertEquals("TIMESTAMPTZ(" + precision + "): partition count", - 7, sortedEntries.size()); + Assertions.assertEquals(7, sortedEntries.size(), "TIMESTAMPTZ(" + precision + "): partition count"); // Hot partitions must have finite cooldown, not // MAX_COOLDOWN_TIME_MS (which would mean the cooldown @@ -3395,16 +3301,13 @@ public void testTimeStampTzHotPartitionCooldownFractionalSeconds() throws Except DataProperty dp = partitionInfo.getDataProperty(entry.getKey()); if (i < 3) { - Assert.assertEquals("TIMESTAMPTZ(" + precision - + ") historical partition should be HDD: idx=" + idx, - TStorageMedium.HDD, dp.getStorageMedium()); + Assertions.assertEquals(TStorageMedium.HDD, dp.getStorageMedium(), "TIMESTAMPTZ(" + precision + + ") historical partition should be HDD: idx=" + idx); } else { - Assert.assertEquals("TIMESTAMPTZ(" + precision - + ") hot partition should be SSD: idx=" + idx, - TStorageMedium.SSD, dp.getStorageMedium()); - Assert.assertNotEquals("TIMESTAMPTZ(" + precision - + ") cooldown must be finite (not MAX): idx=" + idx, - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertEquals(TStorageMedium.SSD, dp.getStorageMedium(), "TIMESTAMPTZ(" + precision + + ") hot partition should be SSD: idx=" + idx); + Assertions.assertNotEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "TIMESTAMPTZ(" + precision + + ") cooldown must be finite (not MAX): idx=" + idx); ZonedDateTime cooldownUtc = ZonedDateTime.ofInstant( java.time.Instant.ofEpochMilli(dp.getCooldownTimeMs()), @@ -3412,9 +3315,8 @@ public void testTimeStampTzHotPartitionCooldownFractionalSeconds() throws Except String upperStr = item.getItems().upperEndpoint().getKeys().get(0) .getStringValue(); ZonedDateTime upperUtc = ZonedDateTime.parse(upperStr, boundFmt); - Assert.assertEquals("TIMESTAMPTZ(" + precision - + ") cooldown must equal partition upper bound: idx=" + idx, - upperUtc.toInstant(), cooldownUtc.toInstant()); + Assertions.assertEquals(upperUtc.toInstant(), cooldownUtc.toInstant(), "TIMESTAMPTZ(" + precision + + ") cooldown must equal partition upper bound: idx=" + idx); } } } @@ -3461,15 +3363,14 @@ public void testTimeStampTzGetHistoricalPartitionsScaledColumn() throws Exceptio .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int totalPartitions = table.getPartitionNames().size(); - Assert.assertEquals(7, totalPartitions); + Assertions.assertEquals(7, totalPartitions); RangePartitionInfo info = (RangePartitionInfo) table.getPartitionInfo(); // Verify that stored lower keys actually have .000000 fractional part. for (PartitionItem item : info.getIdToItem(false).values()) { RangePartitionItem rItem = (RangePartitionItem) item; String lowerStr = rItem.getItems().lowerEndpoint().getKeys().get(0).getStringValue(); - Assert.assertTrue("TIMESTAMPTZ(6) lower key must include .000000: " + lowerStr, - lowerStr.contains(".000000")); + Assertions.assertTrue(lowerStr.contains(".000000"), "TIMESTAMPTZ(6) lower key must include .000000: " + lowerStr); } // Compute currentUtcBorder (no fractional seconds). @@ -3478,8 +3379,8 @@ public void testTimeStampTzGetHistoricalPartitionsScaledColumn() throws Exceptio info.getPartitionColumns().get(0)); String currentUtcBorder = DynamicPartitionUtil.getPartitionRangeString( prop, ZonedDateTime.now(ZoneOffset.UTC), 0, partitionFormat); - Assert.assertFalse("currentUtcBorder should NOT contain fractional seconds: " - + currentUtcBorder, currentUtcBorder.contains(".")); + Assertions.assertFalse(currentUtcBorder.contains("."), "currentUtcBorder should NOT contain fractional seconds: " + + currentUtcBorder); // Without currentUtcBorder: name-based cannot identify the current // partition when nowPartitionName does not match. @@ -3495,8 +3396,7 @@ public void testTimeStampTzGetHistoricalPartitionsScaledColumn() throws Exceptio break; } } - Assert.assertTrue("Scaled TIMESTAMPTZ(6): name-based should fail to exclude current partition", - currentFoundByName); + Assertions.assertTrue(currentFoundByName, "Scaled TIMESTAMPTZ(6): name-based should fail to exclude current partition"); // With the correct nowPartitionName matching the current partition's // actual name, name-based exclusion works correctly even when the @@ -3510,7 +3410,7 @@ public void testTimeStampTzGetHistoricalPartitionsScaledColumn() throws Exceptio break; } } - Assert.assertNotNull("Should find the current partition", currentPartitionName); + Assertions.assertNotNull(currentPartitionName, "Should find the current partition"); List historicalWithName = DynamicPartitionScheduler.getHistoricalPartitions( table, currentPartitionName); boolean currentFoundByNameCorrect = false; @@ -3522,10 +3422,9 @@ public void testTimeStampTzGetHistoricalPartitionsScaledColumn() throws Exceptio break; } } - Assert.assertFalse("Scaled TIMESTAMPTZ(6): name-based must exclude current partition " - + "when nowPartitionName matches", currentFoundByNameCorrect); - Assert.assertEquals("Scaled TIMESTAMPTZ(6): exclude exactly one partition", - totalPartitions - 1, historicalWithName.size()); + Assertions.assertFalse(currentFoundByNameCorrect, "Scaled TIMESTAMPTZ(6): name-based must exclude current partition " + + "when nowPartitionName matches"); + Assertions.assertEquals(totalPartitions - 1, historicalWithName.size(), "Scaled TIMESTAMPTZ(6): exclude exactly one partition"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -3570,12 +3469,11 @@ public void testTimeStampTzGetHistoricalPartitionsOldPrefix() throws Exception { .executeDynamicPartitionFirstTime(db.getId(), table.getId()); int totalPartitions = table.getPartitionNames().size(); - Assert.assertEquals("Initial partitions should be 7", 7, totalPartitions); + Assertions.assertEquals(7, totalPartitions, "Initial partitions should be 7"); // Verify all existing partitions use the old prefix "p". for (String name : table.getPartitionNames()) { - Assert.assertTrue("Existing partitions must use old prefix: " + name, - name.startsWith("p")); + Assertions.assertTrue(name.startsWith("p"), "Existing partitions must use old prefix: " + name); } // Now change the prefix from "p" to "q" via table properties. @@ -3586,7 +3484,7 @@ public void testTimeStampTzGetHistoricalPartitionsOldPrefix() throws Exception { // Re-read the dynamic property to get the updated prefix. DynamicPartitionProperty updatedProp = table.getTableProperty().getDynamicPartitionProperty(); - Assert.assertEquals("Prefix should now be 'q'", "q", updatedProp.getPrefix()); + Assertions.assertEquals("q", updatedProp.getPrefix(), "Prefix should now be 'q'"); // Compute currentUtcBorder from the scheduler's logic. RangePartitionInfo info = (RangePartitionInfo) table.getPartitionInfo(); @@ -3612,8 +3510,7 @@ public void testTimeStampTzGetHistoricalPartitionsOldPrefix() throws Exception { break; } } - Assert.assertTrue("Old prefix: name-based should fail to exclude current partition", - currentFoundByName); + Assertions.assertTrue(currentFoundByName, "Old prefix: name-based should fail to exclude current partition"); // 2. With the correct nowPartitionName (the actual partition name // with old prefix "p"), name-based exclusion works. @@ -3626,8 +3523,8 @@ public void testTimeStampTzGetHistoricalPartitionsOldPrefix() throws Exception { break; } } - Assert.assertNotNull("Should find the current partition", currentPartitionName); - Assert.assertTrue("Current partition should start with 'p'", currentPartitionName.startsWith("p")); + Assertions.assertNotNull(currentPartitionName, "Should find the current partition"); + Assertions.assertTrue(currentPartitionName.startsWith("p"), "Current partition should start with 'p'"); List historicalWithName = DynamicPartitionScheduler.getHistoricalPartitions( table, currentPartitionName); boolean currentFoundByName2 = false; @@ -3639,10 +3536,9 @@ public void testTimeStampTzGetHistoricalPartitionsOldPrefix() throws Exception { break; } } - Assert.assertFalse("Old prefix: name-based must exclude current partition " - + "when nowPartitionName matches", currentFoundByName2); - Assert.assertEquals("Old prefix: exclude exactly one partition", - totalPartitions - 1, historicalWithName.size()); + Assertions.assertFalse(currentFoundByName2, "Old prefix: name-based must exclude current partition " + + "when nowPartitionName matches"); + Assertions.assertEquals(totalPartitions - 1, historicalWithName.size(), "Old prefix: exclude exactly one partition"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } @@ -3702,7 +3598,7 @@ public void testTimeStampTzGetHistoricalPartitionsNoncanonicalRange() throws Exc alterTable("ALTER TABLE test.tstz_noncanonical ADD PARTITION p_hist VALUES " + "[('2020-01-01 00:00:00+00:00'), ('2020-01-02 00:00:00+00:00'))"); - Assert.assertEquals(2, table.getPartitionNames().size()); + Assertions.assertEquals(2, table.getPartitionNames().size()); // currentUtcBorder = today's UTC midnight → inside p_legacy. String currentUtcBorder = fmt.format(todayMidnight) + "+00:00"; @@ -3715,11 +3611,9 @@ public void testTimeStampTzGetHistoricalPartitionsNoncanonicalRange() throws Exc String lowerStr = item.getItems().lowerEndpoint().getKeys().get(0).getStringValue(); String upperStr = item.getItems().upperEndpoint().getKeys().get(0).getStringValue(); if ("p_legacy".equals(table.getPartition(entry.getKey()).getName())) { - Assert.assertTrue("00:00Z must be inside [" + lowerStr + ", " + upperStr + ")", - currentUtcBorder.compareTo(lowerStr) >= 0 - && currentUtcBorder.compareTo(upperStr) < 0); - Assert.assertFalse("00:00Z must NOT equal " + lowerStr, - currentUtcBorder.equals(lowerStr)); + Assertions.assertTrue(currentUtcBorder.compareTo(lowerStr) >= 0 + && currentUtcBorder.compareTo(upperStr) < 0, "00:00Z must be inside [" + lowerStr + ", " + upperStr + ")"); + Assertions.assertFalse(currentUtcBorder.equals(lowerStr), "00:00Z must NOT equal " + lowerStr); } } @@ -3728,19 +3622,15 @@ public void testTimeStampTzGetHistoricalPartitionsNoncanonicalRange() throws Exc // 1. Without currentUtcBorder: name-based fallback returns both. List historicalNoUtc = DynamicPartitionScheduler.getHistoricalPartitions( table, wrongNowPartitionName); - Assert.assertEquals("Name-based fallback returns all partitions", - 2, historicalNoUtc.size()); + Assertions.assertEquals(2, historicalNoUtc.size(), "Name-based fallback returns all partitions"); // 2. With the correct nowPartitionName matching p_legacy, // name-based exclusion removes it. List historicalWithName = DynamicPartitionScheduler.getHistoricalPartitions( table, "p_legacy"); - Assert.assertEquals("Name-based exclusion removes exactly one partition", - 1, historicalWithName.size()); - Assert.assertFalse("p_legacy must be excluded by name match", - "p_legacy".equals(historicalWithName.get(0).getName())); - Assert.assertEquals("p_hist should survive", - "p_hist", historicalWithName.get(0).getName()); + Assertions.assertEquals(1, historicalWithName.size(), "Name-based exclusion removes exactly one partition"); + Assertions.assertFalse("p_legacy".equals(historicalWithName.get(0).getName()), "p_legacy must be excluded by name match"); + Assertions.assertEquals("p_hist", historicalWithName.get(0).getName(), "p_hist should survive"); } finally { connectContext.getSessionVariable().setTimeZone(originalTimeZone); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvFactoryTest.java index ac4c8432de31ad..0ad4d5e520f9e0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvFactoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvFactoryTest.java @@ -26,8 +26,8 @@ import org.apache.doris.common.Config; import org.apache.doris.datasource.InternalCatalog; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class EnvFactoryTest { @@ -35,22 +35,22 @@ public class EnvFactoryTest { public void testCreate() throws Exception { Config.cloud_unique_id = ""; EnvFactory envFactory = EnvFactory.getInstance(); - Assert.assertTrue(envFactory instanceof EnvFactory); - Assert.assertFalse(envFactory instanceof CloudEnvFactory); - Assert.assertTrue(Env.getCurrentEnv() instanceof Env); - Assert.assertFalse(Env.getCurrentEnv() instanceof CloudEnv); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof InternalCatalog); - Assert.assertFalse(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(envFactory.createEnv(false) instanceof Env); - Assert.assertFalse(envFactory.createEnv(false) instanceof CloudEnv); - Assert.assertTrue(envFactory.createInternalCatalog() instanceof InternalCatalog); - Assert.assertFalse(envFactory.createInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(envFactory.createPartition() instanceof Partition); - Assert.assertFalse(envFactory.createPartition() instanceof CloudPartition); - Assert.assertTrue(envFactory.createTablet() instanceof Tablet); - Assert.assertFalse(envFactory.createTablet() instanceof CloudTablet); - Assert.assertTrue(envFactory.createReplica() instanceof Replica); - Assert.assertFalse(envFactory.createReplica() instanceof CloudReplica); + Assertions.assertTrue(envFactory instanceof EnvFactory); + Assertions.assertFalse(envFactory instanceof CloudEnvFactory); + Assertions.assertTrue(Env.getCurrentEnv() instanceof Env); + Assertions.assertFalse(Env.getCurrentEnv() instanceof CloudEnv); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof InternalCatalog); + Assertions.assertFalse(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(envFactory.createEnv(false) instanceof Env); + Assertions.assertFalse(envFactory.createEnv(false) instanceof CloudEnv); + Assertions.assertTrue(envFactory.createInternalCatalog() instanceof InternalCatalog); + Assertions.assertFalse(envFactory.createInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(envFactory.createPartition() instanceof Partition); + Assertions.assertFalse(envFactory.createPartition() instanceof CloudPartition); + Assertions.assertTrue(envFactory.createTablet() instanceof Tablet); + Assertions.assertFalse(envFactory.createTablet() instanceof CloudTablet); + Assertions.assertTrue(envFactory.createReplica() instanceof Replica); + Assertions.assertFalse(envFactory.createReplica() instanceof CloudReplica); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvOperationTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvOperationTest.java index 45ec2d678a1f45..72656d9b1b6907 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvOperationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvOperationTest.java @@ -30,10 +30,10 @@ import org.apache.doris.qe.StmtExecutor; import org.apache.doris.utframe.UtFrameUtils; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.Map; @@ -46,7 +46,7 @@ public class EnvOperationTest { private static ConnectContext connectContext; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { FeConstants.default_scheduler_interval_millisecond = 1000; UtFrameUtils.createDorisCluster(runningDir); @@ -68,7 +68,7 @@ public static void beforeClass() throws Exception { + "properties(\"replication_num\" = \"1\");"); } - @AfterClass + @AfterAll public static void tearDown() { File file = new File(runningDir); file.delete(); @@ -97,40 +97,40 @@ public void testRenameTable() throws Exception { // rename olap table String renameTblStmt = "alter table test.renameTest rename newNewTest"; Database db = Env.getCurrentInternalCatalog().getDbNullable("test"); - Assert.assertNotNull(db); - Assert.assertNotNull(db.getTableNullable("renameTest")); + Assertions.assertNotNull(db); + Assertions.assertNotNull(db.getTableNullable("renameTest")); alterTable(renameTblStmt); - Assert.assertNull(db.getTableNullable("renameTest")); - Assert.assertNotNull(db.getTableNullable("newNewTest")); + Assertions.assertNull(db.getTableNullable("renameTest")); + Assertions.assertNotNull(db.getTableNullable("newNewTest")); // add a rollup and test rename to a rollup name(expect throw exception) String alterStmtStr = "alter table test.newNewTest add rollup r1(k2,k1)"; alterTable(alterStmtStr); Map alterJobs = Env.getCurrentEnv().getMaterializedViewHandler().getAlterJobsV2(); - Assert.assertEquals(1, alterJobs.size()); + Assertions.assertEquals(1, alterJobs.size()); for (AlterJobV2 alterJobV2 : alterJobs.values()) { while (!alterJobV2.getJobState().isFinalState()) { System.out.println("alter job " + alterJobV2.getJobId() + " is running. state: " + alterJobV2.getJobState()); Thread.sleep(1000); } System.out.println("alter job " + alterJobV2.getJobId() + " is done. state: " + alterJobV2.getJobState()); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } Thread.sleep(1000); renameTblStmt = "alter table test.newNewTest rename r1"; try { alterTable(renameTblStmt); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("New name conflicts with rollup index name: r1")); + Assertions.assertTrue(e.getMessage().contains("New name conflicts with rollup index name: r1")); } renameTblStmt = "alter table test.newNewTest rename goodName"; alterTable(renameTblStmt); - Assert.assertNull(db.getTableNullable("newNewTest")); - Assert.assertNotNull(db.getTableNullable("goodName")); + Assertions.assertNull(db.getTableNullable("newNewTest")); + Assertions.assertNotNull(db.getTableNullable("goodName")); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvTest.java index fe3f4aebadde40..d8e767ceb80049 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/EnvTest.java @@ -26,10 +26,10 @@ import org.apache.doris.mysql.privilege.Auth; import org.apache.doris.persist.meta.MetaHeader; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -49,14 +49,14 @@ public class EnvTest { private MockedStatic mockedMetaContext; - @Before + @BeforeEach public void setUp() { MetaContext metaContext = new MetaContext(); mockedMetaContext = Mockito.mockStatic(MetaContext.class); mockedMetaContext.when(MetaContext::get).thenReturn(metaContext); } - @After + @AfterEach public void tearDown() { if (mockedMetaContext != null) { mockedMetaContext.close(); @@ -148,7 +148,7 @@ public void testSaveLoadHeader() throws Exception { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); env = Env.getCurrentEnv(); long checksum2 = env.loadHeader(dis, MetaHeader.EMPTY_HEADER, 0); - Assert.assertEquals(checksum1, checksum2); + Assertions.assertEquals(checksum1, checksum2); dis.close(); deleteDir(dir); @@ -171,7 +171,7 @@ public void testSetLdapDefaultRolesConfigRefreshesLdapCache() throws Exception { env.setMutableConfigWithCallback("ldap_default_roles", "role1,role2"); - Assert.assertArrayEquals(new String[] {"role1", "role2"}, LdapConfig.ldap_default_roles); + Assertions.assertArrayEquals(new String[] {"role1", "role2"}, LdapConfig.ldap_default_roles); Mockito.verify(ldapManager).refresh(true, null); } finally { ConfigBase.confFields = oldConfFields; diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/IndexTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/IndexTest.java index 87ba17a7568946..814a00f66e3c6d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/IndexTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/IndexTest.java @@ -19,8 +19,8 @@ import org.apache.doris.catalog.info.IndexType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -55,9 +55,9 @@ public void testGetColumnUniqueIds() { Index index1 = new Index(1, "test_index1", indexColumns1, IndexType.BITMAP, null, null); List uniqueIds1 = index1.getColumnUniqueIds(schema); - Assert.assertEquals(2, uniqueIds1.size()); - Assert.assertEquals(Integer.valueOf(101), uniqueIds1.get(0)); - Assert.assertEquals(Integer.valueOf(103), uniqueIds1.get(1)); + Assertions.assertEquals(2, uniqueIds1.size()); + Assertions.assertEquals(Integer.valueOf(101), uniqueIds1.get(0)); + Assertions.assertEquals(Integer.valueOf(103), uniqueIds1.get(1)); // Test case 2: Case-insensitive matching List indexColumns2 = new ArrayList<>(); @@ -66,9 +66,9 @@ public void testGetColumnUniqueIds() { Index index2 = new Index(2, "test_index2", indexColumns2, IndexType.BITMAP, null, null); List uniqueIds2 = index2.getColumnUniqueIds(schema); - Assert.assertEquals(2, uniqueIds2.size()); - Assert.assertEquals(Integer.valueOf(101), uniqueIds2.get(0)); - Assert.assertEquals(Integer.valueOf(103), uniqueIds2.get(1)); + Assertions.assertEquals(2, uniqueIds2.size()); + Assertions.assertEquals(Integer.valueOf(101), uniqueIds2.get(0)); + Assertions.assertEquals(Integer.valueOf(103), uniqueIds2.get(1)); // Test case 3: Non-existent column name List indexColumns3 = new ArrayList<>(); @@ -77,22 +77,22 @@ public void testGetColumnUniqueIds() { Index index3 = new Index(3, "test_index3", indexColumns3, IndexType.BITMAP, null, null); List uniqueIds3 = index3.getColumnUniqueIds(schema); - Assert.assertEquals(1, uniqueIds3.size()); - Assert.assertEquals(Integer.valueOf(101), uniqueIds3.get(0)); + Assertions.assertEquals(1, uniqueIds3.size()); + Assertions.assertEquals(Integer.valueOf(101), uniqueIds3.get(0)); // Test case 4: Null schema List uniqueIds4 = index1.getColumnUniqueIds(null); - Assert.assertEquals(0, uniqueIds4.size()); + Assertions.assertEquals(0, uniqueIds4.size()); // Test case 5: Empty column list Index emptyColIndex = new Index(5, "empty_col_index", new ArrayList<>(), IndexType.BITMAP, null, null); List emptyColUniqueIds = emptyColIndex.getColumnUniqueIds(schema); - Assert.assertEquals(0, emptyColUniqueIds.size()); + Assertions.assertEquals(0, emptyColUniqueIds.size()); // Test case 6: Empty schema (non-null) List emptySchemaUniqueIds = index1.getColumnUniqueIds(new ArrayList<>()); - Assert.assertEquals(0, emptySchemaUniqueIds.size()); + Assertions.assertEquals(0, emptySchemaUniqueIds.size()); // Test case 7: Duplicate column names List dupColumns = new ArrayList<>(); @@ -102,10 +102,10 @@ public void testGetColumnUniqueIds() { Index dupIndex = new Index(7, "dup_index", dupColumns, IndexType.BITMAP, null, null); List dupUniqueIds = dupIndex.getColumnUniqueIds(schema); - Assert.assertEquals(3, dupUniqueIds.size()); - Assert.assertEquals(Integer.valueOf(101), dupUniqueIds.get(0)); - Assert.assertEquals(Integer.valueOf(101), dupUniqueIds.get(1)); - Assert.assertEquals(Integer.valueOf(102), dupUniqueIds.get(2)); + Assertions.assertEquals(3, dupUniqueIds.size()); + Assertions.assertEquals(Integer.valueOf(101), dupUniqueIds.get(0)); + Assertions.assertEquals(Integer.valueOf(101), dupUniqueIds.get(1)); + Assertions.assertEquals(Integer.valueOf(102), dupUniqueIds.get(2)); // Test case 8: Special characters in column names List specialColList = new ArrayList<>(); @@ -113,8 +113,8 @@ public void testGetColumnUniqueIds() { Index specialIndex = new Index(8, "special_index", specialColList, IndexType.BITMAP, null, null); List specialUniqueIds = specialIndex.getColumnUniqueIds(schema); - Assert.assertEquals(1, specialUniqueIds.size()); - Assert.assertEquals(Integer.valueOf(104), specialUniqueIds.get(0)); + Assertions.assertEquals(1, specialUniqueIds.size()); + Assertions.assertEquals(Integer.valueOf(104), specialUniqueIds.get(0)); // Test case 9: Mixed case column name List mixedCaseList = new ArrayList<>(); @@ -122,8 +122,8 @@ public void testGetColumnUniqueIds() { Index mixedCaseIndex = new Index(9, "mixed_case_index", mixedCaseList, IndexType.BITMAP, null, null); List mixedCaseUniqueIds = mixedCaseIndex.getColumnUniqueIds(schema); - Assert.assertEquals(1, mixedCaseUniqueIds.size()); - Assert.assertEquals(Integer.valueOf(105), mixedCaseUniqueIds.get(0)); + Assertions.assertEquals(1, mixedCaseUniqueIds.size()); + Assertions.assertEquals(Integer.valueOf(105), mixedCaseUniqueIds.get(0)); // Test case 10: Large number of columns List largeColumnList = new ArrayList<>(); @@ -142,10 +142,10 @@ public void testGetColumnUniqueIds() { Index largeIndex = new Index(10, "large_index", largeColumnList, IndexType.BITMAP, null, null); List largeUniqueIds = largeIndex.getColumnUniqueIds(largeSchema); - Assert.assertEquals(500, largeUniqueIds.size()); + Assertions.assertEquals(500, largeUniqueIds.size()); // Check first and last elements - Assert.assertEquals(Integer.valueOf(1000), largeUniqueIds.get(0)); - Assert.assertEquals(Integer.valueOf(1000 + 998), largeUniqueIds.get(499)); + Assertions.assertEquals(Integer.valueOf(1000), largeUniqueIds.get(0)); + Assertions.assertEquals(Integer.valueOf(1000 + 998), largeUniqueIds.get(499)); // Test case 11: Order preservation - ensure column order in index is preserved in IDs List reverseOrderColumns = new ArrayList<>(); @@ -156,9 +156,9 @@ public void testGetColumnUniqueIds() { Index reverseIndex = new Index(11, "reverse_index", reverseOrderColumns, IndexType.BITMAP, null, null); List reverseUniqueIds = reverseIndex.getColumnUniqueIds(schema); - Assert.assertEquals(3, reverseUniqueIds.size()); - Assert.assertEquals(Integer.valueOf(103), reverseUniqueIds.get(0)); - Assert.assertEquals(Integer.valueOf(102), reverseUniqueIds.get(1)); - Assert.assertEquals(Integer.valueOf(101), reverseUniqueIds.get(2)); + Assertions.assertEquals(3, reverseUniqueIds.size()); + Assertions.assertEquals(Integer.valueOf(103), reverseUniqueIds.get(0)); + Assertions.assertEquals(Integer.valueOf(102), reverseUniqueIds.get(1)); + Assertions.assertEquals(Integer.valueOf(101), reverseUniqueIds.get(2)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/InfoSchemaDbTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/InfoSchemaDbTest.java index 7b1d595c45f166..6832042f8d4707 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/InfoSchemaDbTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/InfoSchemaDbTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.DdlException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -29,10 +29,10 @@ public class InfoSchemaDbTest { public void testNormal() throws IOException, DdlException { Database db = new InfoSchemaDb(); - Assert.assertFalse(db.registerTable(null)); - Assert.assertFalse(db.createTableWithLock(null, false, false).first); + Assertions.assertFalse(db.registerTable(null)); + Assertions.assertFalse(db.createTableWithLock(null, false, false).first); db.unregisterTable("authors"); - Assert.assertThrows(IOException.class, () -> db.write(null)); - Assert.assertNull(db.getTableNullable("authors")); + Assertions.assertThrows(IOException.class, () -> db.write(null)); + Assertions.assertNull(db.getTableNullable("authors")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/JdbcResourceTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/JdbcResourceTest.java index 520a5026ad864a..fce17458111ea5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/JdbcResourceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/JdbcResourceTest.java @@ -30,10 +30,9 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -45,7 +44,7 @@ public class JdbcResourceTest { private Map jdbcProperties; - @Before + @BeforeEach public void setUp() { FeConstants.runningUnitTest = true; jdbcProperties = Maps.newHashMap(); @@ -82,11 +81,11 @@ public void testJdbcResourceCreateWithDefaultProperties() throws UserException { // Verify the default properties were applied during the replay Map properties = jdbcResource.getCopiedProperties(); - Assert.assertEquals("1", properties.get("connection_pool_min_size")); - Assert.assertEquals("30", properties.get("connection_pool_max_size")); - Assert.assertEquals("1800000", properties.get("connection_pool_max_life_time")); - Assert.assertEquals("5000", properties.get("connection_pool_max_wait_time")); - Assert.assertEquals("false", properties.get("connection_pool_keep_alive")); + Assertions.assertEquals("1", properties.get("connection_pool_min_size")); + Assertions.assertEquals("30", properties.get("connection_pool_max_size")); + Assertions.assertEquals("1800000", properties.get("connection_pool_max_life_time")); + Assertions.assertEquals("5000", properties.get("connection_pool_max_wait_time")); + Assertions.assertEquals("false", properties.get("connection_pool_keep_alive")); } } @@ -101,16 +100,16 @@ public void testJdbcResourceReplayWithDefaultProperties() { // Retrieve the replayed resource Resource replayedResource = resourceMgr.getResource("jdbc_resource_pg_14"); - Assert.assertNotNull(replayedResource); - Assert.assertTrue(replayedResource instanceof JdbcResource); + Assertions.assertNotNull(replayedResource); + Assertions.assertTrue(replayedResource instanceof JdbcResource); // Verify the default properties were applied during the replay Map properties = replayedResource.getCopiedProperties(); - Assert.assertEquals("1", properties.get("connection_pool_min_size")); - Assert.assertEquals("30", properties.get("connection_pool_max_size")); - Assert.assertEquals("1800000", properties.get("connection_pool_max_life_time")); - Assert.assertEquals("5000", properties.get("connection_pool_max_wait_time")); - Assert.assertEquals("false", properties.get("connection_pool_keep_alive")); + Assertions.assertEquals("1", properties.get("connection_pool_min_size")); + Assertions.assertEquals("30", properties.get("connection_pool_max_size")); + Assertions.assertEquals("1800000", properties.get("connection_pool_max_life_time")); + Assertions.assertEquals("5000", properties.get("connection_pool_max_wait_time")); + Assertions.assertEquals("false", properties.get("connection_pool_keep_alive")); } @Test @@ -131,16 +130,16 @@ public void testJdbcResourceReplayWithSetProperties() { // Retrieve the replayed resource Resource replayedResource = resourceMgr.getResource("jdbc_resource_pg_14"); - Assert.assertNotNull(replayedResource); - Assert.assertTrue(replayedResource instanceof JdbcResource); + Assertions.assertNotNull(replayedResource); + Assertions.assertTrue(replayedResource instanceof JdbcResource); // Verify the modified properties were applied during the replay Map properties = replayedResource.getCopiedProperties(); - Assert.assertEquals("2", properties.get("connection_pool_min_size")); - Assert.assertEquals("20", properties.get("connection_pool_max_size")); - Assert.assertEquals("3600000", properties.get("connection_pool_max_life_time")); - Assert.assertEquals("10000", properties.get("connection_pool_max_wait_time")); - Assert.assertEquals("true", properties.get("connection_pool_keep_alive")); + Assertions.assertEquals("2", properties.get("connection_pool_min_size")); + Assertions.assertEquals("20", properties.get("connection_pool_max_size")); + Assertions.assertEquals("3600000", properties.get("connection_pool_max_life_time")); + Assertions.assertEquals("10000", properties.get("connection_pool_max_wait_time")); + Assertions.assertEquals("true", properties.get("connection_pool_keep_alive")); } @Test @@ -156,11 +155,11 @@ public void testJdbcResourceReplayWithModifiedAfterSetDefaultProperties() throws newProperties.put(JdbcResource.CONNECTION_POOL_MIN_SIZE, "2"); replayedResource.modifyProperties(newProperties); Map properties = replayedResource.getCopiedProperties(); - Assert.assertEquals("2", properties.get("connection_pool_min_size")); + Assertions.assertEquals("2", properties.get("connection_pool_min_size")); resourceMgr.replayCreateResource(replayedResource); Resource replayedResource2 = resourceMgr.getResource("jdbc_resource_pg_14"); Map properties2 = replayedResource2.getCopiedProperties(); - Assert.assertEquals("2", properties2.get("connection_pool_min_size")); + Assertions.assertEquals("2", properties2.get("connection_pool_min_size")); } @Test @@ -169,8 +168,8 @@ public void testHandleJdbcUrlForMySql() throws DdlException { String resultUrl = JdbcResource.handleJdbcUrl(inputUrl); // Check if the result URL contains the necessary delimiters for MySQL - Assert.assertTrue(resultUrl.contains("?")); - Assert.assertTrue(resultUrl.contains("&")); + Assertions.assertTrue(resultUrl.contains("?")); + Assertions.assertTrue(resultUrl.contains("&")); } @Test @@ -179,11 +178,11 @@ public void testHandleJdbcUrlForSqlServerWithoutParams() throws DdlException { String resultUrl = JdbcResource.handleJdbcUrl(inputUrl); // Ensure that the result URL for SQL Server doesn't have '?' or '&' - Assert.assertFalse(resultUrl.contains("?")); - Assert.assertFalse(resultUrl.contains("&")); + Assertions.assertFalse(resultUrl.contains("?")); + Assertions.assertFalse(resultUrl.contains("&")); // Ensure the result URL still contains ';' - Assert.assertTrue(resultUrl.contains(";")); + Assertions.assertTrue(resultUrl.contains(";")); } @Test @@ -193,11 +192,11 @@ public void testHandleJdbcUrlForSqlServerWithParams() throws DdlException { String resultUrl = JdbcResource.handleJdbcUrl(inputUrl); // Ensure that the result URL for SQL Server doesn't have '?' or '&' - Assert.assertFalse(resultUrl.contains("?")); - Assert.assertFalse(resultUrl.contains("&")); + Assertions.assertFalse(resultUrl.contains("?")); + Assertions.assertFalse(resultUrl.contains("&")); // Ensure the result URL still contains ';' - Assert.assertTrue(resultUrl.contains(";")); + Assertions.assertTrue(resultUrl.contains(";")); } @Test @@ -205,19 +204,19 @@ public void testValidDriverUrls() { String fileUrl = "file://path/to/driver.jar"; Assertions.assertDoesNotThrow(() -> { String result = JdbcResource.getFullDriverUrl(fileUrl); - Assert.assertEquals(fileUrl, result); + Assertions.assertEquals(fileUrl, result); }); String httpUrl = "http://example.com/driver.jar"; Assertions.assertDoesNotThrow(() -> { String result = JdbcResource.getFullDriverUrl(httpUrl); - Assert.assertEquals(httpUrl, result); + Assertions.assertEquals(httpUrl, result); }); String httpsUrl = "https://example.com/driver.jar"; Assertions.assertDoesNotThrow(() -> { String result = JdbcResource.getFullDriverUrl(httpsUrl); - Assert.assertEquals(httpsUrl, result); + Assertions.assertEquals(httpsUrl, result); }); String jarFile = "driver.jar"; @@ -229,22 +228,22 @@ public void testValidDriverUrls() { @Test public void testInvalidDriverUrls() { String invalidUrl1 = "/mnt/path/to/driver.jar"; - Assert.assertThrows(IllegalArgumentException.class, () -> { + Assertions.assertThrows(IllegalArgumentException.class, () -> { JdbcResource.getFullDriverUrl(invalidUrl1); }); String invalidUrl2 = "ftp://example.com/driver.jar"; - Assert.assertThrows(IllegalArgumentException.class, () -> { + Assertions.assertThrows(IllegalArgumentException.class, () -> { JdbcResource.getFullDriverUrl(invalidUrl2); }); String invalidUrl3 = ""; - Assert.assertThrows(IllegalArgumentException.class, () -> { + Assertions.assertThrows(IllegalArgumentException.class, () -> { JdbcResource.getFullDriverUrl(invalidUrl3); }); String invalidUrl4 = "example.com/driver"; - Assert.assertThrows(IllegalArgumentException.class, () -> { + Assertions.assertThrows(IllegalArgumentException.class, () -> { JdbcResource.getFullDriverUrl(invalidUrl4); }); } @@ -255,7 +254,7 @@ public void testSecurePathRejectsPrefixConfusion() { try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; // A directory that merely shares a string prefix must NOT be allowed. - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("file:///opt/doris/jdbc_drivers-evil/x.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -267,7 +266,7 @@ public void testSecurePathRejectsPathTraversal() { String saved = Config.jdbc_driver_secure_path; try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("file:///opt/doris/jdbc_drivers/../../etc/x.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -280,7 +279,7 @@ public void testSecurePathAllowsPathUnderAllowedDir() { try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; String url = "file:///opt/doris/jdbc_drivers/sub/x.jar"; - Assertions.assertDoesNotThrow(() -> Assert.assertEquals(url, JdbcResource.getFullDriverUrl(url))); + Assertions.assertDoesNotThrow(() -> Assertions.assertEquals(url, JdbcResource.getFullDriverUrl(url))); } finally { Config.jdbc_driver_secure_path = saved; } @@ -291,7 +290,7 @@ public void testSecurePathRejectsHostConfusion() { String saved = Config.jdbc_driver_secure_path; try { Config.jdbc_driver_secure_path = "http://good.com/"; - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("http://good.com.evil.com/x.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -304,7 +303,7 @@ public void testSecurePathAllowsRemoteUnderAllowedHost() { try { Config.jdbc_driver_secure_path = "http://good.com/drivers"; String url = "http://good.com/drivers/x.jar"; - Assertions.assertDoesNotThrow(() -> Assert.assertEquals(url, JdbcResource.getFullDriverUrl(url))); + Assertions.assertDoesNotThrow(() -> Assertions.assertEquals(url, JdbcResource.getFullDriverUrl(url))); } finally { Config.jdbc_driver_secure_path = saved; } @@ -316,7 +315,7 @@ public void testSecurePathWildcardAllowsAll() { try { Config.jdbc_driver_secure_path = "*"; String url = "file:///any/where/x.jar"; - Assertions.assertDoesNotThrow(() -> Assert.assertEquals(url, JdbcResource.getFullDriverUrl(url))); + Assertions.assertDoesNotThrow(() -> Assertions.assertEquals(url, JdbcResource.getFullDriverUrl(url))); } finally { Config.jdbc_driver_secure_path = saved; } @@ -328,7 +327,7 @@ public void testSecurePathRejectsEncodedTraversal() { try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; // %2e%2e decodes to "..", which must be resolved the same way the classloader resolves it. - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("file:///opt/doris/jdbc_drivers/%2e%2e/%2e%2e/etc/x.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -341,7 +340,7 @@ public void testSecurePathRejectsRemoteQueryMismatch() { try { Config.jdbc_driver_secure_path = "http://good.com/drivers"; // A query-bearing URL must not be authorized by a query-less allowed prefix. - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("http://good.com/drivers/x.jar?id=evil")); } finally { Config.jdbc_driver_secure_path = saved; @@ -353,7 +352,7 @@ public void testSecurePathRejectsRemoteUserInfoMismatch() { String saved = Config.jdbc_driver_secure_path; try { Config.jdbc_driver_secure_path = "http://good.com/drivers"; - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("http://user@good.com/drivers/x.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -369,7 +368,7 @@ public void testSchemelessLegacyCharsAccepted() { String savedDir = Config.jdbc_drivers_dir; try { Config.jdbc_drivers_dir = "/opt/doris/jdbc_drivers"; - Assert.assertEquals("file:///opt/doris/jdbc_drivers/legacy+patched.jar", + Assertions.assertEquals("file:///opt/doris/jdbc_drivers/legacy+patched.jar", JdbcResource.getFullDriverUrl("legacy+patched.jar")); } finally { Config.jdbc_drivers_dir = savedDir; @@ -382,7 +381,7 @@ public void testSecurePathRejectsFileAuthority() { try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; // A non-local authority makes consumers fetch a remote object though the path matches. - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("file://attacker.example/opt/doris/jdbc_drivers/evil.jar")); } finally { Config.jdbc_driver_secure_path = saved; @@ -394,7 +393,7 @@ public void testSecurePathRejectsFileQuery() { String saved = Config.jdbc_driver_secure_path; try { Config.jdbc_driver_secure_path = "file:///opt/doris/jdbc_drivers"; - Assert.assertThrows(IllegalArgumentException.class, () -> + Assertions.assertThrows(IllegalArgumentException.class, () -> JdbcResource.getFullDriverUrl("file:///opt/doris/jdbc_drivers/x.jar?evil")); } finally { Config.jdbc_driver_secure_path = saved; @@ -408,7 +407,7 @@ public void testEmptySecurePathAllowsAll() { // Empty means allow-all, same as "*" (backward-compatible contract). Config.jdbc_driver_secure_path = ""; String url = "file:///opt/doris/jdbc_drivers/x.jar"; - Assertions.assertDoesNotThrow(() -> Assert.assertEquals(url, JdbcResource.getFullDriverUrl(url))); + Assertions.assertDoesNotThrow(() -> Assertions.assertEquals(url, JdbcResource.getFullDriverUrl(url))); } finally { Config.jdbc_driver_secure_path = saved; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ListPartitionInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ListPartitionInfoTest.java index 55883fc699ef5a..cfbf18824bf07a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ListPartitionInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ListPartitionInfoTest.java @@ -29,9 +29,9 @@ import org.apache.doris.common.util.DebugPointUtil; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.LinkedList; @@ -43,7 +43,7 @@ public class ListPartitionInfoTest { private List singlePartitionDescs; - @Before + @BeforeEach public void setUp() { partitionColumns = new LinkedList<>(); singlePartitionDescs = new LinkedList<>(); @@ -65,7 +65,7 @@ public void testTinyInt() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("-128", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("-128", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); } @@ -85,7 +85,7 @@ public void testSmallInt() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("-32768", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("-32768", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); } @Test @@ -104,7 +104,7 @@ public void testInt() throws DdlException, AnalysisException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("-2147483648", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("-2147483648", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); } @Test @@ -123,7 +123,7 @@ public void testBigInt() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("-9223372036854775808", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("-9223372036854775808", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); } @Test @@ -142,7 +142,7 @@ public void testLargeInt() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("-170141183460469231731687303715884105728", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("-170141183460469231731687303715884105728", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); } @Test @@ -162,8 +162,8 @@ public void testString() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("Beijing", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); - Assert.assertEquals("Shanghai", ((ListPartitionItem) partitionItem).getItems().get(1).getKeys().get(0).getStringValue()); + Assertions.assertEquals("Beijing", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getStringValue()); + Assertions.assertEquals("Shanghai", ((ListPartitionItem) partitionItem).getItems().get(1).getKeys().get(0).getStringValue()); } @Test @@ -182,27 +182,29 @@ public void testBoolean() throws AnalysisException, DdlException { singlePartitionDesc.analyze(1, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals(true, ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getRealValue()); + Assertions.assertEquals(true, ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getRealValue()); } - @Test(expected = DdlException.class) + @Test public void testDuplicateKey() throws AnalysisException, DdlException { - Column k1 = new Column("k1", new ScalarType(PrimitiveType.VARCHAR), true, null, "", ""); - partitionColumns.add(k1); + Assertions.assertThrows(DdlException.class, () -> { + Column k1 = new Column("k1", new ScalarType(PrimitiveType.VARCHAR), true, null, "", ""); + partitionColumns.add(k1); - List> inValues = new ArrayList<>(); - inValues.add(Lists.newArrayList(new PartitionValue("beijing"))); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", - PartitionKeyDesc.createIn(inValues), null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", - PartitionKeyDesc.createIn(inValues), null)); + List> inValues = new ArrayList<>(); + inValues.add(Lists.newArrayList(new PartitionValue("beijing"))); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", + PartitionKeyDesc.createIn(inValues), null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", + PartitionKeyDesc.createIn(inValues), null)); - partitionInfo = new ListPartitionInfo(partitionColumns); - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(1, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + partitionInfo = new ListPartitionInfo(partitionColumns); + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(1, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } @Test @@ -225,8 +227,8 @@ public void testMultiPartitionKeys() throws AnalysisException, DdlException { partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - Assert.assertEquals("beijing", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getRealValue()); - Assert.assertEquals(100, ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(1).getLongValue()); + Assertions.assertEquals("beijing", ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(0).getRealValue()); + Assertions.assertEquals(100, ((ListPartitionItem) partitionItem).getItems().get(0).getKeys().get(1).getLongValue()); } @Test @@ -248,7 +250,7 @@ public void testMultiAutotoSql() throws AnalysisException, DdlException { String sql = partitionInfo.toSql(table, null); String expected = "AUTO PARTITION BY LIST (`k1`, `k2`)"; - Assert.assertTrue("got: " + sql + ", should have: " + expected, sql.contains(expected)); + Assertions.assertTrue(sql.contains(expected), "got: " + sql + ", should have: " + expected); } @Test @@ -274,7 +276,7 @@ public void testListPartitionNullMax() throws AnalysisException, DdlException { singlePartitionDesc.analyze(2, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - Assert.assertEquals("((NULL, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); + Assertions.assertEquals("((NULL, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); inValues = new ArrayList<>(); inValues.add(Lists.newArrayList(new PartitionValue("", true), new PartitionValue("", true))); @@ -283,7 +285,7 @@ public void testListPartitionNullMax() throws AnalysisException, DdlException { singlePartitionDesc.analyze(2, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - Assert.assertEquals("((NULL, NULL))", ((ListPartitionItem) partitionItem).toSql()); + Assertions.assertEquals("((NULL, NULL))", ((ListPartitionItem) partitionItem).toSql()); inValues = new ArrayList<>(); inValues.add(Lists.newArrayList(PartitionValue.MAX_VALUE, new PartitionValue("", true))); @@ -292,7 +294,7 @@ public void testListPartitionNullMax() throws AnalysisException, DdlException { singlePartitionDesc.analyze(2, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - Assert.assertEquals("((MAXVALUE, NULL))", ((ListPartitionItem) partitionItem).toSql()); + Assertions.assertEquals("((MAXVALUE, NULL))", ((ListPartitionItem) partitionItem).toSql()); inValues = new ArrayList<>(); inValues.add(Lists.newArrayList(PartitionValue.MAX_VALUE, PartitionValue.MAX_VALUE)); @@ -301,7 +303,7 @@ public void testListPartitionNullMax() throws AnalysisException, DdlException { singlePartitionDesc.analyze(2, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - Assert.assertEquals("((MAXVALUE, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); + Assertions.assertEquals("((MAXVALUE, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); inValues = new ArrayList<>(); inValues.add(Lists.newArrayList(new PartitionValue("", true), new PartitionValue("", true))); @@ -312,7 +314,7 @@ public void testListPartitionNullMax() throws AnalysisException, DdlException { singlePartitionDesc.analyze(2, null); partitionItem = partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - Assert.assertEquals("((NULL, NULL),(MAXVALUE, NULL),(NULL, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); + Assertions.assertEquals("((NULL, NULL),(MAXVALUE, NULL),(NULL, MAXVALUE))", ((ListPartitionItem) partitionItem).toSql()); } finally { DebugPointUtil.removeDebugPoint("FE.skipCheckMaxValueInListPartition"); Config.enable_debug_points = originalEnableDebugPoints; @@ -329,9 +331,9 @@ public void testRejectMaxValueInListPartition() throws AnalysisException { SinglePartitionDesc singlePartitionDesc = new SinglePartitionDesc(false, "p1", PartitionKeyDesc.createIn(inValues), null); - AnalysisException ex = Assert.assertThrows(AnalysisException.class, + AnalysisException ex = Assertions.assertThrows(AnalysisException.class, () -> singlePartitionDesc.analyze(1, null)); - Assert.assertTrue(ex.getMessage().contains("MAXVALUE is not allowed in LIST partition values")); + Assertions.assertTrue(ex.getMessage().contains("MAXVALUE is not allowed in LIST partition values")); // NULL is still a valid LIST partition value. List> nullValues = new ArrayList<>(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java index 76741526e16659..0fc2bab1b3d61d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/MaterializedIndexTest.java @@ -26,10 +26,10 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.DataInputStream; @@ -52,7 +52,7 @@ public class MaterializedIndexTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { indexId = 10000; @@ -67,7 +67,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -76,22 +76,22 @@ public void tearDown() { @Test public void getMethodTest() { - Assert.assertEquals(indexId, index.getId()); + Assertions.assertEquals(indexId, index.getId()); } @Test public void testRowBinlogFlagGsonUpgradeCompatibility() { MaterializedIndex rowBinlogIndex = new MaterializedIndex(1L, IndexState.NORMAL); - Assert.assertFalse(rowBinlogIndex.isRowBinlog()); + Assertions.assertFalse(rowBinlogIndex.isRowBinlog()); rowBinlogIndex.setIsRowBinlog(true); JsonObject currentJson = JsonParser.parseString(GsonUtils.GSON.toJson(rowBinlogIndex)).getAsJsonObject(); MaterializedIndex deserializedRowBinlogIndex = GsonUtils.GSON.fromJson(currentJson, MaterializedIndex.class); - Assert.assertTrue(deserializedRowBinlogIndex.isRowBinlog()); + Assertions.assertTrue(deserializedRowBinlogIndex.isRowBinlog()); currentJson.remove("isRowBinlog"); MaterializedIndex deserializedLegacyIndex = GsonUtils.GSON.fromJson(currentJson, MaterializedIndex.class); - Assert.assertFalse(deserializedLegacyIndex.isRowBinlog()); + Assertions.assertFalse(deserializedLegacyIndex.isRowBinlog()); } @Test @@ -113,18 +113,18 @@ public void testPartitionIncludesIndependentRowBinlogIndexForStats() { rowBinlogIndex.addTablet(rowBinlogTablet, null, true); partition.createRollupIndex(rowBinlogIndex); - Assert.assertEquals(1, partition.getMaterializedIndices(IndexExtState.VISIBLE).size()); - Assert.assertEquals(2, partition.getMaterializedIndices(IndexExtState.VISIBLE, true).size()); - Assert.assertEquals(1, partition.getMaterializedIndices(IndexExtState.ALL).size()); - Assert.assertEquals(2, partition.getMaterializedIndices(IndexExtState.ALL, true).size()); - Assert.assertEquals(0L, baseIndex.getBinlogSize()); - Assert.assertEquals(20L, rowBinlogIndex.getBinlogSize()); - Assert.assertEquals(120L, partition.getDataSize(false)); - Assert.assertEquals(120L, partition.getDataSizeExcludeEmptyReplica(false)); - Assert.assertEquals(20L, partition.getBinlogDataSize()); - Assert.assertEquals(2L, partition.getReplicaCount()); - Assert.assertEquals(2L, partition.getAllReplicaCount()); - Assert.assertNotEquals(checksumWithoutRowBinlog, partition.getMetaChecksum()); + Assertions.assertEquals(1, partition.getMaterializedIndices(IndexExtState.VISIBLE).size()); + Assertions.assertEquals(2, partition.getMaterializedIndices(IndexExtState.VISIBLE, true).size()); + Assertions.assertEquals(1, partition.getMaterializedIndices(IndexExtState.ALL).size()); + Assertions.assertEquals(2, partition.getMaterializedIndices(IndexExtState.ALL, true).size()); + Assertions.assertEquals(0L, baseIndex.getBinlogSize()); + Assertions.assertEquals(20L, rowBinlogIndex.getBinlogSize()); + Assertions.assertEquals(120L, partition.getDataSize(false)); + Assertions.assertEquals(120L, partition.getDataSizeExcludeEmptyReplica(false)); + Assertions.assertEquals(20L, partition.getBinlogDataSize()); + Assertions.assertEquals(2L, partition.getReplicaCount()); + Assertions.assertEquals(2L, partition.getAllReplicaCount()); + Assertions.assertNotEquals(checksumWithoutRowBinlog, partition.getMetaChecksum()); } @Test @@ -134,15 +134,15 @@ public void testGetTabletsReturnsImmutableSnapshot() { index.addTablet(new LocalTablet(1L), tabletMeta, true); List snapshot = index.getTablets(); - Assert.assertEquals(1, snapshot.size()); + Assertions.assertEquals(1, snapshot.size()); // A write after the snapshot was taken must not be visible in it (copy-on-write). index.addTablet(new LocalTablet(2L), tabletMeta, true); - Assert.assertEquals(1, snapshot.size()); - Assert.assertEquals(2, index.getTablets().size()); + Assertions.assertEquals(1, snapshot.size()); + Assertions.assertEquals(2, index.getTablets().size()); // The returned snapshot is read-only. - Assert.assertThrows(UnsupportedOperationException.class, () -> snapshot.add(new LocalTablet(3L))); + Assertions.assertThrows(UnsupportedOperationException.class, () -> snapshot.add(new LocalTablet(3L))); } @Test @@ -162,7 +162,7 @@ public void testPartitionMetaChecksum() { long pinnedVisibleVersionTime = firstPartition.getVisibleVersionTime(); Partition deserializedPartition = GsonUtils.GSON.fromJson(GsonUtils.GSON.toJson(firstPartition), Partition.class); - Assert.assertEquals(firstPartition.getMetaChecksum(), deserializedPartition.getMetaChecksum()); + Assertions.assertEquals(firstPartition.getMetaChecksum(), deserializedPartition.getMetaChecksum()); MaterializedIndex reorderedIndex = new MaterializedIndex(1L, IndexState.NORMAL); LocalTablet reorderedSecondTablet = new LocalTablet(11L); @@ -176,7 +176,7 @@ public void testPartitionMetaChecksum() { reorderedPartition.setVisibleVersionAndTime(reorderedPartition.getVisibleVersion(), pinnedVisibleVersionTime); reorderedPartition.createRollupIndex(createIndex(3L, 30L, 300L, 3000L)); reorderedPartition.createRollupIndex(createIndex(2L, 20L, 200L, 2000L)); - Assert.assertEquals(firstPartition.getMetaChecksum(), reorderedPartition.getMetaChecksum()); + Assertions.assertEquals(firstPartition.getMetaChecksum(), reorderedPartition.getMetaChecksum()); MaterializedIndex movedIndex = new MaterializedIndex(1L, IndexState.NORMAL); LocalTablet movedTablet = new LocalTablet(10L); @@ -188,10 +188,10 @@ public void testPartitionMetaChecksum() { movedPartition.setVisibleVersionAndTime(movedPartition.getVisibleVersion(), pinnedVisibleVersionTime); movedPartition.createRollupIndex(createIndex(2L, 20L, 200L, 2000L)); movedPartition.createRollupIndex(createIndex(3L, 30L, 300L, 3000L)); - Assert.assertNotEquals(firstPartition.getMetaChecksum(), movedPartition.getMetaChecksum()); + Assertions.assertNotEquals(firstPartition.getMetaChecksum(), movedPartition.getMetaChecksum()); firstPartition.setRemoteMetaChecksum(firstPartition.getMetaChecksum()); - Assert.assertEquals(firstPartition.getMetaChecksum(), firstPartition.getRemoteMetaChecksum()); + Assertions.assertEquals(firstPartition.getMetaChecksum(), firstPartition.getRemoteMetaChecksum()); } @Test @@ -207,32 +207,32 @@ public void testPartitionMetaChecksumChangesOnReplicaQueryFields() { // 1) lastFailedVersion change must invalidate the checksum. replica.updateLastFailedVersion(5L); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); replica.updateLastFailedVersion(-1L); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // 2) state change must invalidate the checksum. replica.setState(Replica.ReplicaState.DECOMMISSION); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); replica.setState(Replica.ReplicaState.NORMAL); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // 3) bad flag change must invalidate the checksum. - Assert.assertTrue(replica.setBad(true)); - Assert.assertNotEquals(original, partition.getMetaChecksum()); - Assert.assertTrue(replica.setBad(false)); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertTrue(replica.setBad(true)); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertTrue(replica.setBad(false)); + Assertions.assertEquals(original, partition.getMetaChecksum()); // 4) pathHash change must invalidate the checksum. replica.setPathHash(99L); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); replica.setPathHash(-1L); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // 5) version change must invalidate the checksum. Replica.updateVersion() // refuses to roll back, so this is asserted last with a one-way change. replica.updateVersion(7L); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); } @Test @@ -248,27 +248,27 @@ public void testPartitionMetaChecksumChangesOnPartitionTopLevelFields() { // RENAME PARTITION only mutates the partition name, with no visible version change; // the checksum must still change so the remote cache can detect the rename. partition.setName("p1_renamed"); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); partition.setName("p1"); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // PartitionState changes (e.g. RESTORE) must invalidate the checksum. partition.setState(Partition.PartitionState.RESTORE); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); partition.setState(Partition.PartitionState.NORMAL); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // DistributionInfo bucket-num change must invalidate the checksum. int oldBucketNum = distributionInfo.getBucketNum(); distributionInfo.setBucketNum(oldBucketNum + 2); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); distributionInfo.setBucketNum(oldBucketNum); - Assert.assertEquals(original, partition.getMetaChecksum()); + Assertions.assertEquals(original, partition.getMetaChecksum()); // nextVersion changes must invalidate the checksum (asserted last; // setNextVersion() can't be reverted to its original value safely). partition.setNextVersion(partition.getNextVersion() + 1); - Assert.assertNotEquals(original, partition.getMetaChecksum()); + Assertions.assertNotEquals(original, partition.getMetaChecksum()); } private MaterializedIndex createIndex(long indexId, long tabletId, long replicaId, long backendId) { @@ -321,7 +321,7 @@ public void testConcurrentGetTabletsNeverThrows() throws InterruptedException { writer.join(); if (error.get() != null) { - Assert.fail("getTablets() iteration threw under concurrent mutation: " + error.get()); + Assertions.fail("getTablets() iteration threw under concurrent mutation: " + error.get()); } } @@ -339,7 +339,7 @@ public void testSerialization() throws Exception { // 2. Read objects from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); MaterializedIndex rIndex = GsonUtils.GSON.fromJson(Text.readString(dis), MaterializedIndex.class); - Assert.assertEquals(index, rIndex); + Assertions.assertEquals(index, rIndex); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/MetaIdGeneratorTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/MetaIdGeneratorTest.java index 7bd1b341582a03..376a2f3c09e56b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/MetaIdGeneratorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/MetaIdGeneratorTest.java @@ -19,8 +19,8 @@ import org.apache.doris.catalog.MetaIdGenerator.IdGeneratorBuffer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MetaIdGeneratorTest { @@ -28,17 +28,17 @@ public class MetaIdGeneratorTest { @Test public void normalTest() { MetaIdGenerator idGenerator = new MetaIdGenerator(10); - Assert.assertEquals(10, idGenerator.getBatchEndId()); - Assert.assertEquals(11, idGenerator.getNextId()); - Assert.assertEquals(1010, idGenerator.getBatchEndId()); + Assertions.assertEquals(10, idGenerator.getBatchEndId()); + Assertions.assertEquals(11, idGenerator.getNextId()); + Assertions.assertEquals(1010, idGenerator.getBatchEndId()); IdGeneratorBuffer idGeneratorBuffer = idGenerator.getIdGeneratorBuffer(3500); - Assert.assertEquals(12, idGeneratorBuffer.getNextId()); - Assert.assertEquals(4010, idGenerator.getBatchEndId()); + Assertions.assertEquals(12, idGeneratorBuffer.getNextId()); + Assertions.assertEquals(4010, idGenerator.getBatchEndId()); for (int i = 1; i < 3500; i++) { - Assert.assertEquals(i + 12, idGeneratorBuffer.getNextId()); + Assertions.assertEquals(i + 12, idGeneratorBuffer.getNextId()); } - Assert.assertEquals(3511, idGeneratorBuffer.getBatchEndId()); - Assert.assertEquals(3512, idGenerator.getNextId()); + Assertions.assertEquals(3511, idGeneratorBuffer.getBatchEndId()); + Assertions.assertEquals(3512, idGenerator.getNextId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/MetadataViewerTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/MetadataViewerTest.java index 9e239c41045cec..0890234b4a6e1f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/MetadataViewerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/MetadataViewerTest.java @@ -25,11 +25,11 @@ import org.apache.doris.system.SystemInfoService; import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.mockito.MockedStatic; import org.mockito.Mockito; @@ -52,7 +52,7 @@ public class MetadataViewerTest { private static Database db; - @BeforeClass + @BeforeAll public static void setUp() throws Exception { Class[] argTypes = new Class[] {String.class, String.class, List.class, ReplicaStatus.class, Operator.class}; getTabletStatusMethod = MetadataViewer.class.getDeclaredMethod("getTabletStatus", argTypes); @@ -65,7 +65,7 @@ public static void setUp() throws Exception { db = CatalogMocker.mockDb(); } - @Before + @BeforeEach public void before() throws Exception { mockedEnvStatic = Mockito.mockStatic(Env.class); @@ -79,7 +79,7 @@ public void before() throws Exception { .thenReturn(Lists.newArrayList(10000L, 10001L, 10002L)); } - @After + @AfterEach public void after() { mockedEnvStatic.close(); } @@ -91,17 +91,17 @@ public void testGetTabletStatus() Object[] args = new Object[] { CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME, partitions, null, null }; List> result = (List>) getTabletStatusMethod.invoke(null, args); - Assert.assertEquals(3, result.size()); + Assertions.assertEquals(3, result.size()); args = new Object[] { CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME, partitions, ReplicaStatus.DEAD, Operator.EQ }; result = (List>) getTabletStatusMethod.invoke(null, args); - Assert.assertEquals(3, result.size()); + Assertions.assertEquals(3, result.size()); args = new Object[] { CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME, partitions, ReplicaStatus.DEAD, Operator.NE }; result = (List>) getTabletStatusMethod.invoke(null, args); - Assert.assertEquals(0, result.size()); + Assertions.assertEquals(0, result.size()); } @Test @@ -109,7 +109,7 @@ public void testGetTabletDistribution() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Object[] args = new Object[] { CatalogMocker.TEST_DB_NAME, CatalogMocker.TEST_TBL_NAME, null }; List> result = (List>) getTabletDistributionMethod.invoke(null, args); - Assert.assertEquals(3, result.size()); + Assertions.assertEquals(3, result.size()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ModifyBrokerInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ModifyBrokerInfoTest.java index 62ed86463a722c..f858a427acb294 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ModifyBrokerInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ModifyBrokerInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.AnalysisException; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -52,10 +52,10 @@ public void testSerialization() throws IOException, AnalysisException { BrokerMgr.ModifyBrokerInfo modifyBrokerInfo2 = BrokerMgr.ModifyBrokerInfo.read(in); - Assert.assertEquals(modifyBrokerInfo1.brokerName, modifyBrokerInfo2.brokerName); - Assert.assertEquals(modifyBrokerInfo1.brokerAddresses.get(0).host, + Assertions.assertEquals(modifyBrokerInfo1.brokerName, modifyBrokerInfo2.brokerName); + Assertions.assertEquals(modifyBrokerInfo1.brokerAddresses.get(0).host, modifyBrokerInfo2.brokerAddresses.get(0).host); - Assert.assertEquals(modifyBrokerInfo1.brokerAddresses.get(0).port, + Assertions.assertEquals(modifyBrokerInfo1.brokerAddresses.get(0).port, modifyBrokerInfo2.brokerAddresses.get(0).port); // 3. delete files diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlDbTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlDbTest.java index 6e17867b4d3b2b..d25c89179fbdc8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlDbTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlDbTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.DdlException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -29,11 +29,11 @@ public class MysqlDbTest { public void testNormal() throws IOException, DdlException { Database db = new MysqlDb(); - Assert.assertFalse(db.registerTable(null)); - Assert.assertFalse(db.createTableWithLock(null, false, false).first); + Assertions.assertFalse(db.registerTable(null)); + Assertions.assertFalse(db.createTableWithLock(null, false, false).first); db.unregisterTable("authors"); - Assert.assertThrows(IOException.class, () -> db.write(null)); - Assert.assertNull(db.getTableNullable("authors")); + Assertions.assertThrows(IOException.class, () -> db.write(null)); + Assertions.assertNull(db.getTableNullable("authors")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlTableTest.java index 6d38aade071d5f..a9242660174a14 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/MysqlTableTest.java @@ -23,10 +23,10 @@ import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.BufferedInputStream; @@ -47,7 +47,7 @@ public class MysqlTableTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { columns = Lists.newArrayList(); Column column = new Column("col1", PrimitiveType.BIGINT); @@ -67,7 +67,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -77,7 +77,7 @@ public void tearDown() { @Test public void testNormal() throws DdlException, IOException { MysqlTable mysqlTable = new MysqlTable(1000, "mysqlTable", columns, properties); - Assert.assertEquals("tbl", mysqlTable.getMysqlTableName()); + Assertions.assertEquals("tbl", mysqlTable.getMysqlTableName()); String dirString = "mysqlTableFamilyGroup"; File dir = new File(dirString); @@ -101,7 +101,7 @@ public void testNormal() throws DdlException, IOException { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); MysqlTable table1 = (MysqlTable) Table.read(dis); - Assert.assertEquals(mysqlTable.toThrift(), table1.toThrift()); + Assertions.assertEquals(mysqlTable.toThrift(), table1.toThrift()); dis.close(); @@ -117,121 +117,137 @@ public void testNormal() throws DdlException, IOException { } } - @Test(expected = DdlException.class) + @Test public void testNoHost() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("host")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("host")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testNoPort() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("port")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("port")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testPortNotNumber() throws DdlException { - Map pro = Maps.transformEntries(properties, - new Maps.EntryTransformer() { - @Override - public String transformEntry(String s, String s2) { - if (s.equalsIgnoreCase("port")) { - return "abc"; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.transformEntries(properties, + new Maps.EntryTransformer() { + @Override + public String transformEntry(String s, String s2) { + if (s.equalsIgnoreCase("port")) { + return "abc"; + } + return s2; } - return s2; - } - }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); + }); } - @Test(expected = DdlException.class) + @Test public void testNoUser() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("user")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("user")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testNoPass() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("password")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("password")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testNoDb() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("database")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("database")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testNoTbl() throws DdlException { - Map pro = Maps.filterKeys(properties, new Predicate() { - @Override - public boolean apply(String s) { - if (s.equalsIgnoreCase("table")) { - return false; - } else { - return true; + Assertions.assertThrows(DdlException.class, () -> { + Map pro = Maps.filterKeys(properties, new Predicate() { + @Override + public boolean apply(String s) { + if (s.equalsIgnoreCase("table")) { + return false; + } else { + return true; + } } - } + }); + new MysqlTable(1000, "mysqlTable", columns, pro); + Assertions.fail("No exception throws."); }); - new MysqlTable(1000, "mysqlTable", columns, pro); - Assert.fail("No exception throws."); } - @Test(expected = DdlException.class) + @Test public void testNoPro() throws DdlException { - new MysqlTable(1000, "mysqlTable", columns, null); - Assert.fail("No exception throws."); + Assertions.assertThrows(DdlException.class, () -> { + new MysqlTable(1000, "mysqlTable", columns, null); + Assertions.fail("No exception throws."); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableTest.java index 0f9b2f8c45099c..9d8e7e608d9f65 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/OlapTableTest.java @@ -37,8 +37,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -68,7 +68,7 @@ public void testPartitionFormatChangeDoesNotChangeLogicalSchemaVersion() { table.setPartitionInvertedIndexFileStorageFormat(TInvertedIndexFileStorageFormat.SNII); - Assert.assertEquals(7, table.getBaseSchemaVersion()); + Assertions.assertEquals(7, table.getBaseSchemaVersion()); } @Test @@ -82,10 +82,10 @@ public void testGetInvertedIndexFileStorageFormatForPartition() { boolean original = Config.enable_partition_inverted_index_storage_format_rollout; try { Config.enable_partition_inverted_index_storage_format_rollout = true; - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getInvertedIndexFileStorageFormatForPartition(10L)); - Assert.assertEquals(TInvertedIndexFileStorageFormat.V2, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.V2, table.getInvertedIndexFileStorageFormatForPartition(11L)); } finally { Config.enable_partition_inverted_index_storage_format_rollout = original; @@ -103,15 +103,15 @@ public void testPartitionInvertedIndexStorageFormatRolloutSwitch() { boolean original = Config.enable_partition_inverted_index_storage_format_rollout; try { Config.enable_partition_inverted_index_storage_format_rollout = false; - Assert.assertEquals(TInvertedIndexFileStorageFormat.V2, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.V2, table.getPartitionInvertedIndexFileStorageFormat()); - Assert.assertEquals(TInvertedIndexFileStorageFormat.V2, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.V2, table.getInvertedIndexFileStorageFormatForPartition(10L)); Config.enable_partition_inverted_index_storage_format_rollout = true; - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getPartitionInvertedIndexFileStorageFormat()); - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, table.getInvertedIndexFileStorageFormatForPartition(10L)); } finally { Config.enable_partition_inverted_index_storage_format_rollout = original; @@ -126,16 +126,16 @@ public void testPartitionInvertedIndexStorageFormatRolloutCannotBeDisabled() thr new Config().init(configFile.toString()); Config.enable_partition_inverted_index_storage_format_rollout = false; ConfigBase.setMutableConfig("enable_partition_inverted_index_storage_format_rollout", " false "); - Assert.assertFalse(Config.enable_partition_inverted_index_storage_format_rollout); + Assertions.assertFalse(Config.enable_partition_inverted_index_storage_format_rollout); ConfigBase.setMutableConfig("enable_partition_inverted_index_storage_format_rollout", "true"); - Assert.assertTrue(Config.enable_partition_inverted_index_storage_format_rollout); + Assertions.assertTrue(Config.enable_partition_inverted_index_storage_format_rollout); try { ConfigBase.setMutableConfig("enable_partition_inverted_index_storage_format_rollout", "false"); - Assert.fail("enabled rollout switch must not be disabled"); + Assertions.fail("enabled rollout switch must not be disabled"); } catch (ConfigException e) { - Assert.assertTrue(e.getMessage().contains("can only be enabled and cannot be disabled")); + Assertions.assertTrue(e.getMessage().contains("can only be enabled and cannot be disabled")); } } finally { Config.enable_partition_inverted_index_storage_format_rollout = original; @@ -161,10 +161,10 @@ public void testGetTableStatusStatsUsesSinglePassSemantics() { olapTable.addPartition(partition); TableIf.TableStatusStats stats = olapTable.getTableStatusStats(); - Assert.assertEquals(20L, stats.getRows()); - Assert.assertEquals(909L, stats.getDataLength()); - Assert.assertEquals(3L, stats.getAvgRowLength()); - Assert.assertEquals(132L, stats.getIndexLength()); + Assertions.assertEquals(20L, stats.getRows()); + Assertions.assertEquals(909L, stats.getDataLength()); + Assertions.assertEquals(3L, stats.getAvgRowLength()); + Assertions.assertEquals(132L, stats.getIndexLength()); } @Test @@ -174,15 +174,15 @@ public void testPartitionTopologyVersionChangesWithPartitionIdSet() { long version = olapTable.getPartitionTopologyVersion(); addPartitionForTopologyVersionTest(olapTable, 1L, "p1"); - Assert.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); + Assertions.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); version = olapTable.getPartitionTopologyVersion(); olapTable.replacePartition(newPartitionForTopologyVersionTest(2L, "p1"), new RecyclePartitionParam()); - Assert.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); + Assertions.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); version = olapTable.getPartitionTopologyVersion(); olapTable.dropPartitionAndReserveTablet("p1"); - Assert.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); + Assertions.assertEquals(version + 1, olapTable.getPartitionTopologyVersion()); } private void addPartitionForTopologyVersionTest(OlapTable olapTable, long partitionId, String partitionName) { @@ -255,15 +255,15 @@ public void testResetPropertiesForRestore() { OlapTable olapTable = new OlapTable(); olapTable.setTableProperty(tableProperty); olapTable.setColocateGroup("test_group"); - Assert.assertTrue(olapTable.isColocateTable()); - Assert.assertTrue(olapTable.getDefaultReplicaAllocation() == ReplicaAllocation.DEFAULT_ALLOCATION); + Assertions.assertTrue(olapTable.isColocateTable()); + Assertions.assertTrue(olapTable.getDefaultReplicaAllocation() == ReplicaAllocation.DEFAULT_ALLOCATION); ReplicaAllocation replicaAlloc = new ReplicaAllocation((short) 4); olapTable.resetPropertiesForRestore(false, false, replicaAlloc, false); - Assert.assertEquals(tableProperty.getProperties(), olapTable.getTableProperty().getProperties()); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(olapTable.isColocateTable()); - Assert.assertEquals((short) 4, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); + Assertions.assertEquals(tableProperty.getProperties(), olapTable.getTableProperty().getProperties()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(olapTable.isColocateTable()); + Assertions.assertEquals((short) 4, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); // restore with dynamic partition keys properties = Maps.newHashMap(); @@ -283,10 +283,10 @@ public void testResetPropertiesForRestore() { Map expectedProperties = Maps.newHashMap(properties); expectedProperties.put(DynamicPartitionProperty.ENABLE, "false"); - Assert.assertEquals(expectedProperties, olapTable.getTableProperty().getProperties()); - Assert.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().isExist()); - Assert.assertFalse(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); - Assert.assertEquals((short) 3, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); + Assertions.assertEquals(expectedProperties, olapTable.getTableProperty().getProperties()); + Assertions.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().isExist()); + Assertions.assertFalse(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertEquals((short) 3, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); } @Test @@ -302,7 +302,7 @@ public void testBfIndexTableLevelFppDoesNotAffectSignature() throws IOException break; } } - Assert.assertNotNull(olapTable); + Assertions.assertNotNull(olapTable); olapTable.setIndexes(Lists.newArrayList(new Index(1L, "bf_v1", Lists.newArrayList("v1"), IndexType.BLOOMFILTER, null, ""))); @@ -314,7 +314,7 @@ public void testBfIndexTableLevelFppDoesNotAffectSignature() throws IOException olapTable.setBloomFilterInfo(null, 0.02); String signatureWithFpp002 = olapTable.getSignature(1, Lists.newArrayList(olapTable.getPartitionNames())); - Assert.assertEquals(signatureWithFpp001, signatureWithFpp002); + Assertions.assertEquals(signatureWithFpp001, signatureWithFpp002); } } @@ -358,19 +358,19 @@ public void testResetPropertiesForRestoreInCloudMode() { olapTable.resetPropertiesForRestore(true, false, cloudReplicaAlloc, false); Map resultProps = olapTable.getTableProperty().getProperties(); - Assert.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_INMEMORY)); - Assert.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_MEDIUM)); - Assert.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_POLICY)); - Assert.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME)); - Assert.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_MIN_LOAD_REPLICA_NUM)); - Assert.assertEquals((short) 1, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); - Assert.assertFalse(olapTable.getTableProperty().isInMemory()); - Assert.assertNull(olapTable.getTableProperty().getStorageMedium()); - Assert.assertEquals("", olapTable.getTableProperty().getStoragePolicy()); - Assert.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); - Assert.assertTrue(resultProps.containsKey(DynamicPartitionProperty.REPLICATION_NUM)); - Assert.assertTrue(resultProps.containsKey(DynamicPartitionProperty.REPLICATION_ALLOCATION)); - Assert.assertFalse(resultProps.containsKey(DynamicPartitionProperty.STORAGE_MEDIUM)); + Assertions.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_INMEMORY)); + Assertions.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_MEDIUM)); + Assertions.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_POLICY)); + Assertions.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME)); + Assertions.assertFalse(resultProps.containsKey(PropertyAnalyzer.PROPERTIES_MIN_LOAD_REPLICA_NUM)); + Assertions.assertEquals((short) 1, olapTable.getDefaultReplicaAllocation().getTotalReplicaNum()); + Assertions.assertFalse(olapTable.getTableProperty().isInMemory()); + Assertions.assertNull(olapTable.getTableProperty().getStorageMedium()); + Assertions.assertEquals("", olapTable.getTableProperty().getStoragePolicy()); + Assertions.assertTrue(olapTable.getTableProperty().getDynamicPartitionProperty().getEnable()); + Assertions.assertTrue(resultProps.containsKey(DynamicPartitionProperty.REPLICATION_NUM)); + Assertions.assertTrue(resultProps.containsKey(DynamicPartitionProperty.REPLICATION_ALLOCATION)); + Assertions.assertFalse(resultProps.containsKey(DynamicPartitionProperty.STORAGE_MEDIUM)); } } @@ -393,13 +393,13 @@ public void testResetPartitionIdForRestore() { mockedConfig.when(Config::isNotCloudMode).thenReturn(true); partitionInfo.resetPartitionIdForRestore(partitionIdMap, restoreReplicaAlloc, false); - Assert.assertEquals((short) 2, + Assertions.assertEquals((short) 2, partitionInfo.getReplicaAllocation(newPartId).getTotalReplicaNum()); DataProperty newDataProperty = partitionInfo.getDataProperty(newPartId); - Assert.assertEquals(TStorageMedium.SSD, newDataProperty.getStorageMedium()); - Assert.assertEquals(1735689600000L, newDataProperty.getCooldownTimeMs()); - Assert.assertEquals("s3_policy", newDataProperty.getStoragePolicy()); - Assert.assertTrue(partitionInfo.getIsInMemory(newPartId)); + Assertions.assertEquals(TStorageMedium.SSD, newDataProperty.getStorageMedium()); + Assertions.assertEquals(1735689600000L, newDataProperty.getCooldownTimeMs()); + Assertions.assertEquals("s3_policy", newDataProperty.getStoragePolicy()); + Assertions.assertTrue(partitionInfo.getIsInMemory(newPartId)); } } @@ -425,14 +425,14 @@ public void testResetPartitionIdForRestoreInCloudMode() { mockedPA.when(PropertyAnalyzer::getInstance).thenReturn(new CloudPropertyAnalyzer()); partitionInfo.resetPartitionIdForRestore(partitionIdMap, cloudReplicaAlloc, false); - Assert.assertEquals((short) 1, + Assertions.assertEquals((short) 1, partitionInfo.getReplicaAllocation(newPartId).getTotalReplicaNum()); DataProperty newDataProperty = partitionInfo.getDataProperty(newPartId); - Assert.assertEquals(DataProperty.DEFAULT_STORAGE_MEDIUM, newDataProperty.getStorageMedium()); - Assert.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, newDataProperty.getCooldownTimeMs()); - Assert.assertEquals("", newDataProperty.getStoragePolicy()); - Assert.assertTrue(newDataProperty.isMutable()); - Assert.assertFalse(partitionInfo.getIsInMemory(newPartId)); + Assertions.assertEquals(DataProperty.DEFAULT_STORAGE_MEDIUM, newDataProperty.getStorageMedium()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, newDataProperty.getCooldownTimeMs()); + Assertions.assertEquals("", newDataProperty.getStoragePolicy()); + Assertions.assertTrue(newDataProperty.isMutable()); + Assertions.assertFalse(partitionInfo.getIsInMemory(newPartId)); } } @@ -444,10 +444,10 @@ public void testBuildVariantEnableFlattenNestedWithLegacyPropertyKey() throws IO TableProperty tableProperty = new TableProperty(properties); tableProperty.gsonPostProcess(); - Assert.assertTrue(tableProperty.variantEnableFlattenNested()); - Assert.assertEquals("true", + Assertions.assertTrue(tableProperty.variantEnableFlattenNested()); + Assertions.assertEquals("true", tableProperty.getProperties().get(PropertyAnalyzer.PROPERTIES_VARIANT_ENABLE_FLATTEN_NESTED)); - Assert.assertFalse( + Assertions.assertFalse( tableProperty.getProperties().containsKey(PropertyAnalyzer.LEGACY_PROPERTIES_VARIANT_ENABLE_FLATTEN_NESTED)); } @@ -456,44 +456,44 @@ public void testGetPartitionRowCount() { OlapTable olapTable = new OlapTable(); // Partition is null. long row = olapTable.getRowCountForPartitionIndex(0, 0, true); - Assert.assertEquals(-1, row); + Assertions.assertEquals(-1, row); // Index is null. MaterializedIndex index = new MaterializedIndex(10, MaterializedIndex.IndexState.NORMAL); Partition partition = new Partition(11, "p1", index, null); olapTable.addPartition(partition); row = olapTable.getRowCountForPartitionIndex(11, 0, true); - Assert.assertEquals(-1, row); + Assertions.assertEquals(-1, row); // Strict is true and index is not reported. index.setRowCountReported(false); index.setRowCount(100); row = olapTable.getRowCountForPartitionIndex(11, 10, true); - Assert.assertEquals(-1, row); + Assertions.assertEquals(-1, row); // Strict is true and index is reported. index.setRowCountReported(true); index.setRowCount(101); row = olapTable.getRowCountForPartitionIndex(11, 10, true); - Assert.assertEquals(101, row); + Assertions.assertEquals(101, row); // Strict is false and index is not reported. index.setRowCountReported(false); index.setRowCount(102); row = olapTable.getRowCountForPartitionIndex(11, 10, false); - Assert.assertEquals(102, row); + Assertions.assertEquals(102, row); // Reported row is -1, we should return 0 index.setRowCountReported(true); index.setRowCount(-1); row = olapTable.getRowCountForPartitionIndex(11, 10, false); - Assert.assertEquals(0, row); + Assertions.assertEquals(0, row); // Return reported row. index.setRowCountReported(true); index.setRowCount(103); row = olapTable.getRowCountForPartitionIndex(11, 10, false); - Assert.assertEquals(103, row); + Assertions.assertEquals(103, row); olapTable.getRowCountForPartitionIndex(11, 10, true); } @@ -526,36 +526,36 @@ public void testGetSchemaAllIndexes() { Mockito.doReturn(Lists.newArrayList(index1)).when(table).getVisibleIndex(); Set schemaAllIndexes = table.getSchemaAllIndexes(false); - Assert.assertEquals(2, schemaAllIndexes.size()); - Assert.assertFalse(schemaAllIndexes.contains(col3)); - Assert.assertFalse(schemaAllIndexes.contains(col4)); - Assert.assertTrue(schemaAllIndexes.contains(col1)); - Assert.assertTrue(schemaAllIndexes.contains(col2)); + Assertions.assertEquals(2, schemaAllIndexes.size()); + Assertions.assertFalse(schemaAllIndexes.contains(col3)); + Assertions.assertFalse(schemaAllIndexes.contains(col4)); + Assertions.assertTrue(schemaAllIndexes.contains(col1)); + Assertions.assertTrue(schemaAllIndexes.contains(col2)); MaterializedIndex index2 = new MaterializedIndex(2, MaterializedIndex.IndexState.NORMAL); Mockito.doReturn(Lists.newArrayList(index2)).when(table).getVisibleIndex(); schemaAllIndexes = table.getSchemaAllIndexes(false); - Assert.assertEquals(2, schemaAllIndexes.size()); - Assert.assertTrue(schemaAllIndexes.contains(col3)); - Assert.assertTrue(schemaAllIndexes.contains(col4)); - Assert.assertFalse(schemaAllIndexes.contains(col1)); - Assert.assertFalse(schemaAllIndexes.contains(col2)); + Assertions.assertEquals(2, schemaAllIndexes.size()); + Assertions.assertTrue(schemaAllIndexes.contains(col3)); + Assertions.assertTrue(schemaAllIndexes.contains(col4)); + Assertions.assertFalse(schemaAllIndexes.contains(col1)); + Assertions.assertFalse(schemaAllIndexes.contains(col2)); Mockito.doReturn(Lists.newArrayList(index1, index2)).when(table).getVisibleIndex(); schemaAllIndexes = table.getSchemaAllIndexes(false); - Assert.assertEquals(4, schemaAllIndexes.size()); - Assert.assertTrue(schemaAllIndexes.contains(col3)); - Assert.assertTrue(schemaAllIndexes.contains(col4)); - Assert.assertTrue(schemaAllIndexes.contains(col1)); - Assert.assertTrue(schemaAllIndexes.contains(col2)); + Assertions.assertEquals(4, schemaAllIndexes.size()); + Assertions.assertTrue(schemaAllIndexes.contains(col3)); + Assertions.assertTrue(schemaAllIndexes.contains(col4)); + Assertions.assertTrue(schemaAllIndexes.contains(col1)); + Assertions.assertTrue(schemaAllIndexes.contains(col2)); col1.setIsVisible(false); schemaAllIndexes = table.getSchemaAllIndexes(false); - Assert.assertEquals(3, schemaAllIndexes.size()); - Assert.assertTrue(schemaAllIndexes.contains(col3)); - Assert.assertTrue(schemaAllIndexes.contains(col4)); - Assert.assertFalse(schemaAllIndexes.contains(col1)); - Assert.assertTrue(schemaAllIndexes.contains(col2)); + Assertions.assertEquals(3, schemaAllIndexes.size()); + Assertions.assertTrue(schemaAllIndexes.contains(col3)); + Assertions.assertTrue(schemaAllIndexes.contains(col4)); + Assertions.assertFalse(schemaAllIndexes.contains(col1)); + Assertions.assertTrue(schemaAllIndexes.contains(col2)); } @Test @@ -598,36 +598,36 @@ public Database getDatabase() { try { // Test 1: Initial state with TTL set, should still call RPC for first time ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 100000; // Set long TTL - Assert.assertEquals(-1, table.getCachedTableVersion()); // Initial state - Assert.assertTrue(table.isCachedTableVersionExpired()); // Should be expired due to -1 + Assertions.assertEquals(-1, table.getCachedTableVersion()); // Initial state + Assertions.assertTrue(table.isCachedTableVersionExpired()); // Should be expired due to -1 long ver0 = table.getVisibleVersion(); - Assert.assertEquals(100, ver0); // Should get from MS - Assert.assertEquals(1, callCount[0]); // First RPC call - Assert.assertEquals(100, table.getCachedTableVersion()); // Cache updated + Assertions.assertEquals(100, ver0); // Should get from MS + Assertions.assertEquals(1, callCount[0]); // First RPC call + Assertions.assertEquals(100, table.getCachedTableVersion()); // Cache updated // Second call should use cache long ver0Again = table.getVisibleVersion(); - Assert.assertEquals(100, ver0Again); // Should use cached version - Assert.assertEquals(1, callCount[0]); // No new RPC call + Assertions.assertEquals(100, ver0Again); // Should use cached version + Assertions.assertEquals(1, callCount[0]); // No new RPC call // Test 2: Disable cache (TTL = 0), should always call RPC ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 0; long ver1 = table.getVisibleVersion(); - Assert.assertEquals(200, ver1); - Assert.assertEquals(2, callCount[0]); // Second RPC call + Assertions.assertEquals(200, ver1); + Assertions.assertEquals(2, callCount[0]); // Second RPC call long ver2 = table.getVisibleVersion(); - Assert.assertEquals(300, ver2); - Assert.assertEquals(3, callCount[0]); // Third RPC call - Assert.assertEquals(300, table.getCachedTableVersion()); // Cache updated to 300 + Assertions.assertEquals(300, ver2); + Assertions.assertEquals(3, callCount[0]); // Third RPC call + Assertions.assertEquals(300, table.getCachedTableVersion()); // Cache updated to 300 // Test 3: Enable cache with long TTL, should use cached version ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 100000; // 100 seconds table.setCachedTableVersion(350); // Set cache to a larger version long ver3 = table.getVisibleVersion(); - Assert.assertEquals(350, ver3); // Should return cached version (350) - Assert.assertEquals(3, callCount[0]); // No new RPC call + Assertions.assertEquals(350, ver3); // Should return cached version (350) + Assertions.assertEquals(3, callCount[0]); // No new RPC call // Test 4: Test setCachedTableVersion only updates when version is greater ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 500; // 500ms TTL @@ -635,35 +635,35 @@ public Database getDatabase() { // At this point, cache is 350 from Test 3 // Set a larger version to 400 table.setCachedTableVersion(400); - Assert.assertEquals(400, table.getCachedTableVersion()); - Assert.assertFalse(table.isCachedTableVersionExpired()); // Not expired yet + Assertions.assertEquals(400, table.getCachedTableVersion()); + Assertions.assertFalse(table.isCachedTableVersionExpired()); // Not expired yet Thread.sleep(300); // Sleep 300ms // Try to set a smaller version (380), should NOT update version or timestamp table.setCachedTableVersion(380); - Assert.assertEquals(400, table.getCachedTableVersion()); // Version should remain 400 + Assertions.assertEquals(400, table.getCachedTableVersion()); // Version should remain 400 Thread.sleep(300); // Total 600ms since setCachedTableVersion(400) // Cache should be expired (600ms > 500ms TTL) // If timestamp was incorrectly reset by setCachedTableVersion(380), cache would not be expired - Assert.assertTrue(table.isCachedTableVersionExpired()); + Assertions.assertTrue(table.isCachedTableVersionExpired()); // Test 5: Setting a greater version should update both version and timestamp ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 500; // 500ms TTL table.setCachedTableVersion(500); // Set to 500 - Assert.assertEquals(500, table.getCachedTableVersion()); - Assert.assertFalse(table.isCachedTableVersionExpired()); // Not expired + Assertions.assertEquals(500, table.getCachedTableVersion()); + Assertions.assertFalse(table.isCachedTableVersionExpired()); // Not expired Thread.sleep(300); // Sleep 300ms // Set a greater version (550), should update both version and timestamp table.setCachedTableVersion(550); - Assert.assertEquals(550, table.getCachedTableVersion()); // Version updated to 550 - Assert.assertFalse(table.isCachedTableVersionExpired()); // Timestamp reset, not expired yet + Assertions.assertEquals(550, table.getCachedTableVersion()); // Version updated to 550 + Assertions.assertFalse(table.isCachedTableVersionExpired()); // Timestamp reset, not expired yet Thread.sleep(300); // Sleep another 300ms (total 600ms from first setCachedTableVersion(500), but only 300ms from setCachedTableVersion(550)) - Assert.assertFalse(table.isCachedTableVersionExpired()); // Still not expired (300ms < 500ms TTL) + Assertions.assertFalse(table.isCachedTableVersionExpired()); // Still not expired (300ms < 500ms TTL) } finally { ConnectContext.remove(); @@ -734,24 +734,24 @@ public void testGetVisibleVersionInBatchCached() throws Exception { ctx.getSessionVariable().cloudTableVersionCacheTtlMs = -1; { List versions = OlapTable.getVisibleVersionInBatch(tables); - Assert.assertEquals(1, callCount[0]); - Assert.assertEquals(Arrays.asList(10L, 20L, 30L), versions); + Assertions.assertEquals(1, callCount[0]); + Assertions.assertEquals(Arrays.asList(10L, 20L, 30L), versions); } // Test 2: cache enabled with long TTL, all should hit cache ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 100000; { List versions = OlapTable.getVisibleVersionInBatch(tables); - Assert.assertEquals(1, callCount[0]); - Assert.assertEquals(Arrays.asList(10L, 20L, 30L), versions); + Assertions.assertEquals(1, callCount[0]); + Assertions.assertEquals(Arrays.asList(10L, 20L, 30L), versions); } // Test 3: cache disabled (TTL = 0), all fetched from MS again ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 0; { List versions = OlapTable.getVisibleVersionInBatch(tables); - Assert.assertEquals(2, callCount[0]); - Assert.assertEquals(Arrays.asList(11L, 21L, 31L), versions); + Assertions.assertEquals(2, callCount[0]); + Assertions.assertEquals(Arrays.asList(11L, 21L, 31L), versions); } // Test 4: short TTL, wait for expiration, then partially refresh @@ -761,27 +761,27 @@ public void testGetVisibleVersionInBatchCached() throws Exception { // refresh one table's cache so it stays hot OlapTable hotTable = tables.get(0); hotTable.setCachedTableVersion(hotTable.getCachedTableVersion()); - Assert.assertFalse(hotTable.isCachedTableVersionExpired()); - Assert.assertTrue(tables.get(1).isCachedTableVersionExpired()); - Assert.assertTrue(tables.get(2).isCachedTableVersionExpired()); + Assertions.assertFalse(hotTable.isCachedTableVersionExpired()); + Assertions.assertTrue(tables.get(1).isCachedTableVersionExpired()); + Assertions.assertTrue(tables.get(2).isCachedTableVersionExpired()); { // batchVersions[2] = [22, 32] for the 2 expired tables List versions = OlapTable.getVisibleVersionInBatch(tables); - Assert.assertEquals(3, callCount[0]); - Assert.assertEquals(3, versions.size()); + Assertions.assertEquals(3, callCount[0]); + Assertions.assertEquals(3, versions.size()); // hot table keeps its cached version - Assert.assertEquals(11L, versions.get(0).longValue()); + Assertions.assertEquals(11L, versions.get(0).longValue()); // expired tables get new versions from MS - Assert.assertEquals(22L, versions.get(1).longValue()); - Assert.assertEquals(32L, versions.get(2).longValue()); + Assertions.assertEquals(22L, versions.get(1).longValue()); + Assertions.assertEquals(32L, versions.get(2).longValue()); } // Test 5: all expired again, full batch fetch ctx.getSessionVariable().cloudTableVersionCacheTtlMs = 0; { List versions = OlapTable.getVisibleVersionInBatch(tables); - Assert.assertEquals(4, callCount[0]); - Assert.assertEquals(Arrays.asList(13L, 23L, 33L), versions); + Assertions.assertEquals(4, callCount[0]); + Assertions.assertEquals(Arrays.asList(13L, 23L, 33L), versions); } } finally { ConnectContext.remove(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/PartitionKeyTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/PartitionKeyTest.java index b5148f982eacf7..d331cbe0407adf 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/PartitionKeyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/PartitionKeyTest.java @@ -23,9 +23,9 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.qe.ConnectContext; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -54,7 +54,7 @@ public class PartitionKeyTest { private Env env; - @BeforeClass + @BeforeAll public static void setUp() { TimeZone tz = TimeZone.getTimeZone("ETC/GMT-0"); TimeZone.setDefault(tz); @@ -83,61 +83,61 @@ public void compareTest() throws AnalysisException { pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("32767")), Arrays.asList(tinyInt, smallInt)); pk2 = PartitionKey.createInfinityPartitionKey(Arrays.asList(tinyInt, smallInt), true); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case2 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127")), Arrays.asList(tinyInt, smallInt)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("-32768")), Arrays.asList(tinyInt, smallInt)); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); // case3 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127")), Arrays.asList(int32, bigInt)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("128"), new PartitionValue("-32768")), Arrays.asList(int32, bigInt)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case4 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("12345")), Arrays.asList(largeInt, bigInt)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("12346")), Arrays.asList(largeInt, bigInt)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case5 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("2014-12-12"), new PartitionValue("2014-12-12 10:00:00")), Arrays.asList(date, datetime)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("2014-12-12"), new PartitionValue("2014-12-12 10:00:01")), Arrays.asList(date, datetime)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case6 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("-128")), Arrays.asList(tinyInt, smallInt)); pk2 = PartitionKey.createInfinityPartitionKey(Arrays.asList(tinyInt, smallInt), false); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); // case7 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127")), Arrays.asList(tinyInt, smallInt)); pk2 = PartitionKey.createInfinityPartitionKey(Arrays.asList(tinyInt, smallInt), true); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case7 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("32767")), Arrays.asList(tinyInt, smallInt)); pk2 = PartitionKey.createInfinityPartitionKey(Arrays.asList(tinyInt, smallInt), true); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case8 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("127"), new PartitionValue("32767"), @@ -146,8 +146,8 @@ public void compareTest() throws AnalysisException { new PartitionValue("9999-12-31"), new PartitionValue("9999-12-31 23:59:59")), allColumns); pk2 = PartitionKey.createInfinityPartitionKey(allColumns, true); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case9 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("-128"), new PartitionValue("-32768"), @@ -156,8 +156,8 @@ public void compareTest() throws AnalysisException { new PartitionValue("0000-01-01"), new PartitionValue("0000-01-01 00:00:00")), allColumns); pk2 = PartitionKey.createInfinityPartitionKey(allColumns, false); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); // case10 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("-128"), new PartitionValue("-32768"), @@ -165,56 +165,56 @@ public void compareTest() throws AnalysisException { new PartitionValue("0"), new PartitionValue("1970-01-01"), new PartitionValue("1970-01-01 00:00:00")), allColumns); pk2 = PartitionKey.createInfinityPartitionKey(allColumns, false); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == 1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == 1); // case11 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("beijing"), new PartitionValue("shanghai")), Arrays.asList(charString, varchar)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("beijing"), new PartitionValue("shanghai")), Arrays.asList(charString, varchar)); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); // case12 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("beijing"), new PartitionValue("shanghai")), Arrays.asList(charString, varchar)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("shijiazhuang"), new PartitionValue("tianjin")), Arrays.asList(charString, varchar)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case13 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("beijing"), new PartitionValue("shanghai")), Arrays.asList(charString, varchar)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("beijing"), new PartitionValue("tianjin")), Arrays.asList(charString, varchar)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == -1); // case14 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("true")), Arrays.asList(bool)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("false")), Arrays.asList(bool)); - Assert.assertTrue(pk1.hashCode() != pk2.hashCode()); - Assert.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == 1); + Assertions.assertTrue(pk1.hashCode() != pk2.hashCode()); + Assertions.assertTrue(!pk1.equals(pk2) && pk1.compareTo(pk2) == 1); // case15 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("true")), Arrays.asList(bool)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("true")), Arrays.asList(bool)); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); // case16 pk1 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("false")), Arrays.asList(bool)); pk2 = PartitionKey.createPartitionKey(Arrays.asList(new PartitionValue("false")), Arrays.asList(bool)); - Assert.assertTrue(pk1.hashCode() == pk2.hashCode()); - Assert.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); + Assertions.assertTrue(pk1.hashCode() == pk2.hashCode()); + Assertions.assertTrue(pk1.equals(pk2) && pk1.compareTo(pk2) == 0); } @Test @@ -261,7 +261,7 @@ public void testSerialization() throws Exception { List types = new ArrayList(); types.add(ScalarType.createType(PrimitiveType.INT)); PartitionKey defaultKey = PartitionKey.createListPartitionKeyWithTypes(keys, types, false); - Assert.assertTrue(defaultKey.isDefaultListPartitionKey()); + Assertions.assertTrue(defaultKey.isDefaultListPartitionKey()); defaultKey.write(dos); dos.flush(); @@ -270,16 +270,16 @@ public void testSerialization() throws Exception { // 2. Read objects from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); PartitionKey rKeyEmpty = PartitionKey.read(dis); - Assert.assertEquals(keyEmpty, rKeyEmpty); + Assertions.assertEquals(keyEmpty, rKeyEmpty); PartitionKey rKey = PartitionKey.read(dis); - Assert.assertEquals(key, rKey); - Assert.assertEquals(key, key); - Assert.assertNotEquals(key, this); + Assertions.assertEquals(key, rKey); + Assertions.assertEquals(key, key); + Assertions.assertNotEquals(key, this); PartitionKey rDefaultKey = PartitionKey.read(dis); - Assert.assertEquals(defaultKey, rDefaultKey); - Assert.assertTrue(rDefaultKey.isDefaultListPartitionKey()); + Assertions.assertEquals(defaultKey, rDefaultKey); + Assertions.assertTrue(rDefaultKey.isDefaultListPartitionKey()); // 3. delete files dis.close(); @@ -289,7 +289,7 @@ public void testSerialization() throws Exception { @Test public void testMaxValueToSql() throws Exception { PartitionKey key = PartitionKey.createInfinityPartitionKey(allColumns, true); - Assert.assertEquals("(MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE)", key.toSql()); + Assertions.assertEquals("(MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE, MAXVALUE)", key.toSql()); } @Test @@ -306,15 +306,15 @@ public void testTimestampTzPartitionKeyKeepsExplicitOffset() throws Exception { Arrays.asList(timestampTz)); DateLiteral literal = (DateLiteral) key.getKeys().get(0); - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertEquals(0, literal.getMicrosecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertEquals(0, literal.getMicrosecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } finally { ConnectContext.remove(); FeConstants.runningUnitTest = originalRunningUnitTest; @@ -328,15 +328,15 @@ public void testTimestampTzPartitionKeyAcceptsNamedTimezone() throws Exception { Arrays.asList(timestampTz)); DateLiteral literal = (DateLiteral) key.getKeys().get(0); - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertEquals(0, literal.getMicrosecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertEquals(0, literal.getMicrosecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } @Test @@ -346,15 +346,15 @@ public void testTimestampTzPartitionKeyAcceptsLowercaseTimezone() throws Excepti Arrays.asList(timestampTz)); DateLiteral literal = (DateLiteral) key.getKeys().get(0); - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertEquals(0, literal.getMicrosecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertEquals(0, literal.getMicrosecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } @Test @@ -371,15 +371,15 @@ public void testTimestampTzPartitionKeyUsesSessionTimezoneWithoutExplicitOffset( Arrays.asList(timestampTz)); DateLiteral literal = (DateLiteral) key.getKeys().get(0); - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(17, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertEquals(0, literal.getMicrosecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 17:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(17, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertEquals(0, literal.getMicrosecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 17:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } finally { ConnectContext.remove(); FeConstants.runningUnitTest = originalRunningUnitTest; @@ -397,14 +397,14 @@ public void testListTimestampTzPartitionKeyAcceptsNamedTimezone() throws Excepti DateLiteral literal = (DateLiteral) key.getKeys().get(0); // Asia/Shanghai (UTC+8) → 20:00 - 8h = 12:00 UTC - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } @Test @@ -417,14 +417,14 @@ public void testListTimestampTzPartitionKeyAcceptsLowercaseTimezone() throws Exc DateLiteral literal = (DateLiteral) key.getKeys().get(0); // uTc = UTC → no offset change - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } @Test @@ -436,13 +436,13 @@ public void testListTimestampTzPartitionKeyKeepsExplicitOffset() throws Exceptio false); DateLiteral literal = (DateLiteral) key.getKeys().get(0); - Assert.assertEquals(2024, literal.getYear()); - Assert.assertEquals(1, literal.getMonth()); - Assert.assertEquals(15, literal.getDay()); - Assert.assertEquals(12, literal.getHour()); - Assert.assertEquals(0, literal.getMinute()); - Assert.assertEquals(0, literal.getSecond()); - Assert.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); - Assert.assertTrue(literal.getStringValue().endsWith("+00:00")); + Assertions.assertEquals(2024, literal.getYear()); + Assertions.assertEquals(1, literal.getMonth()); + Assertions.assertEquals(15, literal.getDay()); + Assertions.assertEquals(12, literal.getHour()); + Assertions.assertEquals(0, literal.getMinute()); + Assertions.assertEquals(0, literal.getSecond()); + Assertions.assertTrue(literal.getStringValue().startsWith("2024-01-15 12:00:00")); + Assertions.assertTrue(literal.getStringValue().endsWith("+00:00")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/RangePartitionInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/RangePartitionInfoTest.java index d4078d47e421fe..9403111657044b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/RangePartitionInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/RangePartitionInfoTest.java @@ -32,9 +32,9 @@ import org.apache.doris.persist.gson.GsonUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -52,81 +52,89 @@ public class RangePartitionInfoTest { private List singlePartitionDescs; - @Before + @BeforeEach public void setUp() { partitionColumns = new LinkedList(); singlePartitionDescs = new LinkedList(); } - @Test(expected = DdlException.class) + @Test public void testTinyInt() throws DdlException, AnalysisException { - Column k1 = new Column("k1", new ScalarType(PrimitiveType.TINYINT), true, null, "", ""); - partitionColumns.add(k1); + Assertions.assertThrows(DdlException.class, () -> { + Column k1 = new Column("k1", new ScalarType(PrimitiveType.TINYINT), true, null, "", ""); + partitionColumns.add(k1); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", - PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-128"))), - null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", + PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-128"))), + null)); - partitionInfo = new RangePartitionInfo(partitionColumns); - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(1, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + partitionInfo = new RangePartitionInfo(partitionColumns); + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(1, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } - @Test(expected = DdlException.class) + @Test public void testSmallInt() throws DdlException, AnalysisException { - Column k1 = new Column("k1", new ScalarType(PrimitiveType.SMALLINT), true, null, "", ""); - partitionColumns.add(k1); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", - PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-32768"))), - null)); - - partitionInfo = new RangePartitionInfo(partitionColumns); - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(1, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + Assertions.assertThrows(DdlException.class, () -> { + Column k1 = new Column("k1", new ScalarType(PrimitiveType.SMALLINT), true, null, "", ""); + partitionColumns.add(k1); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", + PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-32768"))), + null)); + + partitionInfo = new RangePartitionInfo(partitionColumns); + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(1, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } - @Test(expected = DdlException.class) + @Test public void testInt() throws DdlException, AnalysisException { - Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); - partitionColumns.add(k1); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", - PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-2147483648"))), - null)); - - partitionInfo = new RangePartitionInfo(partitionColumns); - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(1, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + Assertions.assertThrows(DdlException.class, () -> { + Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); + partitionColumns.add(k1); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", + PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("-2147483648"))), + null)); + + partitionInfo = new RangePartitionInfo(partitionColumns); + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(1, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } - @Test(expected = DdlException.class) + @Test public void testBigInt() throws DdlException, AnalysisException { - Column k1 = new Column("k1", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); - partitionColumns.add(k1); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", PartitionKeyDesc.createLessThan(Lists - .newArrayList(new PartitionValue("-9223372036854775808"))), null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", PartitionKeyDesc.createLessThan(Lists - .newArrayList(new PartitionValue("-9223372036854775806"))), null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", PartitionKeyDesc.createLessThan(Lists - .newArrayList(new PartitionValue("0"))), null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p4", PartitionKeyDesc.createLessThan(Lists - .newArrayList(new PartitionValue("9223372036854775806"))), null)); - - partitionInfo = new RangePartitionInfo(partitionColumns); - - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(1, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + Assertions.assertThrows(DdlException.class, () -> { + Column k1 = new Column("k1", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); + partitionColumns.add(k1); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", PartitionKeyDesc.createLessThan(Lists + .newArrayList(new PartitionValue("-9223372036854775808"))), null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", PartitionKeyDesc.createLessThan(Lists + .newArrayList(new PartitionValue("-9223372036854775806"))), null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", PartitionKeyDesc.createLessThan(Lists + .newArrayList(new PartitionValue("0"))), null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p4", PartitionKeyDesc.createLessThan(Lists + .newArrayList(new PartitionValue("9223372036854775806"))), null)); + + partitionInfo = new RangePartitionInfo(partitionColumns); + + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(1, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } @Test @@ -203,40 +211,42 @@ public void testFixedRange() throws DdlException, AnalysisException { * partition p3 values less than("2021-02-01") * ) */ - @Test(expected = AnalysisException.class) + @Test public void testFixedRange1() throws DdlException, AnalysisException { - //add columns - Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATE), true, null, "", ""); - Column k2 = new Column("k2", new ScalarType(PrimitiveType.INT), true, null, "", ""); - Column k3 = new Column("k3", new ScalarType(PrimitiveType.INT), true, null, "", ""); - partitionColumns.add(k1); - partitionColumns.add(k2); - partitionColumns.add(k3); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createLessThan( - Lists.newArrayList(new PartitionValue("2019-02-01"), new PartitionValue("100"), new PartitionValue("200"))); - PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2020-02-01"), new PartitionValue("100"), new PartitionValue("200")), - Lists.newArrayList(new PartitionValue("2020-03-01"))); - PartitionKeyDesc p3 = PartitionKeyDesc.createLessThan( - Lists.newArrayList(new PartitionValue("2021-02-01"))); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); - partitionInfo = new RangePartitionInfo(partitionColumns); - PartitionKeyValueType partitionKeyValueType = PartitionKeyValueType.INVALID; - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - // check partitionType - if (partitionKeyValueType == PartitionKeyValueType.INVALID) { - partitionKeyValueType = singlePartitionDesc.getPartitionKeyDesc().getPartitionType(); - } else if (partitionKeyValueType != singlePartitionDesc.getPartitionKeyDesc().getPartitionType()) { - throw new AnalysisException("You can only use one of these methods to create partitions"); + Assertions.assertThrows(AnalysisException.class, () -> { + //add columns + Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATE), true, null, "", ""); + Column k2 = new Column("k2", new ScalarType(PrimitiveType.INT), true, null, "", ""); + Column k3 = new Column("k3", new ScalarType(PrimitiveType.INT), true, null, "", ""); + partitionColumns.add(k1); + partitionColumns.add(k2); + partitionColumns.add(k3); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createLessThan( + Lists.newArrayList(new PartitionValue("2019-02-01"), new PartitionValue("100"), new PartitionValue("200"))); + PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2020-02-01"), new PartitionValue("100"), new PartitionValue("200")), + Lists.newArrayList(new PartitionValue("2020-03-01"))); + PartitionKeyDesc p3 = PartitionKeyDesc.createLessThan( + Lists.newArrayList(new PartitionValue("2021-02-01"))); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); + partitionInfo = new RangePartitionInfo(partitionColumns); + PartitionKeyValueType partitionKeyValueType = PartitionKeyValueType.INVALID; + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + // check partitionType + if (partitionKeyValueType == PartitionKeyValueType.INVALID) { + partitionKeyValueType = singlePartitionDesc.getPartitionKeyDesc().getPartitionType(); + } else if (partitionKeyValueType != singlePartitionDesc.getPartitionKeyDesc().getPartitionType()) { + throw new AnalysisException("You can only use one of these methods to create partitions"); + } + singlePartitionDesc.analyze(partitionColumns.size(), null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - singlePartitionDesc.analyze(partitionColumns.size(), null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + }); } /** @@ -273,28 +283,30 @@ public void testFixedRange2() throws DdlException, AnalysisException { * PARTITION p1 VALUES [("20190301", "400"), ()) * ) */ - @Test (expected = AnalysisException.class) + @Test public void testFixedRange3() throws DdlException, AnalysisException { - //add columns - int columns = 2; - Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); - Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); - partitionColumns.add(k1); - partitionColumns.add(k2); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("200")), - new ArrayList<>()); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - - partitionInfo = new RangePartitionInfo(partitionColumns); - - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(columns, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + Assertions.assertThrows(AnalysisException.class, () -> { + //add columns + int columns = 2; + Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); + Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); + partitionColumns.add(k1); + partitionColumns.add(k2); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("200")), + new ArrayList<>()); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + + partitionInfo = new RangePartitionInfo(partitionColumns); + + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(columns, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } /** @@ -332,128 +344,136 @@ public void testFixedRange4() throws DdlException, AnalysisException { * PARTITION p0 VALUES [("20190101", "100"),("20190101", "100")) * ) */ - @Test (expected = DdlException.class) + @Test public void testFixedRange5() throws DdlException, AnalysisException { - //add columns - int columns = 2; - Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); - Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); - partitionColumns.add(k1); - partitionColumns.add(k2); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100")), - Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100"))); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - - partitionInfo = new RangePartitionInfo(partitionColumns); - - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(columns, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + Assertions.assertThrows(DdlException.class, () -> { + //add columns + int columns = 2; + Column k1 = new Column("k1", new ScalarType(PrimitiveType.INT), true, null, "", ""); + Column k2 = new Column("k2", new ScalarType(PrimitiveType.BIGINT), true, null, "", ""); + partitionColumns.add(k1); + partitionColumns.add(k2); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100")), + Lists.newArrayList(new PartitionValue("20190101"), new PartitionValue("100"))); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + + partitionInfo = new RangePartitionInfo(partitionColumns); + + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(columns, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); + } + }); } - @Test (expected = DdlException.class) + @Test public void testFixedRange6() throws DdlException, AnalysisException { - //add columns - int columns = 2; - Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATE), true, null, "", ""); - partitionColumns.add(k1); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-06-01")), - Lists.newArrayList(new PartitionValue("2021-06-02"))); - - PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-07-01")), - Lists.newArrayList(new PartitionValue("2021-08-01"))); - - PartitionKeyDesc p3 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-06-01")), - Lists.newArrayList(new PartitionValue("2021-07-01"))); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); - partitionInfo = new RangePartitionInfo(partitionColumns); - - long partitionId = 20000L; - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(columns, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, partitionId++, false); - } + Assertions.assertThrows(DdlException.class, () -> { + //add columns + int columns = 2; + Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATE), true, null, "", ""); + partitionColumns.add(k1); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-06-01")), + Lists.newArrayList(new PartitionValue("2021-06-02"))); + + PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-07-01")), + Lists.newArrayList(new PartitionValue("2021-08-01"))); + + PartitionKeyDesc p3 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-06-01")), + Lists.newArrayList(new PartitionValue("2021-07-01"))); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); + partitionInfo = new RangePartitionInfo(partitionColumns); + + long partitionId = 20000L; + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(columns, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, partitionId++, false); + } + }); } - @Test(expected = AnalysisException.class) + @Test public void testFixedRange7() throws DdlException, AnalysisException { - //add columns - Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATEV2), true, null, "", ""); - Column k2 = new Column("k2", new ScalarType(PrimitiveType.INT), true, null, "", ""); - Column k3 = new Column("k3", new ScalarType(PrimitiveType.INT), true, null, "", ""); - partitionColumns.add(k1); - partitionColumns.add(k2); - partitionColumns.add(k3); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("2019-02-01"), - new PartitionValue("100"), new PartitionValue("200"))); - PartitionKeyDesc p2 = PartitionKeyDesc.createFixed(Lists.newArrayList(new PartitionValue("2020-02-01"), - new PartitionValue("100"), new PartitionValue("200")), - Lists.newArrayList(new PartitionValue("2020-03-01"))); - PartitionKeyDesc p3 = PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("2021-02-01"))); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); - partitionInfo = new RangePartitionInfo(partitionColumns); - PartitionKeyValueType partitionKeyValueType = PartitionKeyValueType.INVALID; - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - // check partitionType - if (partitionKeyValueType == PartitionKeyValueType.INVALID) { - partitionKeyValueType = singlePartitionDesc.getPartitionKeyDesc().getPartitionType(); - } else if (partitionKeyValueType != singlePartitionDesc.getPartitionKeyDesc().getPartitionType()) { - throw new AnalysisException("You can only use one of these methods to create partitions"); + Assertions.assertThrows(AnalysisException.class, () -> { + //add columns + Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATEV2), true, null, "", ""); + Column k2 = new Column("k2", new ScalarType(PrimitiveType.INT), true, null, "", ""); + Column k3 = new Column("k3", new ScalarType(PrimitiveType.INT), true, null, "", ""); + partitionColumns.add(k1); + partitionColumns.add(k2); + partitionColumns.add(k3); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("2019-02-01"), + new PartitionValue("100"), new PartitionValue("200"))); + PartitionKeyDesc p2 = PartitionKeyDesc.createFixed(Lists.newArrayList(new PartitionValue("2020-02-01"), + new PartitionValue("100"), new PartitionValue("200")), + Lists.newArrayList(new PartitionValue("2020-03-01"))); + PartitionKeyDesc p3 = PartitionKeyDesc.createLessThan(Lists.newArrayList(new PartitionValue("2021-02-01"))); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); + partitionInfo = new RangePartitionInfo(partitionColumns); + PartitionKeyValueType partitionKeyValueType = PartitionKeyValueType.INVALID; + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + // check partitionType + if (partitionKeyValueType == PartitionKeyValueType.INVALID) { + partitionKeyValueType = singlePartitionDesc.getPartitionKeyDesc().getPartitionType(); + } else if (partitionKeyValueType != singlePartitionDesc.getPartitionKeyDesc().getPartitionType()) { + throw new AnalysisException("You can only use one of these methods to create partitions"); + } + singlePartitionDesc.analyze(partitionColumns.size(), null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); } - singlePartitionDesc.analyze(partitionColumns.size(), null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, 20000L, false); - } + }); } - @Test (expected = DdlException.class) + @Test public void testFixedRange8() throws DdlException, AnalysisException { - //add columns - int columns = 2; - Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATEV2), true, null, "", ""); - partitionColumns.add(k1); - - //add RangePartitionDescs - PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-06-01")), - Lists.newArrayList(new PartitionValue("2021-06-02"))); - - PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-07-01")), - Lists.newArrayList(new PartitionValue("2021-08-01"))); - - PartitionKeyDesc p3 = PartitionKeyDesc.createFixed( - Lists.newArrayList(new PartitionValue("2021-06-01")), - Lists.newArrayList(new PartitionValue("2021-07-01"))); - - singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); - singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); - partitionInfo = new RangePartitionInfo(partitionColumns); - - long partitionId = 20000L; - for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { - singlePartitionDesc.analyze(columns, null); - partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, partitionId++, false); - } + Assertions.assertThrows(DdlException.class, () -> { + //add columns + int columns = 2; + Column k1 = new Column("k1", new ScalarType(PrimitiveType.DATEV2), true, null, "", ""); + partitionColumns.add(k1); + + //add RangePartitionDescs + PartitionKeyDesc p1 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-06-01")), + Lists.newArrayList(new PartitionValue("2021-06-02"))); + + PartitionKeyDesc p2 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-07-01")), + Lists.newArrayList(new PartitionValue("2021-08-01"))); + + PartitionKeyDesc p3 = PartitionKeyDesc.createFixed( + Lists.newArrayList(new PartitionValue("2021-06-01")), + Lists.newArrayList(new PartitionValue("2021-07-01"))); + + singlePartitionDescs.add(new SinglePartitionDesc(false, "p1", p1, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p2", p2, null)); + singlePartitionDescs.add(new SinglePartitionDesc(false, "p3", p3, null)); + partitionInfo = new RangePartitionInfo(partitionColumns); + + long partitionId = 20000L; + for (SinglePartitionDesc singlePartitionDesc : singlePartitionDescs) { + singlePartitionDesc.analyze(columns, null); + partitionInfo.handleNewSinglePartitionDesc(singlePartitionDesc, partitionId++, false); + } + }); } @Test @@ -473,7 +493,7 @@ public void testSerialization() throws IOException, AnalysisException, DdlExcept RangePartitionInfo partitionInfo2 = GsonUtils.GSON.fromJson(Text.readString(in), RangePartitionInfo.class); - Assert.assertEquals(partitionInfo.getType(), partitionInfo2.getType()); + Assertions.assertEquals(partitionInfo.getType(), partitionInfo2.getType()); // 3. delete files in.close(); @@ -501,6 +521,6 @@ public void testAutotoSql() throws AnalysisException, DdlException { String sql = partitionInfo.toSql(table, null); String expected = "AUTO PARTITION BY RANGE (date_trunc(`tbl`.`k1`, 'day'))"; - Assert.assertTrue("got: " + sql + ", should have: " + expected, sql.contains(expected)); + Assertions.assertTrue(sql.contains(expected), "got: " + sql + ", should have: " + expected); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/RefreshManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/RefreshManagerTest.java index 6b6a241250086f..44059931620e82 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/RefreshManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/RefreshManagerTest.java @@ -42,10 +42,10 @@ import org.apache.doris.persist.EditLog; import com.google.common.util.concurrent.MoreExecutors; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockedConstruction; @@ -84,7 +84,7 @@ public class RefreshManagerTest { private AtomicInteger databaseObjectLoadCalls; private TestingCatalogMgr testingCatalogMgr; - @Before + @BeforeEach public void setUp() { Map properties = Collections.singletonMap( "catalog_provider.class", EmptyCatalogProvider.class.getName()); @@ -110,7 +110,7 @@ public void setUp() { mockedEnv.when(Env::getCurrentEnv).thenReturn(testingEnv); } - @After + @AfterEach public void tearDown() { if (mockedEnv != null) { mockedEnv.close(); @@ -147,7 +147,7 @@ public void testReplayHotRefreshDbKeepsRowCountBarrierWhenMetadataInvalidationFa engineCache.failDbInvalidation = true; ExternalObjectLog log = ExternalObjectLog.createForRefreshDb(CATALOG_ID, DATABASE_NAME); - Assert.assertThrows(IllegalStateException.class, () -> new RefreshManager().replayRefreshDb(log)); + Assertions.assertThrows(IllegalStateException.class, () -> new RefreshManager().replayRefreshDb(log)); InOrder order = Mockito.inOrder(metaCacheMgr); order.verify(metaCacheMgr).invalidateDbMetadataCache(CATALOG_ID, DATABASE_NAME); @@ -184,7 +184,7 @@ public void testRefreshTableRemovesRowCountLoadedDuringConnectorInvalidation() t CountDownLatch finishConnectorInvalidation = new CountDownLatch(1); Mockito.doAnswer(inv -> { connectorInvalidationStarted.countDown(); - Assert.assertTrue(finishConnectorInvalidation.await(3L, TimeUnit.SECONDS)); + Assertions.assertTrue(finishConnectorInvalidation.await(3L, TimeUnit.SECONDS)); sourceRowCount.set(200L); return null; }).when(fixture.connector).invalidateTable(DATABASE_NAME, TABLE_NAME); @@ -200,7 +200,7 @@ public void testRefreshTableRemovesRowCountLoadedDuringConnectorInvalidation() t Deencapsulation.setField(metaCacheMgr, "rowCountCache", rowCountCache); Future loadDuringConnectorInvalidation = executor.submit(() -> { - Assert.assertTrue(connectorInvalidationStarted.await(3L, TimeUnit.SECONDS)); + Assertions.assertTrue(connectorInvalidationStarted.await(3L, TimeUnit.SECONDS)); try { return rowCountCache.getCachedRowCount(CATALOG_ID, DATABASE_ID, TABLE_ID, false); } finally { @@ -209,10 +209,10 @@ public void testRefreshTableRemovesRowCountLoadedDuringConnectorInvalidation() t }); new RefreshManager().refreshTableInternal(fixture.database, table, 123L); - Assert.assertEquals(100L, loadDuringConnectorInvalidation.get(3L, TimeUnit.SECONDS).longValue()); - Assert.assertEquals(TableIf.UNKNOWN_ROW_COUNT, + Assertions.assertEquals(100L, loadDuringConnectorInvalidation.get(3L, TimeUnit.SECONDS).longValue()); + Assertions.assertEquals(TableIf.UNKNOWN_ROW_COUNT, rowCountCache.getCachedRowCountIfPresent(CATALOG_ID, DATABASE_ID, TABLE_ID)); - Assert.assertEquals(200L, + Assertions.assertEquals(200L, rowCountCache.getCachedRowCount(CATALOG_ID, DATABASE_ID, TABLE_ID, false)); Mockito.verify(metaCacheMgr).invalidateTable( CATALOG_ID, DATABASE_ID, DATABASE_NAME, TABLE_ID, TABLE_NAME); @@ -235,7 +235,7 @@ public void testRefreshTableKeepsLocalBarrierWhenConnectorInvalidationFails() { Mockito.doThrow(new IllegalStateException("connector invalidation failed")) .when(fixture.connector).invalidateTable(DATABASE_NAME, TABLE_NAME); - Assert.assertThrows(IllegalStateException.class, + Assertions.assertThrows(IllegalStateException.class, () -> new RefreshManager().refreshTableInternal(fixture.database, table, 123L)); Mockito.verify(metaCacheMgr).invalidateTable(table); @@ -256,17 +256,17 @@ public void testRefreshTableAfterExternalMutationLogsBeforeFallibleInvalidation( Mockito.doThrow(refreshFailure).when(refreshManager) .refreshTableInternal(Mockito.eq(database), Mockito.eq(table), Mockito.anyLong()); - IllegalStateException thrown = Assert.assertThrows(IllegalStateException.class, + IllegalStateException thrown = Assertions.assertThrows(IllegalStateException.class, () -> refreshManager.refreshTableAfterExternalMutation(table)); - Assert.assertSame(refreshFailure, thrown); + Assertions.assertSame(refreshFailure, thrown); InOrder order = Mockito.inOrder(editLog, refreshManager); ArgumentCaptor logCaptor = ArgumentCaptor.forClass(ExternalObjectLog.class); order.verify(editLog).logRefreshExternalTable(logCaptor.capture()); ExternalObjectLog log = logCaptor.getValue(); - Assert.assertEquals(CATALOG_ID, log.getCatalogId()); - Assert.assertEquals(DATABASE_NAME, log.getDbName()); - Assert.assertEquals(TABLE_NAME, log.getTableName()); + Assertions.assertEquals(CATALOG_ID, log.getCatalogId()); + Assertions.assertEquals(DATABASE_NAME, log.getDbName()); + Assertions.assertEquals(TABLE_NAME, log.getTableName()); order.verify(refreshManager).refreshTableInternal(database, table, log.getLastUpdateTime()); } @@ -276,11 +276,11 @@ public void testReplayRefreshDbKeepsLocalBarrierWhenConnectorInvalidationFails() Mockito.doThrow(new IllegalStateException("connector invalidation failed")) .when(fixture.connector).invalidateDb(DATABASE_NAME); - Assert.assertThrows(IllegalStateException.class, + Assertions.assertThrows(IllegalStateException.class, () -> new RefreshManager().replayRefreshDb( ExternalObjectLog.createForRefreshDb(CATALOG_ID, DATABASE_NAME))); - Assert.assertFalse(fixture.database.isInitialized()); + Assertions.assertFalse(fixture.database.isInitialized()); Mockito.verify(metaCacheMgr).invalidateDbMetadataCache(CATALOG_ID, DATABASE_NAME); Mockito.verify(metaCacheMgr).invalidateDbRowCountCache(CATALOG_ID, DATABASE_ID); } @@ -300,24 +300,24 @@ public void testReplayRenameEvictsPreexistingSourceAndDestinationRowCounts() { ExternalRowCountCache rowCountCache = new ExternalRowCountCache(MoreExecutors.newDirectExecutorService()); Deencapsulation.setField(metaCacheMgr, "rowCountCache", rowCountCache); - Assert.assertEquals(100L, + Assertions.assertEquals(100L, rowCountCache.getCachedRowCount(CATALOG_ID, DATABASE_ID, sourceTableId, false)); - Assert.assertEquals(200L, + Assertions.assertEquals(200L, rowCountCache.getCachedRowCount(CATALOG_ID, DATABASE_ID, destinationTableId, false)); database.addTableForTest( new TestExternalTable(sourceTableId, TABLE_NAME, TABLE_NAME, catalog, database)); database.addTableForTest( new TestExternalTable(destinationTableId, NEW_TABLE_NAME, NEW_TABLE_NAME, catalog, database)); - Assert.assertNotNull(database.getCachedTableForTest(NEW_TABLE_NAME)); + Assertions.assertNotNull(database.getCachedTableForTest(NEW_TABLE_NAME)); new RefreshManager().replayRefreshTable(ExternalObjectLog.createForRenameTable( CATALOG_ID, DATABASE_NAME, TABLE_NAME, NEW_TABLE_NAME)); - Assert.assertNull(database.getCachedTableForTest(TABLE_NAME)); - Assert.assertNull(database.getCachedTableForTest(NEW_TABLE_NAME)); - Assert.assertEquals(TableIf.UNKNOWN_ROW_COUNT, + Assertions.assertNull(database.getCachedTableForTest(TABLE_NAME)); + Assertions.assertNull(database.getCachedTableForTest(NEW_TABLE_NAME)); + Assertions.assertEquals(TableIf.UNKNOWN_ROW_COUNT, rowCountCache.getCachedRowCountIfPresent(CATALOG_ID, DATABASE_ID, sourceTableId)); - Assert.assertEquals(TableIf.UNKNOWN_ROW_COUNT, + Assertions.assertEquals(TableIf.UNKNOWN_ROW_COUNT, rowCountCache.getCachedRowCountIfPresent(CATALOG_ID, DATABASE_ID, destinationTableId)); } } @@ -337,7 +337,7 @@ private void seedAndEvictTableObject() { TestExternalTable table = new TestExternalTable(TABLE_ID, TABLE_NAME, TABLE_NAME, catalog, database); database.addTableForTest(table); database.evictTableObjectForTest(TABLE_NAME); - Assert.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); + Assertions.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); } private void disableDatabaseObjectCacheWithTtlZero() { @@ -356,7 +356,7 @@ private void disableDatabaseObjectCacheWithTtlZero( Env.getCurrentEnv().getExtMetaCacheMgr().commonRefreshExecutor(), false); Deencapsulation.setField(targetCatalog, "databases", disabledDatabases); - Assert.assertFalse(targetCatalog.getDbForReplay(DATABASE_NAME).isPresent()); + Assertions.assertFalse(targetCatalog.getDbForReplay(DATABASE_NAME).isPresent()); } private Connector usePluginCatalogWithDisabledDatabaseObjectCache() { @@ -380,29 +380,29 @@ private PluginCatalogFixture usePluginCatalog() { } private void assertColdTableInvalidatedByName() { - Assert.assertEquals(1, engineCache.invalidateTableCalls.get()); - Assert.assertEquals(CATALOG_ID, engineCache.lastCatalogId); - Assert.assertEquals(DATABASE_NAME, engineCache.lastDatabaseName); - Assert.assertEquals(TABLE_NAME, engineCache.lastTableName); - Assert.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); - Assert.assertEquals(0, database.buildTableCalls.get()); + Assertions.assertEquals(1, engineCache.invalidateTableCalls.get()); + Assertions.assertEquals(CATALOG_ID, engineCache.lastCatalogId); + Assertions.assertEquals(DATABASE_NAME, engineCache.lastDatabaseName); + Assertions.assertEquals(TABLE_NAME, engineCache.lastTableName); + Assertions.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); + Assertions.assertEquals(0, database.buildTableCalls.get()); } private void assertColdRenameMigrated() { - Assert.assertEquals(CATALOG_ID, engineCache.lastCatalogId); - Assert.assertEquals(DATABASE_NAME, engineCache.lastDatabaseName); - Assert.assertEquals(NEW_TABLE_NAME, engineCache.lastTableName); - Assert.assertNull(database.getCachedTableNameByIdForTest(TABLE_ID)); - Assert.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); - Assert.assertNull(database.getCachedTableNamesForTest()); - Assert.assertEquals(0, database.buildTableCalls.get()); - Assert.assertEquals(1, constraintManager.renameTableCalls.get()); - Assert.assertEquals("test_catalog", constraintManager.oldTableName.getCtl()); - Assert.assertEquals(DATABASE_NAME, constraintManager.oldTableName.getDb()); - Assert.assertEquals(TABLE_NAME, constraintManager.oldTableName.getTbl()); - Assert.assertEquals("test_catalog", constraintManager.newTableName.getCtl()); - Assert.assertEquals(DATABASE_NAME, constraintManager.newTableName.getDb()); - Assert.assertEquals(NEW_TABLE_NAME, constraintManager.newTableName.getTbl()); + Assertions.assertEquals(CATALOG_ID, engineCache.lastCatalogId); + Assertions.assertEquals(DATABASE_NAME, engineCache.lastDatabaseName); + Assertions.assertEquals(NEW_TABLE_NAME, engineCache.lastTableName); + Assertions.assertNull(database.getCachedTableNameByIdForTest(TABLE_ID)); + Assertions.assertFalse(database.getTableForReplay(TABLE_NAME).isPresent()); + Assertions.assertNull(database.getCachedTableNamesForTest()); + Assertions.assertEquals(0, database.buildTableCalls.get()); + Assertions.assertEquals(1, constraintManager.renameTableCalls.get()); + Assertions.assertEquals("test_catalog", constraintManager.oldTableName.getCtl()); + Assertions.assertEquals(DATABASE_NAME, constraintManager.oldTableName.getDb()); + Assertions.assertEquals(TABLE_NAME, constraintManager.oldTableName.getTbl()); + Assertions.assertEquals("test_catalog", constraintManager.newTableName.getCtl()); + Assertions.assertEquals(DATABASE_NAME, constraintManager.newTableName.getDb()); + Assertions.assertEquals(NEW_TABLE_NAME, constraintManager.newTableName.getTbl()); } public static class EmptyCatalogProvider implements TestExternalCatalog.TestCatalogProvider { diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaAllocationTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaAllocationTest.java index 550b2c7d6630a8..c8a4c363b1250c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaAllocationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaAllocationTest.java @@ -29,10 +29,10 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -48,7 +48,7 @@ public class ReplicaAllocationTest { private SystemInfoService systemInfoService = Mockito.mock(SystemInfoService.class); private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setUp() throws DdlException { mockedEnvStatic = Mockito.mockStatic(Env.class); mockedEnvStatic.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); @@ -62,7 +62,7 @@ public void setUp() throws DdlException { Mockito.eq(true)); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -73,36 +73,36 @@ public void tearDown() { public void testNormal() throws AnalysisException { // DEFAULT_ALLOCATION ReplicaAllocation replicaAlloc = ReplicaAllocation.DEFAULT_ALLOCATION; - Assert.assertFalse(replicaAlloc.isNotSet()); - Assert.assertEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); - Assert.assertFalse(replicaAlloc.isEmpty()); - Assert.assertEquals(3, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("tag.location.default: 3", replicaAlloc.toCreateStmt()); + Assertions.assertFalse(replicaAlloc.isNotSet()); + Assertions.assertEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); + Assertions.assertFalse(replicaAlloc.isEmpty()); + Assertions.assertEquals(3, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("tag.location.default: 3", replicaAlloc.toCreateStmt()); // NOT SET replicaAlloc = ReplicaAllocation.NOT_SET; - Assert.assertTrue(replicaAlloc.isNotSet()); - Assert.assertNotEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); - Assert.assertTrue(replicaAlloc.isEmpty()); - Assert.assertEquals(0, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("", replicaAlloc.toCreateStmt()); + Assertions.assertTrue(replicaAlloc.isNotSet()); + Assertions.assertNotEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); + Assertions.assertTrue(replicaAlloc.isEmpty()); + Assertions.assertEquals(0, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("", replicaAlloc.toCreateStmt()); // set replica num replicaAlloc = new ReplicaAllocation((short) 5); - Assert.assertFalse(replicaAlloc.isNotSet()); - Assert.assertNotEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); - Assert.assertFalse(replicaAlloc.isEmpty()); - Assert.assertEquals(5, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("tag.location.default: 5", replicaAlloc.toCreateStmt()); + Assertions.assertFalse(replicaAlloc.isNotSet()); + Assertions.assertNotEquals(replicaAlloc, ReplicaAllocation.DEFAULT_ALLOCATION); + Assertions.assertFalse(replicaAlloc.isEmpty()); + Assertions.assertEquals(5, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("tag.location.default: 5", replicaAlloc.toCreateStmt()); // set replica num with tag replicaAlloc = new ReplicaAllocation(); replicaAlloc.put(Tag.create(Tag.TYPE_LOCATION, "zone1"), (short) 3); replicaAlloc.put(Tag.create(Tag.TYPE_LOCATION, "zone2"), (short) 2); - Assert.assertFalse(replicaAlloc.isNotSet()); - Assert.assertFalse(replicaAlloc.isEmpty()); - Assert.assertEquals(5, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("tag.location.zone2: 2, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); + Assertions.assertFalse(replicaAlloc.isNotSet()); + Assertions.assertFalse(replicaAlloc.isEmpty()); + Assertions.assertEquals(5, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("tag.location.zone2: 2, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); } @Test @@ -110,39 +110,39 @@ public void testPropertyAnalyze() throws AnalysisException { Map properties = Maps.newHashMap(); properties.put(PropertyAnalyzer.PROPERTIES_REPLICATION_NUM, "3"); ReplicaAllocation replicaAlloc = PropertyAnalyzer.analyzeReplicaAllocation(properties, ""); - Assert.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); - Assert.assertTrue(properties.isEmpty()); + Assertions.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); + Assertions.assertTrue(properties.isEmpty()); // not set properties = Maps.newHashMap(); replicaAlloc = PropertyAnalyzer.analyzeReplicaAllocation(properties, ""); - Assert.assertEquals(ReplicaAllocation.NOT_SET, replicaAlloc); + Assertions.assertEquals(ReplicaAllocation.NOT_SET, replicaAlloc); properties = Maps.newHashMap(); properties.put("default." + PropertyAnalyzer.PROPERTIES_REPLICATION_NUM, "3"); replicaAlloc = PropertyAnalyzer.analyzeReplicaAllocation(properties, "default"); - Assert.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); - Assert.assertTrue(properties.isEmpty()); + Assertions.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); + Assertions.assertTrue(properties.isEmpty()); properties = Maps.newHashMap(); properties.put(PropertyAnalyzer.PROPERTIES_REPLICATION_ALLOCATION, "tag.location.zone2: 2, tag.location.zone1: 3"); replicaAlloc = PropertyAnalyzer.analyzeReplicaAllocation(properties, ""); - Assert.assertNotEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); - Assert.assertFalse(replicaAlloc.isNotSet()); - Assert.assertFalse(replicaAlloc.isEmpty()); - Assert.assertEquals(5, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("tag.location.zone2: 2, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); - Assert.assertTrue(properties.isEmpty()); + Assertions.assertNotEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); + Assertions.assertFalse(replicaAlloc.isNotSet()); + Assertions.assertFalse(replicaAlloc.isEmpty()); + Assertions.assertEquals(5, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("tag.location.zone2: 2, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); + Assertions.assertTrue(properties.isEmpty()); properties = Maps.newHashMap(); properties.put("dynamic_partition." + PropertyAnalyzer.PROPERTIES_REPLICATION_ALLOCATION, "tag.location.zone2: 1, tag.location.zone1: 3"); replicaAlloc = PropertyAnalyzer.analyzeReplicaAllocation(properties, "dynamic_partition"); - Assert.assertNotEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); - Assert.assertFalse(replicaAlloc.isNotSet()); - Assert.assertFalse(replicaAlloc.isEmpty()); - Assert.assertEquals(4, replicaAlloc.getTotalReplicaNum()); - Assert.assertEquals("tag.location.zone2: 1, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); - Assert.assertTrue(properties.isEmpty()); + Assertions.assertNotEquals(ReplicaAllocation.DEFAULT_ALLOCATION, replicaAlloc); + Assertions.assertFalse(replicaAlloc.isNotSet()); + Assertions.assertFalse(replicaAlloc.isEmpty()); + Assertions.assertEquals(4, replicaAlloc.getTotalReplicaNum()); + Assertions.assertEquals("tag.location.zone2: 1, tag.location.zone1: 3", replicaAlloc.toCreateStmt()); + Assertions.assertTrue(properties.isEmpty()); } @Test @@ -179,7 +179,7 @@ public void testPersist() throws IOException, AnalysisException { // 2. Read objects from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); ReplicaAllocation newAlloc = ReplicaAllocation.read(dis); - Assert.assertEquals(replicaAlloc, newAlloc); + Assertions.assertEquals(replicaAlloc, newAlloc); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaTest.java index fca8d77617100c..90a281319d27a1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ReplicaTest.java @@ -21,9 +21,9 @@ import org.apache.doris.common.io.Text; import org.apache.doris.persist.gson.GsonUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.DataInputStream; @@ -46,7 +46,7 @@ public class ReplicaTest { private long dataSize; private long rowCount; - @Before + @BeforeEach public void setUp() { replicaId = 10000; backendId = 20000; @@ -58,20 +58,20 @@ public void setUp() { @Test public void getMethodTest() { - Assert.assertEquals(replicaId, replica.getId()); - Assert.assertEquals(backendId, replica.getBackendIdWithoutException()); - Assert.assertEquals(version, replica.getVersion()); - Assert.assertEquals(dataSize, replica.getDataSize()); - Assert.assertEquals(rowCount, replica.getRowCount()); + Assertions.assertEquals(replicaId, replica.getId()); + Assertions.assertEquals(backendId, replica.getBackendIdWithoutException()); + Assertions.assertEquals(version, replica.getVersion()); + Assertions.assertEquals(dataSize, replica.getDataSize()); + Assertions.assertEquals(rowCount, replica.getRowCount()); // update new version long newVersion = version + 1; replica.updateVersion(newVersion); // check version catch up - Assert.assertFalse(replica.checkVersionCatchUp(5, false)); - Assert.assertTrue(replica.checkVersionCatchUp(newVersion, false)); - Assert.assertTrue(replica.checkVersionCatchUp(newVersion, false)); + Assertions.assertFalse(replica.checkVersionCatchUp(5, false)); + Assertions.assertTrue(replica.checkVersionCatchUp(newVersion, false)); + Assertions.assertTrue(replica.checkVersionCatchUp(newVersion, false)); } @Test @@ -99,12 +99,12 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(path)); for (int count = 0; count < 10; ++count) { Replica olapReplica = GsonUtils.GSON.fromJson(Text.readString(dis), Replica.class); - Assert.assertEquals(100 * count, olapReplica.getId()); - Assert.assertEquals(100 * count, olapReplica.getBackendId()); - Assert.assertEquals(100 * count, olapReplica.getVersion()); - Assert.assertEquals(100 * count, olapReplica.getDataSize()); - Assert.assertEquals(100 * count, olapReplica.getRowCount()); - Assert.assertEquals(Replica.ReplicaState.NORMAL, olapReplica.getState()); + Assertions.assertEquals(100 * count, olapReplica.getId()); + Assertions.assertEquals(100 * count, olapReplica.getBackendId()); + Assertions.assertEquals(100 * count, olapReplica.getVersion()); + Assertions.assertEquals(100 * count, olapReplica.getDataSize()); + Assertions.assertEquals(100 * count, olapReplica.getRowCount()); + Assertions.assertEquals(Replica.ReplicaState.NORMAL, olapReplica.getState()); list2.add(olapReplica); } Replica olapReplica = GsonUtils.GSON.fromJson(Text.readString(dis), Replica.class); @@ -112,11 +112,11 @@ public void testSerialization() throws Exception { // 3. Check equal for (int i = 0; i < 11; i++) { - Assert.assertEquals(list1.get(i), list2.get(i)); + Assertions.assertEquals(list1.get(i), list2.get(i)); } - Assert.assertEquals(list1.get(1), list1.get(1)); - Assert.assertNotEquals(list1.get(1), list1); + Assertions.assertEquals(list1.get(1), list1.get(1)); + Assertions.assertNotEquals(list1.get(1), list1); dis.close(); Files.deleteIfExists(path); @@ -127,7 +127,7 @@ public void testUpdateVersion1() { Replica originalReplica = new LocalReplica(10000, 20000, 3, 0, 100, 0, 78, ReplicaState.NORMAL, 0, 3); // new version is little than original version, it is invalid the version will not update originalReplica.updateVersion(2); - Assert.assertEquals(3, originalReplica.getVersion()); + Assertions.assertEquals(3, originalReplica.getVersion()); } @Test @@ -135,8 +135,8 @@ public void testUpdateVersion2() { Replica originalReplica = new LocalReplica(10000, 20000, 3, 0, 100, 0, 78, ReplicaState.NORMAL, 0, 0); originalReplica.updateVersion(3); // if new version >= current version and last success version <= new version, then last success version should be updated - Assert.assertEquals(3, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(3, originalReplica.getVersion()); + Assertions.assertEquals(3, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(3, originalReplica.getVersion()); } @Test @@ -144,54 +144,54 @@ public void testUpdateVersion3() { // version(3) ---> last failed version (8) ---> last success version(10) Replica originalReplica = new LocalReplica(10000, 20000, 3, 111, 0, 0, 78, ReplicaState.NORMAL, 0, 0); originalReplica.updateLastFailedVersion(8); - Assert.assertEquals(3, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(3, originalReplica.getVersion()); - Assert.assertEquals(8, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(3, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(3, originalReplica.getVersion()); + Assertions.assertEquals(8, originalReplica.getLastFailedVersion()); // update last success version 10 originalReplica.updateVersionWithFailed(originalReplica.getVersion(), originalReplica.getLastFailedVersion(), 10); - Assert.assertEquals(10, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(3, originalReplica.getVersion()); - Assert.assertEquals(8, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(10, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(3, originalReplica.getVersion()); + Assertions.assertEquals(8, originalReplica.getLastFailedVersion()); // update version to 8, the last success version and version should be 10 originalReplica.updateVersion(8); - Assert.assertEquals(10, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(10, originalReplica.getVersion()); - Assert.assertEquals(-1, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(10, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(10, originalReplica.getVersion()); + Assertions.assertEquals(-1, originalReplica.getLastFailedVersion()); // update last failed version to 12 originalReplica.updateLastFailedVersion(12); - Assert.assertEquals(10, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(10, originalReplica.getVersion()); - Assert.assertEquals(12, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(10, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(10, originalReplica.getVersion()); + Assertions.assertEquals(12, originalReplica.getLastFailedVersion()); // update last success version to 15 originalReplica.updateVersionWithFailed(originalReplica.getVersion(), originalReplica.getLastFailedVersion(), 15); - Assert.assertEquals(15, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(10, originalReplica.getVersion()); - Assert.assertEquals(12, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(15, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(10, originalReplica.getVersion()); + Assertions.assertEquals(12, originalReplica.getLastFailedVersion()); // update last failed version to 18 originalReplica.updateLastFailedVersion(18); - Assert.assertEquals(10, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(10, originalReplica.getVersion()); - Assert.assertEquals(18, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(10, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(10, originalReplica.getVersion()); + Assertions.assertEquals(18, originalReplica.getLastFailedVersion()); // update version to 17 then version and success version is 17 originalReplica.updateVersion(17); - Assert.assertEquals(17, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(17, originalReplica.getVersion()); - Assert.assertEquals(18, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(17, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(17, originalReplica.getVersion()); + Assertions.assertEquals(18, originalReplica.getLastFailedVersion()); // update version to 18, then version and last success version should be 18 and failed version should be -1 originalReplica.updateVersion(18); - Assert.assertEquals(18, originalReplica.getLastSuccessVersion()); - Assert.assertEquals(18, originalReplica.getVersion()); - Assert.assertEquals(-1, originalReplica.getLastFailedVersion()); + Assertions.assertEquals(18, originalReplica.getLastSuccessVersion()); + Assertions.assertEquals(18, originalReplica.getVersion()); + Assertions.assertEquals(-1, originalReplica.getLastFailedVersion()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/ResourceMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/ResourceMgrTest.java index 2be4ef9ba77ee4..59f0584df3bf69 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/ResourceMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/ResourceMgrTest.java @@ -28,9 +28,9 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -51,7 +51,7 @@ public class ResourceMgrTest { private String s3ConnTimeoutMs; private Map s3Properties; - @Before + @BeforeEach public void setUp() { s3ResName = "s30"; s3ResType = "s3"; @@ -90,9 +90,9 @@ public void testAddAlterDropResource() throws UserException { ResourceMgr mgr = new ResourceMgr(); CreateResourceCommand createResourceCommand = new CreateResourceCommand(new CreateResourceInfo(true, false, s3ResName, ImmutableMap.copyOf(s3Properties))); createResourceCommand.getInfo().validate(); - Assert.assertEquals(0, mgr.getResourceNum()); + Assertions.assertEquals(0, mgr.getResourceNum()); mgr.createResource(createResourceCommand); - Assert.assertEquals(1, mgr.getResourceNum()); + Assertions.assertEquals(1, mgr.getResourceNum()); // alter s3Region = "sh"; @@ -105,29 +105,31 @@ public void testAddAlterDropResource() throws UserException { } } - @Test(expected = DdlException.class) + @Test public void testAddResourceExist() throws UserException { - try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { - Env env = Mockito.mock(Env.class); - EditLog editLog = Mockito.mock(EditLog.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - Mockito.when(env.getEditLog()).thenReturn(editLog); - Mockito.when(env.getAccessManager()).thenReturn(accessManager); - Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) - .thenReturn(true); + Assertions.assertThrows(DdlException.class, () -> { + try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { + Env env = Mockito.mock(Env.class); + EditLog editLog = Mockito.mock(EditLog.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + mockedEnv.when(Env::getCurrentEnv).thenReturn(env); + Mockito.when(env.getEditLog()).thenReturn(editLog); + Mockito.when(env.getAccessManager()).thenReturn(accessManager); + Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) + .thenReturn(true); - // add - ResourceMgr mgr = new ResourceMgr(); - CreateResourceCommand createResourceCommand = new CreateResourceCommand(new CreateResourceInfo(true, false, s3ResName, ImmutableMap.copyOf(s3Properties))); - createResourceCommand.getInfo().validate(); + // add + ResourceMgr mgr = new ResourceMgr(); + CreateResourceCommand createResourceCommand = new CreateResourceCommand(new CreateResourceInfo(true, false, s3ResName, ImmutableMap.copyOf(s3Properties))); + createResourceCommand.getInfo().validate(); - Assert.assertEquals(0, mgr.getResourceNum()); - mgr.createResource(createResourceCommand); - Assert.assertEquals(1, mgr.getResourceNum()); + Assertions.assertEquals(0, mgr.getResourceNum()); + mgr.createResource(createResourceCommand); + Assertions.assertEquals(1, mgr.getResourceNum()); - // add again - mgr.createResource(createResourceCommand); - } + // add again + mgr.createResource(createResourceCommand); + } + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/S3ResourceTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/S3ResourceTest.java index acdd7dedec9b60..57dff9d4d38ed9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/S3ResourceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/S3ResourceTest.java @@ -34,10 +34,10 @@ import com.google.common.collect.ImmutableMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -65,7 +65,7 @@ public class S3ResourceTest { private String s3Bucket; private Map s3Properties; - @Before + @BeforeEach public void setUp() { name = "s3"; type = "s3"; @@ -104,16 +104,16 @@ public void testFromStmt() throws UserException { createResourceCommand.getInfo().validate(); S3Resource s3Resource = (S3Resource) Resource.fromCommand(createResourceCommand); - Assert.assertEquals(name, s3Resource.getName()); - Assert.assertEquals(type, s3Resource.getType().name().toLowerCase()); - Assert.assertEquals(s3Endpoint, s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); - Assert.assertEquals(s3Region, s3Resource.getProperty(S3ResourceCompat.REGION)); - Assert.assertEquals(s3RootPath, s3Resource.getProperty(S3ResourceCompat.ROOT_PATH)); - Assert.assertEquals(s3AccessKey, s3Resource.getProperty(S3ResourceCompat.ACCESS_KEY)); - Assert.assertEquals(s3SecretKey, s3Resource.getProperty(S3ResourceCompat.SECRET_KEY)); - Assert.assertEquals(s3MaxConnections, s3Resource.getProperty(S3ResourceCompat.MAX_CONNECTIONS)); - Assert.assertEquals(s3ReqTimeoutMs, s3Resource.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS)); - Assert.assertEquals(s3ConnTimeoutMs, s3Resource.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS)); + Assertions.assertEquals(name, s3Resource.getName()); + Assertions.assertEquals(type, s3Resource.getType().name().toLowerCase()); + Assertions.assertEquals(s3Endpoint, s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); + Assertions.assertEquals(s3Region, s3Resource.getProperty(S3ResourceCompat.REGION)); + Assertions.assertEquals(s3RootPath, s3Resource.getProperty(S3ResourceCompat.ROOT_PATH)); + Assertions.assertEquals(s3AccessKey, s3Resource.getProperty(S3ResourceCompat.ACCESS_KEY)); + Assertions.assertEquals(s3SecretKey, s3Resource.getProperty(S3ResourceCompat.SECRET_KEY)); + Assertions.assertEquals(s3MaxConnections, s3Resource.getProperty(S3ResourceCompat.MAX_CONNECTIONS)); + Assertions.assertEquals(s3ReqTimeoutMs, s3Resource.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS)); + Assertions.assertEquals(s3ConnTimeoutMs, s3Resource.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS)); // with no default settings s3Properties.put(S3ResourceCompat.MAX_CONNECTIONS, "100"); @@ -125,36 +125,38 @@ public void testFromStmt() throws UserException { createResourceCommand.getInfo().validate(); s3Resource = (S3Resource) Resource.fromCommand(createResourceCommand); - Assert.assertEquals(name, s3Resource.getName()); - Assert.assertEquals(type, s3Resource.getType().name().toLowerCase()); - Assert.assertEquals(s3Endpoint, s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); - Assert.assertEquals(s3Region, s3Resource.getProperty(S3ResourceCompat.REGION)); - Assert.assertEquals(s3RootPath, s3Resource.getProperty(S3ResourceCompat.ROOT_PATH)); - Assert.assertEquals(s3AccessKey, s3Resource.getProperty(S3ResourceCompat.ACCESS_KEY)); - Assert.assertEquals(s3SecretKey, s3Resource.getProperty(S3ResourceCompat.SECRET_KEY)); - Assert.assertEquals("100", s3Resource.getProperty(S3ResourceCompat.MAX_CONNECTIONS)); - Assert.assertEquals("2000", s3Resource.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS)); - Assert.assertEquals("2000", s3Resource.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS)); + Assertions.assertEquals(name, s3Resource.getName()); + Assertions.assertEquals(type, s3Resource.getType().name().toLowerCase()); + Assertions.assertEquals(s3Endpoint, s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); + Assertions.assertEquals(s3Region, s3Resource.getProperty(S3ResourceCompat.REGION)); + Assertions.assertEquals(s3RootPath, s3Resource.getProperty(S3ResourceCompat.ROOT_PATH)); + Assertions.assertEquals(s3AccessKey, s3Resource.getProperty(S3ResourceCompat.ACCESS_KEY)); + Assertions.assertEquals(s3SecretKey, s3Resource.getProperty(S3ResourceCompat.SECRET_KEY)); + Assertions.assertEquals("100", s3Resource.getProperty(S3ResourceCompat.MAX_CONNECTIONS)); + Assertions.assertEquals("2000", s3Resource.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS)); + Assertions.assertEquals("2000", s3Resource.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS)); } } - @Test(expected = DdlException.class) + @Test public void testAbnormalResource() throws UserException { - try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { - Env env = Mockito.mock(Env.class); - AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - Mockito.when(env.getAccessManager()).thenReturn(accessManager); - Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) - .thenReturn(true); - - s3Properties.remove("AWS_ENDPOINT"); - - CreateResourceCommand createResourceCommand = new CreateResourceCommand(new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(s3Properties))); - createResourceCommand.getInfo().validate(); - - Resource.fromCommand(createResourceCommand); - } + Assertions.assertThrows(DdlException.class, () -> { + try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { + Env env = Mockito.mock(Env.class); + AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); + mockedEnv.when(Env::getCurrentEnv).thenReturn(env); + Mockito.when(env.getAccessManager()).thenReturn(accessManager); + Mockito.when(accessManager.checkGlobalPriv(Mockito.nullable(ConnectContext.class), Mockito.eq(PrivPredicate.ADMIN))) + .thenReturn(true); + + s3Properties.remove("AWS_ENDPOINT"); + + CreateResourceCommand createResourceCommand = new CreateResourceCommand(new CreateResourceInfo(true, false, name, ImmutableMap.copyOf(s3Properties))); + createResourceCommand.getInfo().validate(); + + Resource.fromCommand(createResourceCommand); + } + }); } @Test @@ -192,19 +194,19 @@ public void testSerialization() throws Exception { S3Resource rS3Resource1 = (S3Resource) S3Resource.read(s3Dis); S3Resource rS3Resource2 = (S3Resource) S3Resource.read(s3Dis); - Assert.assertEquals("s3_1", rS3Resource1.getName()); - Assert.assertEquals("s3_2", rS3Resource2.getName()); + Assertions.assertEquals("s3_1", rS3Resource1.getName()); + Assertions.assertEquals("s3_2", rS3Resource2.getName()); - Assert.assertEquals("aaa", rS3Resource2.getProperty(S3ResourceCompat.ENDPOINT)); - Assert.assertEquals("aaa", + Assertions.assertEquals("aaa", rS3Resource2.getProperty(S3ResourceCompat.ENDPOINT)); + Assertions.assertEquals("aaa", CloudObjectStoreAdapter.getObjStoreInfoPB(rS3Resource2.getCopiedProperties()).getEndpoint()); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.REGION), "bbb"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.ROOT_PATH), "/path/to/root"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.ACCESS_KEY), "xxx"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.SECRET_KEY), "yyy"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.MAX_CONNECTIONS), "50"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS), "3000"); - Assert.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS), "1000"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.REGION), "bbb"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.ROOT_PATH), "/path/to/root"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.ACCESS_KEY), "xxx"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.SECRET_KEY), "yyy"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.MAX_CONNECTIONS), "50"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.REQUEST_TIMEOUT_MS), "3000"); + Assertions.assertEquals(rS3Resource2.getProperty(S3ResourceCompat.CONNECTION_TIMEOUT_MS), "1000"); // 3. delete s3Dis.close(); @@ -233,16 +235,16 @@ public void testModifyProperties() throws Exception { modify.clear(); modify.put(S3ResourceCompat.ENDPOINT, "new-endpoint"); s3Resource.modifyProperties(modify); - Assert.assertEquals("new-endpoint", s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); - Assert.assertEquals("new-endpoint", s3Resource.getProperty(S3ResourceCompat.Env.ENDPOINT)); - Assert.assertEquals("new-endpoint", + Assertions.assertEquals("new-endpoint", s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); + Assertions.assertEquals("new-endpoint", s3Resource.getProperty(S3ResourceCompat.Env.ENDPOINT)); + Assertions.assertEquals("new-endpoint", CloudObjectStoreAdapter.getObjStoreInfoPB(s3Resource.getCopiedProperties()).getEndpoint()); modify.clear(); modify.put(S3ResourceCompat.Env.ENDPOINT, "http://other-endpoint"); s3Resource.modifyProperties(modify); - Assert.assertEquals("http://other-endpoint", s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); - Assert.assertEquals("http://other-endpoint", s3Resource.getProperty(S3ResourceCompat.Env.ENDPOINT)); + Assertions.assertEquals("http://other-endpoint", s3Resource.getProperty(S3ResourceCompat.ENDPOINT)); + Assertions.assertEquals("http://other-endpoint", s3Resource.getProperty(S3ResourceCompat.Env.ENDPOINT)); } @Test @@ -258,7 +260,7 @@ public void testExplicitSchemeIsPreserved() throws DdlException { ); S3Resource s3Resource = new S3Resource("s3_2"); s3Resource.setProperties(properties); - Assert.assertEquals(s3Resource.getProperty(S3ResourceCompat.ENDPOINT), "https://aaa"); + Assertions.assertEquals(s3Resource.getProperty(S3ResourceCompat.ENDPOINT), "https://aaa"); } @Test @@ -271,12 +273,12 @@ public void testPingS3() { String region = System.getenv("REGION"); String provider = System.getenv("PROVIDER"); - Assume.assumeTrue("ACCESS_KEY isNullOrEmpty.", !Strings.isNullOrEmpty(accessKey)); - Assume.assumeTrue("SECRET_KEY isNullOrEmpty.", !Strings.isNullOrEmpty(secretKey)); - Assume.assumeTrue("BUCKET isNullOrEmpty.", !Strings.isNullOrEmpty(bucket)); - Assume.assumeTrue("ENDPOINT isNullOrEmpty.", !Strings.isNullOrEmpty(endpoint)); - Assume.assumeTrue("REGION isNullOrEmpty.", !Strings.isNullOrEmpty(region)); - Assume.assumeTrue("PROVIDER isNullOrEmpty.", !Strings.isNullOrEmpty(provider)); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(accessKey), "ACCESS_KEY isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(secretKey), "SECRET_KEY isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(bucket), "BUCKET isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(endpoint), "ENDPOINT isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(region), "REGION isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(provider), "PROVIDER isNullOrEmpty."); Map properties = new HashMap<>(); properties.put("s3.endpoint", endpoint); @@ -287,7 +289,7 @@ public void testPingS3() { S3Resource.pingS3(bucket, "fe_ut_prefix", properties); } catch (DdlException e) { LOG.info("testPingS3 exception:", e); - Assert.assertTrue(e.getMessage(), false); + Assertions.assertTrue(false, e.getMessage()); } } @@ -302,12 +304,12 @@ public void testPingS3WithRoleArn() { String externalId = System.getenv("EXTERNAL_ID"); String bucket = System.getenv("BUCKET"); - Assume.assumeTrue("ENDPOINT isNullOrEmpty.", !Strings.isNullOrEmpty(endpoint)); - Assume.assumeTrue("REGION isNullOrEmpty.", !Strings.isNullOrEmpty(region)); - Assume.assumeTrue("PROVIDER isNullOrEmpty.", !Strings.isNullOrEmpty(provider)); - Assume.assumeTrue("ROLE_ARN isNullOrEmpty.", !Strings.isNullOrEmpty(roleArn)); - Assume.assumeTrue("EXTERNAL_ID isNullOrEmpty.", !Strings.isNullOrEmpty(externalId)); - Assume.assumeTrue("BUCKET isNullOrEmpty.", !Strings.isNullOrEmpty(bucket)); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(endpoint), "ENDPOINT isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(region), "REGION isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(provider), "PROVIDER isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(roleArn), "ROLE_ARN isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(externalId), "EXTERNAL_ID isNullOrEmpty."); + Assumptions.assumeTrue(!Strings.isNullOrEmpty(bucket), "BUCKET isNullOrEmpty."); Map properties = new HashMap<>(); properties.put("s3.endpoint", endpoint); @@ -318,7 +320,7 @@ public void testPingS3WithRoleArn() { S3Resource.pingS3(bucket, "fe_ut_role_prefix", properties); } catch (DdlException e) { LOG.info("testPingS3WithRoleArn exception:", e); - Assert.assertTrue(e.getMessage(), false); + Assertions.assertTrue(false, e.getMessage()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/SchemaTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/SchemaTableTest.java index f7422064608414..b1f63ab862cbcb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/SchemaTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/SchemaTableTest.java @@ -35,8 +35,8 @@ import org.apache.doris.nereids.types.StringType; import org.apache.doris.utframe.TestWithFeService; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/SessionVariablesNullFixTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/SessionVariablesNullFixTest.java index 1b9da0dee9f215..da77e889f21530 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/SessionVariablesNullFixTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/SessionVariablesNullFixTest.java @@ -17,8 +17,8 @@ package org.apache.doris.catalog; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -42,9 +42,9 @@ public void testViewSessionVariablesNullInitialized() throws IOException { // gsonPostProcess should initialize it view.gsonPostProcess(); - Assert.assertNotNull(view.getSessionVariables()); - Assert.assertEquals(0, view.getSessionVariables().size()); - Assert.assertEquals("{}", view.getSessionVariables().toString()); + Assertions.assertNotNull(view.getSessionVariables()); + Assertions.assertEquals(0, view.getSessionVariables().size()); + Assertions.assertEquals("{}", view.getSessionVariables().toString()); } /** @@ -59,9 +59,9 @@ public void testColumnSessionVariablesNullInitialized() throws IOException { // gsonPostProcess should initialize it column.gsonPostProcess(); - Assert.assertNotNull(column.getSessionVariables()); - Assert.assertEquals(0, column.getSessionVariables().size()); - Assert.assertEquals("{}", column.getSessionVariables().toString()); + Assertions.assertNotNull(column.getSessionVariables()); + Assertions.assertEquals(0, column.getSessionVariables().size()); + Assertions.assertEquals("{}", column.getSessionVariables().toString()); } /** @@ -81,9 +81,9 @@ public void testAliasFunctionSessionVariablesNullInitialized() throws IOExceptio // gsonPostProcess should initialize it aliasFunction.gsonPostProcess(); - Assert.assertNotNull(aliasFunction.getSessionVariables()); - Assert.assertEquals(0, aliasFunction.getSessionVariables().size()); - Assert.assertEquals("{}", aliasFunction.getSessionVariables().toString()); + Assertions.assertNotNull(aliasFunction.getSessionVariables()); + Assertions.assertEquals(0, aliasFunction.getSessionVariables().size()); + Assertions.assertEquals("{}", aliasFunction.getSessionVariables().toString()); } @@ -102,8 +102,8 @@ public void testSessionVariablesToStringDoesNotThrowNPE() throws IOException { view.gsonPostProcess(); String result = view.getSessionVariables().toString(); - Assert.assertNotNull(result); - Assert.assertEquals("{}", result); + Assertions.assertNotNull(result); + Assertions.assertEquals("{}", result); } /** @@ -119,9 +119,9 @@ public void testSessionVariablesPreservedWhenNotNull() throws IOException { view.gsonPostProcess(); - Assert.assertNotNull(view.getSessionVariables()); - Assert.assertEquals(2, view.getSessionVariables().size()); - Assert.assertEquals("value1", view.getSessionVariables().get("key1")); - Assert.assertEquals("value2", view.getSessionVariables().get("key2")); + Assertions.assertNotNull(view.getSessionVariables()); + Assertions.assertEquals(2, view.getSessionVariables().size()); + Assertions.assertEquals("value1", view.getSessionVariables().get("key1")); + Assertions.assertEquals("value2", view.getSessionVariables().get("key2")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/TablePropertyTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/TablePropertyTest.java index 2673e247141eaf..a601cd4b143f97 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/TablePropertyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/TablePropertyTest.java @@ -24,8 +24,8 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; @@ -48,7 +48,7 @@ public void testPartitionInvertedIndexStorageFormat() { properties.put(PropertyAnalyzer.PROPERTIES_PARTITION_INVERTED_INDEX_STORAGE_FORMAT, "SNII"); TableProperty tableProperty = new TableProperty(properties); - Assert.assertEquals(TInvertedIndexFileStorageFormat.SNII, + Assertions.assertEquals(TInvertedIndexFileStorageFormat.SNII, tableProperty.getPartitionInvertedIndexFileStorageFormat()); } @@ -57,8 +57,8 @@ public void testIgnoreInvalidDynamicPartitionPropertyKey() { Map properties = Maps.newHashMap(); properties.put(DynamicPartitionProperty.DYNAMIC_PARTITION_PROPERTY_PREFIX + "not_a_real_key", "1"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertFalse(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertFalse(tableProperty.hasInvalidDynamicPartition()); } // Only storage_medium (a leftover from a failed ALTER on a non-dynamic table): incomplete, @@ -68,8 +68,8 @@ public void testIncompleteStorageMediumIsDowngraded() { Map properties = Maps.newHashMap(); properties.put(DynamicPartitionProperty.STORAGE_MEDIUM, "hdd"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(tableProperty.hasInvalidDynamicPartition()); } // Symmetric to storage_medium: a leftover storage_policy alone is also incomplete. @@ -78,8 +78,8 @@ public void testIncompleteStoragePolicyIsDowngraded() { Map properties = Maps.newHashMap(); properties.put(DynamicPartitionProperty.STORAGE_POLICY, "test_policy"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(tableProperty.hasInvalidDynamicPartition()); } // time_unit present but end missing: still incomplete (covers the END required-key branch). @@ -88,8 +88,8 @@ public void testIncompleteMissingEndIsDowngraded() { Map properties = Maps.newHashMap(); properties.put(DynamicPartitionProperty.TIME_UNIT, "DAY"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(tableProperty.hasInvalidDynamicPartition()); } // time_unit + end present but prefix missing (covers the PREFIX required-key branch). @@ -99,8 +99,8 @@ public void testIncompleteMissingPrefixIsDowngraded() { properties.put(DynamicPartitionProperty.TIME_UNIT, "DAY"); properties.put(DynamicPartitionProperty.END, "3"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(tableProperty.hasInvalidDynamicPartition()); } // time_unit + end + prefix present but buckets missing (covers the BUCKETS required-key branch). @@ -111,8 +111,8 @@ public void testIncompleteMissingBucketsIsDowngraded() { properties.put(DynamicPartitionProperty.END, "3"); properties.put(DynamicPartitionProperty.PREFIX, "p"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertTrue(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertFalse(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertTrue(tableProperty.hasInvalidDynamicPartition()); } // All required keys present: a real DynamicPartitionProperty is built, not downgraded. @@ -125,10 +125,10 @@ public void testCompleteDynamicPartitionIsBuilt() { properties.put(DynamicPartitionProperty.PREFIX, "p"); properties.put(DynamicPartitionProperty.BUCKETS, "1"); TableProperty tableProperty = new TableProperty(properties).buildDynamicProperty(); - Assert.assertTrue(tableProperty.getDynamicPartitionProperty().isExist()); - Assert.assertFalse(tableProperty.hasInvalidDynamicPartition()); - Assert.assertEquals(3, tableProperty.getDynamicPartitionProperty().getEnd()); - Assert.assertEquals(1, tableProperty.getDynamicPartitionProperty().getBuckets()); + Assertions.assertTrue(tableProperty.getDynamicPartitionProperty().isExist()); + Assertions.assertFalse(tableProperty.hasInvalidDynamicPartition()); + Assertions.assertEquals(3, tableProperty.getDynamicPartitionProperty().getEnd()); + Assertions.assertEquals(1, tableProperty.getDynamicPartitionProperty().getBuckets()); } @Test @@ -144,9 +144,9 @@ public void testStorageMediumIsCaseInsensitiveAfterSerialization() { TStorageMedium expectedStorageMedium = storageMediumValue.equalsIgnoreCase("hdd") ? TStorageMedium.HDD : TStorageMedium.SSD; - Assert.assertEquals(expectedStorageMedium, tableProperty.getStorageMedium()); - Assert.assertEquals(expectedStorageMedium, deserialized.getStorageMedium()); - Assert.assertEquals(storageMediumValue, + Assertions.assertEquals(expectedStorageMedium, tableProperty.getStorageMedium()); + Assertions.assertEquals(expectedStorageMedium, deserialized.getStorageMedium()); + Assertions.assertEquals(storageMediumValue, deserialized.getProperties().get(PropertyAnalyzer.PROPERTIES_STORAGE_MEDIUM)); } } @@ -175,9 +175,9 @@ public void testDeserializeConflictingDefaultReplicaPropertiesPreservesNumericPr tableProperty.gsonPostProcess(); - Assert.assertTrue(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); - Assert.assertTrue(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_ALLOCATION)); - Assert.assertEquals(Short.valueOf((short) 3), + Assertions.assertTrue(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); + Assertions.assertTrue(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_ALLOCATION)); + Assertions.assertEquals(Short.valueOf((short) 3), tableProperty.getReplicaAllocation().getReplicaNumByTag(Tag.DEFAULT_BACKEND_TAG)); } @@ -191,10 +191,10 @@ public void testResetPropertiesForRestoreRemovesLegacyReplicationNum() { ReplicaAllocation restoredReplicaAllocation = new ReplicaAllocation((short) 2); tableProperty.resetPropertiesForRestore(false, false, restoredReplicaAllocation); - Assert.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); - Assert.assertEquals(restoredReplicaAllocation.toCreateStmt(), + Assertions.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); + Assertions.assertEquals(restoredReplicaAllocation.toCreateStmt(), tableProperty.getProperties().get(DEFAULT_REPLICATION_ALLOCATION)); - Assert.assertEquals((short) 2, tableProperty.getReplicaAllocation().getTotalReplicaNum()); + Assertions.assertEquals((short) 2, tableProperty.getReplicaAllocation().getTotalReplicaNum()); } @Test @@ -209,20 +209,20 @@ public void testModifyDefaultReplicationNumRemovesExistingAllocation() { tableProperty.modifyTableProperties(modifiedProperties); tableProperty.buildReplicaAllocation(); - Assert.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_ALLOCATION)); - Assert.assertEquals(Short.valueOf((short) 2), + Assertions.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_ALLOCATION)); + Assertions.assertEquals(Short.valueOf((short) 2), tableProperty.getReplicaAllocation().getReplicaNumByTag(Tag.DEFAULT_BACKEND_TAG)); } private void assertReplicaAllocationWins(TableProperty tableProperty) { - Assert.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); - Assert.assertEquals(Short.valueOf((short) 1), + Assertions.assertFalse(tableProperty.getProperties().containsKey(DEFAULT_REPLICATION_NUM)); + Assertions.assertEquals(Short.valueOf((short) 1), tableProperty.getReplicaAllocation() .getReplicaNumByTag(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_0"))); - Assert.assertEquals(Short.valueOf((short) 1), + Assertions.assertEquals(Short.valueOf((short) 1), tableProperty.getReplicaAllocation() .getReplicaNumByTag(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_1"))); - Assert.assertEquals(Short.valueOf((short) 1), + Assertions.assertEquals(Short.valueOf((short) 1), tableProperty.getReplicaAllocation() .getReplicaNumByTag(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_2"))); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/TableTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/TableTest.java index cdc37c658b94e7..3b6f0cbaf69103 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/TableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/TableTest.java @@ -27,10 +27,10 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -67,7 +67,7 @@ public static OlapTable newOlapTable(long tableId, String tableName, int hashCol private Table table; - @Before + @BeforeEach public void setUp() { table = newOlapTable(10000, "test", 0); fakeEnv = new FakeEnv(); @@ -76,7 +76,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -87,30 +87,30 @@ public void tearDown() { public void lockTest() { table.readLock(); try { - Assert.assertFalse(table.tryWriteLock(0, TimeUnit.SECONDS)); + Assertions.assertFalse(table.tryWriteLock(0, TimeUnit.SECONDS)); } finally { table.readUnlock(); } - Assert.assertFalse(table.isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(table.isWriteLockHeldByCurrentThread()); table.writeLock(); try { - Assert.assertTrue(table.tryWriteLock(1000, TimeUnit.SECONDS)); - Assert.assertTrue(table.isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(table.tryWriteLock(1000, TimeUnit.SECONDS)); + Assertions.assertTrue(table.isWriteLockHeldByCurrentThread()); table.writeUnlock(); } finally { table.writeUnlock(); - Assert.assertFalse(table.isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(table.isWriteLockHeldByCurrentThread()); } - Assert.assertFalse(table.isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(table.isWriteLockHeldByCurrentThread()); table.markDropped(); - Assert.assertFalse(table.writeLockIfExist()); - Assert.assertFalse(table.isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(table.writeLockIfExist()); + Assertions.assertFalse(table.isWriteLockHeldByCurrentThread()); table.unmarkDropped(); - Assert.assertTrue(table.writeLockIfExist()); - Assert.assertTrue(table.writeLockIfExist()); - Assert.assertTrue(table.isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(table.writeLockIfExist()); + Assertions.assertTrue(table.writeLockIfExist()); + Assertions.assertTrue(table.isWriteLockHeldByCurrentThread()); table.writeUnlock(); } @@ -171,9 +171,9 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(path)); Table rFamily1 = Table.read(dis); - Assert.assertEquals(table1, rFamily1); - Assert.assertEquals(table1.getCreateTime(), rFamily1.getCreateTime()); - Assert.assertEquals(table1.getIndexMetaByIndexId(2).getKeysType(), KeysType.AGG_KEYS); + Assertions.assertEquals(table1, rFamily1); + Assertions.assertEquals(table1.getCreateTime(), rFamily1.getCreateTime()); + Assertions.assertEquals(table1.getIndexMetaByIndexId(2).getKeysType(), KeysType.AGG_KEYS); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletTest.java index b87eab37750fec..bc5054a9fcff1e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/TabletTest.java @@ -30,10 +30,10 @@ import com.google.common.collect.Sets; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -59,7 +59,7 @@ public class TabletTest { private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void makeTablet() { invertedIndex = new LocalTabletInvertedIndex(); infoService = new SystemInfoService(); @@ -87,26 +87,26 @@ public void makeTablet() { tablet.addReplica(replica3); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @Test public void getMethodTest() { - Assert.assertEquals(replica1, tablet.getReplicaById(replica1.getId())); - Assert.assertEquals(replica2, tablet.getReplicaById(replica2.getId())); - Assert.assertEquals(replica3, tablet.getReplicaById(replica3.getId())); + Assertions.assertEquals(replica1, tablet.getReplicaById(replica1.getId())); + Assertions.assertEquals(replica2, tablet.getReplicaById(replica2.getId())); + Assertions.assertEquals(replica3, tablet.getReplicaById(replica3.getId())); - Assert.assertEquals(3, tablet.getReplicas().size()); - Assert.assertEquals(replica1, tablet.getReplicaByBackendId(replica1.getBackendIdWithoutException())); - Assert.assertEquals(replica2, tablet.getReplicaByBackendId(replica2.getBackendIdWithoutException())); - Assert.assertEquals(replica3, tablet.getReplicaByBackendId(replica3.getBackendIdWithoutException())); + Assertions.assertEquals(3, tablet.getReplicas().size()); + Assertions.assertEquals(replica1, tablet.getReplicaByBackendId(replica1.getBackendIdWithoutException())); + Assertions.assertEquals(replica2, tablet.getReplicaByBackendId(replica2.getBackendIdWithoutException())); + Assertions.assertEquals(replica3, tablet.getReplicaByBackendId(replica3.getBackendIdWithoutException())); long newTabletId = 20000; tablet.setTabletId(newTabletId); - Assert.assertEquals("tabletId=" + newTabletId, tablet.toString()); + Assertions.assertEquals("tabletId=" + newTabletId, tablet.toString()); } @Test @@ -120,42 +120,42 @@ public void testGetReplicaStatsOnlyUsesNormalReplicas() { statsTablet.addReplica(new LocalReplica(14L, 4L, 100L, 0, 40L, 0L, 400L, ReplicaState.DECOMMISSION, 0L, 100L)); - Assert.assertEquals(30L, statsTablet.getDataSize(false, false)); - Assert.assertEquals(10L, statsTablet.getDataSize(true, false)); - Assert.assertEquals(30L, statsTablet.getDataSize(false, true)); - Assert.assertEquals(600L, statsTablet.getRowCount(false)); - Assert.assertEquals(200L, statsTablet.getRowCount(true)); + Assertions.assertEquals(30L, statsTablet.getDataSize(false, false)); + Assertions.assertEquals(10L, statsTablet.getDataSize(true, false)); + Assertions.assertEquals(30L, statsTablet.getDataSize(false, true)); + Assertions.assertEquals(600L, statsTablet.getRowCount(false)); + Assertions.assertEquals(200L, statsTablet.getRowCount(true)); } @Test public void deleteReplicaTest() { // delete replica1 - Assert.assertTrue(tablet.deleteReplicaByBackendId(replica1.getBackendIdWithoutException())); - Assert.assertNull(tablet.getReplicaById(replica1.getId())); + Assertions.assertTrue(tablet.deleteReplicaByBackendId(replica1.getBackendIdWithoutException())); + Assertions.assertNull(tablet.getReplicaById(replica1.getId())); // err: re-delete replica1 - Assert.assertFalse(tablet.deleteReplicaByBackendId(replica1.getBackendIdWithoutException())); - Assert.assertFalse(tablet.deleteReplica(replica1)); - Assert.assertNull(tablet.getReplicaById(replica1.getId())); + Assertions.assertFalse(tablet.deleteReplicaByBackendId(replica1.getBackendIdWithoutException())); + Assertions.assertFalse(tablet.deleteReplica(replica1)); + Assertions.assertNull(tablet.getReplicaById(replica1.getId())); // delete replica2 - Assert.assertTrue(tablet.deleteReplica(replica2)); - Assert.assertEquals(1, tablet.getReplicas().size()); + Assertions.assertTrue(tablet.deleteReplica(replica2)); + Assertions.assertEquals(1, tablet.getReplicas().size()); } @Test public void testGetReplicasReturnsImmutableSnapshot() { List snapshot = tablet.getReplicas(); - Assert.assertEquals(3, snapshot.size()); + Assertions.assertEquals(3, snapshot.size()); // A write after the snapshot was taken must not be visible in it (copy-on-write). Replica replica4 = new LocalReplica(4L, 4L, 100L, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, 0, 0); tablet.addReplica(replica4); - Assert.assertEquals(3, snapshot.size()); - Assert.assertEquals(4, tablet.getReplicas().size()); + Assertions.assertEquals(3, snapshot.size()); + Assertions.assertEquals(4, tablet.getReplicas().size()); // The returned snapshot is read-only. - Assert.assertThrows(UnsupportedOperationException.class, () -> snapshot.add(replica4)); + Assertions.assertThrows(UnsupportedOperationException.class, () -> snapshot.add(replica4)); } @Test @@ -167,21 +167,21 @@ public void testLocalReplicaBinlogMissingTimeoutAndRetryBudget() { Config.tablet_binlog_missing_max_times = 2; replica1.setBinlogMissing(true); - Assert.assertTrue(replica1.isBinlogMissing()); + Assertions.assertTrue(replica1.isBinlogMissing()); replica1.consumeBinlogMissingRetry(); - Assert.assertTrue(replica1.isBinlogMissing()); + Assertions.assertTrue(replica1.isBinlogMissing()); replica1.consumeBinlogMissingRetry(); - Assert.assertFalse(replica1.isBinlogMissing()); + Assertions.assertFalse(replica1.isBinlogMissing()); replica1.setBinlogMissing(true); - Assert.assertTrue(replica1.isBinlogMissing()); + Assertions.assertTrue(replica1.isBinlogMissing()); replica1.setBinlogMissing(false); - Assert.assertFalse(replica1.isBinlogMissing()); + Assertions.assertFalse(replica1.isBinlogMissing()); Config.tablet_binlog_missing_timeout_second = 0; replica1.setBinlogMissing(true); - Assert.assertFalse(replica1.isBinlogMissing()); + Assertions.assertFalse(replica1.isBinlogMissing()); } finally { Config.tablet_binlog_missing_timeout_second = originTimeoutSecond; Config.tablet_binlog_missing_max_times = originMaxTimes; @@ -196,13 +196,13 @@ public void testIterateReplicasWhileMutatingDoesNotThrow() { // during iteration. int seen = 0; for (Replica r : tablet.getReplicas()) { - Assert.assertNotNull(r); + Assertions.assertNotNull(r); tablet.addReplica(new LocalReplica(100L + seen, 100L + seen, 100L, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, 0, 0)); tablet.deleteReplicaByBackendId(2L); seen++; } - Assert.assertEquals(3, seen); + Assertions.assertEquals(3, seen); } @Test @@ -246,7 +246,7 @@ public void testConcurrentGetReplicasNeverThrows() throws InterruptedException { writer.join(); if (error.get() != null) { - Assert.fail("getReplicas() iteration threw under concurrent mutation: " + error.get()); + Assertions.fail("getReplicas() iteration threw under concurrent mutation: " + error.get()); } } @@ -261,12 +261,12 @@ public void testSerialization() throws Exception { // 2. Read a object from file DataInputStream dis = new DataInputStream(Files.newInputStream(path)); Tablet rTablet1 = GsonUtils.GSON.fromJson(Text.readString(dis), Tablet.class); - Assert.assertEquals(1, rTablet1.getId()); - Assert.assertEquals(3, rTablet1.getReplicas().size()); - Assert.assertEquals(rTablet1.getReplicas().get(0).getVersion(), rTablet1.getReplicas().get(1).getVersion()); + Assertions.assertEquals(1, rTablet1.getId()); + Assertions.assertEquals(3, rTablet1.getReplicas().size()); + Assertions.assertEquals(rTablet1.getReplicas().get(0).getVersion(), rTablet1.getReplicas().get(1).getVersion()); - Assert.assertEquals(rTablet1, tablet); - Assert.assertEquals(rTablet1, rTablet1); + Assertions.assertEquals(rTablet1, tablet); + Assertions.assertEquals(rTablet1, rTablet1); Tablet tablet2 = new LocalTablet(1); Replica replica1 = new LocalReplica(1L, 1L, 100L, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, 0, 0); @@ -274,15 +274,15 @@ public void testSerialization() throws Exception { Replica replica3 = new LocalReplica(3L, 3L, 100L, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, 0, 0); tablet2.addReplica(replica1); tablet2.addReplica(replica2); - Assert.assertNotEquals(tablet2, tablet); + Assertions.assertNotEquals(tablet2, tablet); tablet2.addReplica(replica3); - Assert.assertEquals(tablet2, tablet); + Assertions.assertEquals(tablet2, tablet); Tablet tablet3 = new LocalTablet(1); tablet3.addReplica(replica1); tablet3.addReplica(replica2); tablet3.addReplica(new LocalReplica(4L, 4L, 100L, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, 0, 0)); - Assert.assertNotEquals(tablet3, tablet); + Assertions.assertNotEquals(tablet3, tablet); dis.close(); Files.delete(path); @@ -294,22 +294,22 @@ public void testRowBinlogTabletIdsGsonUpgradeCompatibility() { baseTablet.setRowBinlogTabletId(20L); JsonObject baseTabletJson = JsonParser.parseString(GsonUtils.GSON.toJson(baseTablet)).getAsJsonObject(); Tablet deserializedBaseTablet = GsonUtils.GSON.fromJson(baseTabletJson, Tablet.class); - Assert.assertEquals(20L, deserializedBaseTablet.getRowBinlogTabletId()); - Assert.assertNull(deserializedBaseTablet.rowBinlogBaseTabletId); + Assertions.assertEquals(20L, deserializedBaseTablet.getRowBinlogTabletId()); + Assertions.assertNull(deserializedBaseTablet.rowBinlogBaseTabletId); Tablet rowBinlogTablet = new LocalTablet(20L); rowBinlogTablet.setRowBinlogBaseTabletId(10L); JsonObject rowBinlogTabletJson = JsonParser.parseString(GsonUtils.GSON.toJson(rowBinlogTablet)) .getAsJsonObject(); Tablet deserializedRowBinlogTablet = GsonUtils.GSON.fromJson(rowBinlogTabletJson, Tablet.class); - Assert.assertEquals(10L, deserializedRowBinlogTablet.getRowBinlogBaseTabletId()); - Assert.assertNull(deserializedRowBinlogTablet.rowBinlogTabletId); + Assertions.assertEquals(10L, deserializedRowBinlogTablet.getRowBinlogBaseTabletId()); + Assertions.assertNull(deserializedRowBinlogTablet.rowBinlogTabletId); baseTabletJson.remove("rbti"); baseTabletJson.remove("rbbti"); Tablet deserializedLegacyTablet = GsonUtils.GSON.fromJson(baseTabletJson, Tablet.class); - Assert.assertNull(deserializedLegacyTablet.rowBinlogTabletId); - Assert.assertNull(deserializedLegacyTablet.rowBinlogBaseTabletId); + Assertions.assertNull(deserializedLegacyTablet.rowBinlogTabletId); + Assertions.assertNull(deserializedLegacyTablet.rowBinlogBaseTabletId); } /** @@ -331,7 +331,7 @@ private final void testTabletColocateHealthStatus0(Tablet.TabletStatus exceptedT tablet.addReplica(new LocalReplica(replicaId++, pair.first, versionAndSuccessVersion, 0, 200000L, 0, 3000L, ReplicaState.NORMAL, lastFailVersion, versionAndSuccessVersion)); } - Assert.assertEquals(tablet.getColocateHealth(100L, new ReplicaAllocation((short) 3), + Assertions.assertEquals(tablet.getColocateHealth(100L, new ReplicaAllocation((short) 3), Sets.newHashSet(1L, 2L, 3L)).status, exceptedTabletStatus); } @@ -366,35 +366,35 @@ public void testTabletColocateHealthStatus() { public void testGetMinReplicaRowCount() { Tablet t = new LocalTablet(1); long row = t.getMinReplicaRowCount(1); - Assert.assertEquals(0, row); + Assertions.assertEquals(0, row); Replica r1 = new LocalReplica(1, 1, 10, 0, 0, 0, 100, ReplicaState.NORMAL, 0, 10); t.addReplica(r1); row = t.getMinReplicaRowCount(10); - Assert.assertEquals(100, row); + Assertions.assertEquals(100, row); row = t.getMinReplicaRowCount(11); - Assert.assertEquals(0, row); + Assertions.assertEquals(0, row); Replica r2 = new LocalReplica(2, 2, 10, 0, 0, 0, 110, ReplicaState.NORMAL, 0, 10); Replica r3 = new LocalReplica(3, 3, 10, 0, 0, 0, 90, ReplicaState.NORMAL, 0, 10); t.addReplica(r2); t.addReplica(r3); row = t.getMinReplicaRowCount(11); - Assert.assertEquals(0, row); + Assertions.assertEquals(0, row); row = t.getMinReplicaRowCount(9); - Assert.assertEquals(90, row); + Assertions.assertEquals(90, row); r3.setBad(true); row = t.getMinReplicaRowCount(9); - Assert.assertEquals(100, row); + Assertions.assertEquals(100, row); r3.setBad(false); row = t.getMinReplicaRowCount(9); - Assert.assertEquals(90, row); + Assertions.assertEquals(90, row); r2.updateVersion(11); row = t.getMinReplicaRowCount(9); - Assert.assertEquals(110, row); + Assertions.assertEquals(110, row); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/TypeTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/TypeTest.java index 2029d05c082c76..52808fedb3d380 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/TypeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/TypeTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.Config; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -31,23 +31,23 @@ public class TypeTest { public void testArrayOfArrayExactMatch() { ArrayType a1 = new ArrayType(new ArrayType(Type.INT, true), true); ArrayType a2 = new ArrayType(new ArrayType(Type.INT, true), true); - Assert.assertTrue(Type.matchExactType(a1, a2, false)); + Assertions.assertTrue(Type.matchExactType(a1, a2, false)); // inner type mismatch ArrayType a3 = new ArrayType(new ArrayType(Type.BIGINT, true), true); - Assert.assertFalse(Type.matchExactType(a1, a3, false)); + Assertions.assertFalse(Type.matchExactType(a1, a3, false)); // containsNull is always true now, so a4 is equivalent to a1 ArrayType a4 = new ArrayType(new ArrayType(Type.INT, true), false); - Assert.assertTrue(Type.matchExactType(a1, a4, false)); + Assertions.assertTrue(Type.matchExactType(a1, a4, false)); // array nested decimal test ArrayType a5 = new ArrayType(new ArrayType(ScalarType.createDecimalV3Type(8, 2), true), true); ArrayType a6 = new ArrayType(new ArrayType(ScalarType.createDecimalV3Type(9, 2), true), true); ArrayType a7 = new ArrayType(new ArrayType(ScalarType.createDecimalV3Type(-1, -1), true), true); - Assert.assertFalse(Type.matchExactType(a5, a6, false)); - Assert.assertFalse(Type.matchExactType(a5, a6, true)); - Assert.assertFalse(Type.matchExactType(a6, a7, false)); + Assertions.assertFalse(Type.matchExactType(a5, a6, false)); + Assertions.assertFalse(Type.matchExactType(a5, a6, true)); + Assertions.assertFalse(Type.matchExactType(a6, a7, false)); } // ===================== MapType ===================== @@ -57,17 +57,17 @@ public void testMapWithNestedValueExactMatch() { ArrayType arrayOfD = new ArrayType(d10s2, true); MapType m1 = new MapType(Type.INT, arrayOfD, true, true); MapType m2 = new MapType(Type.INT, new ArrayType(ScalarType.createDecimalV3Type(10, 2), true), true, true); - Assert.assertTrue(Type.matchExactType(m1, m2, false)); + Assertions.assertTrue(Type.matchExactType(m1, m2, false)); // value decimal precision differs, same scale MapType m3 = new MapType(Type.INT, new ArrayType(ScalarType.createDecimalV3Type(12, 2), true), true, true); // ignorePrecision = false -> not match - Assert.assertFalse(Type.matchExactType(m1, m3, false)); - Assert.assertFalse(Type.matchExactType(m1, m3, true)); + Assertions.assertFalse(Type.matchExactType(m1, m3, false)); + Assertions.assertFalse(Type.matchExactType(m1, m3, true)); // key/value containsNull differs, but MapType.equals() ignores it -> matches MapType m4 = new MapType(Type.INT, arrayOfD, false, true); - Assert.assertTrue(Type.matchExactType(m1, m4, false)); + Assertions.assertTrue(Type.matchExactType(m1, m4, false)); } // ===================== StructType ===================== @@ -83,21 +83,21 @@ public void testStructWithNestedFieldsExactMatch() { new StructField("y", new ArrayType(Type.INT, true), null, true) ); // names are ignored by matchExactType recursion; matchesType requires containsNull equal - Assert.assertTrue(Type.matchExactType(s1, s2, false)); + Assertions.assertTrue(Type.matchExactType(s1, s2, false)); // inner element type differs StructType s3 = new StructType( new StructField("f1", Type.INT, null, true), new StructField("f2", new ArrayType(Type.BIGINT, true), null, true) ); - Assert.assertFalse(Type.matchExactType(s1, s3, false)); + Assertions.assertFalse(Type.matchExactType(s1, s3, false)); // field nullability differs -> matchesType fails upfront StructType s4 = new StructType( new StructField("f1", Type.INT, null, false), new StructField("f2", new ArrayType(Type.INT, true), null, true) ); - Assert.assertFalse(Type.matchExactType(s1, s4, false)); + Assertions.assertFalse(Type.matchExactType(s1, s4, false)); } // ===================== VariantType ===================== @@ -113,29 +113,29 @@ public void testVariantPredefinedFieldsExactMatch() { fields2.add(new VariantField("x", Type.INT, "")); fields2.add(new VariantField("y", new ArrayType(ScalarType.createDecimalV3Type(10, 2), true), "")); VariantType v2 = new VariantType(fields2); - Assert.assertTrue(Type.matchExactType(v1, v2, false)); + Assertions.assertTrue(Type.matchExactType(v1, v2, false)); // change type of second field ArrayList fields3 = new ArrayList<>(); fields3.add(new VariantField("a", Type.INT, "")); fields3.add(new VariantField("b", new ArrayType(ScalarType.createDecimalV3Type(12, 2), true), "")); VariantType v3 = new VariantType(fields3); - Assert.assertFalse(Type.matchExactType(v1, v3, false)); + Assertions.assertFalse(Type.matchExactType(v1, v3, false)); // same types but different order -> index-wise comparison fails ArrayList fields4 = new ArrayList<>(); fields4.add(new VariantField("b", new ArrayType(ScalarType.createDecimalV3Type(10, 2), true), "")); fields4.add(new VariantField("a", Type.INT, "")); VariantType v4 = new VariantType(fields4); - Assert.assertFalse(Type.matchExactType(v1, v4, false)); + Assertions.assertFalse(Type.matchExactType(v1, v4, false)); VariantType differentMaxSubcolumns = new VariantType(fields1, 2048, false, 10000, 1, false, 0L, 64, false); - Assert.assertFalse(Type.matchExactType(v1, differentMaxSubcolumns, false)); + Assertions.assertFalse(Type.matchExactType(v1, differentMaxSubcolumns, false)); VariantType docMode = new VariantType(fields1, 0, false, 10000, 1, true, 0L, 64, false); - Assert.assertFalse(Type.matchExactType(v1, docMode, false)); + Assertions.assertFalse(Type.matchExactType(v1, docMode, false)); } @@ -144,7 +144,7 @@ public void testVariantToSqlSerializesNestedGroupProperty() { VariantType variantType = new VariantType(new ArrayList<>(), 0, false, 10000, 0, false, 0L, 64, true); - Assert.assertTrue(variantType.toSql().contains("\"variant_enable_nested_group\" = \"true\"")); + Assertions.assertTrue(variantType.toSql().contains("\"variant_enable_nested_group\" = \"true\"")); } @Test @@ -152,10 +152,10 @@ public void testVariantToThriftUsesGlobalV2Config() { boolean originalEnableVariantV2 = Config.enable_variant_v2; try { Config.enable_variant_v2 = false; - Assert.assertFalse(new VariantType().toThrift().types.get(0).scalar_type.variant_is_v2); + Assertions.assertFalse(new VariantType().toThrift().types.get(0).scalar_type.variant_is_v2); Config.enable_variant_v2 = true; - Assert.assertTrue(new VariantType().toThrift().types.get(0).scalar_type.variant_is_v2); + Assertions.assertTrue(new VariantType().toThrift().types.get(0).scalar_type.variant_is_v2); } finally { Config.enable_variant_v2 = originalEnableVariantV2; } @@ -184,7 +184,7 @@ public void testArrayMapStructCombinationWithPrecision() { MapType innerMap2 = new MapType(Type.INT, innerStruct2, true, true); ArrayType complex2 = new ArrayType(innerMap2, true); - Assert.assertFalse(Type.matchExactType(complex1, complex2, false)); + Assertions.assertFalse(Type.matchExactType(complex1, complex2, false)); } // ===================== Decimal/DATETIMEV2 Precision & Scale ===================== @@ -193,21 +193,21 @@ public void testDecimalPrecisionGroupsIgnorePrecision() { // DECIMAL32 group (<=9) ScalarType d8s2 = ScalarType.createDecimalV3Type(8, 2); ScalarType d9s2 = ScalarType.createDecimalV3Type(9, 2); - Assert.assertFalse(Type.matchExactType(d8s2, d9s2, false)); + Assertions.assertFalse(Type.matchExactType(d8s2, d9s2, false)); // Cross group: DECIMAL32 vs DECIMAL64 -> should be false even when ignorePrecision ScalarType d10s2 = ScalarType.createDecimalV3Type(10, 2); - Assert.assertFalse(Type.matchExactType(d9s2, d10s2, true)); + Assertions.assertFalse(Type.matchExactType(d9s2, d10s2, true)); // DECIMAL64 group (10..18) ScalarType d10s3 = ScalarType.createDecimalV3Type(10, 3); ScalarType d18s3 = ScalarType.createDecimalV3Type(18, 3); - Assert.assertFalse(Type.matchExactType(d10s3, d18s3, false)); + Assertions.assertFalse(Type.matchExactType(d10s3, d18s3, false)); // DECIMAL128 group (19..38) ScalarType d20s1 = ScalarType.createDecimalV3Type(20, 1); ScalarType d38s1 = ScalarType.createDecimalV3Type(38, 1); - Assert.assertFalse(Type.matchExactType(d20s1, d38s1, false)); + Assertions.assertFalse(Type.matchExactType(d20s1, d38s1, false)); } // ===================== exceedsMaxNestingDepth ===================== @@ -229,14 +229,14 @@ private static Type buildMapKeyNestedType(int depth) { public void testMapKeyPathNestingWithinLimit() { // MAP < MAP < ... STRING ...>, STRING > with total nesting == MAX_NESTING_DEPTH should be allowed Type t = buildMapKeyNestedType(Type.MAX_NESTING_DEPTH); - Assert.assertFalse(t.exceedsMaxNestingDepth()); + Assertions.assertFalse(t.exceedsMaxNestingDepth()); } @Test public void testMapKeyPathDeepNestingDetected() { // Nesting depth of MAX_NESTING_DEPTH + 1 via keyType path must be rejected Type t = buildMapKeyNestedType(Type.MAX_NESTING_DEPTH + 1); - Assert.assertTrue(t.exceedsMaxNestingDepth()); + Assertions.assertTrue(t.exceedsMaxNestingDepth()); } @Test @@ -247,7 +247,7 @@ public void testMapValuePathDeepNestingDetected() { for (int i = 0; i <= Type.MAX_NESTING_DEPTH; i++) { current = new MapType(Type.STRING, current, true, true); } - Assert.assertTrue(current.exceedsMaxNestingDepth()); + Assertions.assertTrue(current.exceedsMaxNestingDepth()); } @Test @@ -255,9 +255,9 @@ public void testDatetimeV2ScaleMatching() { ScalarType dtv2s3 = ScalarType.createDatetimeV2Type(3); ScalarType dtv2s6 = ScalarType.createDatetimeV2Type(6); // Different scales -> no match regardless of ignorePrecision - Assert.assertFalse(Type.matchExactType(dtv2s3, dtv2s6, false)); - Assert.assertFalse(Type.matchExactType(dtv2s3, dtv2s6, true)); + Assertions.assertFalse(Type.matchExactType(dtv2s3, dtv2s6, false)); + Assertions.assertFalse(Type.matchExactType(dtv2s3, dtv2s6, true)); // Same scale -> match - Assert.assertTrue(Type.matchExactType(dtv2s6, ScalarType.createDatetimeV2Type(6), false)); + Assertions.assertTrue(Type.matchExactType(dtv2s6, ScalarType.createDatetimeV2Type(6), false)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/UserPropertyTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/UserPropertyTest.java index 84a66d5a07beff..46c5bea29ec639 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/UserPropertyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/UserPropertyTest.java @@ -32,10 +32,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -47,7 +47,7 @@ public class UserPropertyTest { private SqlBlockRuleMgr sqlBlockRuleMgr = Mockito.mock(SqlBlockRuleMgr.class); private MockedStatic mockedStaticEnv; - @Before + @BeforeEach public void setUp() { mockedStaticEnv = Mockito.mockStatic(Env.class); mockedStaticEnv.when(Env::getCurrentEnv).thenReturn(env); @@ -59,7 +59,7 @@ public void setUp() { Mockito.when(sqlBlockRuleMgr.existRule("test3")).thenReturn(true); } - @After + @AfterEach public void tearDown() { if (mockedStaticEnv != null) { mockedStaticEnv.close(); @@ -83,15 +83,15 @@ public void testUpdate() throws UserException { UserProperty userProperty = new UserProperty(); userProperty.update(properties); - Assert.assertEquals(100, userProperty.getMaxConn()); - Assert.assertEquals(3000, userProperty.getMaxQueryInstances()); - Assert.assertEquals(2000, userProperty.getParallelFragmentExecInstanceNum()); - Assert.assertEquals(new String[]{"rule1", "rule2"}, userProperty.getSqlBlockRules()); - Assert.assertEquals(2, userProperty.getCpuResourceLimit()); - Assert.assertEquals(500, userProperty.getQueryTimeout()); - Assert.assertEquals(Sets.newHashSet(), userProperty.getCopiedResourceTags()); - Assert.assertEquals(true, userProperty.getEnablePreferCachedRowset()); - Assert.assertEquals(4500, userProperty.getQueryFreshnessToleranceMs()); + Assertions.assertEquals(100, userProperty.getMaxConn()); + Assertions.assertEquals(3000, userProperty.getMaxQueryInstances()); + Assertions.assertEquals(2000, userProperty.getParallelFragmentExecInstanceNum()); + Assertions.assertArrayEquals(new String[]{"rule1", "rule2"}, userProperty.getSqlBlockRules()); + Assertions.assertEquals(2, userProperty.getCpuResourceLimit()); + Assertions.assertEquals(500, userProperty.getQueryTimeout()); + Assertions.assertEquals(Sets.newHashSet(), userProperty.getCopiedResourceTags()); + Assertions.assertEquals(true, userProperty.getEnablePreferCachedRowset()); + Assertions.assertEquals(4500, userProperty.getQueryFreshnessToleranceMs()); // fetch property List> rows = userProperty.fetchProperty(); @@ -100,15 +100,15 @@ public void testUpdate() throws UserException { String value = row.get(1); if (key.equalsIgnoreCase("max_user_connections")) { - Assert.assertEquals("100", value); + Assertions.assertEquals("100", value); } else if (key.equalsIgnoreCase("max_query_instances")) { - Assert.assertEquals("3000", value); + Assertions.assertEquals("3000", value); } else if (key.equalsIgnoreCase("sql_block_rules")) { - Assert.assertEquals("rule1,rule2", value); + Assertions.assertEquals("rule1,rule2", value); } else if (key.equalsIgnoreCase("cpu_resource_limit")) { - Assert.assertEquals("2", value); + Assertions.assertEquals("2", value); } else if (key.equalsIgnoreCase("query_timeout")) { - Assert.assertEquals("500", value); + Assertions.assertEquals("500", value); } } @@ -116,11 +116,11 @@ public void testUpdate() throws UserException { properties.clear(); properties.add(Pair.of("sql_block_rules", "")); userProperty.update(properties); - Assert.assertEquals(1, userProperty.getSqlBlockRules().length); + Assertions.assertEquals(1, userProperty.getSqlBlockRules().length); properties.clear(); properties.add(Pair.of("sql_block_rules", "test1, test2,test3")); userProperty.update(properties); - Assert.assertEquals(3, userProperty.getSqlBlockRules().length); + Assertions.assertEquals(3, userProperty.getSqlBlockRules().length); } @Test @@ -129,30 +129,30 @@ public void testValidation() throws UserException { properties.add(Pair.of("cpu_resource_limit", "-1")); UserProperty userProperty = new UserProperty(); userProperty.update(properties); - Assert.assertEquals(-1, userProperty.getCpuResourceLimit()); + Assertions.assertEquals(-1, userProperty.getCpuResourceLimit()); properties = Lists.newArrayList(); properties.add(Pair.of("cpu_resource_limit", "-2")); userProperty = new UserProperty(); try { userProperty.update(properties); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("is not valid")); + Assertions.assertTrue(e.getMessage().contains("is not valid")); } - Assert.assertEquals(-1, userProperty.getCpuResourceLimit()); + Assertions.assertEquals(-1, userProperty.getCpuResourceLimit()); // we should allow query_timeout < 0, otherwise, not have command reset query_timeout of user properties = Lists.newArrayList(); properties.add(Pair.of("query_timeout", "-2")); userProperty = new UserProperty(); userProperty.update(properties); - Assert.assertEquals(-2, userProperty.getQueryTimeout()); + Assertions.assertEquals(-2, userProperty.getQueryTimeout()); // we should allow insert_timeout < 0, otherwise, not have command reset insert_timeout of user properties = Lists.newArrayList(); properties.add(Pair.of("insert_timeout", "-2")); userProperty = new UserProperty(); userProperty.update(properties); - Assert.assertEquals(-2, userProperty.getInsertTimeout()); + Assertions.assertEquals(-2, userProperty.getInsertTimeout()); } @Test @@ -176,24 +176,24 @@ public void testUpdateInitCatalog() throws UserException { UserProperty userProperty = new UserProperty(); try { userProperty.update(properties); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("not exists")); + Assertions.assertTrue(e.getMessage().contains("not exists")); } - Assert.assertEquals("internal", userProperty.getInitCatalog()); + Assertions.assertEquals("internal", userProperty.getInitCatalog()); // for exist catalog, use it directly properties = Lists.newArrayList(); properties.add(Pair.of("default_init_catalog", "exist_catalog")); userProperty = new UserProperty(); userProperty.update(properties); - Assert.assertEquals("exist_catalog", userProperty.getInitCatalog()); + Assertions.assertEquals("exist_catalog", userProperty.getInitCatalog()); } @Test public void testExternalTempUserUsesDefaultPropertyFallback() { UserPropertyMgr propertyMgr = new UserPropertyMgr(); - Assert.assertEquals(0, propertyMgr.getMaxConn("external_alice")); + Assertions.assertEquals(0, propertyMgr.getMaxConn("external_alice")); ConnectContext ctx = new ConnectContext(); ctx.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("external_alice", "127.0.0.1")); @@ -204,11 +204,11 @@ public void testExternalTempUserUsesDefaultPropertyFallback() { .build()); ctx.setThreadLocalInfo(); try { - Assert.assertEquals(100, propertyMgr.getMaxConn("external_alice")); - Assert.assertEquals(-1, propertyMgr.getQueryTimeout("external_alice")); - Assert.assertEquals(-1, propertyMgr.getInsertTimeout("external_alice")); - Assert.assertEquals("internal", propertyMgr.getInitCatalog("external_alice")); - Assert.assertEquals(WorkloadGroupMgr.DEFAULT_GROUP_NAME, + Assertions.assertEquals(100, propertyMgr.getMaxConn("external_alice")); + Assertions.assertEquals(-1, propertyMgr.getQueryTimeout("external_alice")); + Assertions.assertEquals(-1, propertyMgr.getInsertTimeout("external_alice")); + Assertions.assertEquals("internal", propertyMgr.getInitCatalog("external_alice")); + Assertions.assertEquals(WorkloadGroupMgr.DEFAULT_GROUP_NAME, propertyMgr.getWorkloadGroup("external_alice")); } finally { ConnectContext.remove(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAccessControllerTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAccessControllerTest.java index 95c3cc2a690c01..bbf4325a401ace 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAccessControllerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAccessControllerTest.java @@ -22,8 +22,8 @@ import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl; import org.apache.ranger.plugin.policyengine.RangerPolicyEngine; import org.apache.ranger.plugin.service.RangerBasePlugin; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Field; @@ -32,9 +32,9 @@ public class RangerHiveAccessControllerTest { @Test public void testRangerAccessTypeMapping() { - Assert.assertEquals("select", RangerHiveAccessController.toRangerAccessType(HiveAccessType.SELECT)); - Assert.assertEquals("update", RangerHiveAccessController.toRangerAccessType(HiveAccessType.UPDATE)); - Assert.assertEquals(RangerPolicyEngine.ANY_ACCESS, + Assertions.assertEquals("select", RangerHiveAccessController.toRangerAccessType(HiveAccessType.SELECT)); + Assertions.assertEquals("update", RangerHiveAccessController.toRangerAccessType(HiveAccessType.UPDATE)); + Assertions.assertEquals(RangerPolicyEngine.ANY_ACCESS, RangerHiveAccessController.toRangerAccessType(HiveAccessType.USE)); } @@ -56,7 +56,7 @@ public void testPolicyRequestsUseLowerCaseSelect() throws Exception { controller.evalRowFilterPolicies(currentUser, "catalog", "database", "table"); controller.evalDataMaskPolicy(currentUser, "catalog", "database", "table", "column"); - Assert.assertEquals("select", rowFilterRequest.getAccessType()); - Assert.assertEquals("select", dataMaskRequest.getAccessType()); + Assertions.assertEquals("select", rowFilterRequest.getAccessType()); + Assertions.assertEquals("select", dataMaskRequest.getAccessType()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAuditLogFlusherTest.java b/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAuditLogFlusherTest.java index 92e9440aaf350a..f2148f8476c9c1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAuditLogFlusherTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/catalog/authorizer/ranger/hive/RangerHiveAuditLogFlusherTest.java @@ -18,8 +18,8 @@ package org.apache.doris.catalog.authorizer.ranger.hive; import org.apache.ranger.audit.model.AuthzAuditEvent; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -65,7 +65,7 @@ public void testProducerCanEnqueueWhileProviderDeliveryIsBlocked() throws Except try { Future flush = executor.submit(auditHandler::flushAudit); - Assert.assertTrue(auditHandler.deliveryStarted.await(10, TimeUnit.SECONDS)); + Assertions.assertTrue(auditHandler.deliveryStarted.await(10, TimeUnit.SECONDS)); Future producer = executor.submit(() -> auditHandler.addAuthzAuditEvent(second)); producer.get(2, TimeUnit.SECONDS); @@ -74,7 +74,7 @@ public void testProducerCanEnqueueWhileProviderDeliveryIsBlocked() throws Except flush.get(10, TimeUnit.SECONDS); auditHandler.flushAudit(); - Assert.assertEquals(List.of(first, second), auditHandler.delivered); + Assertions.assertEquals(List.of(first, second), auditHandler.delivered); } finally { auditHandler.allowDelivery.countDown(); executor.shutdownNow(); @@ -88,14 +88,14 @@ public void testFailedDeliveryIsRetriedBeforeLaterEvents() { AuthzAuditEvent second = allowedEvent(); auditHandler.addAuthzAuditEvent(first); - Assert.assertThrows(RuntimeException.class, auditHandler::flushAudit); - Assert.assertEquals(1, auditHandler.getPendingAuditEventCountForTest()); + Assertions.assertThrows(RuntimeException.class, auditHandler::flushAudit); + Assertions.assertEquals(1, auditHandler.getPendingAuditEventCountForTest()); auditHandler.addAuthzAuditEvent(second); auditHandler.flushAudit(); - Assert.assertEquals(List.of(first, second), auditHandler.delivered); - Assert.assertEquals(0, auditHandler.getPendingAuditEventCountForTest()); + Assertions.assertEquals(List.of(first, second), auditHandler.delivered); + Assertions.assertEquals(0, auditHandler.getPendingAuditEventCountForTest()); } private static AuthzAuditEvent allowedEvent() { diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/BeLoadRebalancePartitionSkewTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/BeLoadRebalancePartitionSkewTest.java index 4de236c470c464..df320ab2c76ade 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/BeLoadRebalancePartitionSkewTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/BeLoadRebalancePartitionSkewTest.java @@ -50,10 +50,10 @@ import com.google.common.collect.Maps; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -113,7 +113,7 @@ public class BeLoadRebalancePartitionSkewTest { private long nextId = 100000L; private String origRebalancerType; - @Before + @BeforeEach public void setUp() throws Exception { FeConstants.runningUnitTest = true; origRebalancerType = Config.tablet_rebalancer_type; @@ -146,7 +146,7 @@ public void setUp() throws Exception { mockedEnvStatic.when(Env::getCurrentInternalCatalog).thenReturn(catalog); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -179,8 +179,8 @@ public void testEmptyTabletBalanceShouldNotBreakRoundRobin() { LOG.info("store_sales before balance: {}", sortedCounts(countReplicaPerBe(storeSales))); LOG.info("background before balance: {}", sortedCounts(countReplicaPerBe(background))); - Assert.assertEquals(1, skewOf(countReplicaPerBe(storeSales))); - Assert.assertEquals(0, skewOf(countReplicaPerBe(background))); + Assertions.assertEquals(1, skewOf(countReplicaPerBe(storeSales))); + Assertions.assertEquals(0, skewOf(countReplicaPerBe(background))); int moves = runBalanceUntilStable(Lists.newArrayList(storeSales, background), 100); @@ -189,9 +189,8 @@ public void testEmptyTabletBalanceShouldNotBreakRoundRobin() { LOG.info("store_sales after balance: {}, moves: {}", sortedCounts(storeSalesAfter), moves); LOG.info("background after balance: {}", sortedCounts(backgroundAfter)); - Assert.assertTrue("the newly created table must keep its round-robin distribution," - + " actual: " + sortedCounts(storeSalesAfter), - skewOf(storeSalesAfter) <= 1); + Assertions.assertTrue(skewOf(storeSalesAfter) <= 1, "the newly created table must keep its round-robin distribution," + + " actual: " + sortedCounts(storeSalesAfter)); // Loaded tablets can legitimately move for capacity balancing. Any resulting per-index // skew belongs to a follow-up change and is intentionally only observed here. LOG.info("background table skew after legitimate capacity balance: {}", skewOf(backgroundAfter)); @@ -213,14 +212,12 @@ public void testLoadedTableIsNotBalancedBeforeSizeIsReportedAfterRestart() { int moves = runBalanceUntilStable(Lists.newArrayList(loadedTable), 100); Map after = countReplicaPerBe(loadedTable); - Assert.assertEquals("no tablet with an unreported size should move", 0, moves); - Assert.assertEquals("the loaded table must retain its distribution during the restart window", - before, after); + Assertions.assertEquals(0, moves, "no tablet with an unreported size should move"); + Assertions.assertEquals(before, after, "the loaded table must retain its distribution during the restart window"); // Selection already filters these out, so nothing ever reaches the scheduler and the stat // counter stays at zero. How many tablets were skipped is reported in the round summary log // instead, because it counts scanned tablets rather than balance attempts. - Assert.assertEquals("selection should filter zero-size tablets before scheduling", - 0L, schedulerStat.counterBalanceRejectByZeroDataSize.get()); + Assertions.assertEquals(0L, schedulerStat.counterBalanceRejectByZeroDataSize.get(), "selection should filter zero-size tablets before scheduling"); } /** The zero-size guard is unconditional and also applies to urgent BE balance. */ @@ -241,16 +238,15 @@ public void testUrgentBalanceRejectsTabletWhoseSizeBecomesZeroBeforeScheduling() LoadStatisticForTag loadStatistic = newLoadStatistic(rebalancer); List lowBEs = Lists.newArrayList(); List highBEs = Lists.newArrayList(); - Assert.assertTrue("the test must exercise urgent balance", - loadStatistic.getLowHighBEsWithIsUrgent(lowBEs, highBEs, TStorageMedium.HDD)); + Assertions.assertTrue(loadStatistic.getLowHighBEsWithIsUrgent(lowBEs, highBEs, TStorageMedium.HDD), "the test must exercise urgent balance"); rebalancer.updateLoadStatistic(Maps.newHashMap( Collections.singletonMap(Tag.DEFAULT_BACKEND_TAG, loadStatistic))); List candidates = rebalancer.selectAlternativeTablets(); - Assert.assertFalse("a reported, non-empty tablet should be selected", candidates.isEmpty()); + Assertions.assertFalse(candidates.isEmpty(), "a reported, non-empty tablet should be selected"); TabletSchedCtx tabletCtx = candidates.get(0); Tablet tablet = findTablet(Lists.newArrayList(index), tabletCtx.getTabletId()); - Assert.assertNotNull(tablet); + Assertions.assertNotNull(tablet); setReplicaSizes(index, 0L); tabletCtx.setTablet(tablet); tabletCtx.updateTabletSize(); @@ -260,14 +256,12 @@ public void testUrgentBalanceRejectsTabletWhoseSizeBecomesZeroBeforeScheduling() int availableSlotsBefore = slots.get(highBeId).getAvailableBalanceNum(replica.getPathHash()); try { rebalancer.completeSchedCtx(tabletCtx); - Assert.fail("urgent balance must reject a tablet whose size is no longer reported"); + Assertions.fail("urgent balance must reject a tablet whose size is no longer reported"); } catch (SchedException e) { - Assert.assertTrue(e.getMessage().contains("size of src replica is zero")); + Assertions.assertTrue(e.getMessage().contains("size of src replica is zero")); } - Assert.assertEquals("the zero-size check must run before taking the source slot", - availableSlotsBefore, slots.get(highBeId).getAvailableBalanceNum(replica.getPathHash())); - Assert.assertEquals("the scheduling-time rejection should increment the counter", - 1L, schedulerStat.counterBalanceRejectByZeroDataSize.get()); + Assertions.assertEquals(availableSlotsBefore, slots.get(highBeId).getAvailableBalanceNum(replica.getPathHash()), "the zero-size check must run before taking the source slot"); + Assertions.assertEquals(1L, schedulerStat.counterBalanceRejectByZeroDataSize.get(), "the scheduling-time rejection should increment the counter"); } /** @@ -285,8 +279,8 @@ public void testZeroSizeMoveIsAcceptedAlthoughCapacityIsUnchanged() { List highBEs = Lists.newArrayList(); stat.getLowHighBEsWithIsUrgent(lowBEs, highBEs, TStorageMedium.HDD); - Assert.assertFalse("the disk usage spread should classify some BE as HIGH", highBEs.isEmpty()); - Assert.assertFalse("the disk usage spread should classify some BE as LOW", lowBEs.isEmpty()); + Assertions.assertFalse(highBEs.isEmpty(), "the disk usage spread should classify some BE as HIGH"); + Assertions.assertFalse(lowBEs.isEmpty(), "the disk usage spread should classify some BE as LOW"); BackendLoadStatistic high = highBEs.get(highBEs.size() - 1); BackendLoadStatistic low = lowBEs.get(0); @@ -294,14 +288,11 @@ public void testZeroSizeMoveIsAcceptedAlthoughCapacityIsUnchanged() { long highUsedBefore = high.getTotalUsedCapacityB(TStorageMedium.HDD); long lowUsedBefore = low.getTotalUsedCapacityB(TStorageMedium.HDD); - Assert.assertTrue("a zero-sized tablet is accepted as a balance move even though it" - + " relocates no data at all", - stat.isMoreBalanced(high.getBeId(), low.getBeId(), 50000L, 0L, TStorageMedium.HDD)); + Assertions.assertTrue(stat.isMoreBalanced(high.getBeId(), low.getBeId(), 50000L, 0L, TStorageMedium.HDD), "a zero-sized tablet is accepted as a balance move even though it" + + " relocates no data at all"); - Assert.assertEquals("the capacity term is untouched by a zero-sized move", - highUsedBefore, high.getTotalUsedCapacityB(TStorageMedium.HDD)); - Assert.assertEquals("the capacity term is untouched by a zero-sized move", - lowUsedBefore, low.getTotalUsedCapacityB(TStorageMedium.HDD)); + Assertions.assertEquals(highUsedBefore, high.getTotalUsedCapacityB(TStorageMedium.HDD), "the capacity term is untouched by a zero-sized move"); + Assertions.assertEquals(lowUsedBefore, low.getTotalUsedCapacityB(TStorageMedium.HDD), "the capacity term is untouched by a zero-sized move"); } /** @@ -329,16 +320,15 @@ public void testGenuinelySkewedIndexIsStillBalanced() { Map before = countReplicaPerBe(index); LOG.info("skewed distribution before balance: {}", sortedCounts(before)); - Assert.assertEquals(8, skewOf(before)); + Assertions.assertEquals(8, skewOf(before)); int moves = runBalanceUntilStable(Lists.newArrayList(index), 100); Map after = countReplicaPerBe(index); LOG.info("skewed distribution after balance: {}, moves: {}", sortedCounts(after), moves); - Assert.assertTrue("balancer should have moved replicas away from the overloaded BE", - moves > 0); - Assert.assertTrue("a genuinely skewed index must still be balanced, actual: " - + sortedCounts(after), skewOf(after) <= 1); + Assertions.assertTrue(moves > 0, "balancer should have moved replicas away from the overloaded BE"); + Assertions.assertTrue(skewOf(after) <= 1, "a genuinely skewed index must still be balanced, actual: " + + sortedCounts(after)); } // ------------------------------------------------------------------------------------------ @@ -483,7 +473,7 @@ private Tablet findTablet(List indexes, long tabletId) { private void applyMove(Tablet tablet, long srcBeId, long destBeId) { TabletMeta tabletMeta = invertedIndex.getTabletMeta(tablet.getId()); Replica srcReplica = tablet.getReplicaByBackendId(srcBeId); - Assert.assertNotNull(srcReplica); + Assertions.assertNotNull(srcReplica); long dataSize = srcReplica.getDataSize(); Replica destReplica = new LocalReplica(nextId++, destBeId, Replica.ReplicaState.NORMAL, diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/ClusterLoadStatisticsTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/ClusterLoadStatisticsTest.java index 4e729ed633d60a..bc9915406e952b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/ClusterLoadStatisticsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/ClusterLoadStatisticsTest.java @@ -32,9 +32,9 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -50,7 +50,7 @@ public class ClusterLoadStatisticsTest { private SystemInfoService systemInfoService; private TabletInvertedIndex invertedIndex; - @Before + @BeforeEach public void setUp() { // be1 // 50%, 95%, 2% @@ -174,15 +174,15 @@ public void test() { Tag.DEFAULT_BACKEND_TAG, systemInfoService, invertedIndex, null); loadStatistic.init(); List> infos = loadStatistic.getStatistic(TStorageMedium.HDD); - Assert.assertEquals(3, infos.size()); + Assertions.assertEquals(3, infos.size()); BackendLoadStatistic beStat1 = loadStatistic.getBackendLoadStatistic(be1.getId()); - Assert.assertNotNull(beStat1); + Assertions.assertNotNull(beStat1); RootPathLoadStatistic path2 = beStat1.getPathStatisticByPathHash(1002); RootPathLoadStatistic path3 = beStat1.getPathStatisticByPathHash(1003); - Assert.assertEquals(Classification.HIGH, path2.getLocalClazz()); - Assert.assertEquals(Classification.HIGH, path2.getGlobalClazz()); - Assert.assertEquals(Classification.LOW, path3.getLocalClazz()); - Assert.assertEquals(Classification.LOW, path3.getGlobalClazz()); + Assertions.assertEquals(Classification.HIGH, path2.getLocalClazz()); + Assertions.assertEquals(Classification.HIGH, path2.getGlobalClazz()); + Assertions.assertEquals(Classification.LOW, path3.getLocalClazz()); + Assertions.assertEquals(Classification.LOW, path3.getGlobalClazz()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/ColocateTableCheckerAndBalancerTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/ColocateTableCheckerAndBalancerTest.java index 211ec62eb8b8de..9338851823249d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/ColocateTableCheckerAndBalancerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/ColocateTableCheckerAndBalancerTest.java @@ -57,9 +57,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -84,7 +84,7 @@ public class ColocateTableCheckerAndBalancerTest { private Map mixLoadScores; - @Before + @BeforeEach public void setUp() { backend1 = new Backend(1L, "192.168.1.1", 9050); backend2 = new Backend(2L, "192.168.1.2", 9050); @@ -165,8 +165,8 @@ KeysType.DUP_KEYS, new RangePartitionInfo(), "buildGlobalColocateStatistic"); List bucketStatistics = globalStatistic.getAllGroupBucketsMap().get(groupId); - Assert.assertEquals(1, bucketStatistics.size()); - Assert.assertEquals(1, bucketStatistics.get(0).totalReplicaNum); + Assertions.assertEquals(1, bucketStatistics.size()); + Assertions.assertEquals(1, bucketStatistics.get(0).totalReplicaNum); } } @@ -224,22 +224,22 @@ KeysType.DUP_KEYS, new RangePartitionInfo(), colocateTableIndex.addTableToGroup(db.getId(), table, "test_db.test_group", groupId); colocateTableIndex.addBackendsPerBucketSeq(groupId, backendsPerBucketSeq); colocateTableIndex.markGroupUnstable(groupId, "seed", false); - Assert.assertTrue(colocateTableIndex.isGroupUnstable(groupId)); + Assertions.assertTrue(colocateTableIndex.isGroupUnstable(groupId)); Deencapsulation.invoke(balancer, "matchGroups"); ArgumentCaptor tabletCtxCaptor = ArgumentCaptor.forClass(TabletSchedCtx.class); Mockito.verify(tabletScheduler).addTablet(tabletCtxCaptor.capture(), Mockito.eq(false)); TabletSchedCtx tabletCtx = tabletCtxCaptor.getValue(); - Assert.assertEquals(rowBinlogIndex.getId(), tabletCtx.getIndexId()); - Assert.assertEquals(rowBinlogTablet.getId(), tabletCtx.getTabletId()); - Assert.assertEquals(TabletStatus.COLOCATE_MISMATCH, tabletCtx.getTabletStatus()); - Assert.assertEquals(Priority.HIGH, tabletCtx.getPriority()); - Assert.assertEquals(Sets.newHashSet(1L, 2L, 3L), tabletCtx.getColocateBackendsSet()); - Assert.assertEquals(ImmutableMap.of(1L, 1L, 2L, 2L, 3L, 3L), + Assertions.assertEquals(rowBinlogIndex.getId(), tabletCtx.getIndexId()); + Assertions.assertEquals(rowBinlogTablet.getId(), tabletCtx.getTabletId()); + Assertions.assertEquals(TabletStatus.COLOCATE_MISMATCH, tabletCtx.getTabletStatus()); + Assertions.assertEquals(Priority.HIGH, tabletCtx.getPriority()); + Assertions.assertEquals(Sets.newHashSet(1L, 2L, 3L), tabletCtx.getColocateBackendsSet()); + Assertions.assertEquals(ImmutableMap.of(1L, 1L, 2L, 2L, 3L, 3L), tabletCtx.getRowBinlogRequiredDestPathHashByBackend()); Mockito.verify(rowBinlogTablet).readyToBeRepaired(infoService, Priority.HIGH); - Assert.assertFalse(colocateTableIndex.isGroupUnstable(groupId)); + Assertions.assertFalse(colocateTableIndex.isGroupUnstable(groupId)); } } @@ -319,8 +319,8 @@ public void testBalance() { balancedBackendsPerBucketSeq, false); List> expected = Lists.partition( Lists.newArrayList(8L, 5L, 6L, 5L, 6L, 7L, 9L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L), 3); - Assert.assertTrue("" + globalColocateStatistic, changed); - Assert.assertEquals(expected, balancedBackendsPerBucketSeq); + Assertions.assertTrue(changed, "" + globalColocateStatistic); + Assertions.assertEquals(expected, balancedBackendsPerBucketSeq); // 2. balance a already balanced group colocateTableIndex = createColocateIndex(groupId, @@ -333,8 +333,8 @@ public void testBalance() { colocateTableIndex, infoService, statistic, globalColocateStatistic, balancedBackendsPerBucketSeq, false); System.out.println(balancedBackendsPerBucketSeq); - Assert.assertFalse(changed); - Assert.assertTrue(balancedBackendsPerBucketSeq.isEmpty()); + Assertions.assertFalse(changed); + Assertions.assertTrue(balancedBackendsPerBucketSeq.isEmpty()); } @Test @@ -375,7 +375,7 @@ public void testFixBalanceEndlessLoop() { boolean changed = Deencapsulation.invoke(balancer, "relocateAndBalance", groupId, Tag.DEFAULT_BACKEND_TAG, new HashSet(), allAvailBackendIds, colocateTableIndex, infoService, statistic, globalColocateStatistic, balancedBackendsPerBucketSeq, false); - Assert.assertFalse(changed); + Assertions.assertFalse(changed); // 2. all backends are checked but this round is not changed // [[7], [7], [7], [7], [7]] @@ -389,7 +389,7 @@ public void testFixBalanceEndlessLoop() { changed = Deencapsulation.invoke(balancer, "relocateAndBalance", groupId, Tag.DEFAULT_BACKEND_TAG, new HashSet(), allAvailBackendIds, colocateTableIndex, infoService, statistic, globalColocateStatistic, balancedBackendsPerBucketSeq, false); - Assert.assertFalse(changed); + Assertions.assertFalse(changed); } @Test @@ -417,7 +417,7 @@ public void testFixBalanceEndlessLoop2() { boolean changed = (Boolean) Deencapsulation.invoke(balancer, "relocateAndBalance", groupId, Tag.DEFAULT_BACKEND_TAG, unAvailBackendIds, availBackendIds, colocateTableIndex, infoService, statistic, globalColocateStatistic, balancedBackendsPerBucketSeq, false); - Assert.assertFalse(changed); + Assertions.assertFalse(changed); } @Test @@ -437,14 +437,14 @@ public void testGetSortedBackendReplicaNumPairs() { List> backends = Deencapsulation.invoke(balancer, "getSortedBackendReplicaNumPairs", allAvailBackendIds, unavailBackendIds, statistic, globalColocateStatistic, flatBackendsPerBucketSeq); long[] backendIds = backends.stream().mapToLong(Map.Entry::getKey).toArray(); - Assert.assertArrayEquals(new long[]{7L, 8L, 6L, 2L, 3L, 5L, 4L, 1L}, backendIds); + Assertions.assertArrayEquals(new long[]{7L, 8L, 6L, 2L, 3L, 5L, 4L, 1L}, backendIds); // 0,1 bucket on same be and 5, 6 on same be flatBackendsPerBucketSeq = Lists.newArrayList(1L, 1L, 3L, 4L, 5L, 6L, 7L, 7L, 9L); backends = Deencapsulation.invoke(balancer, "getSortedBackendReplicaNumPairs", allAvailBackendIds, unavailBackendIds, statistic, globalColocateStatistic, flatBackendsPerBucketSeq); backendIds = backends.stream().mapToLong(Map.Entry::getKey).toArray(); - Assert.assertArrayEquals(new long[]{7L, 1L, 6L, 3L, 5L, 4L, 8L, 2L}, backendIds); + Assertions.assertArrayEquals(new long[]{7L, 1L, 6L, 3L, 5L, 4L, 8L, 2L}, backendIds); } public final class FakeBackendLoadStatistic extends BackendLoadStatistic { @@ -469,7 +469,7 @@ public BalanceStatus isFit(long tabletSize, TStorageMedium medium, List flatBackendsPerBucketSeq = Lists.newArrayList(1L, 2L, 2L, 3L, 4L, 2L); List indexes = Deencapsulation.invoke(balancer, "getBeSeqIndexes", flatBackendsPerBucketSeq, 2L); - Assert.assertArrayEquals(new int[]{1, 2, 5}, indexes.stream().mapToInt(i -> i).toArray()); + Assertions.assertArrayEquals(new int[]{1, 2, 5}, indexes.stream().mapToInt(i -> i).toArray()); System.out.println("backend1 id is " + backend1.getId()); } @@ -523,7 +523,7 @@ public void testGetUnavailableBeIdsInGroup() { Set unavailableBeIds = Deencapsulation.invoke(balancer, "getUnavailableBeIdsInGroup", infoService, colocateTableIndex, groupId, Tag.DEFAULT_BACKEND_TAG); System.out.println(unavailableBeIds); - Assert.assertArrayEquals(new long[]{1L, 3L, 5L}, unavailableBeIds.stream().mapToLong(i -> i).sorted().toArray()); + Assertions.assertArrayEquals(new long[]{1L, 3L, 5L}, unavailableBeIds.stream().mapToLong(i -> i).sorted().toArray()); } @Test @@ -598,7 +598,7 @@ public void testGetAvailableBeIds() throws AnalysisException { List availableBeIds = Deencapsulation.invoke(balancer, "getAvailableBeIds", Tag.DEFAULT_BACKEND_TAG, Sets.newHashSet(999L), infoService); System.out.println(availableBeIds); - Assert.assertArrayEquals(new long[]{2L, 4L}, availableBeIds.stream().mapToLong(i -> i).sorted().toArray()); + Assertions.assertArrayEquals(new long[]{2L, 4L}, availableBeIds.stream().mapToLong(i -> i).sorted().toArray()); } @Test @@ -617,34 +617,34 @@ public void testGlobalColocateStatistic() { Map backendBucketsMap = globalColocateStatistic.getBackendBucketsMap(); BackendBuckets backendBuckets1 = backendBucketsMap.get(1001L); - Assert.assertNotNull(backendBuckets1); - Assert.assertEquals(Lists.newArrayList(0, 2), + Assertions.assertNotNull(backendBuckets1); + Assertions.assertEquals(Lists.newArrayList(0, 2), backendBuckets1.getGroupTabletOrderIndices().get(groupId1)); - Assert.assertEquals(Lists.newArrayList(0, 3), + Assertions.assertEquals(Lists.newArrayList(0, 3), backendBuckets1.getGroupTabletOrderIndices().get(groupId2)); BackendBuckets backendBuckets2 = backendBucketsMap.get(1002L); - Assert.assertNotNull(backendBuckets2); - Assert.assertEquals(Lists.newArrayList(0, 1), + Assertions.assertNotNull(backendBuckets2); + Assertions.assertEquals(Lists.newArrayList(0, 1), backendBuckets2.getGroupTabletOrderIndices().get(groupId1)); - Assert.assertEquals(Lists.newArrayList(1), + Assertions.assertEquals(Lists.newArrayList(1), backendBuckets2.getGroupTabletOrderIndices().get(groupId2)); BackendBuckets backendBuckets3 = backendBucketsMap.get(1003L); - Assert.assertNotNull(backendBuckets3); - Assert.assertEquals(Lists.newArrayList(1, 2), + Assertions.assertNotNull(backendBuckets3); + Assertions.assertEquals(Lists.newArrayList(1, 2), backendBuckets3.getGroupTabletOrderIndices().get(groupId1)); - Assert.assertEquals(Lists.newArrayList(2), + Assertions.assertEquals(Lists.newArrayList(2), backendBuckets3.getGroupTabletOrderIndices().get(groupId2)); Map> allGroupBucketsMap = globalColocateStatistic.getAllGroupBucketsMap(); - Assert.assertEquals(Lists.newArrayList(new BucketStatistic(0, 5, 100L), new BucketStatistic(1, 5, 200L), + Assertions.assertEquals(Lists.newArrayList(new BucketStatistic(0, 5, 100L), new BucketStatistic(1, 5, 200L), new BucketStatistic(2, 5, 300L)), allGroupBucketsMap.get(groupId1)); - Assert.assertEquals(Lists.newArrayList(new BucketStatistic(0, 7, 100L), new BucketStatistic(1, 7, 200L), + Assertions.assertEquals(Lists.newArrayList(new BucketStatistic(0, 7, 100L), new BucketStatistic(1, 7, 200L), new BucketStatistic(2, 7, 300L), new BucketStatistic(3, 7, 400L)), allGroupBucketsMap.get(groupId2)); Map expectAllTagBucketNum = Maps.newHashMap(); expectAllTagBucketNum.put(Tag.DEFAULT_BACKEND_TAG, 10); - Assert.assertEquals(expectAllTagBucketNum, globalColocateStatistic.getAllTagBucketNum()); + Assertions.assertEquals(expectAllTagBucketNum, globalColocateStatistic.getAllTagBucketNum()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/DiskRebalanceTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/DiskRebalanceTest.java index eda438e8c538f7..820ddedb4d9e3e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/DiskRebalanceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/DiskRebalanceTest.java @@ -50,10 +50,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -79,7 +79,7 @@ public class DiskRebalanceTest { private Map statisticMap; private Map backendsWorkingSlots = Maps.newHashMap(); - @Before + @BeforeEach public void setUp() throws Exception { FeConstants.runningUnitTest = true; Config.used_capacity_percent_max_diff = 1.0; @@ -110,13 +110,13 @@ public void setUp() throws Exception { Mockito.when(mockGtm.isPreviousTransactionsFinished(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyList())).thenReturn(true); // Test mock validation - Assert.assertEquals(111, + Assertions.assertEquals(111, Env.getCurrentGlobalTransactionMgr().getTransactionIDGenerator().getNextTransactionId()); - Assert.assertTrue( + Assertions.assertTrue( Env.getCurrentGlobalTransactionMgr().isPreviousTransactionsFinished(1, 2, Lists.newArrayList(3L))); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -186,7 +186,7 @@ public void testDiskRebalancerWithSameUsageDisk() { rebalancer.updateLoadStatistic(statisticMap); List alternativeTablets = rebalancer.selectAlternativeTablets(); // check alternativeTablets; - Assert.assertTrue(alternativeTablets.isEmpty()); + Assertions.assertTrue(alternativeTablets.isEmpty()); } @Test @@ -234,7 +234,7 @@ public void testDiskRebalancerWithDiffUsageDisk() { } List alternativeTablets = rebalancer.selectAlternativeTablets(); // check alternativeTablets; - Assert.assertEquals(2, alternativeTablets.size()); + Assertions.assertEquals(2, alternativeTablets.size()); for (TabletSchedCtx tabletCtx : alternativeTablets) { LOG.info("try to schedule tablet {}", tabletCtx.getTabletId()); try { @@ -246,9 +246,9 @@ public void testDiskRebalancerWithDiffUsageDisk() { AgentTask task = rebalancer.createBalanceTask(tabletCtx); if (tabletCtx.getTabletSize() == 0) { - Assert.fail("no exception"); + Assertions.fail("no exception"); } else { - Assert.assertTrue(task instanceof StorageMediaMigrationTask); + Assertions.assertTrue(task instanceof StorageMediaMigrationTask); } } catch (SchedException e) { LOG.info("schedule tablet {} failed: {}", tabletCtx.getTabletId(), e.getMessage()); diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/PathSlotTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/PathSlotTest.java index 61e0e27f890023..0dde3f87710fe5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/PathSlotTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/PathSlotTest.java @@ -24,8 +24,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -61,7 +61,7 @@ public void test() throws Exception { gotPathHashs.add(ps.takeAnAvailBalanceSlotFrom(availPathHashs, Tag.create(Tag.TYPE_LOCATION, "zone1"), medium)); } - Assert.assertEquals(expectPathHashs, gotPathHashs); + Assertions.assertEquals(expectPathHashs, gotPathHashs); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/RebalanceTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/RebalanceTest.java index 83cebc48e0f30e..949658c9d98f31 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/RebalanceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/RebalanceTest.java @@ -61,10 +61,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -92,7 +92,7 @@ public class RebalanceTest { private final TabletInvertedIndex invertedIndex = new LocalTabletInvertedIndex(); private Map statisticMap; - @Before + @BeforeEach public void setUp() throws Exception { FeConstants.runningUnitTest = true; db = new Database(1, "test db"); @@ -128,9 +128,9 @@ public void setUp() throws Exception { Mockito.when(mockGtm.isPreviousTransactionsFinished(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyList())).thenReturn(true); // Test mock validation - Assert.assertEquals(111, + Assertions.assertEquals(111, Env.getCurrentGlobalTransactionMgr().getTransactionIDGenerator().getNextTransactionId()); - Assert.assertTrue( + Assertions.assertTrue( Env.getCurrentGlobalTransactionMgr().isPreviousTransactionsFinished(1, 2, Lists.newArrayList(3L))); List beIds = Lists.newArrayList(10001L, 10002L, 10003L, 10004L); @@ -161,7 +161,7 @@ public void setUp() throws Exception { generateStatisticMap(); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -197,7 +197,7 @@ public void testPrioBackends() { backends.add(RebalancerTestUtil.createBackend(10086 + i, 2048, 0)); } rebalancer.addPrioBackends(backends, 1000); - Assert.assertTrue(rebalancer.hasPrioBackends()); + Assertions.assertTrue(rebalancer.hasPrioBackends()); } // CHECKSTYLE IGNORE THIS LINE // remove @@ -205,9 +205,9 @@ public void testPrioBackends() { List backends = Lists.newArrayList(RebalancerTestUtil.createBackend(10086 + i, 2048, 0)); rebalancer.removePrioBackends(backends); if (i == 2) { - Assert.assertFalse(rebalancer.hasPrioBackends()); + Assertions.assertFalse(rebalancer.hasPrioBackends()); } else { - Assert.assertTrue(rebalancer.hasPrioBackends()); + Assertions.assertTrue(rebalancer.hasPrioBackends()); } } } @@ -264,7 +264,7 @@ public void testPartitionRebalancer() { List tasks = batchTask.getAllTasks(); List needCheckTablets = tasks.stream().map(AgentTask::getTabletId).collect(Collectors.toList()); LOG.info("created tasks for tablet: {}", needCheckTablets); - needCheckTablets.forEach(t -> Assert.assertEquals(4, invertedIndex.getReplicasByTabletId(t).size())); + needCheckTablets.forEach(t -> Assertions.assertEquals(4, invertedIndex.getReplicasByTabletId(t).size())); for (Long tabletId : needCheckTablets) { TabletSchedCtx tabletSchedCtx = alternativeTablets.stream() @@ -287,8 +287,8 @@ public void testPartitionRebalancer() { // NeedCheckTablets are redundant, TabletChecker will add them to TabletScheduler tabletChecker.runAfterCatalogReady(); - needCheckTablets.forEach(t -> Assert.assertEquals(4, invertedIndex.getReplicasByTabletId(t).size())); - needCheckTablets.forEach(t -> Assert.assertTrue(tabletScheduler.containsTablet(t))); + needCheckTablets.forEach(t -> Assertions.assertEquals(4, invertedIndex.getReplicasByTabletId(t).size())); + needCheckTablets.forEach(t -> Assertions.assertTrue(tabletScheduler.containsTablet(t))); // TabletScheduler handle redundant tablet tabletScheduler.runAfterCatalogReady(); @@ -296,23 +296,23 @@ public void testPartitionRebalancer() { // One replica is set to DECOMMISSION, still 4 replicas needCheckTablets.forEach(t -> { List replicas = invertedIndex.getReplicasByTabletId(t); - Assert.assertEquals(4, replicas.size()); + Assertions.assertEquals(4, replicas.size()); Replica decommissionedReplica = replicas.stream() .filter(r -> r.getState() == Replica.ReplicaState.DECOMMISSION) .collect(MoreCollectors.onlyElement()); - Assert.assertEquals(111, decommissionedReplica.getPreWatermarkTxnId()); - Assert.assertEquals(112, decommissionedReplica.getPostWatermarkTxnId()); + Assertions.assertEquals(111, decommissionedReplica.getPreWatermarkTxnId()); + Assertions.assertEquals(112, decommissionedReplica.getPostWatermarkTxnId()); }); // Delete replica should change invertedIndex too tabletScheduler.runAfterCatalogReady(); - needCheckTablets.forEach(t -> Assert.assertEquals(3, invertedIndex.getReplicasByTabletId(t).size())); + needCheckTablets.forEach(t -> Assertions.assertEquals(3, invertedIndex.getReplicasByTabletId(t).size())); // Check moves completed rebalancer.selectAlternativeTablets(); rebalancer.updateLoadStatistic(statisticMap); AtomicLong succeeded = Deencapsulation.getField(rebalancer, "counterBalanceMoveSucceeded"); - Assert.assertEquals(needCheckTablets.size(), succeeded.get()); + Assertions.assertEquals(needCheckTablets.size(), succeeded.get()); } // Test for OPENSOURCE-192: PartitionRebalancer should not generate moves @@ -373,25 +373,21 @@ public void testPartitionRebalancerSkipBEWithoutMedium() { // Verify: moves were generated (test is meaningful) Map> moves = rebalancer.getMovesInProgress(); - Assert.assertFalse("Should generate moves for skewed SSD partition", moves.isEmpty()); + Assertions.assertFalse(moves.isEmpty(), "Should generate moves for skewed SSD partition"); // Verify: no move targets BE 20003 (HDD-only) or any of the HDD BEs from setUp (10001-10004) for (Map.Entry> entry : moves.entrySet()) { PartitionRebalancer.TabletMove move = entry.getValue().first; - Assert.assertNotEquals("Move should not target HDD-only BE for SSD tablet", - Long.valueOf(20003L), move.toBe); - Assert.assertFalse("Move should not target any BE without SSD", - move.toBe == 10001L || move.toBe == 10002L - || move.toBe == 10003L || move.toBe == 10004L); + Assertions.assertNotEquals(Long.valueOf(20003L), move.toBe, "Move should not target HDD-only BE for SSD tablet"); + Assertions.assertFalse(move.toBe == 10001L || move.toBe == 10002L + || move.toBe == 10003L || move.toBe == 10004L, "Move should not target any BE without SSD"); } // Verify: all moves go from BE 20001 (most loaded) to BE 20002 (least loaded with SSD) for (Map.Entry> entry : moves.entrySet()) { PartitionRebalancer.TabletMove move = entry.getValue().first; - Assert.assertEquals("Source should be the most loaded SSD BE", - Long.valueOf(20001L), move.fromBe); - Assert.assertEquals("Dest should be the least loaded SSD BE", - Long.valueOf(20002L), move.toBe); + Assertions.assertEquals(Long.valueOf(20001L), move.fromBe, "Source should be the most loaded SSD BE"); + Assertions.assertEquals(Long.valueOf(20002L), move.toBe, "Dest should be the least loaded SSD BE"); } LOG.info("testPartitionRebalancerSkipBEWithoutMedium success"); } @@ -406,17 +402,17 @@ public void testMoveInProgressMap() { m.getCache(Tag.DEFAULT_BACKEND_TAG, TStorageMedium.SSD).get().put(3L, Pair.of(null, -1L)); // Maintenance won't clean up the entries of cache m.maintain(); - Assert.assertEquals(3, m.size()); + Assertions.assertEquals(3, m.size()); // Reset the expireAfterAccess, the whole cache map will be cleared. m.updateMapping(statisticMap, 1); - Assert.assertEquals(0, m.size()); + Assertions.assertEquals(0, m.size()); m.getCache(Tag.DEFAULT_BACKEND_TAG, TStorageMedium.SSD).get().put(3L, Pair.of(null, -1L)); try { Thread.sleep(1000); m.maintain(); - Assert.assertEquals(0, m.size()); + Assertions.assertEquals(0, m.size()); } catch (InterruptedException e) { e.printStackTrace(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/RootPathLoadStatisticTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/RootPathLoadStatisticTest.java index efb22d333aec5e..068270ea95f83c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/RootPathLoadStatisticTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/RootPathLoadStatisticTest.java @@ -21,8 +21,8 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -42,11 +42,11 @@ public void test() { // low usage should be ahead Collections.sort(list); - Assert.assertTrue(list.get(0).getPathHash() == usage1.getPathHash()); + Assertions.assertTrue(list.get(0).getPathHash() == usage1.getPathHash()); usage1.incrCopingSizeB(2048L); Collections.sort(list); - Assert.assertTrue(list.get(1).getPathHash() == usage1.getPathHash()); + Assertions.assertTrue(list.get(1).getPathHash() == usage1.getPathHash()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogRebalancerTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogRebalancerTest.java index e70910b0cee0ee..8077652699c226 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogRebalancerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogRebalancerTest.java @@ -36,10 +36,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -60,7 +60,7 @@ public class RowBinlogRebalancerTest { private boolean previousRunningUnitTest; private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setUp() { previousRunningUnitTest = FeConstants.runningUnitTest; FeConstants.runningUnitTest = true; @@ -100,7 +100,7 @@ public void setUp() { db.registerTable(ordinaryTable); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); FeConstants.runningUnitTest = previousRunningUnitTest; @@ -123,11 +123,11 @@ public void allLocalRebalancersSkipOnlyPairMembers() { TabletMeta ordinaryBaseMeta = new TabletMeta(DB_ID, ORDINARY_TABLE_ID, ORDINARY_PARTITION_ID, ORDINARY_BASE_INDEX_ID, 0, TStorageMedium.HDD, false /* isRowBinlog */); for (Rebalancer rebalancer : rebalancers) { - Assert.assertFalse(rebalancer.getClass().getSimpleName(), rebalancer.canBalanceTablet(baseMeta)); - Assert.assertFalse(rebalancer.getClass().getSimpleName(), rebalancer.canBalanceTablet(rowBinlogMeta)); - Assert.assertFalse(rebalancer.getClass().getSimpleName(), rebalancer.canBalanceTablet(fastFilteredMeta)); - Assert.assertTrue(rebalancer.getClass().getSimpleName(), rebalancer.canBalanceTablet(rollupMeta)); - Assert.assertTrue(rebalancer.getClass().getSimpleName(), rebalancer.canBalanceTablet(ordinaryBaseMeta)); + Assertions.assertFalse(rebalancer.canBalanceTablet(baseMeta), rebalancer.getClass().getSimpleName()); + Assertions.assertFalse(rebalancer.canBalanceTablet(rowBinlogMeta), rebalancer.getClass().getSimpleName()); + Assertions.assertFalse(rebalancer.canBalanceTablet(fastFilteredMeta), rebalancer.getClass().getSimpleName()); + Assertions.assertTrue(rebalancer.canBalanceTablet(rollupMeta), rebalancer.getClass().getSimpleName()); + Assertions.assertTrue(rebalancer.canBalanceTablet(ordinaryBaseMeta), rebalancer.getClass().getSimpleName()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogTabletSchedulerTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogTabletSchedulerTest.java index 2d0b588380b76a..7b2f42e7e2dce8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogTabletSchedulerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/RowBinlogTabletSchedulerTest.java @@ -50,10 +50,10 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -66,7 +66,7 @@ public class RowBinlogTabletSchedulerTest { private LocalTabletInvertedIndex invertedIndex; private TabletScheduler tabletScheduler; - @Before + @BeforeEach public void setUp() { infoService = new SystemInfoService(); mockedEnvStatic = Mockito.mockStatic(Env.class); @@ -82,7 +82,7 @@ public void setUp() { new TabletSchedulerStat(), ""); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -120,13 +120,13 @@ public void rowBinlogRequiredPathUsesExactPathAcrossStorageMedium() { Deencapsulation.invoke(tabletScheduler, "handleColocateMismatch", tabletCtx, batchTask); - Assert.assertEquals(1, batchTask.getTaskNum()); + Assertions.assertEquals(1, batchTask.getTaskNum()); CloneTask cloneTask = (CloneTask) batchTask.getAllTasks().get(0); - Assert.assertEquals(destBackendId, cloneTask.getBackendId()); - Assert.assertEquals(TStorageMedium.HDD, cloneTask.getStorageMedium()); - Assert.assertEquals(requiredPathHash, cloneTask.toThrift().getDestPathHash()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); + Assertions.assertEquals(destBackendId, cloneTask.getBackendId()); + Assertions.assertEquals(TStorageMedium.HDD, cloneTask.getStorageMedium()); + Assertions.assertEquals(requiredPathHash, cloneTask.toThrift().getDestPathHash()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); } @Test @@ -141,10 +141,10 @@ public void rowBinlogRequiredPathDoesNotFallbackToOtherPath() { tabletCtx.setRowBinlogRequiredDestPathHashByBackend(ImmutableMap.of(backendId, 79999L)); tabletCtx.setColocateGroupBackendIds(ImmutableSet.of(backendId)); - SchedException exception = Assert.assertThrows(SchedException.class, () -> Deencapsulation.invoke( + SchedException exception = Assertions.assertThrows(SchedException.class, () -> Deencapsulation.invoke( tabletScheduler, "doChooseAvailableDestPath", tabletCtx, Tag.class, true)); - Assert.assertEquals(Status.UNRECOVERABLE, exception.getStatus()); + Assertions.assertEquals(Status.UNRECOVERABLE, exception.getStatus()); } @Test @@ -172,23 +172,23 @@ public void rowBinlogWrongPathUsesInPlaceStorageMigration() { Deencapsulation.invoke(tabletScheduler, "handleColocateMismatch", tabletCtx, batchTask); - Assert.assertEquals(TabletSchedCtx.State.RUNNING, tabletCtx.getState()); - Assert.assertEquals(TabletSchedCtx.BalanceType.DISK_BALANCE, tabletCtx.getBalanceType()); - Assert.assertEquals(backendId, tabletCtx.getSrcBackendId()); - Assert.assertEquals(sourcePathHash, tabletCtx.getSrcPathHash()); - Assert.assertEquals(backendId, tabletCtx.getDestBackendId()); - Assert.assertEquals(requiredPathHash, tabletCtx.getDestPathHash()); - Assert.assertEquals(TStorageMedium.HDD, tabletCtx.getStorageMedium()); - Assert.assertEquals(1, batchTask.getTaskNum()); + Assertions.assertEquals(TabletSchedCtx.State.RUNNING, tabletCtx.getState()); + Assertions.assertEquals(TabletSchedCtx.BalanceType.DISK_BALANCE, tabletCtx.getBalanceType()); + Assertions.assertEquals(backendId, tabletCtx.getSrcBackendId()); + Assertions.assertEquals(sourcePathHash, tabletCtx.getSrcPathHash()); + Assertions.assertEquals(backendId, tabletCtx.getDestBackendId()); + Assertions.assertEquals(requiredPathHash, tabletCtx.getDestPathHash()); + Assertions.assertEquals(TStorageMedium.HDD, tabletCtx.getStorageMedium()); + Assertions.assertEquals(1, batchTask.getTaskNum()); StorageMediaMigrationTask task = (StorageMediaMigrationTask) batchTask.getAllTasks().get(0); - Assert.assertEquals(backendId, task.getBackendId()); - Assert.assertEquals("/required", task.getDataDir()); - Assert.assertEquals(TStorageMedium.HDD, task.getToStorageMedium()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); + Assertions.assertEquals(backendId, task.getBackendId()); + Assertions.assertEquals("/required", task.getDataDir()); + Assertions.assertEquals(TStorageMedium.HDD, task.getToStorageMedium()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); tabletScheduler.updateDestPathHash(tabletCtx); - Assert.assertEquals(requiredPathHash, replica.getPathHash()); + Assertions.assertEquals(requiredPathHash, replica.getPathHash()); } @Test @@ -223,16 +223,16 @@ public void upgradedMixedMediumPairConvergesAfterBaseMigration() { RowBinlogTabletLocality.RowBinlogHealthResult initialHealth = RowBinlogTabletLocality.getRowBinlogHealth( partition, rowBinlogTablet, new ReplicaAllocation((short) 1), 10L); - Assert.assertEquals(TabletStatus.HEALTHY, initialHealth.getTabletHealth().status); + Assertions.assertEquals(TabletStatus.HEALTHY, initialHealth.getTabletHealth().status); // Simulate the next BE report after the configured-medium migration moves the base replica first. baseReplica.setPathHash(newSsdPathHash); RowBinlogTabletLocality.RowBinlogHealthResult healthResult = RowBinlogTabletLocality.getRowBinlogHealth( partition, rowBinlogTablet, new ReplicaAllocation((short) 1), 10L); - Assert.assertEquals(TabletStatus.COLOCATE_MISMATCH, healthResult.getTabletHealth().status); - Assert.assertEquals(RowBinlogRepairReason.PATH_MISMATCH, healthResult.getRepairReason()); - Assert.assertEquals(ImmutableMap.of(backendId, newSsdPathHash), + Assertions.assertEquals(TabletStatus.COLOCATE_MISMATCH, healthResult.getTabletHealth().status); + Assertions.assertEquals(RowBinlogRepairReason.PATH_MISMATCH, healthResult.getRepairReason()); + Assertions.assertEquals(ImmutableMap.of(backendId, newSsdPathHash), healthResult.getRequiredDestPathHashByBackend()); TabletSchedCtx tabletCtx = createTabletCtx(rowBinlogTablet, rowBinlogIndex.getId(), (short) 1); @@ -242,18 +242,18 @@ public void upgradedMixedMediumPairConvergesAfterBaseMigration() { Deencapsulation.invoke(tabletScheduler, "handleColocateMismatch", tabletCtx, batchTask); - Assert.assertEquals(1, batchTask.getTaskNum()); + Assertions.assertEquals(1, batchTask.getTaskNum()); StorageMediaMigrationTask task = (StorageMediaMigrationTask) batchTask.getAllTasks().get(0); - Assert.assertEquals(backendId, task.getBackendId()); - Assert.assertEquals("/base-ssd", task.getDataDir()); - Assert.assertEquals(TStorageMedium.SSD, task.getToStorageMedium()); + Assertions.assertEquals(backendId, task.getBackendId()); + Assertions.assertEquals("/base-ssd", task.getDataDir()); + Assertions.assertEquals(TStorageMedium.SSD, task.getToStorageMedium()); tabletScheduler.updateDestPathHash(tabletCtx); RowBinlogTabletLocality.RowBinlogHealthResult repairedHealth = RowBinlogTabletLocality.getRowBinlogHealth( partition, rowBinlogTablet, new ReplicaAllocation((short) 1), 10L); - Assert.assertEquals(TabletStatus.HEALTHY, repairedHealth.getTabletHealth().status); - Assert.assertEquals(RowBinlogRepairReason.NONE, repairedHealth.getRepairReason()); + Assertions.assertEquals(TabletStatus.HEALTHY, repairedHealth.getTabletHealth().status); + Assertions.assertEquals(RowBinlogRepairReason.NONE, repairedHealth.getRepairReason()); } @Test @@ -289,14 +289,14 @@ public void rowBinlogMissingBackendIsClonedBeforeWrongPathMigration() { Deencapsulation.invoke(tabletScheduler, "handleColocateMismatch", tabletCtx, batchTask); - Assert.assertEquals(1, batchTask.getTaskNum()); - Assert.assertTrue(batchTask.getAllTasks().get(0) instanceof CloneTask); + Assertions.assertEquals(1, batchTask.getTaskNum()); + Assertions.assertTrue(batchTask.getAllTasks().get(0) instanceof CloneTask); CloneTask cloneTask = (CloneTask) batchTask.getAllTasks().get(0); - Assert.assertEquals(missingBackendId, cloneTask.getBackendId()); - Assert.assertEquals(missingRequiredPathHash, cloneTask.toThrift().getDestPathHash()); - Assert.assertEquals(TStorageMedium.HDD, cloneTask.getStorageMedium()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); + Assertions.assertEquals(missingBackendId, cloneTask.getBackendId()); + Assertions.assertEquals(missingRequiredPathHash, cloneTask.toThrift().getDestPathHash()); + Assertions.assertEquals(TStorageMedium.HDD, cloneTask.getStorageMedium()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); } @Test @@ -305,11 +305,11 @@ public void colocateMismatchUsesOnlyColocateCounter() { TabletSchedCtx tabletCtx = createTabletCtx(new LocalTablet(5L), (short) 1); tabletCtx.setColocateGroupBackendIds(ImmutableSet.of(requiredBackendId)); - Assert.assertThrows(SchedException.class, () -> Deencapsulation.invoke( + Assertions.assertThrows(SchedException.class, () -> Deencapsulation.invoke( tabletScheduler, "handleColocateMismatch", tabletCtx, new AgentBatchTask())); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaRowBinlogMismatch.get()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaColocateMismatch.get()); } @Test @@ -320,12 +320,12 @@ public void colocateRedundantUsesOnlyColocateCounter() { TabletSchedCtx tabletCtx = createTabletCtx(tablet, (short) 1); tabletCtx.setColocateGroupBackendIds(ImmutableSet.of(backendId)); - SchedException exception = Assert.assertThrows(SchedException.class, () -> Deencapsulation.invoke( + SchedException exception = Assertions.assertThrows(SchedException.class, () -> Deencapsulation.invoke( tabletScheduler, "handleColocateRedundant", tabletCtx, new AgentBatchTask())); - Assert.assertEquals(Status.UNRECOVERABLE, exception.getStatus()); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaRowBinlogRedundant.get()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaColocateRedundant.get()); + Assertions.assertEquals(Status.UNRECOVERABLE, exception.getStatus()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaRowBinlogRedundant.get()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaColocateRedundant.get()); } @Test @@ -347,12 +347,12 @@ public void rowBinlogRequiredBackendAllowsTemporarySameHostConflict() { Config.allow_replica_on_same_host = false; FeConstants.runningUnitTest = false; - Assert.assertTrue(tabletCtx.filterDestBE(requiredBackendId)); - Assert.assertFalse(tabletCtx.filterRowBinlogRequiredDestBE(requiredBackendId)); + Assertions.assertTrue(tabletCtx.filterDestBE(requiredBackendId)); + Assertions.assertFalse(tabletCtx.filterRowBinlogRequiredDestBE(requiredBackendId)); tabletCtx.setRowBinlogRequiredDestPathHashByBackend( ImmutableMap.of(requiredBackendId, 70001L, unrelatedBackendId, 70002L)); - Assert.assertTrue(tabletCtx.filterRowBinlogRequiredDestBE(requiredBackendId)); + Assertions.assertTrue(tabletCtx.filterRowBinlogRequiredDestBE(requiredBackendId)); } finally { Config.allow_replica_on_same_host = previousAllowReplicaOnSameHost; FeConstants.runningUnitTest = previousRunningUnitTest; @@ -463,14 +463,14 @@ public void redundantRowBinlogReplicaUsesVisibleVersionAndWaitsWhenMarkingFails( Deencapsulation.invoke(tabletScheduler, "markBaseReplicaBinlogMissingIfNeeded", tabletCtx, rowBinlogReplica); - Assert.assertTrue(baseReplica.isBinlogMissing()); + Assertions.assertTrue(baseReplica.isBinlogMissing()); baseReplica.setBinlogMissing(false); rowBinlogReplica.updateLastFailedVersion(11L); - SchedException exception = Assert.assertThrows(SchedException.class, () -> Deencapsulation.invoke( + SchedException exception = Assertions.assertThrows(SchedException.class, () -> Deencapsulation.invoke( tabletScheduler, "markBaseReplicaBinlogMissingIfNeeded", tabletCtx, rowBinlogReplica)); - Assert.assertEquals(Status.SCHEDULE_FAILED, exception.getStatus()); - Assert.assertFalse(baseReplica.isBinlogMissing()); + Assertions.assertEquals(Status.SCHEDULE_FAILED, exception.getStatus()); + Assertions.assertFalse(baseReplica.isBinlogMissing()); Replica otherRowBinlogReplica = replica(10L, backendId + 1, 10L, 70002L); infoService.addBackend(backend(backendId + 1, "127.0.0.2")); @@ -481,14 +481,14 @@ public void redundantRowBinlogReplicaUsesVisibleVersionAndWaitsWhenMarkingFails( markRowBinlogRepair(tabletCtx, RowBinlogRepairReason.REDUNDANT); AgentBatchTask batchTask = new AgentBatchTask(); - exception = Assert.assertThrows(SchedException.class, () -> Deencapsulation.invoke( + exception = Assertions.assertThrows(SchedException.class, () -> Deencapsulation.invoke( tabletScheduler, "handleColocateRedundant", tabletCtx, batchTask)); - Assert.assertEquals(Status.SCHEDULE_FAILED, exception.getStatus()); - Assert.assertEquals(2, rowBinlogTablet.getReplicas().size()); - Assert.assertEquals(0, batchTask.getTaskNum()); - Assert.assertFalse(baseReplica.isBinlogMissing()); - Assert.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogRedundant.get()); - Assert.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateRedundant.get()); + Assertions.assertEquals(Status.SCHEDULE_FAILED, exception.getStatus()); + Assertions.assertEquals(2, rowBinlogTablet.getReplicas().size()); + Assertions.assertEquals(0, batchTask.getTaskNum()); + Assertions.assertFalse(baseReplica.isBinlogMissing()); + Assertions.assertEquals(1L, tabletScheduler.getStat().counterReplicaRowBinlogRedundant.get()); + Assertions.assertEquals(0L, tabletScheduler.getStat().counterReplicaColocateRedundant.get()); } finally { Config.tablet_binlog_missing_timeout_second = previousTimeout; Config.tablet_binlog_missing_max_times = previousMaxTimes; @@ -565,11 +565,11 @@ private void setTabletStatus(TabletSchedCtx tabletCtx, TabletStatus status) { } private void assertCloneUsesPath(AgentBatchTask batchTask, long backendId, long pathHash) { - Assert.assertEquals(1, batchTask.getTaskNum()); - Assert.assertTrue(batchTask.getAllTasks().get(0) instanceof CloneTask); + Assertions.assertEquals(1, batchTask.getTaskNum()); + Assertions.assertTrue(batchTask.getAllTasks().get(0) instanceof CloneTask); CloneTask cloneTask = (CloneTask) batchTask.getAllTasks().get(0); - Assert.assertEquals(backendId, cloneTask.getBackendId()); - Assert.assertEquals(pathHash, cloneTask.toThrift().getDestPathHash()); + Assertions.assertEquals(backendId, cloneTask.getBackendId()); + Assertions.assertEquals(pathHash, cloneTask.toThrift().getDestPathHash()); } private void markRowBinlogRepair(TabletSchedCtx tabletCtx, RowBinlogRepairReason repairReason) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/TabletSchedCtxTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/TabletSchedCtxTest.java index f10031f91f3400..a40801981ccb8c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/TabletSchedCtxTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/TabletSchedCtxTest.java @@ -37,7 +37,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.MinMaxPriorityQueue; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -104,11 +103,11 @@ public void testAddTablet() { while (!queue.isEmpty()) { gotTablets.add(queue.pollFirst()); } - Assert.assertEquals(Config.max_scheduling_tablets, gotTablets.size()); + Assertions.assertEquals(Config.max_scheduling_tablets, gotTablets.size()); for (int i = 0; i < gotTablets.size(); i++) { TabletSchedCtx tablet = gotTablets.get(i); - Assert.assertEquals(Type.REPAIR, tablet.getType()); - Assert.assertEquals((long) i, tablet.getCreateTime()); + Assertions.assertEquals(Type.REPAIR, tablet.getType()); + Assertions.assertEquals((long) i, tablet.getCreateTime()); } } @@ -137,8 +136,8 @@ public void testPriorityCompare() { pendingTablets.add(ctx3); TabletSchedCtx expectedCtx = pendingTablets.poll(); - Assert.assertNotNull(expectedCtx); - Assert.assertEquals(ctx3.getTabletId(), expectedCtx.getTabletId()); + Assertions.assertNotNull(expectedCtx); + Assertions.assertEquals(ctx3.getTabletId(), expectedCtx.getTabletId()); // priority is not equal, info2 is HIGH, should ranks ahead pendingTablets.clear(); @@ -149,14 +148,14 @@ public void testPriorityCompare() { pendingTablets.add(ctx2); pendingTablets.add(ctx1); expectedCtx = pendingTablets.poll(); - Assert.assertNotNull(expectedCtx); - Assert.assertEquals(ctx2.getTabletId(), expectedCtx.getTabletId()); + Assertions.assertNotNull(expectedCtx); + Assertions.assertEquals(ctx2.getTabletId(), expectedCtx.getTabletId()); // add info2 back to priority queue, and it should ranks ahead still. pendingTablets.add(ctx2); expectedCtx = pendingTablets.poll(); - Assert.assertNotNull(expectedCtx); - Assert.assertEquals(ctx2.getTabletId(), expectedCtx.getTabletId()); + Assertions.assertNotNull(expectedCtx); + Assertions.assertEquals(ctx2.getTabletId(), expectedCtx.getTabletId()); } @Test @@ -202,12 +201,12 @@ public void testVersionCountComparator() { Collections.sort(replicaList, countComparator); // user drop false - Assert.assertEquals(50, replicaList.get(0).getVisibleVersionCount()); - Assert.assertEquals(200, replicaList.get(1).getVisibleVersionCount()); - Assert.assertEquals(-1, replicaList.get(2).getVisibleVersionCount()); + Assertions.assertEquals(50, replicaList.get(0).getVisibleVersionCount()); + Assertions.assertEquals(200, replicaList.get(1).getVisibleVersionCount()); + Assertions.assertEquals(-1, replicaList.get(2).getVisibleVersionCount()); // user drop true - Assert.assertEquals(100, replicaList.get(3).getVisibleVersionCount()); - Assert.assertEquals(-1, replicaList.get(4).getVisibleVersionCount()); + Assertions.assertEquals(100, replicaList.get(3).getVisibleVersionCount()); + Assertions.assertEquals(-1, replicaList.get(4).getVisibleVersionCount()); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/clone/TwoDimensionalGreedyRebalanceAlgoTest.java b/fe/fe-core/src/test/java/org/apache/doris/clone/TwoDimensionalGreedyRebalanceAlgoTest.java index c150e6dc4f3f16..ad94d91610bf4e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/clone/TwoDimensionalGreedyRebalanceAlgoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/clone/TwoDimensionalGreedyRebalanceAlgoTest.java @@ -30,9 +30,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.List; @@ -88,14 +88,14 @@ private ClusterBalanceInfo clusterConfigToClusterBalanceInfo(TestClusterConfig t // First verify that the configuration of the test cluster is valid. Set> partitionIds = Sets.newHashSet(); for (TestClusterConfig.PartitionPerBeReplicas p : tcc.partitionReplicas) { - Assert.assertEquals(tcc.beIds.size(), p.numReplicasByServer.size()); + Assertions.assertEquals(tcc.beIds.size(), p.numReplicasByServer.size()); partitionIds.add(Pair.of(p.partitionId, p.indexId)); } - Assert.assertEquals(partitionIds.size(), tcc.partitionReplicas.size()); + Assertions.assertEquals(partitionIds.size(), tcc.partitionReplicas.size()); // Check for uniqueness of the tablet servers' identifiers. Set beIdSet = new HashSet<>(tcc.beIds); - Assert.assertEquals(tcc.beIds.size(), beIdSet.size()); + Assertions.assertEquals(tcc.beIds.size(), beIdSet.size()); ClusterBalanceInfo balance = new ClusterBalanceInfo(); @@ -118,7 +118,7 @@ private ClusterBalanceInfo clusterConfigToClusterBalanceInfo(TestClusterConfig t Long maxCount = info.beByReplicaCount.keySet().last(); Long minCount = info.beByReplicaCount.keySet().first(); - Assert.assertTrue(maxCount >= minCount); + Assertions.assertTrue(maxCount >= minCount); balance.partitionInfoBySkew.put(maxCount - minCount, info); } return balance; @@ -127,11 +127,11 @@ private ClusterBalanceInfo clusterConfigToClusterBalanceInfo(TestClusterConfig t private void verifyMoves(List configs) { for (TestClusterConfig config : configs) { List moves = algo.getNextMoves(clusterConfigToClusterBalanceInfo(config), 0); - Assert.assertEquals(moves, config.expectedMoves); + Assertions.assertEquals(moves, config.expectedMoves); } } - @Before + @BeforeEach public void setUp() { Configurator.setLevel("org.apache.doris.clone.TwoDimensionalGreedyAlgo", Level.WARN); } @@ -149,22 +149,22 @@ public void testApplyMoveFailed() { try { TwoDimensionalGreedyRebalanceAlgo.applyMove(move, beByTotalReplicaCount, skewMap); } catch (Exception e) { - Assert.assertSame(e.getClass(), IllegalStateException.class); + Assertions.assertSame(e.getClass(), IllegalStateException.class); LOG.info(e.getMessage()); } // beByTotalReplicaCount should be modified - Assert.assertEquals(0, beByTotalReplicaCount.keySet().stream().filter(skew -> skew != 10L).count()); + Assertions.assertEquals(0, beByTotalReplicaCount.keySet().stream().filter(skew -> skew != 10L).count()); // invalid info of partition skewMap.put(6L, new PartitionBalanceInfo(11L, 22L)); try { TwoDimensionalGreedyRebalanceAlgo.applyMove(move, beByTotalReplicaCount, skewMap); } catch (Exception e) { - Assert.assertSame(e.getClass(), IllegalStateException.class); + Assertions.assertSame(e.getClass(), IllegalStateException.class); LOG.warn(e.getMessage()); } // beByTotalReplicaCount should be modified - Assert.assertEquals(0, beByTotalReplicaCount.keySet().stream().filter(skew -> skew != 10L).count()); + Assertions.assertEquals(0, beByTotalReplicaCount.keySet().stream().filter(skew -> skew != 10L).count()); } @Test @@ -173,7 +173,7 @@ public void testInvalidClusterBalanceInfo() { try { algo.getNextMoves(new ClusterBalanceInfo(), 0); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } try { @@ -183,7 +183,7 @@ public void testInvalidClusterBalanceInfo() { } }, 0); } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } try { @@ -194,9 +194,9 @@ public void testInvalidClusterBalanceInfo() { beByTotalReplicaCount.put(1L, 10002L); } }, -1); - Assert.fail("Exception will be thrown in GetNextMoves"); + Assertions.fail("Exception will be thrown in GetNextMoves"); } catch (Exception e) { - Assert.assertSame(e.getClass(), IllegalArgumentException.class); + Assertions.assertSame(e.getClass(), IllegalArgumentException.class); LOG.info(e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/CloudWarmUpJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/CloudWarmUpJobTest.java index 800dd89c6b214c..dce7f8e675d105 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/CloudWarmUpJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/CloudWarmUpJobTest.java @@ -37,10 +37,10 @@ import org.apache.doris.thrift.TWarmUpTabletsRequestType; import org.apache.doris.thrift.TWarmUpTabletsResponse; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -66,7 +66,7 @@ public class CloudWarmUpJobTest { private boolean originalRunningUnitTest; @SuppressWarnings("unchecked") - @Before + @BeforeEach public void setUp() { originalRunningUnitTest = FeConstants.runningUnitTest; FeConstants.runningUnitTest = true; @@ -75,7 +75,7 @@ public void setUp() { ClientPool.backendPool = mockBackendPool; } - @After + @AfterEach public void tearDown() { ClientPool.backendPool = originalBackendPool; FeConstants.runningUnitTest = originalRunningUnitTest; @@ -111,10 +111,10 @@ public void testEventDrivenRefreshesSourceBackends() { warmUpJob.refreshEventDrivenBeToThriftAddress(); } - Assert.assertEquals("src_cluster", requestedCluster.get()); - Assert.assertEquals(2, warmUpJob.getBeToThriftAddress().size()); - Assert.assertEquals("host1:9060", warmUpJob.getBeToThriftAddress().get(1L)); - Assert.assertEquals("host2:9061", warmUpJob.getBeToThriftAddress().get(2L)); + Assertions.assertEquals("src_cluster", requestedCluster.get()); + Assertions.assertEquals(2, warmUpJob.getBeToThriftAddress().size()); + Assertions.assertEquals("host1:9060", warmUpJob.getBeToThriftAddress().get(1L)); + Assertions.assertEquals("host2:9061", warmUpJob.getBeToThriftAddress().get(2L)); } @Test @@ -128,7 +128,7 @@ public void testInitClientsKeepsFailFastForWarmUpRpc() throws Exception { Mockito.when(mockBackendPool.borrowObject(firstAddress)).thenReturn(firstClient); Mockito.when(mockBackendPool.borrowObject(secondAddress)).thenThrow(new RuntimeException("down")); - Assert.assertThrows(RuntimeException.class, job::initClients); + Assertions.assertThrows(RuntimeException.class, job::initClients); Mockito.verify(mockBackendPool).returnObject(firstAddress, firstClient); Mockito.verify(mockBackendPool).invalidateObject(secondAddress, null); } @@ -151,8 +151,8 @@ public void testClearJobSkipsUnavailableBackendAndClearsAvailableBackend() throw ArgumentCaptor captor = ArgumentCaptor.forClass(TWarmUpTabletsRequest.class); Mockito.verify(availableClient).warmUpTablets(captor.capture()); TWarmUpTabletsRequest request = captor.getValue(); - Assert.assertEquals(TWarmUpTabletsRequestType.CLEAR_JOB, request.getType()); - Assert.assertEquals(jobId, request.getJobId()); + Assertions.assertEquals(TWarmUpTabletsRequestType.CLEAR_JOB, request.getType()); + Assertions.assertEquals(jobId, request.getJobId()); Mockito.verify(mockBackendPool).returnObject(availableAddress, availableClient); Mockito.verify(mockBackendPool).invalidateObject(unavailableAddress, null); } @@ -181,8 +181,8 @@ public void testPendingRetryKeepsErrMsgWhenJobStarts() throws Exception { invokeRunPendingJob(job); } - Assert.assertEquals(JobState.RUNNING, job.getJobState()); - Assert.assertEquals("previous failure", job.getJobInfo(null).get(COL_ERR_MSG)); + Assertions.assertEquals(JobState.RUNNING, job.getJobState()); + Assertions.assertEquals("previous failure", job.getJobInfo(null).get(COL_ERR_MSG)); Mockito.verify(editLog).logModifyCloudWarmUpJob(job); } @@ -226,11 +226,11 @@ public void testEventDrivenSuccessfulRetryClearsErrMsg() throws Exception { FeConstants.runningUnitTest = runningUnitTest; } - Assert.assertEquals("", job.getJobInfo(null).get(COL_ERR_MSG)); + Assertions.assertEquals("", job.getJobInfo(null).get(COL_ERR_MSG)); ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(CloudWarmUpJob.class); Mockito.verify(editLog, Mockito.times(1)).logModifyCloudWarmUpJob(jobCaptor.capture()); CloudWarmUpJob replayedJob = copyBySerialization(jobCaptor.getValue()); - Assert.assertEquals("", replayedJob.getJobInfo(null).get(COL_ERR_MSG)); + Assertions.assertEquals("", replayedJob.getJobInfo(null).get(COL_ERR_MSG)); Mockito.verify(client, Mockito.times(2)).warmUpTablets(Mockito.any(TWarmUpTabletsRequest.class)); Mockito.verify(mockBackendPool, Mockito.times(2)).returnObject(address, client); } @@ -270,7 +270,7 @@ public void testEventDrivenFailedRetryKeepsErrMsg() throws Exception { FeConstants.runningUnitTest = runningUnitTest; } - Assert.assertEquals("previous failure", job.getJobInfo(null).get(COL_ERR_MSG)); + Assertions.assertEquals("previous failure", job.getJobInfo(null).get(COL_ERR_MSG)); Mockito.verify(client).warmUpTablets(Mockito.any(TWarmUpTabletsRequest.class)); Mockito.verify(mockBackendPool).returnObject(address, client); } @@ -318,8 +318,8 @@ public void testRunningRetryClearsErrMsgWhenJobFinishes() throws Exception { FeConstants.runningUnitTest = runningUnitTest; } - Assert.assertEquals(JobState.PENDING, job.getJobState()); - Assert.assertEquals("", job.getJobInfo(null).get(COL_ERR_MSG)); + Assertions.assertEquals(JobState.PENDING, job.getJobState()); + Assertions.assertEquals("", job.getJobInfo(null).get(COL_ERR_MSG)); Mockito.verify(cacheHotspotManager).notifyJobStop(job); Mockito.verify(editLog, Mockito.atLeastOnce()).logModifyCloudWarmUpJob(job); Mockito.verify(mockBackendPool).returnObject(address, client); diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/alter/CloudSchemaChangeHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/alter/CloudSchemaChangeHandlerTest.java index 4bb56910022f75..885e39052fb3a5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/alter/CloudSchemaChangeHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/alter/CloudSchemaChangeHandlerTest.java @@ -41,10 +41,10 @@ import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -61,7 +61,7 @@ public class CloudSchemaChangeHandlerTest { private String originalMetaServiceEndpoint; private boolean originalEnableDebugPoints; - @Before + @BeforeEach public void setUp() { originalCloudTxnTabletBatchSize = Config.cloud_txn_tablet_batch_size; originalCloudUniqueId = Config.cloud_unique_id; @@ -74,7 +74,7 @@ public void setUp() { DebugPointUtil.clearDebugPoints(); } - @After + @AfterEach public void tearDown() { Config.cloud_txn_tablet_batch_size = originalCloudTxnTabletBatchSize; Config.cloud_unique_id = originalCloudUniqueId; @@ -130,10 +130,10 @@ public void testUpdateTablePropertiesNotifiesAllAliveBackendsInBatches() throws ArgumentCaptor.forClass(Cloud.UpdateTabletRequest.class); Mockito.verify(metaServiceProxy, Mockito.times(2)).updateTablet(updateCaptor.capture()); List updateRequests = updateCaptor.getAllValues(); - Assert.assertEquals(Arrays.asList(101L, 102L), + Assertions.assertEquals(Arrays.asList(101L, 102L), updateRequests.get(0).getTabletMetaInfosList().stream() .map(Cloud.TabletMetaInfoPB::getTabletId).collect(Collectors.toList())); - Assert.assertEquals(Arrays.asList(103L), + Assertions.assertEquals(Arrays.asList(103L), updateRequests.get(1).getTabletMetaInfosList().stream() .map(Cloud.TabletMetaInfoPB::getTabletId).collect(Collectors.toList())); @@ -144,15 +144,15 @@ public void testUpdateTablePropertiesNotifiesAllAliveBackendsInBatches() throws .syncTabletMeta(addressCaptor.capture(), syncCaptor.capture()); List addresses = addressCaptor.getAllValues(); - Assert.assertFalse(addresses.stream().anyMatch(addr -> "be-dead".equals(addr.getHostname()))); - Assert.assertEquals(2L, addresses.stream().filter(addr -> "be-1".equals(addr.getHostname())).count()); - Assert.assertEquals(2L, addresses.stream().filter(addr -> "be-2".equals(addr.getHostname())).count()); + Assertions.assertFalse(addresses.stream().anyMatch(addr -> "be-dead".equals(addr.getHostname()))); + Assertions.assertEquals(2L, addresses.stream().filter(addr -> "be-1".equals(addr.getHostname())).count()); + Assertions.assertEquals(2L, addresses.stream().filter(addr -> "be-2".equals(addr.getHostname())).count()); List syncRequests = syncCaptor.getAllValues(); - Assert.assertEquals(Arrays.asList(101L, 102L), syncRequests.get(0).getTabletIdsList()); - Assert.assertEquals(Arrays.asList(101L, 102L), syncRequests.get(1).getTabletIdsList()); - Assert.assertEquals(Arrays.asList(103L), syncRequests.get(2).getTabletIdsList()); - Assert.assertEquals(Arrays.asList(103L), syncRequests.get(3).getTabletIdsList()); + Assertions.assertEquals(Arrays.asList(101L, 102L), syncRequests.get(0).getTabletIdsList()); + Assertions.assertEquals(Arrays.asList(101L, 102L), syncRequests.get(1).getTabletIdsList()); + Assertions.assertEquals(Arrays.asList(103L), syncRequests.get(2).getTabletIdsList()); + Assertions.assertEquals(Arrays.asList(103L), syncRequests.get(3).getTabletIdsList()); } @Test @@ -169,9 +169,9 @@ public void testUpdateTablePropertiesThrowsWhenUpdateTabletFails() throws Except Map properties = new HashMap<>(); properties.put("compaction_policy", "time_series"); - UserException exception = Assert.assertThrows(UserException.class, + UserException exception = Assertions.assertThrows(UserException.class, () -> handler.updateTableProperties(db, "tbl", properties)); - Assert.assertTrue(exception.getMessage().contains("update failed")); + Assertions.assertTrue(exception.getMessage().contains("update failed")); } } @@ -193,9 +193,9 @@ public void testUpdateTablePropertiesThrowsWhenUpdateTabletResponseNotOk() throw Map properties = new HashMap<>(); properties.put("compaction_policy", "time_series"); - UserException exception = Assert.assertThrows(UserException.class, + UserException exception = Assertions.assertThrows(UserException.class, () -> handler.updateTableProperties(db, "tbl", properties)); - Assert.assertTrue(exception.getMessage().contains("meta service rejected")); + Assertions.assertTrue(exception.getMessage().contains("meta service rejected")); } } @@ -299,7 +299,7 @@ public void testNotifyBackendsToSyncTabletMetaSkipsUnavailableBackends() throws ArgumentCaptor.forClass(InternalService.PSyncTabletMetaRequest.class); Mockito.verify(backendServiceProxy, Mockito.times(1)) .syncTabletMeta(Mockito.argThat(addr -> "be-1".equals(addr.getHostname())), syncCaptor.capture()); - Assert.assertEquals(Arrays.asList(101L, 102L), syncCaptor.getValue().getTabletIdsList()); + Assertions.assertEquals(Arrays.asList(101L, 102L), syncCaptor.getValue().getTabletIdsList()); } @Test @@ -493,7 +493,7 @@ public void testUpdatePartitionInvertedIndexStorageFormatReturnsWhenFormatUnchan Mockito.verify(env, Mockito.never()).modifyTableProperties(database, table, properties); Mockito.verify(table).readLock(); Mockito.verify(table).readUnlock(); - Assert.assertEquals("v3", properties.get( + Assertions.assertEquals("v3", properties.get( PropertyAnalyzer.PROPERTIES_PARTITION_INVERTED_INDEX_STORAGE_FORMAT)); } finally { Config.enable_partition_inverted_index_storage_format_rollout = previousRollout; @@ -521,7 +521,7 @@ public void testUpdatePartitionInvertedIndexStorageFormatIsIgnoredWhenRolloutDis Mockito.verify(env, Mockito.never()).modifyTableProperties(database, table, properties); Mockito.verify(table, Mockito.never()).getPartitionInvertedIndexFileStorageFormat(); - Assert.assertEquals("SNII", properties.get( + Assertions.assertEquals("SNII", properties.get( PropertyAnalyzer.PROPERTIES_PARTITION_INVERTED_INDEX_STORAGE_FORMAT)); } finally { Config.enable_partition_inverted_index_storage_format_rollout = previousRollout; diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/backup/CloudRestoreJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/backup/CloudRestoreJobTest.java index d384a8c1bfaff3..3956302e4fb2bd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/backup/CloudRestoreJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/backup/CloudRestoreJobTest.java @@ -51,10 +51,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -90,7 +90,7 @@ public class CloudRestoreJobTest { private MockedStatic mockedMetaServiceProxy; private MetaServiceProxy mockMetaServiceProxyInstance; - @Before + @BeforeEach public void setUp() throws Exception { Config.cloud_unique_id = "test_unique_id"; Config.meta_service_endpoint = "127.0.0.1:11111"; @@ -108,8 +108,8 @@ public void setUp() throws Exception { ctx.setThreadLocalInfo(); ctx.setCloudCluster("test_compute_group"); - Assert.assertTrue(cloudEnv instanceof CloudEnv); - Assert.assertTrue(cloudSystemInfoService instanceof CloudSystemInfoService); + Assertions.assertTrue(cloudEnv instanceof CloudEnv); + Assertions.assertTrue(cloudSystemInfoService instanceof CloudSystemInfoService); Mockito.when(storageVaultMgr.getVaultNameById(Mockito.anyString())).thenReturn("test_vault"); @@ -198,7 +198,7 @@ false, new ReplicaAllocation((short) 1), 100000, -1, false, false, false, cloudEnv, repo.getId(), "test_vault"); } - @After + @AfterEach public void tearDown() { if (fakeEditLog != null) { fakeEditLog.close(); @@ -218,7 +218,7 @@ public void tearDown() { public void testStorageVaultCheck() throws UserException { // Case 1: Storage vault exists job.checkStorageVault(expectedRestoreTbl); - Assert.assertTrue(job.getStatus().ok()); + Assertions.assertTrue(job.getStatus().ok()); // Case 2: Storage vault does not exist Map properties = Maps.newHashMap(); @@ -226,7 +226,7 @@ public void testStorageVaultCheck() throws UserException { TableProperty tableProperty = new TableProperty(properties); expectedRestoreTbl.setTableProperty(tableProperty); job.checkStorageVault(expectedRestoreTbl); - Assert.assertFalse(job.getStatus().ok()); + Assertions.assertFalse(job.getStatus().ok()); } @Test @@ -238,12 +238,12 @@ public void testCloudClusterCheck() throws UserException { // Case 1: Cloud cluster exists Mockito.doReturn("test_cluster_id").when(spySysInfo).getCloudClusterIdByName(Mockito.anyString()); job.checkIfNeedCancel(); - Assert.assertTrue(job.getStatus().ok()); + Assertions.assertTrue(job.getStatus().ok()); // Case 2: Cloud cluster not exists Mockito.doReturn(null).when(spySysInfo).getCloudClusterIdByName(Mockito.anyString()); job.checkIfNeedCancel(); - Assert.assertFalse(job.getStatus().ok()); + Assertions.assertFalse(job.getStatus().ok()); } @Test @@ -251,9 +251,9 @@ public void testCreateReplicas() throws UserException { for (Partition expectedRestorePart : expectedRestoreTbl.getPartitions()) { job.createReplicas(db, expectedRestoreTbl, expectedRestorePart, null); } - Assert.assertTrue(job.getStatus().ok()); + Assertions.assertTrue(job.getStatus().ok()); job.doCreateReplicas(); - Assert.assertTrue(job.getStatus().ok()); + Assertions.assertTrue(job.getStatus().ok()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/cache/CacheHotspotManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/cache/CacheHotspotManagerTest.java index e921f5d079f527..7c866a4187a1bb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/cache/CacheHotspotManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/cache/CacheHotspotManagerTest.java @@ -42,10 +42,10 @@ import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Property; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -73,7 +73,7 @@ public class CacheHotspotManagerTest { private EditLog editLog; private MockedStatic envMockedStatic; - @Before + @BeforeEach public void setUp() { originalRunningUnitTest = FeConstants.runningUnitTest; FeConstants.runningUnitTest = true; @@ -88,7 +88,7 @@ public void setUp() { cacheHotspotManager = new CacheHotspotManager(cloudSystemInfoService); } - @After + @AfterEach public void tearDown() { envMockedStatic.close(); FeConstants.runningUnitTest = originalRunningUnitTest; @@ -143,12 +143,12 @@ public void testWarmUpNewClusterByTable() { Map> result = cacheHotspotManager.warmUpNewClusterByTable( jobId, dstClusterName, tables, true); - Assert.assertEquals(1, result.size()); - Assert.assertEquals(1001L, result.get(11L).get(0).getId()); + Assertions.assertEquals(1, result.size()); + Assertions.assertEquals(1001L, result.get(11L).get(0).getId()); - RuntimeException exception = Assert.assertThrows(RuntimeException.class, () -> + RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> cacheHotspotManager.warmUpNewClusterByTable(jobId, dstClusterName, tables, false)); - Assert.assertEquals("The cluster " + dstClusterName + " cache size is not enough", exception.getMessage()); + Assertions.assertEquals("The cluster " + dstClusterName + " cache size is not enough", exception.getMessage()); } @Test @@ -156,14 +156,14 @@ public void testCreateTableOnceJobRejectsPendingDuplicateOrderDifference() throw long firstJobId = cacheHotspotManager.createJob(newTableStmt("dst", false, Triple.of("db1", "tbl1", ""), Triple.of("db2", "tbl2", "p1"))); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, () -> + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> cacheHotspotManager.createJob(newTableStmt("dst", false, Triple.of("db2", "tbl2", "p1"), Triple.of("db1", "tbl1", "")))); - Assert.assertTrue(exception.getMessage().contains("already has a pending job")); - Assert.assertTrue(exception.getMessage().contains("job id: " + firstJobId)); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertTrue(exception.getMessage().contains("already has a pending job")); + Assertions.assertTrue(exception.getMessage().contains("job id: " + firstJobId)); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); Mockito.verify(env, Mockito.times(1)).getNextId(); Mockito.verify(editLog, Mockito.times(1)).logModifyCloudWarmUpJob(Mockito.any(CloudWarmUpJob.class)); } @@ -173,12 +173,12 @@ public void testCreateTableOnceJobRejectsPendingDuplicateTableEntries() throws A long firstJobId = cacheHotspotManager.createJob(newTableStmt("dst", false, Triple.of("db1", "tbl1", ""), Triple.of("db1", "tbl1", ""))); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, () -> + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> cacheHotspotManager.createJob(newTableStmt("dst", false, Triple.of("db1", "tbl1", "")))); - Assert.assertTrue(exception.getMessage().contains("already has a pending job")); - Assert.assertTrue(exception.getMessage().contains("job id: " + firstJobId)); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertTrue(exception.getMessage().contains("already has a pending job")); + Assertions.assertTrue(exception.getMessage().contains("job id: " + firstJobId)); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -188,8 +188,8 @@ public void testCreateTableOnceJobDoesNotDedupDifferentForce() throws AnalysisEx long forceTrueJobId = cacheHotspotManager.createJob(newTableStmt("dst", true, Triple.of("db1", "tbl1", ""))); - Assert.assertNotEquals(forceFalseJobId, forceTrueJobId); - Assert.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertNotEquals(forceFalseJobId, forceTrueJobId); + Assertions.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -197,8 +197,8 @@ public void testCreateClusterOnceJobDedupesPendingJob() throws AnalysisException long firstJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); long reusedJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); - Assert.assertEquals(firstJobId, reusedJobId); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(firstJobId, reusedJobId); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -206,8 +206,8 @@ public void testCreateClusterOnceJobDedupesRegardlessOfForceFlag() throws Analys long firstJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); long reusedJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", true)); - Assert.assertEquals(firstJobId, reusedJobId); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(firstJobId, reusedJobId); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -217,9 +217,9 @@ public void testCreateClusterOnceJobAllowsNewPendingWhenOnlyRunningExists() thro long newJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); - Assert.assertNotEquals(runningJob.getJobId(), newJobId); - Assert.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); - Assert.assertEquals(JobState.PENDING, cacheHotspotManager.getCloudWarmUpJob(newJobId).getJobState()); + Assertions.assertNotEquals(runningJob.getJobId(), newJobId); + Assertions.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(JobState.PENDING, cacheHotspotManager.getCloudWarmUpJob(newJobId).getJobState()); } @Test @@ -231,8 +231,8 @@ public void testCreateClusterOnceJobReusesPendingWhenRunningAndPendingExist() th long reusedJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); - Assert.assertEquals(pendingJob.getJobId(), reusedJobId); - Assert.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(pendingJob.getJobId(), reusedJobId); + Assertions.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -242,9 +242,9 @@ public void testCreateOnceJobIgnoresFinishedHistory() throws AnalysisException { long newJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); - Assert.assertNotEquals(finishedJob.getJobId(), newJobId); - Assert.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); - Assert.assertEquals(JobState.PENDING, cacheHotspotManager.getCloudWarmUpJob(newJobId).getJobState()); + Assertions.assertNotEquals(finishedJob.getJobId(), newJobId); + Assertions.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(JobState.PENDING, cacheHotspotManager.getCloudWarmUpJob(newJobId).getJobState()); } @Test @@ -256,8 +256,8 @@ public void testCreateClusterOnceJobReusesOldestHistoricalPendingDuplicateAfterR long reusedJobId = cacheHotspotManager.createJob(newClusterStmt("dst", "src", false)); - Assert.assertEquals(olderPendingJob.getJobId(), reusedJobId); - Assert.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(olderPendingJob.getJobId(), reusedJobId); + Assertions.assertEquals(2, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -273,12 +273,12 @@ public Map> warmUpNewClusterByTable(long jobId, String dstClu }; try { - RuntimeException exception = Assert.assertThrows(RuntimeException.class, () -> + RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> cacheHotspotManager.createJob(newTableStmt("dst", false, Triple.of("db1", "tbl1", "")))); - Assert.assertEquals("mock create failure", exception.getMessage()); - Assert.assertEquals(0, getOncePendingCreateLockCount()); - Assert.assertEquals(0, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals("mock create failure", exception.getMessage()); + Assertions.assertEquals(0, getOncePendingCreateLockCount()); + Assertions.assertEquals(0, cacheHotspotManager.getCloudWarmUpJobs().size()); } finally { FeConstants.runningUnitTest = previousRunningUnitTest; } @@ -292,7 +292,7 @@ public void testConcurrentCreateClusterOnceJobReleasesRefCountedLockAfterWaiterC Mockito.when(env.getNextId()).thenAnswer(invocation -> { if (getNextIdCalls.incrementAndGet() == 1) { firstCreateEntered.countDown(); - Assert.assertTrue(allowFirstCreateToContinue.await(5, TimeUnit.SECONDS)); + Assertions.assertTrue(allowFirstCreateToContinue.await(5, TimeUnit.SECONDS)); } return nextJobId.getAndIncrement(); }); @@ -301,7 +301,7 @@ public void testConcurrentCreateClusterOnceJobReleasesRefCountedLockAfterWaiterC try { Future firstCreate = executor.submit(() -> createJobWithThreadLocalEnv( newClusterStmt("dst", "src", false))); - Assert.assertTrue(firstCreateEntered.await(5, TimeUnit.SECONDS)); + Assertions.assertTrue(firstCreateEntered.await(5, TimeUnit.SECONDS)); Future secondCreate = executor.submit(() -> createJobWithThreadLocalEnv( newClusterStmt("dst", "src", false))); @@ -311,10 +311,10 @@ public void testConcurrentCreateClusterOnceJobReleasesRefCountedLockAfterWaiterC long firstJobId = firstCreate.get(5, TimeUnit.SECONDS); long secondJobId = secondCreate.get(5, TimeUnit.SECONDS); - Assert.assertEquals(firstJobId, secondJobId); - Assert.assertEquals(1, getNextIdCalls.get()); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); - Assert.assertEquals(0, getOncePendingCreateLockCount()); + Assertions.assertEquals(firstJobId, secondJobId); + Assertions.assertEquals(1, getNextIdCalls.get()); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(0, getOncePendingCreateLockCount()); } finally { allowFirstCreateToContinue.countDown(); executor.shutdownNow(); @@ -325,24 +325,24 @@ public void testConcurrentCreateClusterOnceJobReleasesRefCountedLockAfterWaiterC public void testCreatePeriodicJobUnaffected() throws AnalysisException { WarmUpClusterCommand periodicStmt = newClusterStmt("dst", "src", false, periodicProperties(60)); long firstJobId = cacheHotspotManager.createJob(periodicStmt); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, () -> + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> cacheHotspotManager.createJob(newClusterStmt("dst", "src", false, periodicProperties(60)))); - Assert.assertEquals(1000L, firstJobId); - Assert.assertTrue(exception.getMessage().contains("already has a runnable job")); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(1000L, firstJobId); + Assertions.assertTrue(exception.getMessage().contains("already has a runnable job")); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test public void testCreateEventDrivenJobUnaffected() throws AnalysisException { WarmUpClusterCommand eventDrivenStmt = newClusterStmt("dst", "src", false, eventDrivenProperties("load")); long firstJobId = cacheHotspotManager.createJob(eventDrivenStmt); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, () -> + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> cacheHotspotManager.createJob(newClusterStmt("dst", "src", false, eventDrivenProperties("load")))); - Assert.assertEquals(1000L, firstJobId); - Assert.assertTrue(exception.getMessage().contains("already has a runnable job")); - Assert.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); + Assertions.assertEquals(1000L, firstJobId); + Assertions.assertTrue(exception.getMessage().contains("already has a runnable job")); + Assertions.assertEquals(1, cacheHotspotManager.getCloudWarmUpJobs().size()); } @Test @@ -355,18 +355,18 @@ public void testTryRegisterRunningJobLogsBlockedResult() { appender.start(); logger.addAppender(appender); try { - Assert.assertTrue(cacheHotspotManager.tryRegisterRunningJob(runningJob)); - Assert.assertFalse(cacheHotspotManager.tryRegisterRunningJob(blockedJob)); + Assertions.assertTrue(cacheHotspotManager.tryRegisterRunningJob(runningJob)); + Assertions.assertFalse(cacheHotspotManager.tryRegisterRunningJob(blockedJob)); } finally { logger.removeAppender(appender); appender.stop(); } String logs = appender.messagesAsString(); - Assert.assertTrue(logs, logs.contains("warmup-lock register")); - Assert.assertTrue(logs, logs.contains("jobId=11")); - Assert.assertTrue(logs, logs.contains("existingJobId=10")); - Assert.assertTrue(logs, logs.contains("registerResult=blocked")); + Assertions.assertTrue(logs.contains("warmup-lock register"), logs); + Assertions.assertTrue(logs.contains("jobId=11"), logs); + Assertions.assertTrue(logs.contains("existingJobId=10"), logs); + Assertions.assertTrue(logs.contains("registerResult=blocked"), logs); } private WarmUpClusterCommand newTableStmt(String dstClusterName, boolean force, @@ -434,7 +434,7 @@ private long createJobWithThreadLocalEnv(WarmUpClusterCommand command) throws An private int getOnlyOncePendingCreateLockRefCount() throws Exception { Map locks = getOncePendingCreateLocks(); - Assert.assertEquals(1, locks.size()); + Assertions.assertEquals(1, locks.size()); Object lockEntry = locks.values().iterator().next(); Field refCountField = lockEntry.getClass().getDeclaredField("refCount"); refCountField.setAccessible(true); @@ -456,7 +456,7 @@ && getOnlyOncePendingCreateLockRefCount() == expectedRefCount) { } Thread.sleep(10L); } - Assert.fail("Timed out waiting for once pending create lock ref count " + expectedRefCount); + Assertions.fail("Timed out waiting for once pending create lock ref count " + expectedRefCount); } private static class RecordingAppender extends AbstractAppender { diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudEnvFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudEnvFactoryTest.java index c7af444c99ccb8..d7267679ebab42 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudEnvFactoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudEnvFactoryTest.java @@ -30,8 +30,8 @@ import org.apache.doris.thrift.TUniqueId; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; @@ -42,20 +42,20 @@ public class CloudEnvFactoryTest { public void testCreate() throws Exception { Config.cloud_unique_id = "test_cloud"; EnvFactory envFactory = EnvFactory.getInstance(); - Assert.assertTrue(envFactory instanceof CloudEnvFactory); - Assert.assertTrue(Env.getCurrentEnv() instanceof CloudEnv); - Assert.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(envFactory.createEnv(false) instanceof CloudEnv); - Assert.assertTrue(envFactory.createInternalCatalog() instanceof CloudInternalCatalog); - Assert.assertTrue(envFactory.createPartition() instanceof CloudPartition); - Assert.assertTrue(envFactory.createTablet() instanceof CloudTablet); - Assert.assertTrue(envFactory.createReplica() instanceof CloudReplica); + Assertions.assertTrue(envFactory instanceof CloudEnvFactory); + Assertions.assertTrue(Env.getCurrentEnv() instanceof CloudEnv); + Assertions.assertTrue(Env.getCurrentInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(envFactory.createEnv(false) instanceof CloudEnv); + Assertions.assertTrue(envFactory.createInternalCatalog() instanceof CloudInternalCatalog); + Assertions.assertTrue(envFactory.createPartition() instanceof CloudPartition); + Assertions.assertTrue(envFactory.createTablet() instanceof CloudTablet); + Assertions.assertTrue(envFactory.createReplica() instanceof CloudReplica); Map properties = Maps.newHashMap(); properties.put(PropertyAnalyzer.PROPERTIES_REPLICATION_NUM, "100"); PropertyAnalyzer.getInstance().rewriteOlapProperties( "catalog_not_exist", "db_not_exist", properties); - Assert.assertEquals("1", properties.get(PropertyAnalyzer.PROPERTIES_REPLICATION_NUM)); + Assertions.assertEquals("1", properties.get(PropertyAnalyzer.PROPERTIES_REPLICATION_NUM)); } @Test @@ -70,13 +70,13 @@ public void testLegacyLoadCoordinatorSetsFunctionVersionOptions() { 1L, new TUniqueId(1L, 1L), new DescriptorTable(), Collections.emptyList(), Collections.emptyList(), "UTC", false, false); - Assert.assertTrue(coordinator instanceof CloudCoordinator); - Assert.assertTrue(coordinator.getQueryOptions().isSetNewVersionUnixTimestamp()); - Assert.assertTrue(coordinator.getQueryOptions().isNewVersionUnixTimestamp()); - Assert.assertTrue(coordinator.getQueryOptions().isSetNewVersionPercentile()); - Assert.assertTrue(coordinator.getQueryOptions().isNewVersionPercentile()); - Assert.assertTrue(coordinator.getQueryOptions().isSetNewVersionBitmapOpCount()); - Assert.assertTrue(coordinator.getQueryOptions().isNewVersionBitmapOpCount()); + Assertions.assertTrue(coordinator instanceof CloudCoordinator); + Assertions.assertTrue(coordinator.getQueryOptions().isSetNewVersionUnixTimestamp()); + Assertions.assertTrue(coordinator.getQueryOptions().isNewVersionUnixTimestamp()); + Assertions.assertTrue(coordinator.getQueryOptions().isSetNewVersionPercentile()); + Assertions.assertTrue(coordinator.getQueryOptions().isNewVersionPercentile()); + Assertions.assertTrue(coordinator.getQueryOptions().isSetNewVersionBitmapOpCount()); + Assertions.assertTrue(coordinator.getQueryOptions().isNewVersionBitmapOpCount()); } finally { ConnectContext.remove(); FeConstants.runningUnitTest = runningUnitTest; diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudPartitionTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudPartitionTest.java index 0f1beb5f612f34..8ba448a46cd882 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudPartitionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudPartitionTest.java @@ -23,9 +23,9 @@ import org.apache.doris.qe.SessionVariable; import org.apache.doris.rpc.RpcException; -import org.junit.Ignore; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -35,7 +35,7 @@ public class CloudPartitionTest { - @Ignore + @Disabled public void getCachedVisibleVersion() { } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudUpgradeMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudUpgradeMgrTest.java index 938bc54f9cbb1f..6db568e0d57103 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudUpgradeMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/catalog/CloudUpgradeMgrTest.java @@ -25,10 +25,10 @@ import org.apache.doris.transaction.TransactionState; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -42,12 +42,12 @@ public class CloudUpgradeMgrTest { private boolean oldEnableAbortConflictTxn; - @Before + @BeforeEach public void setUp() { oldEnableAbortConflictTxn = Config.enable_abort_txn_by_checking_conflict_txn; } - @After + @AfterEach public void tearDown() { Config.enable_abort_txn_by_checking_conflict_txn = oldEnableAbortConflictTxn; } @@ -75,9 +75,9 @@ public void testLogAndAbortFailedConflictTxnsWhenEnabled() throws Exception { long endTransactionId = invocation.getArgument(0); long actualDbId = invocation.getArgument(1); List actualTableIdList = invocation.getArgument(2); - Assert.assertEquals(waterTxnId, endTransactionId); - Assert.assertEquals(dbId, actualDbId); - Assert.assertEquals(tableIdList, actualTableIdList); + Assertions.assertEquals(waterTxnId, endTransactionId); + Assertions.assertEquals(dbId, actualDbId); + Assertions.assertEquals(tableIdList, actualTableIdList); return conflictTxns; }).when(txnMgr).getUnFinishedPreviousLoad(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyList()); @@ -85,8 +85,8 @@ public void testLogAndAbortFailedConflictTxnsWhenEnabled() throws Exception { Long actualDbId = invocation.getArgument(0); Long txnId = invocation.getArgument(1); String reason = invocation.getArgument(2); - Assert.assertEquals(dbId, actualDbId.longValue()); - Assert.assertEquals("Cancel by cloud upgrade", reason); + Assertions.assertEquals(dbId, actualDbId.longValue()); + Assertions.assertEquals("Cancel by cloud upgrade", reason); abortedTxnIds.add(txnId); return null; }).when(txnMgr).abortTransaction(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString()); @@ -97,7 +97,7 @@ public void testLogAndAbortFailedConflictTxnsWhenEnabled() throws Exception { mockedGlobalTxnMgr.when(() -> GlobalTransactionMgr.checkFailedTxns(Mockito.anyList())) .thenAnswer(invocation -> { List txns = invocation.getArgument(0); - Assert.assertEquals(conflictTxns, txns); + Assertions.assertEquals(conflictTxns, txns); return failedTxns; }); @@ -105,7 +105,7 @@ public void testLogAndAbortFailedConflictTxnsWhenEnabled() throws Exception { tableIdList); } - Assert.assertEquals(Lists.newArrayList(101L, 103L), abortedTxnIds); + Assertions.assertEquals(Lists.newArrayList(101L, 103L), abortedTxnIds); } @Test @@ -146,8 +146,8 @@ public void testLogAndAbortFailedConflictTxnsWhenDisabled() throws Exception { tableIdList); } - Assert.assertEquals(0, checkFailedCallCount.get()); - Assert.assertEquals(0, abortCallCount.get()); + Assertions.assertEquals(0, checkFailedCallCount.get()); + Assertions.assertEquals(0, abortCallCount.get()); } @Test @@ -188,7 +188,7 @@ public void testLogAndAbortFailedConflictTxnsContinueWhenAbortFailed() throws Ex tableIdList); } - Assert.assertEquals(2, abortAttemptCount.get()); + Assertions.assertEquals(2, abortAttemptCount.get()); } private static TransactionState newTxn(long dbId, long txnId, String label) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/common/util/CopyUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/common/util/CopyUtilTest.java index 061a35d3b51f16..ed390a1991a636 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/common/util/CopyUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/common/util/CopyUtilTest.java @@ -22,8 +22,8 @@ import org.apache.doris.persist.gson.GsonUtils; import com.google.gson.annotations.SerializedName; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataOutput; import java.io.IOException; @@ -130,44 +130,44 @@ public void testCopyToChildNormal() { Parent parent = new Parent("Alice", 30); Child child = CopyUtil.copyToChild(parent, Child.class); - Assert.assertNotNull(child); - Assert.assertEquals("Alice", child.name); - Assert.assertEquals(30, child.age); - Assert.assertEquals(10000.50, child.salary, 0.001); - Assert.assertTrue(child.isActive); + Assertions.assertNotNull(child); + Assertions.assertEquals("Alice", child.name); + Assertions.assertEquals(30, child.age); + Assertions.assertEquals(10000.50, child.salary, 0.001); + Assertions.assertTrue(child.isActive); - Assert.assertEquals(Status.ACTIVE, child.status); - Assert.assertEquals("Beijing", child.address.city); - Assert.assertEquals("XiErQi", child.address.street); + Assertions.assertEquals(Status.ACTIVE, child.status); + Assertions.assertEquals("Beijing", child.address.city); + Assertions.assertEquals("XiErQi", child.address.street); - Assert.assertEquals(3, child.hobbies.size()); - Assert.assertTrue(child.hobbies.contains("Reading")); - Assert.assertEquals(3, child.scores.size()); - Assert.assertTrue(child.scores.contains(90)); + Assertions.assertEquals(3, child.hobbies.size()); + Assertions.assertTrue(child.hobbies.contains("Reading")); + Assertions.assertEquals(3, child.scores.size()); + Assertions.assertTrue(child.scores.contains(90)); - Assert.assertEquals(2, child.attributes.size()); - Assert.assertEquals("dev", child.attributes.get("Department")); - Assert.assertEquals(3L, child.attributes.get("Level")); + Assertions.assertEquals(2, child.attributes.size()); + Assertions.assertEquals("dev", child.attributes.get("Department")); + Assertions.assertEquals(3L, child.attributes.get("Level")); - Assert.assertNull(child.tag); - Assert.assertEquals(0, child.scr); - Assert.assertNull(child.workAddresses); - Assert.assertNull(child.statusDescriptions); + Assertions.assertNull(child.tag); + Assertions.assertEquals(0, child.scr); + Assertions.assertNull(child.workAddresses); + Assertions.assertNull(child.statusDescriptions); - Assert.assertEquals("Child", child.getClass().getSimpleName()); + Assertions.assertEquals("Child", child.getClass().getSimpleName()); } @Test public void testCopyToChildWithNullParent() { Child child = CopyUtil.copyToChild(null, Child.class); - Assert.assertNull(child); + Assertions.assertNull(child); } @Test public void testCopyToChildWithNullChildClass() { Parent parent = new Parent("Mike", 30); Child child = CopyUtil.copyToChild(parent, null); - Assert.assertNull(child); + Assertions.assertNull(child); } @Test @@ -178,10 +178,10 @@ public void testCopyToChildWithEmptyCollections() { parent.attributes = new HashMap<>(); Child child = CopyUtil.copyToChild(parent, Child.class); - Assert.assertNotNull(child); - Assert.assertTrue(child.hobbies.isEmpty()); - Assert.assertTrue(child.scores.isEmpty()); - Assert.assertTrue(child.attributes.isEmpty()); + Assertions.assertNotNull(child); + Assertions.assertTrue(child.hobbies.isEmpty()); + Assertions.assertTrue(child.scores.isEmpty()); + Assertions.assertTrue(child.attributes.isEmpty()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogBloomFilterMaterializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogBloomFilterMaterializationTest.java index bb5f15fd0c86d0..a9abdf49451f8f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogBloomFilterMaterializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogBloomFilterMaterializationTest.java @@ -35,8 +35,8 @@ import org.apache.doris.thrift.TTabletType; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashSet; @@ -69,10 +69,10 @@ public void testCreateTabletMetaBuilderMaterializesBfIndex() throws Exception { 65536L, EncryptionAlgorithmPB.PLAINTEXT, 262144L, false, Collections.emptyMap(), 5, OlapFile.TabletRolePB.TABLET_ROLE_DATA).build(); - Assert.assertFalse(tabletMeta.getSchema().hasBfFpp()); - Assert.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); - Assert.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); - Assert.assertEquals("0.02", tabletMeta.getSchema().getIndex(0).getPropertiesMap().get("bloom_filter_fpp")); + Assertions.assertFalse(tabletMeta.getSchema().hasBfFpp()); + Assertions.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); + Assertions.assertEquals("0.02", tabletMeta.getSchema().getIndex(0).getPropertiesMap().get("bloom_filter_fpp")); } @Test @@ -95,8 +95,8 @@ public void testCreateTabletMetaBuilderMaterializesBfIndexWithEmptyBfColumns() t 65536L, EncryptionAlgorithmPB.PLAINTEXT, 262144L, false, Collections.emptyMap(), 5, OlapFile.TabletRolePB.TABLET_ROLE_DATA).build(); - Assert.assertFalse(tabletMeta.getSchema().hasBfFpp()); - Assert.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(tabletMeta.getSchema().hasBfFpp()); + Assertions.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); } @Test @@ -115,8 +115,8 @@ public void testCreateTabletMetaBuilderDoesNotSetBfFppWithoutBloomFilter() throw 65536L, EncryptionAlgorithmPB.PLAINTEXT, 262144L, false, Collections.emptyMap(), 5, OlapFile.TabletRolePB.TABLET_ROLE_DATA).build(); - Assert.assertFalse(tabletMeta.getSchema().hasBfFpp()); - Assert.assertFalse(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(tabletMeta.getSchema().hasBfFpp()); + Assertions.assertFalse(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); } @Test @@ -140,10 +140,10 @@ public void testCreateTabletMetaBuilderMaterializesBfColumnsWithExplicitFpp() th EncryptionAlgorithmPB.PLAINTEXT, 262144L, false, Collections.emptyMap(), 5, OlapFile.TabletRolePB.TABLET_ROLE_DATA).build(); - Assert.assertTrue(tabletMeta.getSchema().hasBfFpp()); - Assert.assertEquals(0.02, tabletMeta.getSchema().getBfFpp(), 0); - Assert.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); - Assert.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); + Assertions.assertTrue(tabletMeta.getSchema().hasBfFpp()); + Assertions.assertEquals(0.02, tabletMeta.getSchema().getBfFpp(), 0); + Assertions.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); } @Test @@ -170,10 +170,10 @@ public void testCreateTabletMetaBuilderMaterializesShadowBfIndexWithIndexes() th EncryptionAlgorithmPB.PLAINTEXT, 262144L, false, Collections.emptyMap(), 5, OlapFile.TabletRolePB.TABLET_ROLE_DATA).build(); - Assert.assertFalse(tabletMeta.getSchema().hasBfFpp()); - Assert.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); - Assert.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); - Assert.assertEquals("k1", tabletMeta.getSchema().getColumn(0).getName()); - Assert.assertEquals("0.03", tabletMeta.getSchema().getIndex(0).getPropertiesMap().get("bloom_filter_fpp")); + Assertions.assertFalse(tabletMeta.getSchema().hasBfFpp()); + Assertions.assertTrue(tabletMeta.getSchema().getColumn(0).getIsBfColumn()); + Assertions.assertFalse(tabletMeta.getSchema().getColumn(1).getIsBfColumn()); + Assertions.assertEquals("k1", tabletMeta.getSchema().getColumn(0).getName()); + Assertions.assertEquals("0.03", tabletMeta.getSchema().getIndex(0).getPropertiesMap().get("bloom_filter_fpp")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogTest.java index 1fbe95efe6fe57..0725fe070497ef 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/datasource/CloudInternalCatalogTest.java @@ -29,8 +29,8 @@ import org.apache.doris.thrift.TStorageFormat; import org.apache.doris.thrift.TTabletType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Collections; @@ -48,21 +48,21 @@ public void testCreateTabletMetaUsesCurrentSchemaVersionAndFormat() throws Excep try { Config.enable_partition_inverted_index_storage_format_rollout = false; OlapFile.TabletMetaCloudPB disabledTabletMeta = createTabletMeta(tablet); - Assert.assertEquals(17, disabledTabletMeta.getSchemaVersion()); - Assert.assertEquals(17, disabledTabletMeta.getSchema().getSchemaVersion()); - Assert.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, + Assertions.assertEquals(17, disabledTabletMeta.getSchemaVersion()); + Assertions.assertEquals(17, disabledTabletMeta.getSchema().getSchemaVersion()); + Assertions.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, disabledTabletMeta.getSchema().getInvertedIndexStorageFormat()); - Assert.assertFalse(disabledTabletMeta.hasInvertedIndexStorageFormat()); - Assert.assertEquals(1, disabledTabletMeta.getRsMetasCount()); - Assert.assertFalse(disabledTabletMeta.getRsMetas(0).hasInvertedIndexStorageFormat()); + Assertions.assertFalse(disabledTabletMeta.hasInvertedIndexStorageFormat()); + Assertions.assertEquals(1, disabledTabletMeta.getRsMetasCount()); + Assertions.assertFalse(disabledTabletMeta.getRsMetas(0).hasInvertedIndexStorageFormat()); Config.enable_partition_inverted_index_storage_format_rollout = true; OlapFile.TabletMetaCloudPB enabledTabletMeta = createTabletMeta(tablet); - Assert.assertTrue(enabledTabletMeta.hasInvertedIndexStorageFormat()); - Assert.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, + Assertions.assertTrue(enabledTabletMeta.hasInvertedIndexStorageFormat()); + Assertions.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, enabledTabletMeta.getInvertedIndexStorageFormat()); - Assert.assertTrue(enabledTabletMeta.getRsMetas(0).hasInvertedIndexStorageFormat()); - Assert.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, + Assertions.assertTrue(enabledTabletMeta.getRsMetas(0).hasInvertedIndexStorageFormat()); + Assertions.assertEquals(OlapFile.InvertedIndexStorageFormatPB.SNII, enabledTabletMeta.getRsMetas(0).getInvertedIndexStorageFormat()); } finally { Config.enable_partition_inverted_index_storage_format_rollout = original; diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CloudBrokerLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CloudBrokerLoadJobTest.java index 4ef6401963870c..89851507932cba 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CloudBrokerLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CloudBrokerLoadJobTest.java @@ -27,8 +27,8 @@ import org.apache.doris.transaction.TxnStateCallbackFactory; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -55,12 +55,12 @@ public void testRetryStartsNewTransactionAfterAbort() throws Exception { Mockito.anyLong(), Mockito.anyLong())).thenReturn(5001L); job.unprotectedExecuteRetry(new FailMsg(FailMsg.CancelType.ETL_RUN_FAIL, "rpc failed")); - Assert.assertEquals(0L, job.getTransactionId()); + Assertions.assertEquals(0L, job.getTransactionId()); job.beginTxn(); } - Assert.assertEquals(5001L, job.getTransactionId()); - Assert.assertEquals(JobState.RETRY, job.getState()); + Assertions.assertEquals(5001L, job.getTransactionId()); + Assertions.assertEquals(JobState.RETRY, job.getState()); Mockito.verify(transactionMgr).abortTransaction(2001L, "cloud_broker_load_retry", "rpc failed"); } @@ -83,7 +83,7 @@ public void testRetryClearsTransactionIdWhenAbortFails() throws Exception { job.unprotectedExecuteRetry(new FailMsg(FailMsg.CancelType.ETL_RUN_FAIL, "rpc failed")); } - Assert.assertEquals(0L, job.getTransactionId()); - Assert.assertEquals(JobState.RETRY, job.getState()); + Assertions.assertEquals(0L, job.getTransactionId()); + Assertions.assertEquals(JobState.RETRY, job.getState()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyJobTest.java index 4dca768b7c71c8..9f83512d145543 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyJobTest.java @@ -39,10 +39,10 @@ import com.google.common.collect.Lists; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -63,7 +63,7 @@ public class CopyJobTest { private static FakeEnv fakeEnv; private static Env masterEnv; - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { fakeEditLog = new FakeEditLog(); @@ -75,7 +75,7 @@ public void setUp() throws InstantiationException, IllegalAccessException, Illeg metaContext.setThreadLocalInfo(); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -94,16 +94,16 @@ public void testParseLoadFiles() { "org1/instance1/stage/bob/8f3b7371-c096-48ef-b81c-0eb951dd0f52", "stage/root/root"); for (String stagePrefix : stagePrefixes) { Pair, List> files = generateLoadFiles(bucket, stagePrefix); - Assert.assertEquals(files.second, StageUtil.parseLoadFiles(files.first, bucket, stagePrefix)); + Assertions.assertEquals(files.second, StageUtil.parseLoadFiles(files.first, bucket, stagePrefix)); } - Assert.assertNull(StageUtil.parseLoadFiles(null, bucket, stagePrefixes.get(0))); + Assertions.assertNull(StageUtil.parseLoadFiles(null, bucket, stagePrefixes.get(0))); - Assert.assertNull(StageUtil.parseLoadFiles(new ArrayList<>(), bucket, "instance1/data/dbId")); + Assertions.assertNull(StageUtil.parseLoadFiles(new ArrayList<>(), bucket, "instance1/data/dbId")); Config.cloud_delete_loaded_internal_stage_files = false; Pair, List> files = generateLoadFiles(bucket, stagePrefixes.get(0)); - Assert.assertNull(StageUtil.parseLoadFiles(files.first, bucket, stagePrefixes.get(0))); + Assertions.assertNull(StageUtil.parseLoadFiles(files.first, bucket, stagePrefixes.get(0))); } private Pair, List> generateLoadFiles(String bucket, String stagePrefix) { @@ -151,9 +151,9 @@ public void testSerialization() throws IOException, MetaNotFoundException { DataInputStream in = new DataInputStream(new FileInputStream(file)); LoadJob copyJob2 = LoadJob.read(in); - Assert.assertEquals(copyJob1.getDbId(), copyJob2.getDbId()); + Assertions.assertEquals(copyJob1.getDbId(), copyJob2.getDbId()); in.close(); file.delete(); - Assert.assertEquals(copyJob1.getDbId(), copyJob2.getDbId()); + Assertions.assertEquals(copyJob1.getDbId(), copyJob2.getDbId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyLoadPendingTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyLoadPendingTaskTest.java index b403ae3d8c13aa..0ca4a407cf3041 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyLoadPendingTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/load/CopyLoadPendingTaskTest.java @@ -37,7 +37,7 @@ import org.apache.doris.utframe.UtFrameUtils; import com.google.common.collect.Lists; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -190,21 +190,21 @@ public void testGlob() { String globPrefix = "glob:"; // file name contains "," which is a special character in Glob String fileName = "1,csv"; - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "1,csv")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "1\\,csv")); - Assert.assertEquals(false, matchGlob(fileName, globPrefix + "{1,csv}")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\,csv}")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\,csv,2\\,csv}")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "1,csv")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "1\\,csv")); + Assertions.assertEquals(false, matchGlob(fileName, globPrefix + "{1,csv}")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\,csv}")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\,csv,2\\,csv}")); fileName = "1?csv"; String fileName2 = "12csv"; - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "1?csv")); - Assert.assertEquals(true, matchGlob(fileName2, globPrefix + "1?csv")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "1\\?csv")); - Assert.assertEquals(false, matchGlob(fileName2, globPrefix + "1\\?csv")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "{1?csv}")); - Assert.assertEquals(true, matchGlob(fileName2, globPrefix + "{1?csv}")); - Assert.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\?csv}")); - Assert.assertEquals(false, matchGlob(fileName2, globPrefix + "{1\\?csv}")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "1?csv")); + Assertions.assertEquals(true, matchGlob(fileName2, globPrefix + "1?csv")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "1\\?csv")); + Assertions.assertEquals(false, matchGlob(fileName2, globPrefix + "1\\?csv")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "{1?csv}")); + Assertions.assertEquals(true, matchGlob(fileName2, globPrefix + "{1?csv}")); + Assertions.assertEquals(true, matchGlob(fileName, globPrefix + "{1\\?csv}")); + Assertions.assertEquals(false, matchGlob(fileName2, globPrefix + "{1\\?csv}")); } private boolean matchGlob(String file, String pattern) { @@ -251,7 +251,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, sizeLimit, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals(pair.second.intValue(), fileStatus.size()); + Assertions.assertEquals(pair.second.intValue(), fileStatus.size()); } // test loaded files is not empty do { @@ -259,7 +259,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, 200, "q1", pattern, sizeLimit, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals(9, fileStatus.size()); + Assertions.assertEquals(9, fileStatus.size()); } while (false); // test size limit do { @@ -267,7 +267,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, 100, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals(10, fileStatus.size()); // 4, files limit are filtered in begin_copy + Assertions.assertEquals(10, fileStatus.size()); // 4, files limit are filtered in begin_copy } while (false); // test file num limit do { @@ -275,7 +275,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, sizeLimit, 6, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals(10, fileStatus.size()); // 6 + Assertions.assertEquals(10, fileStatus.size()); // 6 } while (false); // test file meta size limit do { @@ -283,7 +283,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, sizeLimit, fileNumLimit, 60, fileStatus, objectInfo, false); - Assert.assertEquals(10, fileStatus.size()); // 2 + Assertions.assertEquals(10, fileStatus.size()); // 2 } while (false); // test size and file num limit do { @@ -291,7 +291,7 @@ public void testParseFileForCopyJob() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, 100, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals(10, fileStatus.size()); // 4 + Assertions.assertEquals(10, fileStatus.size()); // 4 } while (false); } @@ -382,8 +382,7 @@ public void testContinuationToken() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, sizeLimit, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals("pattern=" + pattern + " with pagination", - pair.second.intValue(), fileStatus.size()); + Assertions.assertEquals(pair.second.intValue(), fileStatus.size(), "pattern=" + pattern + " with pagination"); } } @@ -468,7 +467,7 @@ public void testParseFileForCopyJobV2() throws Exception { List> fileStatus = new ArrayList<>(); task.parseFileForCopyJob(stageId, tableId, "q1", pattern, sizeLimit, fileNumLimit, fileMetaSizeLimit, fileStatus, objectInfo, false); - Assert.assertEquals("pattern=" + pattern, pair.second.intValue(), fileStatus.size()); + Assertions.assertEquals(pair.second.intValue(), fileStatus.size(), "pattern=" + pattern); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/master/CloudReportHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/master/CloudReportHandlerTest.java index d6611cb1df651f..430f5cc4a7269c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/master/CloudReportHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/master/CloudReportHandlerTest.java @@ -20,8 +20,8 @@ import org.apache.doris.catalog.Env; import org.apache.doris.cloud.catalog.CloudEnv; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -32,7 +32,7 @@ public class CloudReportHandlerTest { private CloudEnv mockCloudEnv = Mockito.mock(CloudEnv.class); private MockedStatic mockedEnvStatic; - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceProxyTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceProxyTest.java index e53280d34e55b2..5b80b6ab77a441 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceProxyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceProxyTest.java @@ -27,10 +27,10 @@ import com.google.protobuf.DescriptorProtos; import com.google.protobuf.Descriptors; import com.google.protobuf.DynamicMessage; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Map; @@ -51,7 +51,7 @@ public class MetaServiceProxyTest { private int originRateLimitBurstSeconds; private long originRateLimitWaitTimeoutMs; - @Before + @BeforeEach public void setUp() { originEndpoint = Config.meta_service_endpoint; originReconnectIntervalMs = Config.meta_service_rpc_reconnect_interval_ms; @@ -75,7 +75,7 @@ public void setUp() { MetaServiceProxy.resetMetaServiceRpcRateLimitForTest(); } - @After + @AfterEach public void tearDown() { Config.meta_service_endpoint = originEndpoint; Config.meta_service_rpc_reconnect_interval_ms = originReconnectIntervalMs; @@ -109,7 +109,7 @@ public void testExecuteRequestNoShutdownOnSuccess() throws RpcException { .build(); Cloud.GetVersionResponse response = wrapper.executeRequest("ignored", (ignored) -> okResponse, Cloud.GetVersionResponse::getStatus); - Assert.assertEquals(Cloud.MetaServiceCode.OK, response.getStatus().getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.OK, response.getStatus().getCode()); Mockito.verify(client, Mockito.never()).shutdown(Mockito.anyBoolean()); } @@ -131,7 +131,7 @@ public void testExecuteRequestShutdownOnFailure() { wrapper.executeRequest("ignored", (ignored) -> { throw new RuntimeException("rpc failed"); }, Cloud.GetVersionResponse::getStatus); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException ignored) { // expected } @@ -182,9 +182,9 @@ public void testExecuteRequestNoShutdownOnTooBusyFailure() throws RpcException { try { wrapper.executeRequest("ignored", (ignored) -> response, Cloud.GetVersionResponse::getStatus); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertEquals("server is overloaded", e.getMessage()); + Assertions.assertEquals("server is overloaded", e.getMessage()); } Mockito.verify(client, Mockito.never()).shutdown(Mockito.anyBoolean()); } @@ -217,8 +217,8 @@ public void testExecuteRequestRetryOnTooBusy() throws RpcException { Cloud.GetVersionResponse result = wrapper.executeRequest("ignored", (ignored) -> callCount.incrementAndGet() == 1 ? tooBusyResponse : okResponse, Cloud.GetVersionResponse::getStatus); - Assert.assertEquals(Cloud.MetaServiceCode.OK, result.getStatus().getCode()); - Assert.assertEquals(2, callCount.get()); + Assertions.assertEquals(Cloud.MetaServiceCode.OK, result.getStatus().getCode()); + Assertions.assertEquals(2, callCount.get()); Mockito.verify(client, Mockito.never()).shutdown(Mockito.anyBoolean()); } @@ -230,8 +230,8 @@ public void testGetInstancePrefersKnownActualCode() throws RpcException { .setActualCode(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), status.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), status.getActualCode()); } @Test @@ -241,7 +241,7 @@ public void testGetInstanceUsesKnownActualCodeWithoutFallback() throws RpcExcept .setActualCode(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); } @Test @@ -252,8 +252,8 @@ public void testGetInstanceKeepsLegacyCodeForUnknownActualCode() throws RpcExcep .setActualCode(Integer.MAX_VALUE) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, status.getCode()); - Assert.assertEquals(Integer.MAX_VALUE, status.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, status.getCode()); + Assertions.assertEquals(Integer.MAX_VALUE, status.getActualCode()); } @Test @@ -264,15 +264,15 @@ public void testGetInstanceFailsClosedForUnknownActualCodeWithoutErrorFallback() .setActualCode(Integer.MAX_VALUE) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); - Assert.assertEquals(Integer.MAX_VALUE, status.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); + Assertions.assertEquals(Integer.MAX_VALUE, status.getActualCode()); status = callGetInstanceWithStatus(Cloud.MetaServiceResponseStatus.newBuilder() .setActualCode(Integer.MAX_VALUE) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); - Assert.assertEquals(Integer.MAX_VALUE, status.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); + Assertions.assertEquals(Integer.MAX_VALUE, status.getActualCode()); } @Test @@ -280,7 +280,7 @@ public void testGetInstanceFailsClosedWithoutAnyCode() throws RpcException { Cloud.MetaServiceResponseStatus status = callGetInstanceWithStatus( Cloud.MetaServiceResponseStatus.getDefaultInstance()); - Assert.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, status.getCode()); } @Test @@ -290,8 +290,8 @@ public void testResponseFailsClosedWithoutStatus() { "restoreActualCode", Cloud.GetInstanceResponse.getDefaultInstance()); - Assert.assertTrue(response.hasStatus()); - Assert.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, response.getStatus().getCode()); + Assertions.assertTrue(response.hasStatus()); + Assertions.assertEquals(Cloud.MetaServiceCode.UNDEFINED_ERR, response.getStatus().getCode()); } @Test @@ -301,8 +301,8 @@ public void testGetInstanceKeepsLegacyCodeWithoutActualCode() throws RpcExceptio .setCode(Cloud.MetaServiceCode.KV_TXN_CONFLICT) .build()); - Assert.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, status.getCode()); - Assert.assertFalse(status.hasActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, status.getCode()); + Assertions.assertFalse(status.hasActualCode()); } @Test @@ -324,8 +324,8 @@ public void testGetVisibleVersionAsyncPrefersKnownActualCode() throws Exception Cloud.GetVersionResponse response = normalizedFuture.get(); response = Deencapsulation.invoke(MetaServiceClient.class, "restoreActualCode", response); Cloud.MetaServiceResponseStatus status = response.getStatus(); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), status.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY, status.getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), status.getActualCode()); } @Test @@ -342,16 +342,16 @@ public void testLegacySchemaWireCompatibility() throws Exception { legacyStatusDescriptor, currentStatus.toByteArray()); Descriptors.EnumValueDescriptor legacyCode = (Descriptors.EnumValueDescriptor) legacyStatus.getField(legacyCodeField); - Assert.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT.getNumber(), legacyCode.getNumber()); - Assert.assertNull(legacyStatusDescriptor.findFieldByName("actual_code")); - Assert.assertTrue(legacyStatus.getUnknownFields().hasField(3)); - Assert.assertEquals(Long.valueOf(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()), + Assertions.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT.getNumber(), legacyCode.getNumber()); + Assertions.assertNull(legacyStatusDescriptor.findFieldByName("actual_code")); + Assertions.assertTrue(legacyStatus.getUnknownFields().hasField(3)); + Assertions.assertEquals(Long.valueOf(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()), legacyStatus.getUnknownFields().getField(3).getVarintList().get(0)); Cloud.MetaServiceResponseStatus roundTripStatus = Cloud.MetaServiceResponseStatus.parseFrom(legacyStatus.toByteArray()); - Assert.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, roundTripStatus.getCode()); - Assert.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), roundTripStatus.getActualCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.KV_TXN_CONFLICT, roundTripStatus.getCode()); + Assertions.assertEquals(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber(), roundTripStatus.getActualCode()); } @Test @@ -366,10 +366,10 @@ public void testLegacySchemaReadsUnknownEnumAsDefaultOk() throws Exception { legacyStatusDescriptor, incompatibleStatus.toByteArray()); Descriptors.EnumValueDescriptor legacyCode = (Descriptors.EnumValueDescriptor) legacyStatus.getField(legacyCodeField); - Assert.assertFalse(legacyStatus.hasField(legacyCodeField)); - Assert.assertEquals(Cloud.MetaServiceCode.OK.getNumber(), legacyCode.getNumber()); - Assert.assertTrue(legacyStatus.getUnknownFields().hasField(1)); - Assert.assertEquals(Long.valueOf(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()), + Assertions.assertFalse(legacyStatus.hasField(legacyCodeField)); + Assertions.assertEquals(Cloud.MetaServiceCode.OK.getNumber(), legacyCode.getNumber()); + Assertions.assertTrue(legacyStatus.getUnknownFields().hasField(1)); + Assertions.assertEquals(Long.valueOf(Cloud.MetaServiceCode.MS_TOO_BUSY.getNumber()), legacyStatus.getUnknownFields().getField(1).getVarintList().get(0)); } @@ -395,12 +395,12 @@ public void testExecuteRequestFailureAfterTooBusyRetries() throws RpcException { callCount.incrementAndGet(); return tooBusyResponse; }, Cloud.GetVersionResponse::getStatus); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertEquals("server is overloaded", e.getMessage()); + Assertions.assertEquals("server is overloaded", e.getMessage()); } - Assert.assertEquals(2, callCount.get()); + Assertions.assertEquals(2, callCount.get()); Mockito.verify(client, Mockito.never()).shutdown(Mockito.anyBoolean()); } @@ -426,12 +426,12 @@ public void testExecuteRequestRateLimitedWithoutRetryOrShutdown() throws RpcExce callCount.incrementAndGet(); return okResponse; }, Cloud.GetVersionResponse::getStatus); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("meta service rpc rate limited")); + Assertions.assertTrue(e.getMessage().contains("meta service rpc rate limited")); } - Assert.assertEquals(CPU_CORES, callCount.get()); + Assertions.assertEquals(CPU_CORES, callCount.get()); Mockito.verify(client, Mockito.never()).shutdown(Mockito.anyBoolean()); } @@ -452,9 +452,9 @@ public void testRateLimitSharedBetweenProxies() throws RpcException { try { secondWrapper.executeRequest("shared", (ignored) -> okResponse, Cloud.GetVersionResponse::getStatus); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("meta service rpc rate limited")); + Assertions.assertTrue(e.getMessage().contains("meta service rpc rate limited")); } } @@ -468,9 +468,9 @@ public void testGetInstanceRateLimitedBeforeRpc() throws RpcException { try { proxy.getInstance(Cloud.GetInstanceRequest.newBuilder().build()); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("meta service rpc rate limited")); + Assertions.assertTrue(e.getMessage().contains("meta service rpc rate limited")); } Mockito.verify(client, Mockito.never()).getInstance(Mockito.any()); @@ -494,9 +494,9 @@ public void testGetVisibleVersionAsyncRateLimitedBeforeRpc() throws RpcException try { proxy.getVisibleVersionAsync(Cloud.GetVersionRequest.newBuilder().build()); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("meta service rpc rate limited")); + Assertions.assertTrue(e.getMessage().contains("meta service rpc rate limited")); } Mockito.verify(client, Mockito.times(1)).getVisibleVersionAsync(Mockito.any()); @@ -518,9 +518,9 @@ public void testBatchGetVisibleVersionAsyncConsumesMultipleRateLimitPermits() th proxy.getVisibleVersionAsync(Cloud.GetVersionRequest.newBuilder() .setIsTableVersion(true) .build()); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("meta service rpc rate limited")); + Assertions.assertTrue(e.getMessage().contains("meta service rpc rate limited")); } Mockito.verify(client, Mockito.times(1)).getVisibleVersionAsync(Mockito.any()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiterTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiterTest.java index 2a31c44618e848..05d23b4b94162a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiterTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiterTest.java @@ -28,10 +28,10 @@ import org.apache.doris.metric.MetricRepo; import org.apache.doris.rpc.RpcException; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Collections; @@ -53,7 +53,7 @@ public class MetaServiceRpcRateLimiterTest { private MetaServiceRpcRateLimiter rateLimiter; - @Before + @BeforeEach public void setUp() { originRateLimitEnabled = Config.meta_service_rpc_rate_limit_enabled; originRateLimitDryRun = Config.meta_service_rpc_rate_limit_dry_run; @@ -78,7 +78,7 @@ public void setUp() { enableRateLimit(1, "", 1, 0); } - @After + @AfterEach public void tearDown() { Config.meta_service_rpc_rate_limit_enabled = originRateLimitEnabled; Config.meta_service_rpc_rate_limit_dry_run = originRateLimitDryRun; @@ -117,14 +117,14 @@ public void testDryRunDoesNotReject() throws RpcException { consumePermits("dryRun", CPU_CORES); rateLimiter.acquire("dryRun"); - Assert.assertEquals(1L, CloudMetrics.META_SERVICE_RPC_ALL_RATE_LIMITED.getValue().longValue()); - Assert.assertEquals(1L, + Assertions.assertEquals(1L, CloudMetrics.META_SERVICE_RPC_ALL_RATE_LIMITED.getValue().longValue()); + Assertions.assertEquals(1L, CloudMetrics.META_SERVICE_RPC_RATE_LIMITED.getOrAdd("dryRun").getValue().longValue()); Config.meta_service_rpc_rate_limit_dry_run = false; assertRateLimited("dryRun"); - Assert.assertEquals(2L, CloudMetrics.META_SERVICE_RPC_ALL_RATE_LIMITED.getValue().longValue()); - Assert.assertEquals(2L, + Assertions.assertEquals(2L, CloudMetrics.META_SERVICE_RPC_ALL_RATE_LIMITED.getValue().longValue()); + Assertions.assertEquals(2L, CloudMetrics.META_SERVICE_RPC_RATE_LIMITED.getOrAdd("dryRun").getValue().longValue()); } @@ -134,8 +134,8 @@ public void testDryRunDoesNotWait() throws RpcException { Config.meta_service_rpc_rate_limit_dry_run = true; consumePermits("dryRunWait", CPU_CORES); - Assert.assertEquals(0, rateLimiter.acquire("dryRunWait")); - Assert.assertEquals(1L, CloudMetrics.META_SERVICE_RPC_RATE_LIMIT_WAIT_LATENCY.getOrAdd("dryRunWait") + Assertions.assertEquals(0, rateLimiter.acquire("dryRunWait")); + Assertions.assertEquals(1L, CloudMetrics.META_SERVICE_RPC_RATE_LIMIT_WAIT_LATENCY.getOrAdd("dryRunWait") .getHistogram().getCount()); } @@ -178,7 +178,7 @@ public void testWeightedAcquireUsesTimeoutCapacity() throws RpcException { long waitNs = rateLimiter.acquire("timeoutCapacity", CPU_CORES * 2); - Assert.assertTrue(waitNs > 0); + Assertions.assertTrue(waitNs > 0); } @Test @@ -205,7 +205,7 @@ public void testWaitTimeoutRejectsWithoutWaitingForNextRefreshPeriod() throws Rp long startTimeMs = System.currentTimeMillis(); assertRateLimited("waitTimeout"); - Assert.assertTrue(System.currentTimeMillis() - startTimeMs < TimeUnit.SECONDS.toMillis(1)); + Assertions.assertTrue(System.currentTimeMillis() - startTimeMs < TimeUnit.SECONDS.toMillis(1)); } @Test @@ -215,7 +215,7 @@ public void testAcquireReturnsActualWaitTime() throws RpcException { long waitNs = rateLimiter.acquire("wait"); - Assert.assertTrue(waitNs > 0); + Assertions.assertTrue(waitNs > 0); } @Test @@ -249,7 +249,7 @@ public void testInvalidBurstSecondsConfigHandler() throws Exception { assertConfigHandlerRejects(handler, field, "-1", "must be positive"); handler.handle(field, " 2 "); - Assert.assertEquals(2, Config.meta_service_rpc_rate_limit_burst_seconds); + Assertions.assertEquals(2, Config.meta_service_rpc_rate_limit_burst_seconds); } @Test @@ -269,7 +269,7 @@ public void testInvalidWaitTimeoutMsConfigHandler() throws Exception { assertConfigHandlerRejects(handler, field, "-1", "must be non-negative"); handler.handle(field, " 0 "); - Assert.assertEquals(0, Config.meta_service_rpc_rate_limit_wait_timeout_ms); + Assertions.assertEquals(0, Config.meta_service_rpc_rate_limit_wait_timeout_ms); } @Test @@ -309,9 +309,9 @@ private void assertConfigHandlerRejects(ConfigBase.ConfHandler handler, Field fi String expectedMessage) throws Exception { try { handler.handle(field, config); - Assert.fail("should throw exception"); + Assertions.fail("should throw exception"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains(expectedMessage)); + Assertions.assertTrue(e.getMessage().contains(expectedMessage)); } } @@ -322,9 +322,9 @@ private void assertRateLimited(String methodName) throws RpcException { private void assertRpcException(String expectedMessage, RpcCall rpcCall) throws RpcException { try { rpcCall.run(); - Assert.fail("should throw RpcException"); + Assertions.fail("should throw RpcException"); } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains(expectedMessage)); + Assertions.assertTrue(e.getMessage().contains(expectedMessage)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/snapshot/CloudSnapshotHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/snapshot/CloudSnapshotHandlerTest.java index 337c2c6b6c0567..63e38effc794a3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/snapshot/CloudSnapshotHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/snapshot/CloudSnapshotHandlerTest.java @@ -20,10 +20,10 @@ import org.apache.doris.catalog.Env; import org.apache.doris.common.Config; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; @@ -40,7 +40,7 @@ public class CloudSnapshotHandlerTest { private String originalHandlerClass; private ClassLoader originalContextClassLoader; - @Before + @BeforeEach public void setUp() { originalHandlerClass = Config.cloud_snapshot_handler_class; originalContextClassLoader = Thread.currentThread().getContextClassLoader(); @@ -48,7 +48,7 @@ public void setUp() { CloudSnapshotHandler.setSnapshotEnv(null); } - @After + @AfterEach public void tearDown() { Config.cloud_snapshot_handler_class = originalHandlerClass; Thread.currentThread().setContextClassLoader(originalContextClassLoader); @@ -60,7 +60,7 @@ public void testDefaultHandlerWithoutProvider() { Thread.currentThread().setContextClassLoader(new SnapshotHandlerClassLoader(null)); CloudSnapshotHandler handler = CloudSnapshotHandler.getInstance(); - Assert.assertEquals(CloudSnapshotHandler.class, handler.getClass()); + Assertions.assertEquals(CloudSnapshotHandler.class, handler.getClass()); } @Test @@ -69,7 +69,7 @@ public void testLoadHandlerFromServiceProvider() { new SnapshotHandlerClassLoader(ServiceLoadedSnapshotHandler.class)); CloudSnapshotHandler handler = CloudSnapshotHandler.getInstance(); - Assert.assertTrue(handler instanceof ServiceLoadedSnapshotHandler); + Assertions.assertTrue(handler instanceof ServiceLoadedSnapshotHandler); } @Test @@ -80,7 +80,7 @@ public void testConfiguredHandlerTakesPrecedenceOverServiceProvider() { CloudSnapshotHandler handler = CloudSnapshotHandler.getInstance(); - Assert.assertTrue(handler instanceof ConfiguredSnapshotHandler); + Assertions.assertTrue(handler instanceof ConfiguredSnapshotHandler); } @Test @@ -89,8 +89,8 @@ public void testSnapshotEnvOverridesCurrentEnv() { CloudSnapshotHandler.setSnapshotEnv(snapshotEnv); - Assert.assertSame(snapshotEnv, CloudSnapshotHandler.getSnapshotEnv()); - Assert.assertSame(snapshotEnv, Env.getCurrentEnv()); + Assertions.assertSame(snapshotEnv, CloudSnapshotHandler.getSnapshotEnv()); + Assertions.assertSame(snapshotEnv, Env.getCurrentEnv()); } public static class ServiceLoadedSnapshotHandler extends CloudSnapshotHandler { diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/stage/StageUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/stage/StageUtilTest.java index 354e1efbd6fa13..487674f11020f4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/stage/StageUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/stage/StageUtilTest.java @@ -34,8 +34,8 @@ import org.apache.commons.lang3.tuple.Triple; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -65,7 +65,7 @@ public List readMockedOssUrl() throws Exception { @Test public void testListAndFilterFilesV2() throws Exception { List keys = readMockedOssUrl(); - Assert.assertEquals(4956, keys.size()); + Assertions.assertEquals(4956, keys.size()); // Mock FileSystemFactory and related dependencies ObjFileSystem mockFs = Mockito.mock(ObjFileSystem.class); @@ -112,7 +112,7 @@ public void testListAndFilterFilesV2() throws Exception { LOG.info("triple:{}, fileStatus.size():{}", triple, fileStatus.size()); // All 4956 test keys match the pattern, but the meta size limit (51200 bytes) // caps the result at 500 files (5 batches of cloud_filter_copy_file_num_limit=100). - Assert.assertEquals(500, fileStatus.size()); + Assertions.assertEquals(500, fileStatus.size()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/storage/ObjectInfoAdapterTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/storage/ObjectInfoAdapterTest.java index 9afe4c4168abb4..ed26ad4a0aab41 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/storage/ObjectInfoAdapterTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/storage/ObjectInfoAdapterTest.java @@ -22,8 +22,8 @@ import org.apache.doris.datasource.storage.StorageTypeId; import org.apache.doris.filesystem.properties.S3CompatibleFileSystemProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ObjectInfoAdapterTest { @@ -45,12 +45,12 @@ public void testToStorageAdapterPreservesAwsRoleFields() { StorageAdapter adapter = ObjectInfoAdapter.toStorageAdapter(objectInfo); S3CompatibleFileSystemProperties s3 = (S3CompatibleFileSystemProperties) adapter.getSpiProperties(); - Assert.assertEquals(StorageTypeId.S3, adapter.getType()); - Assert.assertEquals("s3.us-west-2.amazonaws.com", s3.getEndpoint()); - Assert.assertEquals("us-west-2", s3.getRegion()); - Assert.assertEquals("snapshot-bucket", s3.getBucket()); - Assert.assertEquals("arn:aws:iam::123456789012:role/snapshot-role", s3.getRoleArn()); - Assert.assertEquals("snapshot-external-id", s3.getExternalId()); + Assertions.assertEquals(StorageTypeId.S3, adapter.getType()); + Assertions.assertEquals("s3.us-west-2.amazonaws.com", s3.getEndpoint()); + Assertions.assertEquals("us-west-2", s3.getRegion()); + Assertions.assertEquals("snapshot-bucket", s3.getBucket()); + Assertions.assertEquals("arn:aws:iam::123456789012:role/snapshot-role", s3.getRoleArn()); + Assertions.assertEquals("snapshot-external-id", s3.getExternalId()); } @Test @@ -75,12 +75,12 @@ public void testOssStageBindingCarriesEveryField() { StorageAdapter adapter = ObjectInfoAdapter.toStorageAdapter(objectInfo); S3CompatibleFileSystemProperties oss = (S3CompatibleFileSystemProperties) adapter.getSpiProperties(); - Assert.assertEquals(StorageTypeId.OSS, adapter.getType()); - Assert.assertEquals("doris-regression-hk", oss.getBucket()); - Assert.assertEquals("oss-cn-hongkong-internal.aliyuncs.com", oss.getEndpoint()); - Assert.assertEquals("cn-hongkong", oss.getRegion()); - Assert.assertEquals("stage-ak", oss.getAccessKey()); - Assert.assertEquals("stage-sk", oss.getSecretKey()); - Assert.assertEquals("stage-token", oss.getSessionToken()); + Assertions.assertEquals(StorageTypeId.OSS, adapter.getType()); + Assertions.assertEquals("doris-regression-hk", oss.getBucket()); + Assertions.assertEquals("oss-cn-hongkong-internal.aliyuncs.com", oss.getEndpoint()); + Assertions.assertEquals("cn-hongkong", oss.getRegion()); + Assertions.assertEquals("stage-ak", oss.getAccessKey()); + Assertions.assertEquals("stage-sk", oss.getSecretKey()); + Assertions.assertEquals("stage-token", oss.getSessionToken()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/system/CloudSystemInfoServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/system/CloudSystemInfoServiceTest.java index 194bc6a8a59172..18734d8a1b0705 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/system/CloudSystemInfoServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/system/CloudSystemInfoServiceTest.java @@ -29,9 +29,9 @@ import org.apache.doris.resource.Tag; import org.apache.doris.system.Backend; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -42,7 +42,7 @@ public class CloudSystemInfoServiceTest { private CloudSystemInfoService infoService; - @Before + @BeforeEach public void setUp() { // Enable cloud mode for testing Config.cloud_unique_id = "test_cloud_unique_id"; @@ -55,7 +55,7 @@ public void testGetPhysicalClusterNotExist() { // not exist cluster String c1 = "not_exist_cluster_1"; String res = infoService.getPhysicalCluster(c1); - Assert.assertEquals(c1, res); + Assertions.assertEquals(c1, res); } @Test @@ -63,7 +63,7 @@ public void testGetPhysicalClusterPhysicalCluster() { infoService = new CloudSystemInfoService(); String c1 = "physical_cluster_1"; String res = infoService.getPhysicalCluster(c1); - Assert.assertEquals(c1, res); + Assertions.assertEquals(c1, res); } // virtual cluster does not contain physical cluster @@ -99,7 +99,7 @@ public void testGetPhysicalClusterEmptyCluster() { infoService.addComputeGroup(pcgName2, pcg2); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName1, res); + Assertions.assertEquals(pcgName1, res); } // active is empty cluster and standby has 3 alive be @@ -136,7 +136,7 @@ public void testGetPhysicalClusterStandbyAvailable() { infoService.updateCloudClusterMapNoLock(toAdd, new ArrayList<>()); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName2, res); + Assertions.assertEquals(pcgName2, res); } // active has 3 alive be and standby is empty cluster @@ -173,7 +173,7 @@ public void testGetPhysicalClusterActiveAvailable() { infoService.updateCloudClusterMapNoLock(toAdd, new ArrayList<>()); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName1, res); + Assertions.assertEquals(pcgName1, res); } // active has 3 alive be and standby has 3 dead be @@ -222,15 +222,15 @@ public void testGetPhysicalClusterActive3AliveBe() { infoService.updateCloudClusterMapNoLock(toAdd2, new ArrayList<>()); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName1, res); + Assertions.assertEquals(pcgName1, res); Backend activeBackend = toAdd1.get(1); - Assert.assertSame(activeBackend, + Assertions.assertSame(activeBackend, infoService.getBackendInCurrentCluster(pcgName1, activeBackend.getId())); - Assert.assertSame(activeBackend, + Assertions.assertSame(activeBackend, infoService.getBackendInCurrentCluster(vcgName, activeBackend.getId())); - Assert.assertNull(infoService.getBackendInCurrentCluster(vcgName, toAdd2.get(1).getId())); - Assert.assertNull(infoService.getBackendInCurrentCluster(vcgName, Long.MAX_VALUE)); + Assertions.assertNull(infoService.getBackendInCurrentCluster(vcgName, toAdd2.get(1).getId())); + Assertions.assertNull(infoService.getBackendInCurrentCluster(vcgName, Long.MAX_VALUE)); } // active has 3 dead be and standby has 3 alive be @@ -279,7 +279,7 @@ public void testGetPhysicalClusterStandby3AliveBe() { infoService.updateCloudClusterMapNoLock(toAdd2, new ArrayList<>()); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName2, res); + Assertions.assertEquals(pcgName2, res); } @Test @@ -314,8 +314,8 @@ public void testGetPhysicalClusterSwitchActiveStandbyMetric() throws Exception { toAdd2.add(b); } infoService.updateCloudClusterMapNoLock(toAdd2, new ArrayList<>()); - Assert.assertNull(infoService.getComputeGroupByName(pcgName1)); - Assert.assertTrue(infoService.isComputeGroupAvailable(pcgName2, policy.getUnhealthyNodeThresholdPercent())); + Assertions.assertNull(infoService.getComputeGroupByName(pcgName1)); + Assertions.assertTrue(infoService.isComputeGroupAvailable(pcgName2, policy.getUnhealthyNodeThresholdPercent())); CloudEnv cloudEnv = Mockito.mock(CloudEnv.class); Mockito.when(cloudEnv.getCloudInstanceId()).thenReturn("instance_id"); @@ -335,7 +335,7 @@ public void testGetPhysicalClusterSwitchActiveStandbyMetric() throws Exception { String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName2, res); + Assertions.assertEquals(pcgName2, res); mockedMetricRepo.verify(() -> MetricRepo.increaseVirtualComputeGroupSwitch(vcgId, vcgName, "id2", pcgName1, "id3", pcgName2)); } @@ -391,7 +391,7 @@ public void testGetPhysicalClusterActive1AliveBe2DeadBe() { infoService.updateCloudClusterMapNoLock(toAdd2, new ArrayList<>()); String res = infoService.getPhysicalCluster(vcgName); - Assert.assertEquals(pcgName1, res); + Assertions.assertEquals(pcgName1, res); } @Test @@ -418,13 +418,13 @@ public void testIsStandByComputeGroup() { infoService.addComputeGroup(pcgName3, pcg3); boolean res = infoService.isStandByComputeGroup(vcgName); - Assert.assertFalse(res); + Assertions.assertFalse(res); res = infoService.isStandByComputeGroup(pcgName1); - Assert.assertFalse(res); + Assertions.assertFalse(res); res = infoService.isStandByComputeGroup(pcgName2); - Assert.assertTrue(res); + Assertions.assertTrue(res); res = infoService.isStandByComputeGroup(pcgName3); - Assert.assertFalse(res); + Assertions.assertFalse(res); } // Test for getMinPipelineExecutorSize method @@ -444,7 +444,7 @@ public void testGetMinPipelineExecutorSizeWithEmptyCluster() { try { // Since there are no backends in the cluster, should return 1 int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(1, result); + Assertions.assertEquals(1, result); } finally { ConnectContext.remove(); } @@ -478,7 +478,7 @@ public void testGetMinPipelineExecutorSizeWithSingleBackend() { try { // Should return the pipeline executor size of the single backend int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(8, result); + Assertions.assertEquals(8, result); } finally { ConnectContext.remove(); } @@ -529,7 +529,7 @@ public void testGetMinPipelineExecutorSizeWithMultipleBackends() { try { // Should return the minimum pipeline executor size (6) int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(6, result); + Assertions.assertEquals(6, result); } finally { ConnectContext.remove(); } @@ -580,7 +580,7 @@ public void testGetMinPipelineExecutorSizeWithZeroSizeBackends() { try { // Should return the minimum positive pipeline executor size (4) int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(4, result); + Assertions.assertEquals(4, result); } finally { ConnectContext.remove(); } @@ -624,7 +624,7 @@ public void testGetMinPipelineExecutorSizeWithAllZeroSizeBackends() { // Should return 1 when no valid pipeline executor sizes are // found int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(1, result); + Assertions.assertEquals(1, result); } finally { ConnectContext.remove(); } @@ -640,7 +640,7 @@ public void testGetMinPipelineExecutorSizeWithNoClusterInContext() { try { // Should return 1 when no cluster is set in ConnectContext int result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(1, result); + Assertions.assertEquals(1, result); } finally { ConnectContext.remove(); } @@ -703,7 +703,7 @@ public void testGetMinPipelineExecutorSizeWithMixedValidInvalidBackends() { try { // Should return 8 (minimum valid size) int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(8, result); + Assertions.assertEquals(8, result); } finally { ConnectContext.remove(); } @@ -754,7 +754,7 @@ public void testGetMinPipelineExecutorSizeWithLargeValues() { try { // Should return 512 (minimum among large values) int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(512, result); + Assertions.assertEquals(512, result); } finally { ConnectContext.remove(); } @@ -790,7 +790,7 @@ public void testGetMinPipelineExecutorSizeConsistency() { try { // Should return 32 (consistent across all backends) int result = infoService.getMinPipelineExecutorSize(clusterName); - Assert.assertEquals(32, result); + Assertions.assertEquals(32, result); } finally { ConnectContext.remove(); } @@ -861,7 +861,7 @@ public void testGetMinPipelineExecutorSizeWithMultipleComputeGroups() { try { // Should return 8 (minimum from current cluster2), not 2 (global minimum from cluster1) int result = infoService.getMinPipelineExecutorSize(cluster2Name); - Assert.assertEquals(8, result); + Assertions.assertEquals(8, result); } finally { ConnectContext.remove(); } @@ -935,14 +935,14 @@ public void testGetMinPipelineExecutorSizeWithVirtualComputeGroup() { // Should return 32 (minimum from virtual cluster's physical cluster), not 8 // (from other cluster) int result = infoService.getMinPipelineExecutorSize(virtualClusterName); - Assert.assertEquals(32, result); + Assertions.assertEquals(32, result); // Switch to other cluster ctx.setCloudCluster(otherClusterName); // Should return 8 (from other cluster) result = infoService.getMinPipelineExecutorSize(otherClusterName); - Assert.assertEquals(8, result); + Assertions.assertEquals(8, result); } finally { // Clean up ConnectContext @@ -960,7 +960,7 @@ public void testGetMinPipelineExecutorSizeWithConnectContextNoCluster() { try { // Should return 1 because no cluster is set (will catch AnalysisException) int result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(1, result); + Assertions.assertEquals(1, result); } finally { // Clean up ConnectContext @@ -1033,14 +1033,14 @@ public void testGetMinPipelineExecutorSizeWithConnectContext() { try { // Should return 2 (minimum from cluster1), not 16 (minimum from cluster2) int result = infoService.getMinPipelineExecutorSize(cluster1Name); - Assert.assertEquals(2, result); + Assertions.assertEquals(2, result); // Now switch to cluster2 ctx.setCloudCluster(cluster2Name); // Should return 16 (minimum from cluster2), not 2 (minimum from cluster1) result = infoService.getMinPipelineExecutorSize(cluster2Name); - Assert.assertEquals(16, result); + Assertions.assertEquals(16, result); } finally { // Clean up ConnectContext ConnectContext.remove(); @@ -1051,15 +1051,15 @@ public void testGetMinPipelineExecutorSizeWithConnectContext() { public void testContainsCloudCluster() { infoService = new CloudSystemInfoService(); // Empty / null inputs short-circuit without touching the map. - Assert.assertFalse(infoService.containsCloudCluster(null)); - Assert.assertFalse(infoService.containsCloudCluster("")); + Assertions.assertFalse(infoService.containsCloudCluster(null)); + Assertions.assertFalse(infoService.containsCloudCluster("")); // Unknown cluster name -> false. - Assert.assertFalse(infoService.containsCloudCluster("absent_cluster")); + Assertions.assertFalse(infoService.containsCloudCluster("absent_cluster")); // Register a cluster; lookup must hit. infoService.addVirtualClusterInfoToMapsNoLock("cid_1", "cluster_1"); - Assert.assertTrue(infoService.containsCloudCluster("cluster_1")); + Assertions.assertTrue(infoService.containsCloudCluster("cluster_1")); // Different name in same map -> still false. - Assert.assertFalse(infoService.containsCloudCluster("cluster_2")); + Assertions.assertFalse(infoService.containsCloudCluster("cluster_2")); } /** diff --git a/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java index 66a25dab02a71c..a4dcf4d04614ea 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cloud/transaction/CloudGlobalTransactionMgrTest.java @@ -46,11 +46,10 @@ import org.apache.doris.transaction.TxnStateChangeCallback; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -71,7 +70,7 @@ public class CloudGlobalTransactionMgrTest { private TransactionState.TxnCoordinator transactionSource = new TransactionState.TxnCoordinator( TransactionState.TxnSourceType.FE, 0, "localfe", System.currentTimeMillis()); - @Before + @BeforeEach public void setUp() throws Exception { Config.cloud_unique_id = "cloud_unique_id"; @@ -83,7 +82,7 @@ public void setUp() throws Exception { masterTransMgr = masterEnv.getGlobalTransactionMgr(); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -111,7 +110,7 @@ public void testBeginTransaction() throws Exception { transactionSource, TransactionState.LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); - Assert.assertEquals(transactionId + 1, id.get()); + Assertions.assertEquals(transactionId + 1, id.get()); } } @@ -140,7 +139,7 @@ public void testBeginTransactionConflict() throws Exception { transactionSource, TransactionState.LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); - Assert.assertEquals(transactionId + 1, id.get()); + Assertions.assertEquals(transactionId + 1, id.get()); } } @@ -271,14 +270,14 @@ public void testCommitTransactionCarriesTableStreamUpdates() throws Exception { ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Cloud.CommitTxnRequest.class); Mockito.verify(mockProxy).commitTxn(requestCaptor.capture()); - Assert.assertTrue(requestCaptor.getValue().hasCommitTso()); - Assert.assertEquals(2, requestCaptor.getValue().getTableStreamUpdatesCount()); - Assert.assertEquals(identity, requestCaptor.getValue().getTableStreamUpdates(0).getIdentity()); - Assert.assertEquals(partitionUpdate, + Assertions.assertTrue(requestCaptor.getValue().hasCommitTso()); + Assertions.assertEquals(2, requestCaptor.getValue().getTableStreamUpdatesCount()); + Assertions.assertEquals(identity, requestCaptor.getValue().getTableStreamUpdates(0).getIdentity()); + Assertions.assertEquals(partitionUpdate, requestCaptor.getValue().getTableStreamUpdates(0).getPartitionUpdates(0)); - Assert.assertEquals(secondIdentity, + Assertions.assertEquals(secondIdentity, requestCaptor.getValue().getTableStreamUpdates(1).getIdentity()); - Assert.assertEquals(secondPartitionUpdate, + Assertions.assertEquals(secondPartitionUpdate, requestCaptor.getValue().getTableStreamUpdates(1).getPartitionUpdates(0)); } } @@ -291,7 +290,7 @@ public void testSkipMakeTmpRsVisibleForIncompleteLazyCommit() throws Exception { .setIsLazyCommitIncomplete(true) .build(); - Assert.assertFalse(invokeNotifyBesMakeTmpRsVisible(response)); + Assertions.assertFalse(invokeNotifyBesMakeTmpRsVisible(response)); } @Test @@ -302,7 +301,7 @@ public void testMakeTmpRsVisibleForNonLazyCommitWithIncompleteFlag() throws Exce .setIsLazyCommitIncomplete(true) .build(); - Assert.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); + Assertions.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); } @Test @@ -313,7 +312,7 @@ public void testMakeTmpRsVisibleForCompletedLazyCommit() throws Exception { .setIsLazyCommitIncomplete(false) .build(); - Assert.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); + Assertions.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); } @Test @@ -324,7 +323,7 @@ public void testMakeTmpRsVisibleForNonLazyCommit() throws Exception { .setIsLazyCommitIncomplete(false) .build(); - Assert.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); + Assertions.assertTrue(invokeNotifyBesMakeTmpRsVisible(response)); } private boolean invokeNotifyBesMakeTmpRsVisible(CommitTxnResponse response) throws Exception { @@ -480,8 +479,8 @@ public void testAbortRoutineLoadTransactionWithAttachment() throws Exception { mockedStatic.when(MetaServiceProxy::getInstance).thenReturn(mockProxy); Mockito.doAnswer(invocation -> { Cloud.AbortTxnRequest request = invocation.getArgument(0); - Assert.assertTrue(request.hasCommitAttachment()); - Assert.assertEquals("invalid source row", request.getCommitAttachment() + Assertions.assertTrue(request.hasCommitAttachment()); + Assertions.assertEquals("invalid source row", request.getCommitAttachment() .getRlTaskTxnCommitAttachment().getFirstErrorMsg()); return AbortTxnResponse.newBuilder() .setStatus(Cloud.MetaServiceResponseStatus.newBuilder() @@ -501,7 +500,7 @@ public void testAbortRoutineLoadTransactionWithAttachment() throws Exception { Mockito.eq("data quality error")); RLTaskTxnCommitAttachment callbackAttachment = (RLTaskTxnCommitAttachment) txnStateCaptor.getValue().getTxnCommitAttachment(); - Assert.assertEquals("invalid source row", callbackAttachment.getFirstErrorMsg()); + Assertions.assertEquals("invalid source row", callbackAttachment.getFirstErrorMsg()); } finally { masterTransMgr.getCallbackFactory().removeCallback(jobId); } @@ -587,7 +586,7 @@ public void testIsPreviousTransactionsFinished() throws Exception { Mockito.doReturn(response).when(mockProxy).checkTxnConflict(Mockito.any()); boolean result = masterTransMgr.isPreviousTransactionsFinished(12131231, CatalogTestUtil.testDbId1, Lists.newArrayList(CatalogTestUtil.testTableId1)); - Assert.assertEquals(result, true); + Assertions.assertEquals(result, true); } } @@ -604,7 +603,7 @@ public void testIsPreviousTransactionsFinishedException() throws Exception { Mockito.doReturn(response).when(mockProxy).checkTxnConflict(Mockito.any()); boolean result = masterTransMgr.isPreviousTransactionsFinished(12131231, CatalogTestUtil.testDbId1, Lists.newArrayList(CatalogTestUtil.testTableId1)); - Assert.assertEquals(result, false); + Assertions.assertEquals(result, false); } } @@ -620,7 +619,7 @@ public void testGetNextTransactionId() throws Exception { .build(); Mockito.doReturn(response).when(mockProxy).getCurrentMaxTxnId(Mockito.any()); long result = masterTransMgr.getNextTransactionId(); - Assert.assertEquals(1000, result); + Assertions.assertEquals(1000, result); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardExceptionTest.java b/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardExceptionTest.java index efc95f6cc10fb8..0eb1ab242eb0f1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardExceptionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardExceptionTest.java @@ -17,24 +17,24 @@ package org.apache.doris.cluster; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ClusterGuardExceptionTest { @Test public void testMessageConstructor() { ClusterGuardException ex = new ClusterGuardException("policy violated"); - Assert.assertEquals("policy violated", ex.getMessage()); - Assert.assertNull(ex.getCause()); + Assertions.assertEquals("policy violated", ex.getMessage()); + Assertions.assertNull(ex.getCause()); } @Test public void testMessageAndCauseConstructor() { RuntimeException cause = new RuntimeException("root cause"); ClusterGuardException ex = new ClusterGuardException("wrapped", cause); - Assert.assertEquals("wrapped", ex.getMessage()); - Assert.assertSame(cause, ex.getCause()); + Assertions.assertEquals("wrapped", ex.getMessage()); + Assertions.assertSame(cause, ex.getCause()); } @Test @@ -42,7 +42,7 @@ public void testIsCheckedException() { // ClusterGuardException must be a checked exception (extends Exception, not RuntimeException). // Cast to Object first so the compiler does not reject the instanceof check as always-false. Object ex = new ClusterGuardException("test"); - Assert.assertTrue(ex instanceof Exception); - Assert.assertFalse(ex instanceof RuntimeException); + Assertions.assertTrue(ex instanceof Exception); + Assertions.assertFalse(ex instanceof RuntimeException); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardFactoryTest.java index 7726fbf0a2de2f..4f456462174c36 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardFactoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cluster/ClusterGuardFactoryTest.java @@ -17,10 +17,10 @@ package org.apache.doris.cluster; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -57,14 +57,14 @@ public class ClusterGuardFactoryTest { private Field instanceField; - @Before + @BeforeEach public void setUp() throws Exception { instanceField = ClusterGuardFactory.class.getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, null); // reset singleton } - @After + @AfterEach public void tearDown() throws Exception { instanceField.set(null, null); // clean up after each test } @@ -82,7 +82,7 @@ public void tearDown() throws Exception { public void testNoSentinelNoImpl_returnsNoOp() { ClassLoader cl = new SentinelClassLoader(false, false); ClusterGuard guard = ClusterGuardFactory.loadGuard(cl); - Assert.assertSame(NoOpClusterGuard.INSTANCE, guard); + Assertions.assertSame(NoOpClusterGuard.INSTANCE, guard); } /** @@ -97,10 +97,8 @@ public void testNoSentinelNoImpl_returnsNoOp() { public void testNoSentinelWithImpl_returnsImpl() { ClassLoader cl = new SentinelClassLoader(false, true); ClusterGuard guard = ClusterGuardFactory.loadGuard(cl); - Assert.assertTrue( - "Expected a StubClusterGuard instance, got: " + guard.getClass(), - guard instanceof StubClusterGuard); - Assert.assertNotSame(NoOpClusterGuard.INSTANCE, guard); + Assertions.assertTrue(guard instanceof StubClusterGuard, "Expected a StubClusterGuard instance, got: " + guard.getClass()); + Assertions.assertNotSame(NoOpClusterGuard.INSTANCE, guard); } /** @@ -115,10 +113,8 @@ public void testNoSentinelWithImpl_returnsImpl() { public void testSentinelPresentWithImpl_returnsImpl() { ClassLoader cl = new SentinelClassLoader(true, true); ClusterGuard guard = ClusterGuardFactory.loadGuard(cl); - Assert.assertTrue( - "Expected a StubClusterGuard instance, got: " + guard.getClass(), - guard instanceof StubClusterGuard); - Assert.assertNotSame(NoOpClusterGuard.INSTANCE, guard); + Assertions.assertTrue(guard instanceof StubClusterGuard, "Expected a StubClusterGuard instance, got: " + guard.getClass()); + Assertions.assertNotSame(NoOpClusterGuard.INSTANCE, guard); } /** @@ -131,11 +127,9 @@ public void testSentinelPresentNoImpl_throwsRuntimeException() { ClassLoader cl = new SentinelClassLoader(true, false); try { ClusterGuardFactory.loadGuard(cl); - Assert.fail("Expected RuntimeException when sentinel is present but no impl found"); + Assertions.fail("Expected RuntimeException when sentinel is present but no impl found"); } catch (RuntimeException e) { - Assert.assertTrue( - "Error message should mention ClusterGuard", - e.getMessage().contains("ClusterGuard")); + Assertions.assertTrue(e.getMessage().contains("ClusterGuard"), "Error message should mention ClusterGuard"); } } @@ -146,14 +140,14 @@ public void testSentinelPresentNoImpl_throwsRuntimeException() { @Test public void testGetGuardReturnsNonNull() { ClusterGuard guard = ClusterGuardFactory.getGuard(); - Assert.assertNotNull(guard); + Assertions.assertNotNull(guard); } @Test public void testGetGuardReturnsSameInstance() { ClusterGuard first = ClusterGuardFactory.getGuard(); ClusterGuard second = ClusterGuardFactory.getGuard(); - Assert.assertSame(first, second); + Assertions.assertSame(first, second); } @Test @@ -161,7 +155,7 @@ public void testGetGuardReturnsNoOpWhenNoSpiProviderFound() { // In the test classpath there is no META-INF/services/org.apache.doris.cluster.ClusterGuard // and no sentinel file, so the factory must fall back to NoOpClusterGuard. ClusterGuard guard = ClusterGuardFactory.getGuard(); - Assert.assertSame(NoOpClusterGuard.INSTANCE, guard); + Assertions.assertSame(NoOpClusterGuard.INSTANCE, guard); } // ----------------------------------------------------------------------- @@ -185,7 +179,7 @@ public void testNoOpGuardTimeValidityAlwaysPasses() throws ClusterGuardException @Test public void testNoOpGuardInfoIsEmptyJson() { ClusterGuard guard = ClusterGuardFactory.getGuard(); - Assert.assertEquals("{}", guard.getGuardInfo()); + Assertions.assertEquals("{}", guard.getGuardInfo()); } // ----------------------------------------------------------------------- @@ -198,8 +192,8 @@ public void testCustomGuardIsReturnedWhenInjected() throws Exception { instanceField.set(null, custom); ClusterGuard guard = ClusterGuardFactory.getGuard(); - Assert.assertSame(custom, guard); - Assert.assertEquals("custom-info", guard.getGuardInfo()); + Assertions.assertSame(custom, guard); + Assertions.assertEquals("custom-info", guard.getGuardInfo()); } @Test @@ -221,9 +215,9 @@ public void checkNodeLimit(int currentNodeCount) throws ClusterGuardException { try { guard.checkNodeLimit(4); - Assert.fail("Expected ClusterGuardException"); + Assertions.fail("Expected ClusterGuardException"); } catch (ClusterGuardException e) { - Assert.assertTrue(e.getMessage().contains("Node limit exceeded")); + Assertions.assertTrue(e.getMessage().contains("Node limit exceeded")); } } @@ -239,9 +233,9 @@ public void onStartup(String dorisHomeDir) throws ClusterGuardException { try { ClusterGuardFactory.getGuard().onStartup("/doris/home"); - Assert.fail("Expected ClusterGuardException"); + Assertions.fail("Expected ClusterGuardException"); } catch (ClusterGuardException e) { - Assert.assertEquals("startup failed", e.getMessage()); + Assertions.assertEquals("startup failed", e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cluster/NoOpClusterGuardTest.java b/fe/fe-core/src/test/java/org/apache/doris/cluster/NoOpClusterGuardTest.java index 15a1b89d2b82e6..9f29f9542f9087 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cluster/NoOpClusterGuardTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cluster/NoOpClusterGuardTest.java @@ -17,8 +17,8 @@ package org.apache.doris.cluster; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class NoOpClusterGuardTest { @@ -45,11 +45,11 @@ public void testCheckNodeLimitDoesNotThrow() throws ClusterGuardException { @Test public void testGetGuardInfoReturnsEmptyJson() { String info = NoOpClusterGuard.INSTANCE.getGuardInfo(); - Assert.assertEquals("{}", info); + Assertions.assertEquals("{}", info); } @Test public void testSingletonIdentity() { - Assert.assertSame(NoOpClusterGuard.INSTANCE, NoOpClusterGuard.INSTANCE); + Assertions.assertSame(NoOpClusterGuard.INSTANCE, NoOpClusterGuard.INSTANCE); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cluster/SystemInfoServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/cluster/SystemInfoServiceTest.java index 431d830b44fa6c..1ed86c6b254432 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cluster/SystemInfoServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cluster/SystemInfoServiceTest.java @@ -37,10 +37,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -67,7 +67,7 @@ public class SystemInfoServiceTest { private long backendId = 10000L; - @Before + @BeforeEach public void setUp() throws IOException { mockedEnvStatic = Mockito.mockStatic(Env.class); @@ -87,7 +87,7 @@ public void setUp() throws IOException { mockedEnvStatic.when(Env::getCurrentEnvJournalVersion).thenReturn(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -149,16 +149,20 @@ public void clearAllBackend() { Env.getCurrentSystemInfo().dropAllBackend(); } - @Test(expected = AnalysisException.class) + @Test public void validHostAndPortTest1() throws Exception { - createHostAndPort(1); - systemInfoService.validateHostAndPort(hostPort); + Assertions.assertThrows(AnalysisException.class, () -> { + createHostAndPort(1); + systemInfoService.validateHostAndPort(hostPort); + }); } - @Test(expected = AnalysisException.class) + @Test public void validHostAndPortTest3() throws Exception { - createHostAndPort(3); - systemInfoService.validateHostAndPort(hostPort); + Assertions.assertThrows(AnalysisException.class, () -> { + createHostAndPort(3); + systemInfoService.validateHostAndPort(hostPort); + }); } @Test @@ -175,25 +179,25 @@ public void addBackendTest() throws UserException { try { Env.getCurrentSystemInfo().addBackends(op.getHostInfos(), true); } catch (DdlException e) { - Assert.fail(); + Assertions.fail(); } try { Env.getCurrentSystemInfo().addBackends(op.getHostInfos(), true); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("already exists")); + Assertions.assertTrue(e.getMessage().contains("already exists")); } - Assert.assertNotNull(Env.getCurrentSystemInfo().getBackend(backendId)); - Assert.assertNotNull(Env.getCurrentSystemInfo().getBackendWithHeartbeatPort("192.168.0.1", 1234)); + Assertions.assertNotNull(Env.getCurrentSystemInfo().getBackend(backendId)); + Assertions.assertNotNull(Env.getCurrentSystemInfo().getBackendWithHeartbeatPort("192.168.0.1", 1234)); - Assert.assertTrue(Env.getCurrentSystemInfo().getAllBackendIds(false).size() == 1); - Assert.assertTrue(Env.getCurrentSystemInfo().getAllBackendIds(false).get(0) == backendId); + Assertions.assertTrue(Env.getCurrentSystemInfo().getAllBackendIds(false).size() == 1); + Assertions.assertTrue(Env.getCurrentSystemInfo().getAllBackendIds(false).get(0) == backendId); - Assert.assertTrue(Env.getCurrentSystemInfo().getBackendReportVersion(backendId) == 0L); + Assertions.assertTrue(Env.getCurrentSystemInfo().getBackendReportVersion(backendId) == 0L); Env.getCurrentSystemInfo().updateBackendReportVersion(backendId, 2L, 20000L, 30000L, true); - Assert.assertTrue(Env.getCurrentSystemInfo().getBackendReportVersion(backendId) == 2L); + Assertions.assertTrue(Env.getCurrentSystemInfo().getBackendReportVersion(backendId) == 2L); } @Test @@ -213,13 +217,13 @@ public void removeBackendTest() throws UserException { Env.getCurrentSystemInfo().dropBackends(dropBackendOp.getHostInfos()); } catch (DdlException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } try { Env.getCurrentSystemInfo().dropBackends(dropBackendOp.getHostInfos()); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("does not exist")); + Assertions.assertTrue(e.getMessage().contains("does not exist")); } } @@ -240,13 +244,13 @@ public void removeBackendTestByBackendId() throws UserException { Env.getCurrentSystemInfo().dropBackends(dropBackendOp.getHostInfos()); } catch (DdlException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } try { Env.getCurrentSystemInfo().dropBackends(dropBackendOp.getHostInfos()); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("does not exist")); + Assertions.assertTrue(e.getMessage().contains("does not exist")); } } @@ -269,10 +273,10 @@ public void testSaveLoadBackend() throws Exception { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); long checksum2 = systemInfoService.loadBackends(dis, 0); - Assert.assertEquals(checksum1, checksum2); - Assert.assertEquals(1, systemInfoService.getAllBackendsByAllCluster().size()); + Assertions.assertEquals(checksum1, checksum2); + Assertions.assertEquals(1, systemInfoService.getAllBackendsByAllCluster().size()); Backend back2 = systemInfoService.getBackend(1); - Assert.assertEquals(back1, back2); + Assertions.assertEquals(back1, back2); dis.close(); deleteDir(dir); diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/CidrTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/CidrTest.java index e8c3d3bede4d88..c52016733aad20 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/CidrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/CidrTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class CidrTest { @Test @@ -27,27 +27,27 @@ public void testWrongFormat() { try { new CIDR("192.168.17.0/"); // should not be here - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e instanceof IllegalArgumentException); } // mask is too big try { new CIDR("192.168.17.0/88"); // should not be here - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e instanceof IllegalArgumentException); } // ip is too short try { new CIDR("192.168./88"); // should not be here - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e instanceof IllegalArgumentException); } } @@ -55,26 +55,26 @@ public void testWrongFormat() { public void testNormal() throws Exception { // the real value is 10.1.16.0/20 CIDR cidr = new CIDR("192.168.17.0/20"); - Assert.assertEquals("192.168.17.0", cidr.getIP()); + Assertions.assertEquals("192.168.17.0", cidr.getIP()); } @Test public void testContain() { CIDR cidrV4 = new CIDR("192.168.17.0/16"); - Assert.assertTrue(cidrV4.contains("192.168.88.88")); - Assert.assertFalse(cidrV4.contains("192.2.88.88")); + Assertions.assertTrue(cidrV4.contains("192.168.88.88")); + Assertions.assertFalse(cidrV4.contains("192.2.88.88")); CIDR cidr2V4 = new CIDR("192.168.17.0/20"); - Assert.assertTrue(cidr2V4.contains("192.168.31.1")); - Assert.assertFalse(cidr2V4.contains("192.168.32.1")); + Assertions.assertTrue(cidr2V4.contains("192.168.31.1")); + Assertions.assertFalse(cidr2V4.contains("192.168.32.1")); CIDR cidrV6 = new CIDR("fdbd:ff1:ce00:1c26::d8/64"); - Assert.assertTrue(cidrV6.contains("fdbd:ff1:ce00:1c26::d8")); - Assert.assertTrue(cidrV6.contains("fdbd:ff1:ce00:1c26::12:234b:def8")); - Assert.assertFalse(cidrV6.contains("fdbd:ff1:ce00:1c27::12:234b:def8")); + Assertions.assertTrue(cidrV6.contains("fdbd:ff1:ce00:1c26::d8")); + Assertions.assertTrue(cidrV6.contains("fdbd:ff1:ce00:1c26::12:234b:def8")); + Assertions.assertFalse(cidrV6.contains("fdbd:ff1:ce00:1c27::12:234b:def8")); CIDR cidr2V6 = new CIDR("fdbd:ff1:ce00:1c26:1000::d8/68"); - Assert.assertTrue(cidr2V6.contains("fdbd:ff1:ce00:1c26:1a3f:12:234b:def8")); - Assert.assertFalse(cidr2V6.contains("fdbd:ff1:ce00:1c26::d8")); + Assertions.assertTrue(cidr2V6.contains("fdbd:ff1:ce00:1c26:1a3f:12:234b:def8")); + Assertions.assertFalse(cidr2V6.contains("fdbd:ff1:ce00:1c26::d8")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/CommandLineOptionsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/CommandLineOptionsTest.java index 8575da58ca406c..c6e85cefa55091 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/CommandLineOptionsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/CommandLineOptionsTest.java @@ -19,27 +19,27 @@ import org.apache.doris.journal.bdbje.BDBToolOptions; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class CommandLineOptionsTest { @Test public void test() { CommandLineOptions options = new CommandLineOptions(true, "", null, ""); - Assert.assertTrue(options.isVersion()); - Assert.assertFalse(options.runBdbTools()); - Assert.assertFalse(options.runImageTool()); + Assertions.assertTrue(options.isVersion()); + Assertions.assertFalse(options.runBdbTools()); + Assertions.assertFalse(options.runImageTool()); options = new CommandLineOptions(false, "", new BDBToolOptions(true, "", false, "", "", 0), ""); - Assert.assertFalse(options.isVersion()); - Assert.assertTrue(options.runBdbTools()); - Assert.assertFalse(options.runImageTool()); + Assertions.assertFalse(options.isVersion()); + Assertions.assertTrue(options.runBdbTools()); + Assertions.assertFalse(options.runImageTool()); options = new CommandLineOptions(false, "", null, "image.0"); - Assert.assertFalse(options.isVersion()); - Assert.assertFalse(options.runBdbTools()); - Assert.assertTrue(options.runImageTool()); + Assertions.assertFalse(options.isVersion()); + Assertions.assertFalse(options.runBdbTools()); + Assertions.assertTrue(options.runImageTool()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/DNSCacheTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/DNSCacheTest.java index 6d2afa59d9a761..31c3b0a0f66f46 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/DNSCacheTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/DNSCacheTest.java @@ -19,10 +19,10 @@ import org.apache.doris.common.util.NetUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -37,7 +37,7 @@ public class DNSCacheTest { private MockedStatic netUtilsMockedStatic; private boolean originalFqdnMode; - @Before + @BeforeEach public void setUp() { // Save original config originalFqdnMode = Config.enable_fqdn_mode; @@ -49,7 +49,7 @@ public void setUp() { netUtilsMockedStatic = Mockito.mockStatic(NetUtils.class); } - @After + @AfterEach public void tearDown() { // Restore original config Config.enable_fqdn_mode = originalFqdnMode; @@ -74,11 +74,11 @@ public void testGetResolvesAndCachesHostname() throws UnknownHostException { // First call - should resolve and cache String ip1 = dnsCache.get(hostname); - Assert.assertEquals(expectedIp, ip1); + Assertions.assertEquals(expectedIp, ip1); // Second call - should return cached value without calling NetUtils again String ip2 = dnsCache.get(hostname); - Assert.assertEquals(expectedIp, ip2); + Assertions.assertEquals(expectedIp, ip2); // Verify NetUtils.getIpByHost was called only once (cached on subsequent calls) netUtilsMockedStatic.verify(() -> NetUtils.getIpByHost(hostname, 0), Mockito.times(1)); @@ -97,11 +97,11 @@ public void testGetReturnsEmptyStringOnResolutionFailure() throws UnknownHostExc // Should return empty string instead of throwing exception String ip = dnsCache.get(hostname); - Assert.assertEquals("", ip); + Assertions.assertEquals("", ip); // Verify the result is cached (subsequent calls don't resolve again) String ip2 = dnsCache.get(hostname); - Assert.assertEquals("", ip2); + Assertions.assertEquals("", ip2); // Should only attempt resolution once netUtilsMockedStatic.verify(() -> NetUtils.getIpByHost(hostname, 0), Mockito.times(1)); @@ -128,8 +128,8 @@ public void testMultipleHostnamesCached() throws UnknownHostException { String result2 = dnsCache.get(hostname2); // Verify both are cached correctly - Assert.assertEquals(ip1, result1); - Assert.assertEquals(ip2, result2); + Assertions.assertEquals(ip1, result1); + Assertions.assertEquals(ip2, result2); // Verify each was resolved once netUtilsMockedStatic.verify(() -> NetUtils.getIpByHost(hostname1, 0), Mockito.times(1)); @@ -150,8 +150,7 @@ public void testLocalhostResolution() { String ip = realDnsCache.get("localhost"); // localhost should resolve to 127.0.0.1 or ::1 - Assert.assertTrue("localhost should resolve to an IP", - ip.equals("127.0.0.1") || ip.contains(":")); + Assertions.assertTrue(ip.equals("127.0.0.1") || ip.contains(":"), "localhost should resolve to an IP"); } /** @@ -168,7 +167,7 @@ public void testIpAddressInput() throws UnknownHostException { String result = dnsCache.get(ipAddress); - Assert.assertEquals(ipAddress, result); + Assertions.assertEquals(ipAddress, result); } /** @@ -186,7 +185,7 @@ public void testStartWithFqdnModeEnabled() { cache.start(); // Verify it completes successfully - Assert.assertNotNull(cache); + Assertions.assertNotNull(cache); } /** @@ -202,7 +201,7 @@ public void testStartWithFqdnModeDisabled() { cache.start(); // Verify it completes successfully - Assert.assertNotNull(cache); + Assertions.assertNotNull(cache); } /** @@ -219,7 +218,7 @@ public void testConcurrentAccess() throws InterruptedException, UnknownHostExcep // Pre-populate the cache by calling get() once before concurrent access // This ensures the cache is initialized and subsequent calls will hit the cache String initialIp = dnsCache.get(hostname); - Assert.assertEquals(expectedIp, initialIp); + Assertions.assertEquals(expectedIp, initialIp); int threadCount = 10; Thread[] threads = new Thread[threadCount]; @@ -228,7 +227,7 @@ public void testConcurrentAccess() throws InterruptedException, UnknownHostExcep for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(() -> { String ip = dnsCache.get(hostname); - Assert.assertEquals(expectedIp, ip); + Assertions.assertEquals(expectedIp, ip); }); } @@ -284,11 +283,11 @@ public void testConcurrentAccessWithRealDns() throws InterruptedException { // All threads should get the same result String expectedResult = results[0]; - Assert.assertNotNull("Result should not be null", expectedResult); - Assert.assertFalse("Result should not be empty", expectedResult.isEmpty()); + Assertions.assertNotNull(expectedResult, "Result should not be null"); + Assertions.assertFalse(expectedResult.isEmpty(), "Result should not be empty"); for (int i = 1; i < threadCount; i++) { - Assert.assertEquals("All threads should get the same result", expectedResult, results[i]); + Assertions.assertEquals(expectedResult, results[i], "All threads should get the same result"); } } @@ -307,7 +306,7 @@ public void testRefreshKeepsCachedIpOnResolutionFailure() throws Exception { // Populate the cache String ip = dnsCache.get(hostname); - Assert.assertEquals(cachedIp, ip); + Assertions.assertEquals(cachedIp, ip); // Now mock resolution failure netUtilsMockedStatic.when(() -> NetUtils.getIpByHost(hostname, 0)) @@ -320,7 +319,7 @@ public void testRefreshKeepsCachedIpOnResolutionFailure() throws Exception { // The cached IP should remain unchanged after refresh failure String ipAfterRefresh = dnsCache.get(hostname); - Assert.assertEquals("Cached IP should remain unchanged after refresh failure", cachedIp, ipAfterRefresh); + Assertions.assertEquals(cachedIp, ipAfterRefresh, "Cached IP should remain unchanged after refresh failure"); } /** @@ -338,7 +337,7 @@ public void testRefreshUpdatesCachedIpOnSuccess() throws Exception { // Populate the cache String ip = dnsCache.get(hostname); - Assert.assertEquals(originalIp, ip); + Assertions.assertEquals(originalIp, ip); // Now mock resolution with new IP netUtilsMockedStatic.when(() -> NetUtils.getIpByHost(hostname, 0)) @@ -351,6 +350,6 @@ public void testRefreshUpdatesCachedIpOnSuccess() throws Exception { // The cached IP should be updated to the new IP String ipAfterRefresh = dnsCache.get(hostname); - Assert.assertEquals("Cached IP should be updated after successful refresh", newIp, ipAfterRefresh); + Assertions.assertEquals(newIp, ipAfterRefresh, "Cached IP should be updated after successful refresh"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/ExceptionChecker.java b/fe/fe-core/src/test/java/org/apache/doris/common/ExceptionChecker.java index 5353cfd0274736..d4cdb4c3c320a7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/ExceptionChecker.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/ExceptionChecker.java @@ -18,7 +18,6 @@ package org.apache.doris.common; import com.google.common.base.Strings; -import junit.framework.AssertionFailedError; public class ExceptionChecker { @@ -35,7 +34,7 @@ public static void expectThrowsNoException(ThrowingRunnable runnable) { runnable.run(); } catch (Throwable e) { e.printStackTrace(); - throw new AssertionFailedError(e.getMessage()); + throw new AssertionError(e.getMessage()); } } @@ -70,7 +69,7 @@ public static T expectThrows(Class expectedType, String if (expectedType.isInstance(e)) { if (!Strings.isNullOrEmpty(exceptionMsg)) { if (!e.getMessage().contains(exceptionMsg)) { - AssertionFailedError assertion = new AssertionFailedError( + AssertionError assertion = new AssertionError( "expected msg: " + exceptionMsg + ", actual: " + e.getMessage()); assertion.initCause(e); assertion.printStackTrace(); @@ -79,11 +78,11 @@ public static T expectThrows(Class expectedType, String } return expectedType.cast(e); } - AssertionFailedError assertion = new AssertionFailedError( + AssertionError assertion = new AssertionError( "Unexpected exception type, expected " + expectedType.getSimpleName() + " but got " + e); assertion.initCause(e); throw assertion; } - throw new AssertionFailedError(noExceptionMessage); + throw new AssertionError(noExceptionMessage); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/GenericPoolTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/GenericPoolTest.java index f02dc7f6d7b8ce..6c6d7956a758ca 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/GenericPoolTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/GenericPoolTest.java @@ -62,10 +62,10 @@ import org.apache.thrift.TException; import org.apache.thrift.TProcessor; import org.apache.thrift.transport.TSocket; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; @@ -86,7 +86,7 @@ static void close() { } } - @BeforeClass + @BeforeAll public static void beforeClass() throws IOException { try { GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); @@ -110,7 +110,7 @@ public static void beforeClass() throws IOException { } } - @AfterClass + @AfterAll public static void afterClass() throws IOException { close(); } @@ -282,15 +282,15 @@ public void testSetMaxPerKey() throws Exception { flag = true; // pass } catch (Exception e) { - Assert.fail(); + Assertions.fail(); } - Assert.assertTrue(flag); + Assertions.assertTrue(flag); // fourth success, because we drop the object1 backendService.returnObject(address, object1); object3 = null; object3 = backendService.borrowObject(address); - Assert.assertTrue(object3 != null); + Assertions.assertTrue(object3 != null); backendService.returnObject(address, object2); backendService.returnObject(address, object3); @@ -304,15 +304,15 @@ public void testReopenSetsShortTimeoutBeforeOpen() throws Exception { // Verify the high timeout is set TSocket socket = (TSocket) client.getOutputProtocol().getTransport(); - Assert.assertTrue(socket.isOpen()); + Assertions.assertTrue(socket.isOpen()); // reopen should succeed and restore the provided timeout int savedConnectTimeout = Config.thrift_rpc_connect_timeout_ms; Config.thrift_rpc_connect_timeout_ms = 5000; try { boolean ok = backendService.reopen(client, 60000); - Assert.assertTrue(ok); - Assert.assertTrue(client.getOutputProtocol().getTransport().isOpen()); + Assertions.assertTrue(ok); + Assertions.assertTrue(client.getOutputProtocol().getTransport().isOpen()); } finally { Config.thrift_rpc_connect_timeout_ms = savedConnectTimeout; } @@ -329,8 +329,8 @@ public void testReopenNoArgRestoresPoolDefaultTimeout() throws Exception { Config.thrift_rpc_connect_timeout_ms = 5000; try { boolean ok = backendService.reopen(client); - Assert.assertTrue(ok); - Assert.assertTrue(client.getOutputProtocol().getTransport().isOpen()); + Assertions.assertTrue(ok); + Assertions.assertTrue(client.getOutputProtocol().getTransport().isOpen()); } finally { Config.thrift_rpc_connect_timeout_ms = savedConnectTimeout; } @@ -348,11 +348,11 @@ public void testReopenOrClearSuccessDoesNotClearPool() throws Exception { // reopenOrClear should succeed and NOT clear the pool boolean ok = backendService.reopenOrClear(address, client1, 60000); - Assert.assertTrue(ok); + Assertions.assertTrue(ok); // The other idle connection should still be available BackendService.Client client3 = backendService.borrowObject(address); - Assert.assertNotNull(client3); + Assertions.assertNotNull(client3); backendService.returnObject(address, client1); backendService.returnObject(address, client3); @@ -377,7 +377,7 @@ public void testReopenOrClearFailureClearsPool() throws Exception { // For now just verify the API contract: reopenOrClear calls clearPool on the given address. boolean ok = backendService.reopenOrClear(address, client2, 60000); // reopen to the same running server should succeed - Assert.assertTrue(ok); + Assertions.assertTrue(ok); } finally { Config.thrift_rpc_connect_timeout_ms = savedConnectTimeout; } @@ -395,8 +395,8 @@ public void testReopenWithZeroConnectTimeout() throws Exception { Config.thrift_rpc_connect_timeout_ms = 0; try { boolean ok = backendService.reopen(client, 60000); - Assert.assertTrue(ok); - Assert.assertTrue(client.getOutputProtocol().getTransport().isOpen()); + Assertions.assertTrue(ok); + Assertions.assertTrue(client.getOutputProtocol().getTransport().isOpen()); } finally { Config.thrift_rpc_connect_timeout_ms = savedConnectTimeout; } @@ -415,7 +415,7 @@ public void testException() throws Exception { } catch (NullPointerException e) { flag = true; } - Assert.assertTrue(flag); + Assertions.assertTrue(flag); flag = false; // return twice object = backendService.borrowObject(address); @@ -425,6 +425,6 @@ public void testException() throws Exception { } catch (java.lang.IllegalStateException e) { flag = true; } - Assert.assertTrue(flag); + Assertions.assertTrue(flag); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/JdkUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/JdkUtilsTest.java index c0766e2cfe585c..b3a98baf7051bd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/JdkUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/JdkUtilsTest.java @@ -19,30 +19,30 @@ import org.apache.doris.common.util.JdkUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class JdkUtilsTest { @Test public void testNormal() { - Assert.assertTrue(JdkUtils.checkJavaVersion()); + Assertions.assertTrue(JdkUtils.checkJavaVersion()); } @Test public void testFunctions() { String versionStr = JdkUtils.getJavaVersionFromFullVersion("java full version \"1.8.0_131-b11\""); - Assert.assertEquals("1.8.0_131-b11", versionStr); + Assertions.assertEquals("1.8.0_131-b11", versionStr); versionStr = JdkUtils.getJavaVersionFromFullVersion("openjdk full version \"13.0.1+9\""); - Assert.assertEquals("13.0.1+9", versionStr); + Assertions.assertEquals("13.0.1+9", versionStr); int version = JdkUtils.getJavaVersionAsInteger("1.8.0_131-b11"); - Assert.assertEquals(8, version); + Assertions.assertEquals(8, version); version = JdkUtils.getJavaVersionAsInteger("1.7.0_79-b15"); - Assert.assertEquals(7, version); + Assertions.assertEquals(7, version); version = JdkUtils.getJavaVersionAsInteger("13.0.1+9"); - Assert.assertEquals(13, version); + Assertions.assertEquals(13, version); version = JdkUtils.getJavaVersionAsInteger("11.0.0+7"); - Assert.assertEquals(11, version); + Assertions.assertEquals(11, version); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/Log4jConfigTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/Log4jConfigTest.java index 9d199fdbb06070..4a0a5f0d6fffbb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/Log4jConfigTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/Log4jConfigTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -52,10 +52,8 @@ public void testGetXmlConfByStrategyReadsConfig() throws Exception { builderField.set(null, sizeBuilder); method.invoke(null, "info_sys_accumulated_file_size", "sys_log_delete_age"); String sizeResult = sizeBuilder.toString(); - Assert.assertTrue("Size strategy should use IfAccumulatedFileSize", - sizeResult.contains("IfAccumulatedFileSize")); - Assert.assertFalse("Size strategy should not use IfLastModified", - sizeResult.contains("IfLastModified")); + Assertions.assertTrue(sizeResult.contains("IfAccumulatedFileSize"), "Size strategy should use IfAccumulatedFileSize"); + Assertions.assertFalse(sizeResult.contains("IfLastModified"), "Size strategy should not use IfLastModified"); // Test age strategy Config.log_rollover_strategy = "age"; @@ -63,10 +61,8 @@ public void testGetXmlConfByStrategyReadsConfig() throws Exception { builderField.set(null, ageBuilder); method.invoke(null, "info_sys_accumulated_file_size", "sys_log_delete_age"); String ageResult = ageBuilder.toString(); - Assert.assertTrue("Age strategy should use IfLastModified", - ageResult.contains("IfLastModified")); - Assert.assertFalse("Age strategy should not use IfAccumulatedFileSize", - ageResult.contains("IfAccumulatedFileSize")); + Assertions.assertTrue(ageResult.contains("IfLastModified"), "Age strategy should use IfLastModified"); + Assertions.assertFalse(ageResult.contains("IfAccumulatedFileSize"), "Age strategy should not use IfAccumulatedFileSize"); } finally { // Restore original state Config.log_rollover_strategy = origStrategy; diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/MD5Test.java b/fe/fe-core/src/test/java/org/apache/doris/common/MD5Test.java index 2e61abe31f146e..3c55898d7e6c67 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/MD5Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/MD5Test.java @@ -18,9 +18,9 @@ package org.apache.doris.common; import org.apache.commons.codec.digest.DigestUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileInputStream; @@ -32,7 +32,7 @@ public class MD5Test { private static String fileName = "job_info.txt"; - @BeforeClass + @BeforeAll public static void createFile() { String json = "{'key': 'value'}"; @@ -43,7 +43,7 @@ public static void createFile() { } } - @AfterClass + @AfterAll public static void deleteFile() { File file = new File(fileName); if (file.exists()) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/MarkDownParserTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/MarkDownParserTest.java index bcdbf3e23c9622..536f43824e990c 100755 --- a/fe/fe-core/src/test/java/org/apache/doris/common/MarkDownParserTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/MarkDownParserTest.java @@ -18,8 +18,8 @@ package org.apache.doris.common; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -43,14 +43,14 @@ public void testNormal() throws UserException { lines.add("http://www.baidu.com"); MarkDownParser parser = new MarkDownParser(lines); Map> map = parser.parse(); - Assert.assertNotNull(map.get("show taBLES")); - Assert.assertEquals("SHOW TABLES\n", map.get("SHOW TABLES").get("name")); - Assert.assertEquals("SYNTAX:\n\tSHOW TABLES [FROM] database\n", map.get("SHOW TABLES").get("description")); - Assert.assertEquals("show tables;\n", map.get("SHOW TABLES").get("example")); - Assert.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); - Assert.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); + Assertions.assertNotNull(map.get("show taBLES")); + Assertions.assertEquals("SHOW TABLES\n", map.get("SHOW TABLES").get("name")); + Assertions.assertEquals("SYNTAX:\n\tSHOW TABLES [FROM] database\n", map.get("SHOW TABLES").get("description")); + Assertions.assertEquals("show tables;\n", map.get("SHOW TABLES").get("example")); + Assertions.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); + Assertions.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); for (Map.Entry> doc : map.entrySet()) { - Assert.assertEquals("SHOW TABLES\n", doc.getValue().get("NAme")); + Assertions.assertEquals("SHOW TABLES\n", doc.getValue().get("NAme")); } } @@ -77,15 +77,15 @@ public void testMultiDoc() throws UserException { lines.add("### keywords"); MarkDownParser parser = new MarkDownParser(lines); Map> map = parser.parse(); - Assert.assertNotNull(map.get("SHOW TABLES")); - Assert.assertEquals("SHOW TABLES\n", map.get("SHOW TABLES").get("name")); - Assert.assertEquals("SYNTAX:\n\tSHOW TABLES [FROM] database\n", map.get("SHOW TABLES").get("description")); - Assert.assertEquals("show tables;\n", map.get("SHOW TABLES").get("example")); - Assert.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); - Assert.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); - Assert.assertNotNull(map.get("SHOW DATABASES")); - Assert.assertNotNull(map.get("DATABASES")); - Assert.assertNull(map.get("DATABASES abc")); + Assertions.assertNotNull(map.get("SHOW TABLES")); + Assertions.assertEquals("SHOW TABLES\n", map.get("SHOW TABLES").get("name")); + Assertions.assertEquals("SYNTAX:\n\tSHOW TABLES [FROM] database\n", map.get("SHOW TABLES").get("description")); + Assertions.assertEquals("show tables;\n", map.get("SHOW TABLES").get("example")); + Assertions.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); + Assertions.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); + Assertions.assertNotNull(map.get("SHOW DATABASES")); + Assertions.assertNotNull(map.get("DATABASES")); + Assertions.assertNull(map.get("DATABASES abc")); } @Test @@ -106,19 +106,21 @@ public void testNoDoc() throws UserException { lines.add(" DATABASES"); MarkDownParser parser = new MarkDownParser(lines); Map> map = parser.parse(); - Assert.assertNull(map.get("SHOW TABLES")); - Assert.assertNull(map.get("SHOW DATABASES")); - Assert.assertNull(map.get("DATABASES")); - Assert.assertNull(map.get("DATABASES abc")); + Assertions.assertNull(map.get("SHOW TABLES")); + Assertions.assertNull(map.get("SHOW DATABASES")); + Assertions.assertNull(map.get("DATABASES")); + Assertions.assertNull(map.get("DATABASES abc")); } - @Test(expected = UserException.class) + @Test public void testNoFirst() throws UserException { - List lines = Lists.newArrayList(); - lines.add("## SHOW TABLES"); - MarkDownParser parser = new MarkDownParser(lines); - parser.parse(); - Assert.fail("No exception throws."); + Assertions.assertThrows(UserException.class, () -> { + List lines = Lists.newArrayList(); + lines.add("## SHOW TABLES"); + MarkDownParser parser = new MarkDownParser(lines); + parser.parse(); + Assertions.fail("No exception throws."); + }); } @Test @@ -142,31 +144,33 @@ public void testMultiHeadLevel() throws UserException { lines.add("http://www.baidu.com"); MarkDownParser parser = new MarkDownParser(lines); Map> map = parser.parse(); - Assert.assertNotNull(map.get("SHOW TABLES")); - Assert.assertEquals(" SHOW TABLES\n", map.get("SHOW TABLES").get("name")); - Assert.assertEquals("####Syntax\nSYNTAX:\n\tSHOW TABLES [FROM] database\n####Parameter\n>table_name\n", map.get("SHOW TABLES").get("description")); - Assert.assertEquals("show tables;\n#### Exam1\nexam1\n", map.get("SHOW TABLES").get("example")); - Assert.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); - Assert.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); + Assertions.assertNotNull(map.get("SHOW TABLES")); + Assertions.assertEquals(" SHOW TABLES\n", map.get("SHOW TABLES").get("name")); + Assertions.assertEquals("####Syntax\nSYNTAX:\n\tSHOW TABLES [FROM] database\n####Parameter\n>table_name\n", map.get("SHOW TABLES").get("description")); + Assertions.assertEquals("show tables;\n#### Exam1\nexam1\n", map.get("SHOW TABLES").get("example")); + Assertions.assertEquals("SHOW, TABLES\n", map.get("SHOW TABLES").get("keywords")); + Assertions.assertEquals("http://www.baidu.com\n", map.get("SHOW TABLES").get("url")); } // the level of "description" is wrong - @Test(expected = DdlException.class) + @Test public void testEmptyTitle() throws UserException { - List lines = Lists.newArrayList(); - lines.add("#"); - lines.add("## "); - lines.add("SHOW TABLES"); - lines.add("## description"); - lines.add("SYNTAX:\n\tSHOW TABLES [FROM] database"); - lines.add("### example"); - lines.add("show tables;"); - lines.add("### keywords"); - lines.add("SHOW, TABLES"); - lines.add("### url"); - lines.add("http://www.baidu.com"); - MarkDownParser parser = new MarkDownParser(lines); - parser.parse(); + Assertions.assertThrows(DdlException.class, () -> { + List lines = Lists.newArrayList(); + lines.add("#"); + lines.add("## "); + lines.add("SHOW TABLES"); + lines.add("## description"); + lines.add("SYNTAX:\n\tSHOW TABLES [FROM] database"); + lines.add("### example"); + lines.add("show tables;"); + lines.add("### keywords"); + lines.add("SHOW, TABLES"); + lines.add("### url"); + lines.add("http://www.baidu.com"); + MarkDownParser parser = new MarkDownParser(lines); + parser.parse(); + }); } // no valid topic @@ -177,6 +181,6 @@ public void testOneName() throws UserException { lines.add("# TABLE"); MarkDownParser parser = new MarkDownParser(lines); Map> map = parser.parse(); - Assert.assertTrue(map.isEmpty()); + Assertions.assertTrue(map.isEmpty()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/PatternMatcherTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/PatternMatcherTest.java index 98c3bcae36f1e7..4daa666a02d835 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/PatternMatcherTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/PatternMatcherTest.java @@ -17,93 +17,93 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PatternMatcherTest { @Test public void testNormal() { try { PatternMatcher matcher = PatternMatcher.createMysqlPattern("%abc", false); - Assert.assertTrue(matcher.match("kljfdljasabc")); - Assert.assertTrue(matcher.match("kljfdljasABc")); - Assert.assertTrue(matcher.match("ABc")); - Assert.assertFalse(matcher.match("kljfdljasABc ")); + Assertions.assertTrue(matcher.match("kljfdljasabc")); + Assertions.assertTrue(matcher.match("kljfdljasABc")); + Assertions.assertTrue(matcher.match("ABc")); + Assertions.assertFalse(matcher.match("kljfdljasABc ")); matcher = PatternMatcher.createMysqlPattern("ab%c", false); - Assert.assertTrue(matcher.match("ab12121dfksjfla c")); - Assert.assertTrue(matcher.match("abc")); + Assertions.assertTrue(matcher.match("ab12121dfksjfla c")); + Assertions.assertTrue(matcher.match("abc")); matcher = PatternMatcher.createMysqlPattern("_abc", false); - Assert.assertTrue(matcher.match("1ABC")); - Assert.assertFalse(matcher.match("12abc")); - Assert.assertFalse(matcher.match("abc")); + Assertions.assertTrue(matcher.match("1ABC")); + Assertions.assertFalse(matcher.match("12abc")); + Assertions.assertFalse(matcher.match("abc")); matcher = PatternMatcher.createMysqlPattern("a_bc", false); - Assert.assertTrue(matcher.match("A1BC")); - Assert.assertFalse(matcher.match("abc")); - Assert.assertFalse(matcher.match("a12bc")); + Assertions.assertTrue(matcher.match("A1BC")); + Assertions.assertFalse(matcher.match("abc")); + Assertions.assertFalse(matcher.match("a12bc")); // Escape from MySQL result // "abc" like "ab\c" True matcher = PatternMatcher.createMysqlPattern("ab\\c", false); - Assert.assertTrue(matcher.match("abc")); + Assertions.assertTrue(matcher.match("abc")); // "ab\c" like "ab\\c" matcher = PatternMatcher.createMysqlPattern("ab\\\\c", false); - Assert.assertTrue(matcher.match("ab\\c")); + Assertions.assertTrue(matcher.match("ab\\c")); // "ab\\c" like "ab\\\\c" matcher = PatternMatcher.createMysqlPattern("ab\\\\\\\\c", false); - Assert.assertTrue(matcher.match("ab\\\\c")); + Assertions.assertTrue(matcher.match("ab\\\\c")); // "ab\" like "ab\" matcher = PatternMatcher.createMysqlPattern("ab\\", false); - Assert.assertTrue(matcher.match("ab\\")); + Assertions.assertTrue(matcher.match("ab\\")); // Empty pattern matcher = PatternMatcher.createMysqlPattern("", false); - Assert.assertTrue(matcher.match("")); - Assert.assertFalse(matcher.match(null)); - Assert.assertFalse(matcher.match(" ")); + Assertions.assertTrue(matcher.match("")); + Assertions.assertFalse(matcher.match(null)); + Assertions.assertFalse(matcher.match(" ")); matcher = PatternMatcher.createMysqlPattern("192.168.1.%", false); - Assert.assertTrue(matcher.match("192.168.1.1")); - Assert.assertFalse(matcher.match("192a168.1.1")); + Assertions.assertTrue(matcher.match("192.168.1.1")); + Assertions.assertFalse(matcher.match("192a168.1.1")); matcher = PatternMatcher.createMysqlPattern("192.1_8.1.%", false); - Assert.assertTrue(matcher.match("192.168.1.1")); - Assert.assertTrue(matcher.match("192.158.1.100")); - Assert.assertFalse(matcher.match("192.18.1.1")); + Assertions.assertTrue(matcher.match("192.168.1.1")); + Assertions.assertTrue(matcher.match("192.158.1.100")); + Assertions.assertFalse(matcher.match("192.18.1.1")); matcher = PatternMatcher.createMysqlPattern("192.1\\_8.1.%", false); - Assert.assertTrue(matcher.match("192.1_8.1.1")); - Assert.assertFalse(matcher.match("192.158.1.100")); + Assertions.assertTrue(matcher.match("192.1_8.1.1")); + Assertions.assertFalse(matcher.match("192.158.1.100")); matcher = PatternMatcher.createMysqlPattern("192.1\\_8.1.\\%", false); - Assert.assertTrue(matcher.match("192.1_8.1.%")); - Assert.assertFalse(matcher.match("192.1_8.1.100")); + Assertions.assertTrue(matcher.match("192.1_8.1.%")); + Assertions.assertFalse(matcher.match("192.1_8.1.100")); matcher = PatternMatcher.createMysqlPattern("192.%", false); - Assert.assertTrue(matcher.match("192.1.8.1")); + Assertions.assertTrue(matcher.match("192.1.8.1")); matcher = PatternMatcher.createMysqlPattern("192.168.%", false); - Assert.assertTrue(matcher.match("192.168.8.1")); + Assertions.assertTrue(matcher.match("192.168.8.1")); matcher = PatternMatcher.createMysqlPattern("my-host", false); - Assert.assertTrue(matcher.match("my-host")); - Assert.assertFalse(matcher.match("my-hostabc")); - Assert.assertFalse(matcher.match("abcmy-host")); + Assertions.assertTrue(matcher.match("my-host")); + Assertions.assertFalse(matcher.match("my-hostabc")); + Assertions.assertFalse(matcher.match("abcmy-host")); matcher = PatternMatcher.createMysqlPattern("my-%-host", false); - Assert.assertTrue(matcher.match("my-abc-host")); - Assert.assertFalse(matcher.match("my-abc-hostabc")); - Assert.assertFalse(matcher.match("abcmy-abc-host")); - Assert.assertTrue(matcher.match("my-%-host")); + Assertions.assertTrue(matcher.match("my-abc-host")); + Assertions.assertFalse(matcher.match("my-abc-hostabc")); + Assertions.assertFalse(matcher.match("abcmy-abc-host")); + Assertions.assertTrue(matcher.match("my-%-host")); matcher = PatternMatcher.createMysqlPattern("test_dropped_partition_field$partitions", false); - Assert.assertTrue(matcher.match("test_dropped_partition_field$partitions")); - Assert.assertFalse(matcher.match("test_dropped_partition_fieldapartitions")); + Assertions.assertTrue(matcher.match("test_dropped_partition_field$partitions")); + Assertions.assertFalse(matcher.match("test_dropped_partition_fieldapartitions")); } catch (Exception e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -111,21 +111,21 @@ public void testNormal() { public void testAbnormal() { try { PatternMatcher.createMysqlPattern("^abc", false); - Assert.fail(); + Assertions.fail(); } catch (PatternMatcherException e) { System.out.println(e.getMessage()); } try { PatternMatcher.createMysqlPattern("\\\\(abc", false); - Assert.fail(); + Assertions.fail(); } catch (PatternMatcherException e) { System.out.println(e.getMessage()); } try { PatternMatcher.createMysqlPattern("\\*abc", false); - Assert.fail(); + Assertions.fail(); } catch (PatternMatcherException e) { System.out.println(e.getMessage()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/PropertyAnalyzerTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/PropertyAnalyzerTest.java index 67aaa87bee9ee2..03b7699d790e6d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/PropertyAnalyzerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/PropertyAnalyzerTest.java @@ -37,11 +37,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.time.ZoneId; @@ -56,9 +53,6 @@ public class PropertyAnalyzerTest { - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - @Test public void testBfColumns() throws AnalysisException { List columns = Lists.newArrayList(); @@ -75,7 +69,7 @@ public void testBfColumns() throws AnalysisException { properties.put(PropertyAnalyzer.PROPERTIES_BF_COLUMNS, "k1"); Set bfColumns = PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); - Assert.assertEquals(Sets.newHashSet("k1"), bfColumns); + Assertions.assertEquals(Sets.newHashSet("k1"), bfColumns); } @Test @@ -95,10 +89,10 @@ public void testBfColumnsError() { // no bf columns properties.put(PropertyAnalyzer.PROPERTIES_BF_COLUMNS, ""); try { - Assert.assertEquals(Sets.newHashSet(), PropertyAnalyzer.analyzeBloomFilterColumns( + Assertions.assertEquals(Sets.newHashSet(), PropertyAnalyzer.analyzeBloomFilterColumns( properties, columns, KeysType.AGG_KEYS)); } catch (AnalysisException e) { - Assert.fail(); + Assertions.fail(); } // k4 not exist @@ -106,7 +100,7 @@ public void testBfColumnsError() { try { PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("column does not exist in table")); + Assertions.assertTrue(e.getMessage().contains("column does not exist in table")); } // tinyint not supported @@ -114,7 +108,7 @@ public void testBfColumnsError() { try { PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("TINYINT is not supported")); + Assertions.assertTrue(e.getMessage().contains("TINYINT is not supported")); } // bool not supported @@ -122,7 +116,7 @@ public void testBfColumnsError() { try { PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("BOOLEAN is not supported")); + Assertions.assertTrue(e.getMessage().contains("BOOLEAN is not supported")); } // not replace value @@ -130,7 +124,7 @@ public void testBfColumnsError() { try { PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Bloom filter index should only be used")); + Assertions.assertTrue(e.getMessage().contains("Bloom filter index should only be used")); } // reduplicated column @@ -138,7 +132,7 @@ public void testBfColumnsError() { try { PropertyAnalyzer.analyzeBloomFilterColumns(properties, columns, KeysType.AGG_KEYS); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Reduplicated bloom filter column")); + Assertions.assertTrue(e.getMessage().contains("Reduplicated bloom filter column")); } } @@ -146,44 +140,44 @@ public void testBfColumnsError() { public void testBfFpp() throws AnalysisException { Map properties = Maps.newHashMap(); properties.put(PropertyAnalyzer.PROPERTIES_BF_FPP, "0.05"); - Assert.assertEquals(0.05, PropertyAnalyzer.analyzeBloomFilterFpp(properties), 0.0001); + Assertions.assertEquals(0.05, PropertyAnalyzer.analyzeBloomFilterFpp(properties), 0.0001); } @Test public void testAnalyzeFileCacheTtlSeconds() throws AnalysisException { Map properties = Maps.newHashMap(); properties.put(PropertyAnalyzer.PROPERTIES_FILE_CACHE_TTL_SECONDS, "0"); - Assert.assertEquals(0L, PropertyAnalyzer.analyzeTTL(properties)); + Assertions.assertEquals(0L, PropertyAnalyzer.analyzeTTL(properties)); properties.put(PropertyAnalyzer.PROPERTIES_FILE_CACHE_TTL_SECONDS, String.valueOf(PropertyAnalyzer.MAX_FILE_CACHE_TTL_SECONDS)); - Assert.assertEquals(PropertyAnalyzer.MAX_FILE_CACHE_TTL_SECONDS, PropertyAnalyzer.analyzeTTL(properties)); + Assertions.assertEquals(PropertyAnalyzer.MAX_FILE_CACHE_TTL_SECONDS, PropertyAnalyzer.analyzeTTL(properties)); properties.put(PropertyAnalyzer.PROPERTIES_FILE_CACHE_TTL_SECONDS, String.valueOf(PropertyAnalyzer.MAX_FILE_CACHE_TTL_SECONDS + 1L)); try { PropertyAnalyzer.analyzeTTL(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("please use " + Assertions.assertTrue(e.getMessage().contains("please use " + PropertyAnalyzer.MAX_FILE_CACHE_TTL_SECONDS)); } properties.put(PropertyAnalyzer.PROPERTIES_FILE_CACHE_TTL_SECONDS, String.valueOf(Long.MAX_VALUE)); try { PropertyAnalyzer.analyzeTTL(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Larger values may overflow in BE")); - Assert.assertTrue(e.getMessage().contains("please use")); + Assertions.assertTrue(e.getMessage().contains("Larger values may overflow in BE")); + Assertions.assertTrue(e.getMessage().contains("please use")); } properties.put(PropertyAnalyzer.PROPERTIES_FILE_CACHE_TTL_SECONDS, "invalid"); try { PropertyAnalyzer.analyzeTTL(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("formats error or is out of range")); + Assertions.assertTrue(e.getMessage().contains("formats error or is out of range")); } } @@ -199,7 +193,7 @@ public void testStorageMedium() throws AnalysisException { DataProperty dataProperty = PropertyAnalyzer.analyzeDataProperty(properties, new DataProperty(TStorageMedium.SSD)); // avoid UT fail because time zone different DateLiteral dateLiteral = DateLiteralUtils.createDateLiteral(tomorrowTimeStr, Type.DATETIME); - Assert.assertEquals(dateLiteral.unixTimestamp(TimeUtils.getTimeZone()), dataProperty.getCooldownTimeMs()); + Assertions.assertEquals(dateLiteral.unixTimestamp(TimeUtils.getTimeZone()), dataProperty.getCooldownTimeMs()); } @Test @@ -210,13 +204,14 @@ public void testStorageFormat() throws AnalysisException { propertiesV1.put(PropertyAnalyzer.PROPERTIES_STORAGE_FORMAT, "v1"); propertiesV2.put(PropertyAnalyzer.PROPERTIES_STORAGE_FORMAT, "v2"); propertiesDefault.put(PropertyAnalyzer.PROPERTIES_STORAGE_FORMAT, "default"); - Assert.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(null)); - Assert.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(propertiesV2)); - Assert.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(propertiesDefault)); - expectedEx.expect(AnalysisException.class); - expectedEx.expectMessage( - "Storage format V1 has been deprecated since version 0.14," + " please use V2 instead"); - PropertyAnalyzer.analyzeStorageFormat(propertiesV1); + Assertions.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(null)); + Assertions.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(propertiesV2)); + Assertions.assertEquals(TStorageFormat.V2, PropertyAnalyzer.analyzeStorageFormat(propertiesDefault)); + AnalysisException e = Assertions.assertThrows(AnalysisException.class, () -> { + PropertyAnalyzer.analyzeStorageFormat(propertiesV1); + }); + Assertions.assertTrue(e.getMessage().contains("Storage format V1 has been deprecated since version 0.14," + " please use V2 instead"), + "unexpected message: " + e.getMessage()); } @Test @@ -225,14 +220,14 @@ public void testTag() throws AnalysisException { properties.put("tag.location", "l1"); properties.put("other", "prop"); Map tagMap = PropertyAnalyzer.analyzeBackendTagsProperties(properties, null); - Assert.assertEquals("l1", tagMap.get("location")); - Assert.assertEquals(1, tagMap.size()); - Assert.assertEquals(1, properties.size()); + Assertions.assertEquals("l1", tagMap.get("location")); + Assertions.assertEquals(1, tagMap.size()); + Assertions.assertEquals(1, properties.size()); properties.clear(); tagMap = PropertyAnalyzer.analyzeBackendTagsProperties(properties, Tag.DEFAULT_BACKEND_TAG); - Assert.assertEquals(1, tagMap.size()); - Assert.assertEquals(Tag.DEFAULT_BACKEND_TAG.value, tagMap.get(Tag.TYPE_LOCATION)); + Assertions.assertEquals(1, tagMap.size()); + Assertions.assertEquals(Tag.DEFAULT_BACKEND_TAG.value, tagMap.get(Tag.TYPE_LOCATION)); } @Test @@ -240,46 +235,46 @@ public void testStorageDictPageSize() throws AnalysisException { Map properties = Maps.newHashMap(); // Test default value - Assert.assertEquals(PropertyAnalyzer.STORAGE_DICT_PAGE_SIZE_DEFAULT_VALUE, + Assertions.assertEquals(PropertyAnalyzer.STORAGE_DICT_PAGE_SIZE_DEFAULT_VALUE, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); // Test valid value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "8192"); // 8KB - Assert.assertEquals(8192, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); + Assertions.assertEquals(8192, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); // Test lower boundary value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "4096"); // 4KB - Assert.assertEquals(4096, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); + Assertions.assertEquals(4096, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); // Test upper boundary value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "10485760"); // 10MB - Assert.assertEquals(10485760, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); + Assertions.assertEquals(10485760, PropertyAnalyzer.analyzeStorageDictPageSize(properties)); // Test invalid number format properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "invalid"); try { PropertyAnalyzer.analyzeStorageDictPageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Invalid storage dict page size")); + Assertions.assertTrue(e.getMessage().contains("Invalid storage dict page size")); } // Test value below minimum limit properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "-1024"); // 1KB try { PropertyAnalyzer.analyzeStorageDictPageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Storage dict page size must be between 0 and 100MB")); + Assertions.assertTrue(e.getMessage().contains("Storage dict page size must be between 0 and 100MB")); } // Test value above maximum limit properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_DICT_PAGE_SIZE, "209715200"); // 200MB try { PropertyAnalyzer.analyzeStorageDictPageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Storage dict page size must be between 0 and 100MB")); + Assertions.assertTrue(e.getMessage().contains("Storage dict page size must be between 0 and 100MB")); } } @@ -288,46 +283,46 @@ public void testStoragePageSize() throws AnalysisException { Map properties = Maps.newHashMap(); // Test default value - Assert.assertEquals(PropertyAnalyzer.STORAGE_PAGE_SIZE_DEFAULT_VALUE, + Assertions.assertEquals(PropertyAnalyzer.STORAGE_PAGE_SIZE_DEFAULT_VALUE, PropertyAnalyzer.analyzeStoragePageSize(properties)); // Test valid value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "8192"); // 8KB - Assert.assertEquals(8192, PropertyAnalyzer.analyzeStoragePageSize(properties)); + Assertions.assertEquals(8192, PropertyAnalyzer.analyzeStoragePageSize(properties)); // Test lower boundary value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "4096"); // 4KB - Assert.assertEquals(4096, PropertyAnalyzer.analyzeStoragePageSize(properties)); + Assertions.assertEquals(4096, PropertyAnalyzer.analyzeStoragePageSize(properties)); // Test upper boundary value properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "10485760"); // 10MB - Assert.assertEquals(10485760, PropertyAnalyzer.analyzeStoragePageSize(properties)); + Assertions.assertEquals(10485760, PropertyAnalyzer.analyzeStoragePageSize(properties)); // Test invalid number format properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "invalid"); try { PropertyAnalyzer.analyzeStoragePageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Invalid storage page size")); + Assertions.assertTrue(e.getMessage().contains("Invalid storage page size")); } // Test value below minimum limit properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "1024"); // 1KB try { PropertyAnalyzer.analyzeStoragePageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Storage page size must be between 4KB and 10MB")); + Assertions.assertTrue(e.getMessage().contains("Storage page size must be between 4KB and 10MB")); } // Test value above maximum limit properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_PAGE_SIZE, "20971520"); // 20MB try { PropertyAnalyzer.analyzeStoragePageSize(properties); - Assert.fail("Expected an AnalysisException to be thrown"); + Assertions.fail("Expected an AnalysisException to be thrown"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Storage page size must be between 4KB and 10MB")); + Assertions.assertTrue(e.getMessage().contains("Storage page size must be between 4KB and 10MB")); } } @@ -571,7 +566,7 @@ public void testAnalyzeSequenceMap() throws AnalysisException { try { PropertyAnalyzer.analyzeSeqMapping(properties, columns, KeysType.UNIQUE_KEYS); } catch (AnalysisException e) { - Assert.fail(); + Assertions.fail(); } } @@ -588,8 +583,7 @@ public void testStorageCooldownTimeWithTzOffset() throws AnalysisException { properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME, cooldownStr); DataProperty dp = PropertyAnalyzer.analyzeDataProperty(properties, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("TZ offset +00:00 should parse as exact UTC instant", - expectedMillis, dp.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dp.getCooldownTimeMs(), "TZ offset +00:00 should parse as exact UTC instant"); // -05:00 offset — same instant, different representation String cooldownStr2 = "2027-06-15 07:30:00-05:00"; @@ -598,8 +592,7 @@ public void testStorageCooldownTimeWithTzOffset() throws AnalysisException { properties2.put(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME, cooldownStr2); DataProperty dp2 = PropertyAnalyzer.analyzeDataProperty(properties2, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("TZ offset -05:00 should parse as same UTC instant", - expectedMillis, dp2.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dp2.getCooldownTimeMs(), "TZ offset -05:00 should parse as same UTC instant"); } @Test @@ -615,8 +608,7 @@ public void testStorageCooldownTimeWithTzOffsetFractionalSeconds() throws Analys properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME, cooldownStr); DataProperty dp = PropertyAnalyzer.analyzeDataProperty(properties, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("Fractional seconds with TZ offset should parse correctly", - expectedMillis, dp.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dp.getCooldownTimeMs(), "Fractional seconds with TZ offset should parse correctly"); // TIMESTAMPTZ(0) — no fractional seconds, with +00:00 String cooldownStr2 = "2027-06-15 12:30:00+00:00"; @@ -625,10 +617,8 @@ public void testStorageCooldownTimeWithTzOffsetFractionalSeconds() throws Analys properties2.put(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME, cooldownStr2); DataProperty dp2 = PropertyAnalyzer.analyzeDataProperty(properties2, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("No fractional seconds (precision 0) should still parse", - ZonedDateTime.of(2027, 6, 15, 12, 30, 0, 0, ZoneOffset.UTC) - .toInstant().toEpochMilli(), - dp2.getCooldownTimeMs()); + Assertions.assertEquals(ZonedDateTime.of(2027, 6, 15, 12, 30, 0, 0, ZoneOffset.UTC) + .toInstant().toEpochMilli(), dp2.getCooldownTimeMs(), "No fractional seconds (precision 0) should still parse"); } @Test @@ -641,8 +631,7 @@ public void testStorageCooldownTimeInvalidTzFormat() throws AnalysisException { properties.put(PropertyAnalyzer.PROPERTIES_STORAGE_COOLDOWN_TIME, "2027-06-15 12:30:00+00"); DataProperty dp = PropertyAnalyzer.analyzeDataProperty(properties, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("Malformed TZ offset should fall back to MAX", - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "Malformed TZ offset should fall back to MAX"); } @Test @@ -657,8 +646,7 @@ public void testStorageCooldownTimeStrictDateValidation() throws AnalysisExcepti "2027-02-29 00:00:00+00:00"); DataProperty dp = PropertyAnalyzer.analyzeDataProperty(properties, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("Invalid date (Feb 29 in non-leap year) should fall back to MAX", - DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp.getCooldownTimeMs(), "Invalid date (Feb 29 in non-leap year) should fall back to MAX"); // Also test an impossible month (month=13) Map properties2 = Maps.newHashMap(); @@ -667,8 +655,7 @@ public void testStorageCooldownTimeStrictDateValidation() throws AnalysisExcepti "2027-13-01 00:00:00+00:00"); DataProperty dp2 = PropertyAnalyzer.analyzeDataProperty(properties2, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("Invalid month (13) should fall back to MAX", - DataProperty.MAX_COOLDOWN_TIME_MS, dp2.getCooldownTimeMs()); + Assertions.assertEquals(DataProperty.MAX_COOLDOWN_TIME_MS, dp2.getCooldownTimeMs(), "Invalid month (13) should fall back to MAX"); } @Test @@ -693,8 +680,7 @@ public void testStorageCooldownTimeDstFallbackDistinctInstants() throws Analysis DataProperty dpEarlier = PropertyAnalyzer.analyzeDataProperty(propsEarlier, new DataProperty(TStorageMedium.SSD)); long earlierMillis = baseUtc.toInstant().toEpochMilli(); - Assert.assertEquals("Explicit +00:00 should parse earlier DST hour correctly", - earlierMillis, dpEarlier.getCooldownTimeMs()); + Assertions.assertEquals(earlierMillis, dpEarlier.getCooldownTimeMs(), "Explicit +00:00 should parse earlier DST hour correctly"); // Later instant (1 hour later, e.g. 07:30 UTC) ZonedDateTime laterUtc = baseUtc.plusHours(1); @@ -705,12 +691,10 @@ public void testStorageCooldownTimeDstFallbackDistinctInstants() throws Analysis DataProperty dpLater = PropertyAnalyzer.analyzeDataProperty(propsLater, new DataProperty(TStorageMedium.SSD)); long laterMillis = laterUtc.toInstant().toEpochMilli(); - Assert.assertEquals("Explicit +00:00 should parse later DST hour correctly", - laterMillis, dpLater.getCooldownTimeMs()); + Assertions.assertEquals(laterMillis, dpLater.getCooldownTimeMs(), "Explicit +00:00 should parse later DST hour correctly"); // The two instants must be distinct (1 hour apart). - Assert.assertEquals("DST fall-back hours must differ by exactly 1 hour", - 3600000L, laterMillis - earlierMillis); + Assertions.assertEquals(3600000L, laterMillis - earlierMillis, "DST fall-back hours must differ by exactly 1 hour"); } @Test @@ -743,8 +727,7 @@ public void testStorageCooldownTimeTzZoneIdsWinterTarget() throws AnalysisExcept "2027-01-01 00:00:00Z"); DataProperty dpZ = PropertyAnalyzer.analyzeDataProperty(propsZ, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("'Z' suffix winter target must parse as UTC instant", - expectedMillis, dpZ.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dpZ.getCooldownTimeMs(), "'Z' suffix winter target must parse as UTC instant"); // Test with UTC suffix Map propsUtc = Maps.newHashMap(); @@ -753,8 +736,7 @@ public void testStorageCooldownTimeTzZoneIdsWinterTarget() throws AnalysisExcept "2027-01-01 00:00:00UTC"); DataProperty dpUtc = PropertyAnalyzer.analyzeDataProperty(propsUtc, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("'UTC' suffix winter target must parse as UTC instant", - expectedMillis, dpUtc.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dpUtc.getCooldownTimeMs(), "'UTC' suffix winter target must parse as UTC instant"); // Test with GMT suffix Map propsGmt = Maps.newHashMap(); @@ -763,8 +745,7 @@ public void testStorageCooldownTimeTzZoneIdsWinterTarget() throws AnalysisExcept "2027-01-01 00:00:00GMT"); DataProperty dpGmt = PropertyAnalyzer.analyzeDataProperty(propsGmt, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("'GMT' suffix winter target must parse as UTC instant", - expectedMillis, dpGmt.getCooldownTimeMs()); + Assertions.assertEquals(expectedMillis, dpGmt.getCooldownTimeMs(), "'GMT' suffix winter target must parse as UTC instant"); // Summer-target Z with summer-time JVM must also work (baseline). ZonedDateTime summerZdt = ZonedDateTime.of( @@ -776,8 +757,7 @@ public void testStorageCooldownTimeTzZoneIdsWinterTarget() throws AnalysisExcept "2027-07-01 00:00:00Z"); DataProperty dpSummer = PropertyAnalyzer.analyzeDataProperty(propsSummer, new DataProperty(TStorageMedium.SSD)); - Assert.assertEquals("Summer target with JVM summer must also work", - expectedSummer, dpSummer.getCooldownTimeMs()); + Assertions.assertEquals(expectedSummer, dpSummer.getCooldownTimeMs(), "Summer target with JVM summer must also work"); } finally { TimeZone.setDefault(originalTimezone); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/TestEvictableCache.java b/fe/fe-core/src/test/java/org/apache/doris/common/TestEvictableCache.java index 3bfdc73b78e358..6ea6e0a23e9011 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/TestEvictableCache.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/TestEvictableCache.java @@ -30,8 +30,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.gaul.modernizer_maven_annotations.SuppressModernizer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import java.util.ArrayList; @@ -81,7 +81,7 @@ public void testLoad() Cache cache = EvictableCacheBuilder.newBuilder() .maximumSize(10_000) .build(); - Assert.assertEquals("abc", cache.get(42, () -> "abc")); + Assertions.assertEquals("abc", cache.get(42, () -> "abc")); } @Test @@ -95,15 +95,15 @@ public void testEvictBySize() for (int i = 0; i < 10_000; i++) { int value = i * 10; - Assert.assertEquals(value, (Object) cache.get(i, () -> value)); + Assertions.assertEquals(value, (Object) cache.get(i, () -> value)); } cache.cleanUp(); - Assert.assertEquals(maximumSize, cache.size()); - Assert.assertEquals(maximumSize, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals(maximumSize, cache.size()); + Assertions.assertEquals(maximumSize, ((EvictableCache) cache).tokensCount()); // Ensure cache is effective, i.e. some entries preserved int lastKey = 10_000 - 1; - Assert.assertEquals(lastKey * 10, (Object) cache.get(lastKey, () -> { + Assertions.assertEquals(lastKey * 10, (Object) cache.get(lastKey, () -> { throw new UnsupportedOperationException(); })); } @@ -118,32 +118,32 @@ public void testEvictByWeight() throws Exception { for (int i = 0; i < 10; i++) { String value = String.join("", Collections.nCopies(i, "a")); - Assert.assertEquals(value, cache.get(i, () -> value)); + Assertions.assertEquals(value, cache.get(i, () -> value)); } cache.cleanUp(); // It's not deterministic which entries get evicted int cacheSize = Math.toIntExact(cache.size()); - Assert.assertEquals(cacheSize, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals(cacheSize, cache.asMap().keySet().size()); + Assertions.assertEquals(cacheSize, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals(cacheSize, cache.asMap().keySet().size()); int keySum = cache.asMap().keySet().stream() .mapToInt(i -> i) .sum(); - Assert.assertTrue("key sum should be <= 20", keySum <= 20); + Assertions.assertTrue(keySum <= 20, "key sum should be <= 20"); - Assert.assertEquals(cacheSize, cache.asMap().values().size()); + Assertions.assertEquals(cacheSize, cache.asMap().values().size()); int valuesLengthSum = cache.asMap().values().stream() .mapToInt(String::length) .sum(); - Assert.assertTrue("values length sum should be <= 20", valuesLengthSum <= 20); + Assertions.assertTrue(valuesLengthSum <= 20, "values length sum should be <= 20"); // Ensure cache is effective, i.e. some entries preserved int lastKey = 9; // 10 - 1 String expected = String.join("", Collections.nCopies(lastKey, "a")); // java8 替代 repeat - Assert.assertEquals(expected, cache.get(lastKey, () -> { + Assertions.assertEquals(expected, cache.get(lastKey, () -> { throw new UnsupportedOperationException(); })); } @@ -158,17 +158,17 @@ public void testEvictByTime() throws Exception { .expireAfterWrite(ttl, TimeUnit.MILLISECONDS) .build(); - Assert.assertEquals("1 ala ma kota", cache.get(1, () -> "1 ala ma kota")); + Assertions.assertEquals("1 ala ma kota", cache.get(1, () -> "1 ala ma kota")); ticker.increment(ttl, TimeUnit.MILLISECONDS); - Assert.assertEquals("2 ala ma kota", cache.get(2, () -> "2 ala ma kota")); + Assertions.assertEquals("2 ala ma kota", cache.get(2, () -> "2 ala ma kota")); cache.cleanUp(); // First entry should be expired and its token removed int cacheSize = Math.toIntExact(cache.size()); - Assert.assertEquals(1, cacheSize); - Assert.assertEquals(cacheSize, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals(cacheSize, cache.asMap().keySet().size()); - Assert.assertEquals(cacheSize, cache.asMap().values().size()); + Assertions.assertEquals(1, cacheSize); + Assertions.assertEquals(cacheSize, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals(cacheSize, cache.asMap().keySet().size()); + Assertions.assertEquals(cacheSize, cache.asMap().values().size()); } @Test @@ -182,23 +182,23 @@ public void testPreserveValueLoadedAfterTimeExpiration() throws Exception { .build(); int key = 11; - Assert.assertEquals("11 ala ma kota", cache.get(key, () -> "11 ala ma kota")); - Assert.assertEquals(1, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals("11 ala ma kota", cache.get(key, () -> "11 ala ma kota")); + Assertions.assertEquals(1, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals("11 ala ma kota", cache.get(key, () -> "something else")); - Assert.assertEquals(1, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals("11 ala ma kota", cache.get(key, () -> "something else")); + Assertions.assertEquals(1, ((EvictableCache) cache).tokensCount()); ticker.increment(ttl, TimeUnit.MILLISECONDS); - Assert.assertEquals("new value", cache.get(key, () -> "new value")); - Assert.assertEquals(1, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals("new value", cache.get(key, () -> "new value")); + Assertions.assertEquals(1, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals("new value", cache.get(key, () -> "something yet different")); - Assert.assertEquals(1, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals("new value", cache.get(key, () -> "something yet different")); + Assertions.assertEquals(1, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals(1, cache.size()); - Assert.assertEquals(1, ((EvictableCache) cache).tokensCount()); - Assert.assertEquals(1, cache.asMap().keySet().size()); - Assert.assertEquals(1, cache.asMap().values().size()); + Assertions.assertEquals(1, cache.size()); + Assertions.assertEquals(1, ((EvictableCache) cache).tokensCount()); + Assertions.assertEquals(1, cache.asMap().keySet().size()); + Assertions.assertEquals(1, cache.asMap().values().size()); } @Test @@ -214,34 +214,34 @@ public void testReplace() throws Exception { cache.get(key, () -> initialValue); - Assert.assertTrue("Should successfully replace value", cache.asMap().replace(key, initialValue, replacedValue)); - Assert.assertEquals("Cache should contain replaced value", replacedValue, cache.getIfPresent(key).intValue()); + Assertions.assertTrue(cache.asMap().replace(key, initialValue, replacedValue), "Should successfully replace value"); + Assertions.assertEquals(replacedValue, cache.getIfPresent(key).intValue(), "Cache should contain replaced value"); - Assert.assertFalse("Should not replace when current value is different", cache.asMap().replace(key, initialValue, replacedValue)); - Assert.assertEquals("Cache should maintain replaced value", replacedValue, cache.getIfPresent(key).intValue()); + Assertions.assertFalse(cache.asMap().replace(key, initialValue, replacedValue), "Should not replace when current value is different"); + Assertions.assertEquals(replacedValue, cache.getIfPresent(key).intValue(), "Cache should maintain replaced value"); - Assert.assertFalse("Should not replace non-existent key", cache.asMap().replace(100000, replacedValue, 22)); - Assert.assertEquals("Cache should only contain original key", ImmutableSet.of(key), cache.asMap().keySet()); - Assert.assertEquals("Original key should maintain its value", replacedValue, cache.getIfPresent(key).intValue()); + Assertions.assertFalse(cache.asMap().replace(100000, replacedValue, 22), "Should not replace non-existent key"); + Assertions.assertEquals(ImmutableSet.of(key), cache.asMap().keySet(), "Cache should only contain original key"); + Assertions.assertEquals(replacedValue, cache.getIfPresent(key).intValue(), "Original key should maintain its value"); int anotherKey = 13; int anotherInitialValue = 14; cache.get(anotherKey, () -> anotherInitialValue); cache.invalidate(anotherKey); - Assert.assertFalse("Should not replace after invalidation", cache.asMap().replace(anotherKey, anotherInitialValue, 15)); - Assert.assertEquals("Cache should only contain original key after invalidation", ImmutableSet.of(key), cache.asMap().keySet()); + Assertions.assertFalse(cache.asMap().replace(anotherKey, anotherInitialValue, 15), "Should not replace after invalidation"); + Assertions.assertEquals(ImmutableSet.of(key), cache.asMap().keySet(), "Cache should only contain original key after invalidation"); } @Test @Timeout(TEST_TIMEOUT_SECONDS) public void testDisabledCache() throws Exception { - Exception exception = Assert.assertThrows(IllegalStateException.class, () -> + Exception exception = Assertions.assertThrows(IllegalStateException.class, () -> EvictableCacheBuilder.newBuilder() .maximumSize(0) .build()); - Assert.assertEquals("Even when cache is disabled, the loads are synchronized and both load results and failures are shared between threads. " + Assertions.assertEquals("Even when cache is disabled, the loads are synchronized and both load results and failures are shared between threads. " + "This is rarely desired, thus builder caller is expected to either opt-in into this behavior with shareResultsAndFailuresEvenIfDisabled(), " + "or choose not to share results (and failures) between concurrent invocations with shareNothingWhenDisabled().", exception.getMessage()); @@ -262,13 +262,13 @@ public void testDisabledCache() throws Exception { private void testDisabledCache(Cache cache) throws Exception { for (int i = 0; i < 10; i++) { int value = i * 10; - Assert.assertEquals(value, cache.get(i, () -> value).intValue()); + Assertions.assertEquals(value, cache.get(i, () -> value).intValue()); } cache.cleanUp(); - Assert.assertEquals(0, cache.size()); - Assert.assertTrue(cache.asMap().keySet().isEmpty()); - Assert.assertTrue(cache.asMap().values().isEmpty()); + Assertions.assertEquals(0, cache.size()); + Assertions.assertTrue(cache.asMap().keySet().isEmpty()); + Assertions.assertTrue(cache.asMap().values().isEmpty()); } private static class CacheStatsAssertions { @@ -327,9 +327,9 @@ public T calling(Callable callable) long missesDelta = afterStats.missCount() - beforeStats.missCount(); long hitsDelta = afterStats.hitCount() - beforeStats.hitCount(); - Assert.assertEquals(loads, loadDelta); - Assert.assertEquals(hits, hitsDelta); - Assert.assertEquals(misses, missesDelta); + Assertions.assertEquals(loads, loadDelta); + Assertions.assertEquals(hits, hitsDelta); + Assertions.assertEquals(misses, missesDelta); return value; } @@ -344,24 +344,24 @@ public void testLoadStats() .recordStats() .build(); - Assert.assertEquals(new CacheStats(0, 0, 0, 0, 0, 0), cache.stats()); + Assertions.assertEquals(new CacheStats(0, 0, 0, 0, 0, 0), cache.stats()); String value = CacheStatsAssertions.assertCacheStats(cache) .misses(1) .loads(1) .calling(() -> cache.get(42, () -> "abc")); - Assert.assertEquals("abc", value); + Assertions.assertEquals("abc", value); value = CacheStatsAssertions.assertCacheStats(cache) .hits(1) .calling(() -> cache.get(42, () -> "xyz")); - Assert.assertEquals("abc", value); + Assertions.assertEquals("abc", value); // with equal, but not the same key value = CacheStatsAssertions.assertCacheStats(cache) .hits(1) .calling(() -> cache.get(newInteger(42), () -> "xyz")); - Assert.assertEquals("abc", value); + Assertions.assertEquals("abc", value); } @Test @@ -393,12 +393,12 @@ public void testLoadFailure() return cache.get(key, () -> { if (first) { Thread secondThread = exchanger.exchange(null, 10, TimeUnit.SECONDS); - Assert.assertTrue(secondUnblocked.await(10, TimeUnit.SECONDS)); + Assertions.assertTrue(secondUnblocked.await(10, TimeUnit.SECONDS)); // Wait for the second one to hang inside the cache.get call. long start = System.nanoTime(); while (!Thread.currentThread().isInterrupted()) { try { - Assert.assertNotEquals(Thread.State.RUNNABLE, secondThread.getState()); + Assertions.assertNotEquals(Thread.State.RUNNABLE, secondThread.getState()); break; } catch (Exception | AssertionError e) { if (System.nanoTime() - start > TimeUnit.SECONDS.toNanos(30)) { @@ -431,12 +431,12 @@ public void testLoadFailure() // Note: if this starts to fail, that suggests that Guava implementation changed and NoopCache may be redundant now. String expectedError = "com.google.common.util.concurrent.UncheckedExecutionException: " + "java.lang.RuntimeException: first attempt is poised to fail"; - Assert.assertEquals(2, results.size()); - Assert.assertEquals(expectedError, results.get(0)); - Assert.assertEquals(expectedError, results.get(1)); + Assertions.assertEquals(2, results.size()); + Assertions.assertEquals(expectedError, results.get(0)); + Assertions.assertEquals(expectedError, results.get(1)); } finally { executor.shutdownNow(); - Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); } } @@ -445,7 +445,7 @@ private static Integer newInteger(int value) { Integer integer = value; @SuppressWarnings({"UnnecessaryBoxing", "BoxedPrimitiveConstructor", "CachedNumberConstructorCall", "removal"}) Integer newInteger = new Integer(value); - Assert.assertNotSame(integer, newInteger); + Assertions.assertNotSame(integer, newInteger); return newInteger; } @@ -485,7 +485,7 @@ public void testConcurrentGetWithCallableShareLoad() concurrentInvocations.decrementAndGet(); return -key; }); - Assert.assertEquals(-invocation, value); + Assertions.assertEquals(-invocation, value); } return null; })); @@ -494,16 +494,14 @@ public void testConcurrentGetWithCallableShareLoad() for (Future future : futures) { future.get(10, TimeUnit.SECONDS); } - Assert.assertTrue( - String.format( + Assertions.assertTrue(loads.intValue() >= invocationsPerThread && loads.intValue() <= threads * invocationsPerThread - 1, String.format( "loads (%d) should be between %d and %d", loads.intValue(), invocationsPerThread, - threads * invocationsPerThread - 1), - loads.intValue() >= invocationsPerThread && loads.intValue() <= threads * invocationsPerThread - 1); + threads * invocationsPerThread - 1)); } finally { executor.shutdownNow(); - Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); } } @@ -537,7 +535,7 @@ public void testInvalidateOngoingLoad() Future threadA = executor.submit(() -> { String value = cache.get(key, () -> { loadOngoing.countDown(); // 1 - Assert.assertTrue(invalidated.await(10, TimeUnit.SECONDS)); // 2 + Assertions.assertTrue(invalidated.await(10, TimeUnit.SECONDS)); // 2 return "stale value"; }); getReturned.countDown(); // 3 @@ -546,7 +544,7 @@ public void testInvalidateOngoingLoad() // thread B Future threadB = executor.submit(() -> { - Assert.assertTrue(loadOngoing.await(10, TimeUnit.SECONDS)); // 1 + Assertions.assertTrue(loadOngoing.await(10, TimeUnit.SECONDS)); // 1 switch (invalidation) { case INVALIDATE_KEY: @@ -570,16 +568,16 @@ public void testInvalidateOngoingLoad() invalidated.countDown(); // 2 // Cache may persist value after loader returned, but before `cache.get(...)` returned. Ensure the latter completed. - Assert.assertTrue(getReturned.await(10, TimeUnit.SECONDS)); // 3 + Assertions.assertTrue(getReturned.await(10, TimeUnit.SECONDS)); // 3 return cache.get(key, () -> "fresh value"); }); - Assert.assertEquals("stale value", threadA.get()); - Assert.assertEquals("fresh value", threadB.get()); + Assertions.assertEquals("stale value", threadA.get()); + Assertions.assertEquals("fresh value", threadB.get()); } finally { executor.shutdownNow(); - Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); } } } @@ -607,7 +605,7 @@ public void testInvalidateAndLoadConcurrently() List> futures = IntStream.range(0, threads) .mapToObj(threadNumber -> executor.submit(() -> { // prime the cache - Assert.assertEquals(1L, (long) cache.get(key, remoteState::get)); + Assertions.assertEquals(1L, (long) cache.get(key, remoteState::get)); int prime = primes[threadNumber]; barrier.await(10, TimeUnit.SECONDS); @@ -654,11 +652,11 @@ public void testInvalidateAndLoadConcurrently() } } - Assert.assertEquals(2 * 3 * 5 * 7, remoteState.get()); - Assert.assertEquals(remoteState.get(), (long) cache.get(key, remoteState::get)); + Assertions.assertEquals(2 * 3 * 5 * 7, remoteState.get()); + Assertions.assertEquals(remoteState.get(), (long) cache.get(key, remoteState::get)); } finally { executor.shutdownNow(); - Assert.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); } } } @@ -674,10 +672,10 @@ public void testPutOnEmptyCacheImplementation() { int key = 0; int value = 1; - Assert.assertNull(cacheMap.put(key, value)); - Assert.assertNull(cacheMap.put(key, value)); - Assert.assertNull(cacheMap.putIfAbsent(key, value)); - Assert.assertNull(cacheMap.putIfAbsent(key, value)); + Assertions.assertNull(cacheMap.put(key, value)); + Assertions.assertNull(cacheMap.put(key, value)); + Assertions.assertNull(cacheMap.putIfAbsent(key, value)); + Assertions.assertNull(cacheMap.putIfAbsent(key, value)); } } @@ -691,17 +689,13 @@ public void testPutOnNonEmptyCacheImplementation() { int key = 0; int value = 1; - Exception putException = Assert.assertThrows("put operation should throw UnsupportedOperationException", - UnsupportedOperationException.class, - () -> cacheMap.put(key, value)); - Assert.assertEquals( + Exception putException = Assertions.assertThrows(UnsupportedOperationException.class, () -> cacheMap.put(key, value), "put operation should throw UnsupportedOperationException"); + Assertions.assertEquals( "The operation is not supported, as in inherently races with cache invalidation. Use get(key, callable) instead.", putException.getMessage()); - Exception putIfAbsentException = Assert.assertThrows("putIfAbsent operation should throw UnsupportedOperationException", - UnsupportedOperationException.class, - () -> cacheMap.putIfAbsent(key, value)); - Assert.assertEquals( + Exception putIfAbsentException = Assertions.assertThrows(UnsupportedOperationException.class, () -> cacheMap.putIfAbsent(key, value), "putIfAbsent operation should throw UnsupportedOperationException"); + Assertions.assertEquals( "The operation is not supported, as in inherently races with cache invalidation", putIfAbsentException.getMessage()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/ThreadPoolManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/ThreadPoolManagerTest.java index 2ed1ddd67e8922..a00c37d880509f 100755 --- a/fe/fe-core/src/test/java/org/apache/doris/common/ThreadPoolManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/ThreadPoolManagerTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.ThreadPoolExecutor; @@ -33,9 +33,9 @@ public void testNormal() throws InterruptedException { ThreadPoolManager.registerThreadPoolMetric("test_cache_pool", testCachedPool); ThreadPoolManager.registerThreadPoolMetric("test_fixed_thread_pool", testFixedThreaddPool); - Assert.assertEquals(ThreadPoolManager.LogDiscardPolicy.class, + Assertions.assertEquals(ThreadPoolManager.LogDiscardPolicy.class, testCachedPool.getRejectedExecutionHandler().getClass()); - Assert.assertEquals(ThreadPoolManager.BlockedPolicy.class, + Assertions.assertEquals(ThreadPoolManager.BlockedPolicy.class, testFixedThreaddPool.getRejectedExecutionHandler().getClass()); Runnable task = () -> { @@ -49,32 +49,32 @@ public void testNormal() throws InterruptedException { testCachedPool.submit(task); } - Assert.assertEquals(2, testCachedPool.getPoolSize()); - Assert.assertEquals(2, testCachedPool.getActiveCount()); - Assert.assertEquals(0, testCachedPool.getQueue().size()); - Assert.assertEquals(0, testCachedPool.getCompletedTaskCount()); + Assertions.assertEquals(2, testCachedPool.getPoolSize()); + Assertions.assertEquals(2, testCachedPool.getActiveCount()); + Assertions.assertEquals(0, testCachedPool.getQueue().size()); + Assertions.assertEquals(0, testCachedPool.getCompletedTaskCount()); Thread.sleep(700); - Assert.assertEquals(2, testCachedPool.getPoolSize()); - Assert.assertEquals(0, testCachedPool.getActiveCount()); - Assert.assertEquals(0, testCachedPool.getQueue().size()); - Assert.assertEquals(2, testCachedPool.getCompletedTaskCount()); + Assertions.assertEquals(2, testCachedPool.getPoolSize()); + Assertions.assertEquals(0, testCachedPool.getActiveCount()); + Assertions.assertEquals(0, testCachedPool.getQueue().size()); + Assertions.assertEquals(2, testCachedPool.getCompletedTaskCount()); for (int i = 0; i < 4; i++) { testFixedThreaddPool.submit(task); } - Assert.assertTrue(testFixedThreaddPool.getActiveCount() <= 2); - Assert.assertTrue(testFixedThreaddPool.getQueue().size() > 0); - Assert.assertEquals(2, testFixedThreaddPool.getPoolSize()); - Assert.assertEquals(0, testFixedThreaddPool.getCompletedTaskCount()); + Assertions.assertTrue(testFixedThreaddPool.getActiveCount() <= 2); + Assertions.assertTrue(testFixedThreaddPool.getQueue().size() > 0); + Assertions.assertEquals(2, testFixedThreaddPool.getPoolSize()); + Assertions.assertEquals(0, testFixedThreaddPool.getCompletedTaskCount()); Thread.sleep(2000); - Assert.assertEquals(2, testFixedThreaddPool.getPoolSize()); - Assert.assertEquals(0, testFixedThreaddPool.getActiveCount()); - Assert.assertEquals(0, testFixedThreaddPool.getQueue().size()); - Assert.assertEquals(4, testFixedThreaddPool.getCompletedTaskCount()); + Assertions.assertEquals(2, testFixedThreaddPool.getPoolSize()); + Assertions.assertEquals(0, testFixedThreaddPool.getActiveCount()); + Assertions.assertEquals(0, testFixedThreaddPool.getQueue().size()); + Assertions.assertEquals(4, testFixedThreaddPool.getCompletedTaskCount()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/io/DeepCopyTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/io/DeepCopyTest.java index 4d9fb3172275b8..15bed85f1a07e9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/io/DeepCopyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/io/DeepCopyTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.persist.TableInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class DeepCopyTest { @@ -29,8 +29,8 @@ public class DeepCopyTest { public void test() { TableInfo info = TableInfo.createForTableRename(1, 2, "newTbl"); TableInfo copied = DeepCopy.copy(info, TableInfo.class, FeConstants.meta_version); - Assert.assertEquals(1, copied.getDbId()); - Assert.assertEquals(2, copied.getTableId()); - Assert.assertEquals("newTbl", copied.getNewTableName()); + Assertions.assertEquals(1, copied.getDbId()); + Assertions.assertEquals(2, copied.getTableId()); + Assertions.assertEquals("newTbl", copied.getNewTableName()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/parquet/ParquetReaderTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/parquet/ParquetReaderTest.java index d797a9c1b26ed5..6953638af187a5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/parquet/ParquetReaderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/parquet/ParquetReaderTest.java @@ -22,8 +22,8 @@ import com.google.common.collect.Maps; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.Map; @@ -34,7 +34,7 @@ public class ParquetReaderTest { // localfile, remote file // ak, sk, broker desc // before running this test - @Ignore + @Disabled @Test public void testWrongFormat() { try { diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/AlterProcDirFilterExpressionTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/AlterProcDirFilterExpressionTest.java index 18622536d34ce7..5fff3f75c76376 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/AlterProcDirFilterExpressionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/AlterProcDirFilterExpressionTest.java @@ -26,8 +26,8 @@ import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal; import org.apache.doris.nereids.types.DateTimeV2Type; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -38,9 +38,9 @@ public void testSchemaChangeFilterResultExpressionWithAnd() throws AnalysisExcep SchemaChangeProcDir schemaChangeProcDir = new SchemaChangeProcDir(null, null); HashMap filter = buildCreateTimeRangeFilter(); - Assert.assertTrue(schemaChangeProcDir.filterResultExpression( + Assertions.assertTrue(schemaChangeProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:34.380", filter)); - Assert.assertFalse(schemaChangeProcDir.filterResultExpression( + Assertions.assertFalse(schemaChangeProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:23.070", filter)); } @@ -49,9 +49,9 @@ public void testRollupFilterResultExpressionWithAnd() throws AnalysisException { RollupProcDir rollupProcDir = new RollupProcDir(null, null); HashMap filter = buildCreateTimeRangeFilter(); - Assert.assertTrue(rollupProcDir.filterResultExpression( + Assertions.assertTrue(rollupProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:34.380", filter)); - Assert.assertFalse(rollupProcDir.filterResultExpression( + Assertions.assertFalse(rollupProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:23.070", filter)); } @@ -60,9 +60,9 @@ public void testBuildIndexFilterResultExpressionWithAnd() throws AnalysisExcepti BuildIndexProcDir buildIndexProcDir = new BuildIndexProcDir(null, null); HashMap filter = buildCreateTimeRangeFilter(); - Assert.assertTrue(buildIndexProcDir.filterResultExpression( + Assertions.assertTrue(buildIndexProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:34.380", filter)); - Assert.assertFalse(buildIndexProcDir.filterResultExpression( + Assertions.assertFalse(buildIndexProcDir.filterResultExpression( "CreateTime", "2026-04-17 10:44:23.070", filter)); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendProcNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendProcNodeTest.java index 9c6826df4d3467..965b160a1db550 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendProcNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendProcNodeTest.java @@ -26,10 +26,10 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -41,7 +41,7 @@ public class BackendProcNodeTest { private EditLog editLog; private MockedStatic mockedEnv; - @Before + @BeforeEach public void setUp() { env = Mockito.mock(Env.class); editLog = Mockito.mock(EditLog.class); @@ -60,7 +60,7 @@ public void setUp() { b1.setDisks(immutableMap); } - @After + @AfterEach public void tearDown() { if (mockedEnv != null) { mockedEnv.close(); @@ -74,11 +74,11 @@ public void testResultNormal() throws AnalysisException { // fetch result result = node.fetchResult(); - Assert.assertNotNull(result); - Assert.assertTrue(result instanceof BaseProcResult); + Assertions.assertNotNull(result); + Assertions.assertTrue(result instanceof BaseProcResult); - Assert.assertTrue(result.getRows().size() >= 1); - Assert.assertEquals(Lists.newArrayList("RootPath", "DataUsedCapacity", "OtherUsedCapacity", "AvailCapacity", + Assertions.assertTrue(result.getRows().size() >= 1); + Assertions.assertEquals(Lists.newArrayList("RootPath", "DataUsedCapacity", "OtherUsedCapacity", "AvailCapacity", "TotalCapacity", "TotalUsedPct", "State", "PathHash", "StorageMedium"), result.getColumnNames()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendsProcDirTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendsProcDirTest.java index a4a78a79f11e36..c07a067347292c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendsProcDirTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/BackendsProcDirTest.java @@ -25,10 +25,10 @@ import org.apache.doris.system.SystemInfoService; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -44,7 +44,7 @@ public class BackendsProcDirTest { private EditLog editLog = Mockito.mock(EditLog.class); private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setUp() { b1 = new Backend(1000, "host1", 10000); b1.updateOnce(10001, 10003, 10005); @@ -64,7 +64,7 @@ public void setUp() { mockedEnvStatic.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -76,36 +76,38 @@ public void testRegister() { BackendsProcDir dir; dir = new BackendsProcDir(systemInfoService); - Assert.assertFalse(dir.register("100000", new BaseProcDir())); + Assertions.assertFalse(dir.register("100000", new BaseProcDir())); } - @Test(expected = AnalysisException.class) + @Test public void testLookupNormal() throws AnalysisException { - BackendsProcDir dir; - ProcNodeInterface node; - - dir = new BackendsProcDir(systemInfoService); - try { - node = dir.lookup("1000"); - Assert.assertNotNull(node); - Assert.assertTrue(node instanceof BackendProcNode); - } catch (AnalysisException e) { - e.printStackTrace(); - Assert.fail(); - } - - dir = new BackendsProcDir(systemInfoService); - try { - node = dir.lookup("1001"); - Assert.assertNotNull(node); - Assert.assertTrue(node instanceof BackendProcNode); - } catch (AnalysisException e) { - Assert.fail(); - } - - dir = new BackendsProcDir(systemInfoService); - node = dir.lookup("1002"); - Assert.fail(); + Assertions.assertThrows(AnalysisException.class, () -> { + BackendsProcDir dir; + ProcNodeInterface node; + + dir = new BackendsProcDir(systemInfoService); + try { + node = dir.lookup("1000"); + Assertions.assertNotNull(node); + Assertions.assertTrue(node instanceof BackendProcNode); + } catch (AnalysisException e) { + e.printStackTrace(); + Assertions.fail(); + } + + dir = new BackendsProcDir(systemInfoService); + try { + node = dir.lookup("1001"); + Assertions.assertNotNull(node); + Assertions.assertTrue(node instanceof BackendProcNode); + } catch (AnalysisException e) { + Assertions.fail(); + } + + dir = new BackendsProcDir(systemInfoService); + node = dir.lookup("1002"); + Assertions.fail(); + }); } @Test @@ -133,8 +135,8 @@ public void testFetchResultNormal() throws AnalysisException { dir = new BackendsProcDir(systemInfoService); result = dir.fetchResult(); - Assert.assertNotNull(result); - Assert.assertTrue(result instanceof BaseProcResult); + Assertions.assertNotNull(result); + Assertions.assertTrue(result instanceof BaseProcResult); } @Test @@ -157,9 +159,9 @@ public void testBackendInfoFieldOrder() throws AnalysisException { int runningTasksIdx = columnNames.indexOf("RunningTasks"); int nodeRoleIdx = columnNames.indexOf("NodeRole"); - Assert.assertTrue("CpuCores should be before Memory", cpuCoresIdx < memoryIdx); - Assert.assertTrue("Memory should be before LiveSince", memoryIdx < liveSinceIdx); - Assert.assertTrue("LiveSince should be before RunningTasks", liveSinceIdx < runningTasksIdx); - Assert.assertTrue("RunningTasks should be before NodeRole", runningTasksIdx < nodeRoleIdx); + Assertions.assertTrue(cpuCoresIdx < memoryIdx, "CpuCores should be before Memory"); + Assertions.assertTrue(memoryIdx < liveSinceIdx, "Memory should be before LiveSince"); + Assertions.assertTrue(liveSinceIdx < runningTasksIdx, "LiveSince should be before RunningTasks"); + Assertions.assertTrue(runningTasksIdx < nodeRoleIdx, "RunningTasks should be before NodeRole"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/CloudProcVersionDisplayTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/CloudProcVersionDisplayTest.java index 4565aef7a4a251..d5e83d7ac594ab 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/CloudProcVersionDisplayTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/CloudProcVersionDisplayTest.java @@ -46,10 +46,10 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -75,7 +75,7 @@ public class CloudProcVersionDisplayTest { private String originCloudUniqueId; private boolean originEnableQueryHitStats; - @Before + @BeforeEach public void setUp() throws AnalysisException { originDeployMode = Config.deploy_mode; originCloudUniqueId = Config.cloud_unique_id; @@ -97,7 +97,7 @@ public void setUp() throws AnalysisException { mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); } - @After + @AfterEach public void tearDown() { if (mockedEnv != null) { mockedEnv.close(); @@ -113,10 +113,10 @@ public void testIndicesLookupPropagatesPartitionCachedVersionToTabletsProc() thr IndicesProcDir indicesProcDir = new IndicesProcDir(context.db, context.table, context.partition); ProcNodeInterface procNode = indicesProcDir.lookup(String.valueOf(INDEX_ID)); - Assert.assertTrue(procNode instanceof TabletsProcDir); + Assertions.assertTrue(procNode instanceof TabletsProcDir); ProcResult result = procNode.fetchResult(); - Assert.assertEquals(1, result.getRows().size()); + Assertions.assertEquals(1, result.getRows().size()); assertVersionColumns(result, PARTITION_VISIBLE_VERSION); } @@ -131,19 +131,19 @@ public void testReplicasProcNodeShowsPartitionCachedVersionInCloudMode() throws ReplicasProcNode procNode = new ReplicasProcNode(TABLET_ID, context.tablet.getReplicas()); ProcResult result = procNode.fetchResult(); - Assert.assertEquals(1, result.getRows().size()); + Assertions.assertEquals(1, result.getRows().size()); assertVersionColumns(result, PARTITION_VISIBLE_VERSION); } private void assertVersionColumns(ProcResult result, long expectedVersion) { int versionIndex = result.getColumnNames().indexOf("Version"); int lastSuccessVersionIndex = result.getColumnNames().indexOf("LstSuccessVersion"); - Assert.assertTrue(versionIndex >= 0); - Assert.assertTrue(lastSuccessVersionIndex >= 0); + Assertions.assertTrue(versionIndex >= 0); + Assertions.assertTrue(lastSuccessVersionIndex >= 0); String expected = String.valueOf(expectedVersion); - Assert.assertEquals(expected, result.getRows().get(0).get(versionIndex)); - Assert.assertEquals(expected, result.getRows().get(0).get(lastSuccessVersionIndex)); + Assertions.assertEquals(expected, result.getRows().get(0).get(versionIndex)); + Assertions.assertEquals(expected, result.getRows().get(0).get(lastSuccessVersionIndex)); } private ProcTestContext createProcTestContext() { diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/CurrentQueryStatisticsProcDirTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/CurrentQueryStatisticsProcDirTest.java index 0c9accd89e55f9..52a4775e56d08c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/CurrentQueryStatisticsProcDirTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/CurrentQueryStatisticsProcDirTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.proc; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Unit test for CurrentQueryStatisticsProcDir progress formatting. @@ -29,61 +29,61 @@ public class CurrentQueryStatisticsProcDirTest { @Test public void testProgressNormal() { // 7 out of 20 tasks finished = 35.0% - Assert.assertEquals("35.0%", CurrentQueryStatisticsProcDir.formatProgress(20, 7)); + Assertions.assertEquals("35.0%", CurrentQueryStatisticsProcDir.formatProgress(20, 7)); } @Test public void testProgressAllFinished() { // 8 out of 8 = 100.0% - Assert.assertEquals("100.0%", CurrentQueryStatisticsProcDir.formatProgress(8, 8)); + Assertions.assertEquals("100.0%", CurrentQueryStatisticsProcDir.formatProgress(8, 8)); } @Test public void testProgressOneThird() { // 1 out of 3 = 33.3% - Assert.assertEquals("33.3%", CurrentQueryStatisticsProcDir.formatProgress(3, 1)); + Assertions.assertEquals("33.3%", CurrentQueryStatisticsProcDir.formatProgress(3, 1)); } @Test public void testProgressTwoThirds() { // 2 out of 3 = 66.7% - Assert.assertEquals("66.7%", CurrentQueryStatisticsProcDir.formatProgress(3, 2)); + Assertions.assertEquals("66.7%", CurrentQueryStatisticsProcDir.formatProgress(3, 2)); } @Test public void testProgressZeroPercent() { // 0 out of 5 = 0.0% - Assert.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(5, 0)); + Assertions.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(5, 0)); } @Test public void testProgressZeroTotal() { // total = 0, finished = 0 → "0.0%" (no division by zero) - Assert.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(0, 0)); + Assertions.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(0, 0)); } @Test public void testProgressFinishedExceedsTotal() { // Defensive: if finished > total, still returns a percentage (may exceed 100%) - Assert.assertEquals("200.0%", CurrentQueryStatisticsProcDir.formatProgress(5, 10)); + Assertions.assertEquals("200.0%", CurrentQueryStatisticsProcDir.formatProgress(5, 10)); } @Test public void testProgressNegativeTotal() { // total < 0 → returns "0.0%" - Assert.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(-1, 5)); + Assertions.assertEquals("0.0%", CurrentQueryStatisticsProcDir.formatProgress(-1, 5)); } @Test public void testProgressLargeValues() { // Verify no overflow with large numbers - Assert.assertEquals("50.0%", + Assertions.assertEquals("50.0%", CurrentQueryStatisticsProcDir.formatProgress(Integer.MAX_VALUE, Integer.MAX_VALUE / 2)); } @Test public void testProgressFractional() { // 1 out of 7 = 14.3% (14.2857... rounds to 14.3) - Assert.assertEquals("14.3%", CurrentQueryStatisticsProcDir.formatProgress(7, 1)); + Assertions.assertEquals("14.3%", CurrentQueryStatisticsProcDir.formatProgress(7, 1)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/DbsProcDirTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/DbsProcDirTest.java index 0f273e7a7c35bc..d1239390b4b1c0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/DbsProcDirTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/DbsProcDirTest.java @@ -28,10 +28,10 @@ import org.apache.doris.transaction.GlobalTransactionMgr; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Arrays; @@ -50,13 +50,13 @@ public class DbsProcDirTest { // | - db1 // | - db2 - @Before + @BeforeEach public void setUp() { db1 = new Database(10000L, "db1"); db2 = new Database(10001L, "db2"); } - @After + @AfterEach public void tearDown() { env = null; } @@ -66,43 +66,45 @@ public void testRegister() { DbsProcDir dir; dir = new DbsProcDir(env, catalog); - Assert.assertFalse(dir.register("db1", new BaseProcDir())); + Assertions.assertFalse(dir.register("db1", new BaseProcDir())); } - @Test(expected = AnalysisException.class) + @Test public void testLookupNormal() throws AnalysisException { - Mockito.when(env.getInternalCatalog()).thenReturn(catalog); - Mockito.when(catalog.getDbNullable("db1")).thenReturn(db1); - Mockito.when(catalog.getDbNullable("db2")).thenReturn(db2); - Mockito.when(catalog.getDbNullable("db3")).thenReturn(null); - Mockito.when(catalog.getDbNullable(Mockito.anyLong())).thenReturn(null); - Mockito.when(catalog.getDbNullable(db1.getId())).thenReturn(db1); - Mockito.when(catalog.getDbNullable(db2.getId())).thenReturn(db2); - - DbsProcDir dir; - ProcNodeInterface node; - - dir = new DbsProcDir(env, catalog); - try { - node = dir.lookup(String.valueOf(db1.getId())); - Assert.assertNotNull(node); - Assert.assertTrue(node instanceof TablesProcDir); - } catch (AnalysisException e) { - Assert.fail(); - } - - dir = new DbsProcDir(env, catalog); - try { - node = dir.lookup(String.valueOf(db2.getId())); - Assert.assertNotNull(node); - Assert.assertTrue(node instanceof TablesProcDir); - } catch (AnalysisException e) { - Assert.fail(); - } - - dir = new DbsProcDir(env, catalog); - node = dir.lookup("10002"); - Assert.assertNull(node); + Assertions.assertThrows(AnalysisException.class, () -> { + Mockito.when(env.getInternalCatalog()).thenReturn(catalog); + Mockito.when(catalog.getDbNullable("db1")).thenReturn(db1); + Mockito.when(catalog.getDbNullable("db2")).thenReturn(db2); + Mockito.when(catalog.getDbNullable("db3")).thenReturn(null); + Mockito.when(catalog.getDbNullable(Mockito.anyLong())).thenReturn(null); + Mockito.when(catalog.getDbNullable(db1.getId())).thenReturn(db1); + Mockito.when(catalog.getDbNullable(db2.getId())).thenReturn(db2); + + DbsProcDir dir; + ProcNodeInterface node; + + dir = new DbsProcDir(env, catalog); + try { + node = dir.lookup(String.valueOf(db1.getId())); + Assertions.assertNotNull(node); + Assertions.assertTrue(node instanceof TablesProcDir); + } catch (AnalysisException e) { + Assertions.fail(); + } + + dir = new DbsProcDir(env, catalog); + try { + node = dir.lookup(String.valueOf(db2.getId())); + Assertions.assertNotNull(node); + Assertions.assertTrue(node instanceof TablesProcDir); + } catch (AnalysisException e) { + Assertions.fail(); + } + + dir = new DbsProcDir(env, catalog); + node = dir.lookup("10002"); + Assertions.assertNull(node); + }); } @Test @@ -144,10 +146,10 @@ public void testFetchResultNormal() throws AnalysisException { dir = new DbsProcDir(env, catalog); result = dir.fetchResult(); - Assert.assertNotNull(result); - Assert.assertTrue(result instanceof BaseProcResult); + Assertions.assertNotNull(result); + Assertions.assertTrue(result instanceof BaseProcResult); - Assert.assertEquals(Lists.newArrayList("DbId", "DbName", "TableNum", "Size", "Quota", + Assertions.assertEquals(Lists.newArrayList("DbId", "DbName", "TableNum", "Size", "Quota", "LastConsistencyCheckTime", "ReplicaCount", "ReplicaQuota", "RunningTransactionNum", "TransactionQuota", "LastUpdateTime"), result.getColumnNames()); List> rows = Lists.newArrayList(); @@ -155,7 +157,7 @@ public void testFetchResultNormal() throws AnalysisException { FeConstants.null_string, "0", "1073741824", "10", String.valueOf(Config.max_running_txn_num_per_db), FeConstants.null_string)); rows.add(Arrays.asList(String.valueOf(db2.getId()), db2.getFullName(), "0", "0.000 ", "8388608.000 TB", FeConstants.null_string, "0", "1073741824", "20", String.valueOf(Config.max_running_txn_num_per_db), FeConstants.null_string)); - Assert.assertEquals(rows, result.getRows()); + Assertions.assertEquals(rows, result.getRows()); } @Test @@ -175,12 +177,12 @@ public void testFetchResultInvalid() throws AnalysisException { dir = new DbsProcDir(env, catalog); result = dir.fetchResult(); - Assert.assertEquals(Lists.newArrayList("DbId", "DbName", "TableNum", "Size", "Quota", + Assertions.assertEquals(Lists.newArrayList("DbId", "DbName", "TableNum", "Size", "Quota", "LastConsistencyCheckTime", "ReplicaCount", "ReplicaQuota", "RunningTransactionNum", "TransactionQuota", "LastUpdateTime"), result.getColumnNames()); List> rows = Lists.newArrayList(); - Assert.assertEquals(rows, result.getRows()); + Assertions.assertEquals(rows, result.getRows()); } @Test @@ -196,10 +198,10 @@ public void testListTableNameFailed() throws AnalysisException { DbsProcDir dbsProcDir = new DbsProcDir(env, ctlg); ProcResult procResult = dbsProcDir.fetchResult(); List> rows = procResult.getRows(); - Assert.assertEquals(1, rows.size()); + Assertions.assertEquals(1, rows.size()); List strings = rows.get(0); - Assert.assertEquals("3", strings.get(0)); // id - Assert.assertEquals("db1", strings.get(1)); // name - Assert.assertEquals("-1", strings.get(2)); // tableNum + Assertions.assertEquals("3", strings.get(0)); // id + Assertions.assertEquals("db1", strings.get(1)); // name + Assertions.assertEquals("-1", strings.get(2)); // tableNum } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexSchemaProcNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexSchemaProcNodeTest.java index c65d6795d3ed3a..bcb7352fd7f5b4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexSchemaProcNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexSchemaProcNodeTest.java @@ -30,8 +30,8 @@ import org.apache.doris.qe.SqlModeHelper; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -52,10 +52,10 @@ public void testFetchResult() throws AnalysisException { columnList.add(column2); IndexSchemaProcNode indexSchemaProcNode = new IndexSchemaProcNode(columnList, null); ProcResult procResult = indexSchemaProcNode.fetchResult(); - Assert.assertEquals(2, procResult.getRows().size()); - Assert.assertTrue(procResult.getRows().get(1).contains(column2.getDisplayName())); - Assert.assertEquals("The column size should be 6", 6, procResult.getColumnNames().size()); - Assert.assertEquals("The row size should be 6", 6, procResult.getRows().get(1).size()); + Assertions.assertEquals(2, procResult.getRows().size()); + Assertions.assertTrue(procResult.getRows().get(1).contains(column2.getDisplayName())); + Assertions.assertEquals(6, procResult.getColumnNames().size(), "The column size should be 6"); + Assertions.assertEquals(6, procResult.getRows().get(1).size(), "The row size should be 6"); } @@ -69,8 +69,8 @@ public void testCreateResultShowsNestedCommentsWhenCommentsRequested() { Lists.newArrayList(column), null, Lists.newArrayList(IndexSchemaProcNode.COMMENT_COLUMN_TITLE)); - Assert.assertTrue(result.getRows().get(0).get(1).contains("nested-comment")); - Assert.assertEquals("top-level-comment", result.getRows().get(0).get(6)); + Assertions.assertTrue(result.getRows().get(0).get(1).contains("nested-comment")); + Assertions.assertEquals("top-level-comment", result.getRows().get(0).get(6)); } @Test @@ -84,17 +84,17 @@ public void testCreateResultPreservesNestedRequirednessWithAndWithoutComments() Lists.newArrayList(column), null, Lists.newArrayList(IndexSchemaProcNode.COMMENT_COLUMN_TITLE)) .getRows().get(0).get(1); - Assert.assertTrue(typeWithComments.contains( + Assertions.assertTrue(typeWithComments.contains( "required_value:int not null comment \"required-comment\"")); - Assert.assertTrue(typeWithComments.contains( + Assertions.assertTrue(typeWithComments.contains( "optional_value:int comment \"optional-comment\"")); String typeWithoutComments = IndexSchemaProcNode.createResult( Lists.newArrayList(column), null, Lists.newArrayList()) .getRows().get(0).get(1); - Assert.assertTrue(typeWithoutComments.contains("required_value:int not null")); - Assert.assertFalse(typeWithoutComments.contains("required-comment")); - Assert.assertFalse(typeWithoutComments.contains("optional-comment")); + Assertions.assertTrue(typeWithoutComments.contains("required_value:int not null")); + Assertions.assertFalse(typeWithoutComments.contains("required-comment")); + Assertions.assertFalse(typeWithoutComments.contains("optional-comment")); } @Test @@ -110,7 +110,7 @@ public void testCreateResultQuotesNestedCommentsAsSqlLiterals() { Lists.newArrayList(IndexSchemaProcNode.COMMENT_COLUMN_TITLE)) .getRows().get(0).get(1); - Assert.assertTrue(displayedType.contains("comment \"owner's \\\\path\"")); + Assertions.assertTrue(displayedType.contains("comment \"owner's \\\\path\"")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexesProcNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexesProcNodeTest.java index db10fb563b016d..8a8a76168408e8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexesProcNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/IndexesProcNodeTest.java @@ -28,8 +28,8 @@ import org.apache.doris.common.AnalysisException; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; @@ -62,31 +62,31 @@ public void testFetchResult() throws AnalysisException { IndexesProcNode indexesProcNode = new IndexesProcNode(table); ProcResult procResult = indexesProcNode.fetchResult(); - Assert.assertEquals(3, procResult.getRows().size()); + Assertions.assertEquals(3, procResult.getRows().size()); - Assert.assertEquals(procResult.getRows().get(0).get(0), "tbl_test_indexes_proc"); - Assert.assertEquals(procResult.getRows().get(0).get(1), "2"); - Assert.assertEquals(procResult.getRows().get(0).get(3), "inverted_index"); - Assert.assertEquals(procResult.getRows().get(0).get(5), "col_2"); - Assert.assertEquals(procResult.getRows().get(0).get(11), "INVERTED"); - Assert.assertEquals(procResult.getRows().get(0).get(12), "inverted index on col_2"); - Assert.assertEquals(procResult.getRows().get(0).get(13), "(\"lower_case\" = \"true\", \"parser\" = \"unicode\", \"support_phrase\" = \"true\")"); + Assertions.assertEquals(procResult.getRows().get(0).get(0), "tbl_test_indexes_proc"); + Assertions.assertEquals(procResult.getRows().get(0).get(1), "2"); + Assertions.assertEquals(procResult.getRows().get(0).get(3), "inverted_index"); + Assertions.assertEquals(procResult.getRows().get(0).get(5), "col_2"); + Assertions.assertEquals(procResult.getRows().get(0).get(11), "INVERTED"); + Assertions.assertEquals(procResult.getRows().get(0).get(12), "inverted index on col_2"); + Assertions.assertEquals(procResult.getRows().get(0).get(13), "(\"lower_case\" = \"true\", \"parser\" = \"unicode\", \"support_phrase\" = \"true\")"); - Assert.assertEquals(procResult.getRows().get(1).get(0), "tbl_test_indexes_proc"); - Assert.assertEquals(procResult.getRows().get(1).get(1), "3"); - Assert.assertEquals(procResult.getRows().get(1).get(3), "bloomfilter_index"); - Assert.assertEquals(procResult.getRows().get(1).get(5), "col_3"); - Assert.assertEquals(procResult.getRows().get(1).get(11), "BLOOMFILTER"); - Assert.assertEquals(procResult.getRows().get(1).get(12), "bloomfilter index on col_3"); - Assert.assertEquals(procResult.getRows().get(1).get(13), ""); + Assertions.assertEquals(procResult.getRows().get(1).get(0), "tbl_test_indexes_proc"); + Assertions.assertEquals(procResult.getRows().get(1).get(1), "3"); + Assertions.assertEquals(procResult.getRows().get(1).get(3), "bloomfilter_index"); + Assertions.assertEquals(procResult.getRows().get(1).get(5), "col_3"); + Assertions.assertEquals(procResult.getRows().get(1).get(11), "BLOOMFILTER"); + Assertions.assertEquals(procResult.getRows().get(1).get(12), "bloomfilter index on col_3"); + Assertions.assertEquals(procResult.getRows().get(1).get(13), ""); - Assert.assertEquals(procResult.getRows().get(2).get(0), "tbl_test_indexes_proc"); - Assert.assertEquals(procResult.getRows().get(2).get(1), "4"); - Assert.assertEquals(procResult.getRows().get(2).get(3), "ngram_bf_index"); - Assert.assertEquals(procResult.getRows().get(2).get(5), "col_4"); - Assert.assertEquals(procResult.getRows().get(2).get(11), "NGRAM_BF"); - Assert.assertEquals(procResult.getRows().get(2).get(12), "ngram_bf index on col_4"); - Assert.assertEquals(procResult.getRows().get(2).get(13), "(\"bf_size\" = \"256\", \"gram_size\" = \"3\")"); + Assertions.assertEquals(procResult.getRows().get(2).get(0), "tbl_test_indexes_proc"); + Assertions.assertEquals(procResult.getRows().get(2).get(1), "4"); + Assertions.assertEquals(procResult.getRows().get(2).get(3), "ngram_bf_index"); + Assertions.assertEquals(procResult.getRows().get(2).get(5), "col_4"); + Assertions.assertEquals(procResult.getRows().get(2).get(11), "NGRAM_BF"); + Assertions.assertEquals(procResult.getRows().get(2).get(12), "ngram_bf index on col_4"); + Assertions.assertEquals(procResult.getRows().get(2).get(13), "(\"bf_size\" = \"256\", \"gram_size\" = \"3\")"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/PartitionsProcDirTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/PartitionsProcDirTest.java index 15d11b3f57d681..0ff625f6565b35 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/PartitionsProcDirTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/PartitionsProcDirTest.java @@ -20,16 +20,16 @@ import org.apache.doris.common.Config; import org.apache.doris.common.FeConstants; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class PartitionsProcDirTest { private String originDeployMode; private String originCloudUniqueId; - @Before + @BeforeEach public void setUp() { originDeployMode = Config.deploy_mode; originCloudUniqueId = Config.cloud_unique_id; @@ -37,7 +37,7 @@ public void setUp() { Config.cloud_unique_id = ""; } - @After + @AfterEach public void tearDown() { Config.deploy_mode = originDeployMode; Config.cloud_unique_id = originCloudUniqueId; @@ -45,17 +45,17 @@ public void tearDown() { @Test public void testDisplayInNonCloudMode() { - Assert.assertEquals("HDD", PartitionsProcDir.getStorageMediumDisplay("HDD")); - Assert.assertEquals("tag.location.default: 1", + Assertions.assertEquals("HDD", PartitionsProcDir.getStorageMediumDisplay("HDD")); + Assertions.assertEquals("tag.location.default: 1", PartitionsProcDir.getReplicaAllocationDisplay("tag.location.default: 1")); } @Test public void testDisplayInCloudMode() { Config.deploy_mode = "cloud"; - Assert.assertEquals(PartitionsProcDir.CLOUD_STORAGE_MEDIUM_DISPLAY, + Assertions.assertEquals(PartitionsProcDir.CLOUD_STORAGE_MEDIUM_DISPLAY, PartitionsProcDir.getStorageMediumDisplay("HDD")); - Assert.assertEquals(FeConstants.null_string, + Assertions.assertEquals(FeConstants.null_string, PartitionsProcDir.getReplicaAllocationDisplay("tag.location.default: 1")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/proc/ProcServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/proc/ProcServiceTest.java index b8c50c5e12fc2b..eaa743f32d4abe 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/proc/ProcServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/proc/ProcServiceTest.java @@ -32,10 +32,10 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.ImmutableMap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -60,28 +60,28 @@ public ProcResult fetchResult() { // | - conf // | - build.sh // | - common - @Before + @BeforeEach public void beforeTest() { ProcService procService = ProcService.getInstance(); BaseProcDir paloDir = new BaseProcDir(); - Assert.assertTrue(procService.register("palo", paloDir)); + Assertions.assertTrue(procService.register("palo", paloDir)); BaseProcDir beDir = new BaseProcDir(); - Assert.assertTrue(paloDir.register("be", beDir)); - Assert.assertTrue(beDir.register("src", new BaseProcDir())); - Assert.assertTrue(beDir.register("deps", new BaseProcDir())); + Assertions.assertTrue(paloDir.register("be", beDir)); + Assertions.assertTrue(beDir.register("src", new BaseProcDir())); + Assertions.assertTrue(beDir.register("deps", new BaseProcDir())); BaseProcDir feDir = new BaseProcDir(); - Assert.assertTrue(paloDir.register("fe", feDir)); - Assert.assertTrue(feDir.register("src", new BaseProcDir())); - Assert.assertTrue(feDir.register("conf", new BaseProcDir())); - Assert.assertTrue(feDir.register("build.sh", new EmptyProcNode())); + Assertions.assertTrue(paloDir.register("fe", feDir)); + Assertions.assertTrue(feDir.register("src", new BaseProcDir())); + Assertions.assertTrue(feDir.register("conf", new BaseProcDir())); + Assertions.assertTrue(feDir.register("build.sh", new EmptyProcNode())); - Assert.assertTrue(paloDir.register("common", new BaseProcDir())); + Assertions.assertTrue(paloDir.register("common", new BaseProcDir())); } - @After + @AfterEach public void afterTest() { ProcService.destroy(); } @@ -92,7 +92,7 @@ public void testRegisterNormal() { String name = "test"; BaseProcDir dir = new BaseProcDir(); - Assert.assertTrue(procService.register(name, dir)); + Assertions.assertTrue(procService.register(name, dir)); } // register second time @@ -102,8 +102,8 @@ public void testRegisterSecond() { String name = "test"; BaseProcDir dir = new BaseProcDir(); - Assert.assertTrue(procService.register(name, dir)); - Assert.assertFalse(procService.register(name, dir)); + Assertions.assertTrue(procService.register(name, dir)); + Assertions.assertFalse(procService.register(name, dir)); } // register invalid @@ -113,9 +113,9 @@ public void testRegisterInvalidInput() { String name = "test"; BaseProcDir dir = new BaseProcDir(); - Assert.assertFalse(procService.register(null, dir)); - Assert.assertFalse(procService.register("", dir)); - Assert.assertFalse(procService.register(name, null)); + Assertions.assertFalse(procService.register(null, dir)); + Assertions.assertFalse(procService.register("", dir)); + Assertions.assertFalse(procService.register(name, null)); } @Test @@ -123,16 +123,16 @@ public void testOpenNormal() throws AnalysisException { ProcService procService = ProcService.getInstance(); // assert root - Assert.assertNotNull(procService.open("/")); - Assert.assertNotNull(procService.open("/palo")); - Assert.assertNotNull(procService.open("/palo/be")); - Assert.assertNotNull(procService.open("/palo/be/src")); - Assert.assertNotNull(procService.open("/palo/be/deps")); - Assert.assertNotNull(procService.open("/palo/fe")); - Assert.assertNotNull(procService.open("/palo/fe/src")); - Assert.assertNotNull(procService.open("/palo/fe/conf")); - Assert.assertNotNull(procService.open("/palo/fe/build.sh")); - Assert.assertNotNull(procService.open("/palo/common")); + Assertions.assertNotNull(procService.open("/")); + Assertions.assertNotNull(procService.open("/palo")); + Assertions.assertNotNull(procService.open("/palo/be")); + Assertions.assertNotNull(procService.open("/palo/be/src")); + Assertions.assertNotNull(procService.open("/palo/be/deps")); + Assertions.assertNotNull(procService.open("/palo/fe")); + Assertions.assertNotNull(procService.open("/palo/fe/src")); + Assertions.assertNotNull(procService.open("/palo/fe/conf")); + Assertions.assertNotNull(procService.open("/palo/fe/build.sh")); + Assertions.assertNotNull(procService.open("/palo/common")); } @Test @@ -140,18 +140,18 @@ public void testOpenSapceNormal() throws AnalysisException { ProcService procService = ProcService.getInstance(); // assert space - Assert.assertNotNull(procService.open(" \r/")); - Assert.assertNotNull(procService.open(" \r/ ")); - Assert.assertNotNull(procService.open(" /palo \r\n")); - Assert.assertNotNull(procService.open("\n\r\t /palo/be \n\r")); + Assertions.assertNotNull(procService.open(" \r/")); + Assertions.assertNotNull(procService.open(" \r/ ")); + Assertions.assertNotNull(procService.open(" /palo \r\n")); + Assertions.assertNotNull(procService.open("\n\r\t /palo/be \n\r")); // assert last '/' - Assert.assertNotNull(procService.open(" /palo/be/")); - Assert.assertNotNull(procService.open(" /palo/fe/ ")); + Assertions.assertNotNull(procService.open(" /palo/be/")); + Assertions.assertNotNull(procService.open(" /palo/fe/ ")); ProcNodeInterface node = procService.open("/dbs"); - Assert.assertNotNull(node); - Assert.assertTrue(node instanceof DbsProcDir); + Assertions.assertNotNull(node); + Assertions.assertTrue(node instanceof DbsProcDir); } @Test @@ -166,29 +166,29 @@ public void testOpenFail() { ++errCount; } try { - Assert.assertNull(procService.open("/palo/b e")); + Assertions.assertNull(procService.open("/palo/b e")); } catch (AnalysisException e) { ++errCount; } try { - Assert.assertNull(procService.open("/palo/fe/build.sh/")); + Assertions.assertNull(procService.open("/palo/fe/build.sh/")); } catch (AnalysisException e) { ++errCount; } // assert no root try { - Assert.assertNull(procService.open("palo")); + Assertions.assertNull(procService.open("palo")); } catch (AnalysisException e) { ++errCount; } try { - Assert.assertNull(procService.open(" palo")); + Assertions.assertNull(procService.open(" palo")); } catch (AnalysisException e) { ++errCount; } - Assert.assertEquals(5, errCount); + Assertions.assertEquals(5, errCount); } @Test @@ -235,14 +235,14 @@ public void testTabletProc() throws AnalysisException { ProcResult result = new ReplicasProcNode(tabletId, Collections.singletonList(replica)).fetchResult(); List> rows = result.getRows(); - Assert.assertEquals(1, rows.size()); + Assertions.assertEquals(1, rows.size()); List row = rows.get(0); - Assert.assertEquals(replicasTitles.size(), row.size()); - Assert.assertEquals("6006", row.get(replicaIdIdx)); - Assert.assertEquals("10002", row.get(backendIdIdx)); - Assert.assertEquals("101", row.get(versionIdx)); - Assert.assertEquals("100", row.get(lastSuccessVersionIdx)); + Assertions.assertEquals(replicasTitles.size(), row.size()); + Assertions.assertEquals("6006", row.get(replicaIdIdx)); + Assertions.assertEquals("10002", row.get(backendIdIdx)); + Assertions.assertEquals("101", row.get(versionIdx)); + Assertions.assertEquals("100", row.get(lastSuccessVersionIdx)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/AutoProfileTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/AutoProfileTest.java index 2b6914e016d110..6c310c820a6681 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/AutoProfileTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/AutoProfileTest.java @@ -20,9 +20,9 @@ import org.apache.doris.common.util.DebugUtil; import org.apache.doris.thrift.TUniqueId; -import org.junit.Test; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import org.mockito.Mockito; diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ExecutionProfileTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ExecutionProfileTest.java index bd8310148bda9a..cdf63bb54f3b6a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ExecutionProfileTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ExecutionProfileTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; @@ -51,14 +51,14 @@ public void testAggregatedProfileUnevenPipelineCounts() { // Must not throw despite the uneven pipeline counts. RuntimeProfile result = executionProfile.getPipelineAggregatedProfile(Maps.newHashMap()); - Assert.assertNotNull(result); - Assert.assertEquals("Fragments", result.getName()); + Assertions.assertNotNull(result); + Assertions.assertEquals("Fragments", result.getName()); // The max pipeline count (2) is used, so both pipelines are represented. List> fragments = result.getChildList(); - Assert.assertEquals(1, fragments.size()); + Assertions.assertEquals(1, fragments.size()); RuntimeProfile fragment0 = fragments.get(0).first; - Assert.assertEquals("Fragment 0", fragment0.getName()); - Assert.assertEquals(2, fragment0.getChildList().size()); + Assertions.assertEquals("Fragment 0", fragment0.getName()); + Assertions.assertEquals(2, fragment0.getChildList().size()); } private RuntimeProfile pipelineWithTasks(String name, int taskNum) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfilePersistentTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfilePersistentTest.java index 3e289e2d61ba72..861404cb8cc6de 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfilePersistentTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfilePersistentTest.java @@ -29,8 +29,8 @@ import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import java.io.ByteArrayInputStream; @@ -120,7 +120,7 @@ public void summaryProfileBasicTest() { writeFailed = true; } - Assert.assertFalse(writeFailed); + Assertions.assertFalse(writeFailed); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); @@ -134,21 +134,21 @@ public void summaryProfileBasicTest() { LOG.info("read failed: {}", e.getMessage(), e); readFailed = true; } - Assert.assertFalse(readFailed); + Assertions.assertFalse(readFailed); SafeStringBuilder builder1 = new SafeStringBuilder(); summaryProfile.prettyPrint(builder1); SafeStringBuilder builder2 = new SafeStringBuilder(); deserializedSummaryProfile.prettyPrint(builder2); - Assert.assertNotEquals("", builder1.toString()); - Assert.assertEquals(builder1.toString(), builder2.toString()); + Assertions.assertNotEquals("", builder1.toString()); + Assertions.assertEquals(builder1.toString(), builder2.toString()); for (Entry entry : summaryProfile.getAsInfoStings().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String deserializedValue = deserializedSummaryProfile.getAsInfoStings().get(key); - Assert.assertEquals(value, deserializedValue); + Assertions.assertEquals(value, deserializedValue); } } @@ -165,19 +165,19 @@ public void profileBasicTest() throws IOException { // so we store the original answer to a string String profileContentString = profile.getProfileByLevel(); String profileStoragePathTmp = profile.getProfileStoragePath(); - Assert.assertFalse(Strings.isNullOrEmpty(profileStoragePathTmp)); + Assertions.assertFalse(Strings.isNullOrEmpty(profileStoragePathTmp)); LOG.info("Profile storage path: {}", profileStoragePathTmp); Profile deserializedProfile = Profile.read(profileStoragePathTmp); - Assert.assertNotNull(deserializedProfile); - Assert.assertEquals(profileContentString, profile.getProfileByLevel()); - Assert.assertEquals(profile.getProfileByLevel(), deserializedProfile.getProfileByLevel()); + Assertions.assertNotNull(deserializedProfile); + Assertions.assertEquals(profileContentString, profile.getProfileByLevel()); + Assertions.assertEquals(profile.getProfileByLevel(), deserializedProfile.getProfileByLevel()); // make sure file is removed profile.deleteFromStorage(); File tmpFile = new File(profileStoragePathTmp); - Assert.assertFalse(tmpFile.exists()); + Assertions.assertFalse(tmpFile.exists()); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } @@ -192,23 +192,23 @@ public void testWriteAndReadStorage() throws IOException { try { // Test writeToStorage profile.writeToStorage(tempDir.toString()); - Assert.assertFalse(Strings.isNullOrEmpty(profile.getProfileStoragePath())); - Assert.assertTrue(new File(profile.getProfileStoragePath()).exists()); + Assertions.assertFalse(Strings.isNullOrEmpty(profile.getProfileStoragePath())); + Assertions.assertTrue(new File(profile.getProfileStoragePath()).exists()); // Test read Profile readProfile = Profile.read(profile.getProfileStoragePath()); - Assert.assertNotNull(readProfile); - Assert.assertEquals(profile.getId(), readProfile.getId()); - Assert.assertEquals(profile.getQueryFinishTimestamp(), readProfile.getQueryFinishTimestamp()); + Assertions.assertNotNull(readProfile); + Assertions.assertEquals(profile.getId(), readProfile.getId()); + Assertions.assertEquals(profile.getQueryFinishTimestamp(), readProfile.getQueryFinishTimestamp()); // Verify content is readable SafeStringBuilder builder = new SafeStringBuilder(); readProfile.getOnStorageProfile(builder); - Assert.assertFalse(Strings.isNullOrEmpty(builder.toString())); + Assertions.assertFalse(Strings.isNullOrEmpty(builder.toString())); // Clean up profile.deleteFromStorage(); - Assert.assertFalse(new File(profile.getProfileStoragePath()).exists()); + Assertions.assertFalse(new File(profile.getProfileStoragePath()).exists()); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } @@ -227,14 +227,14 @@ public void testCreateProfileFileInputStream() throws IOException { // Test createPorfileFileInputStream FileInputStream fis = Profile.createPorfileFileInputStream(path); - Assert.assertNotNull(fis); + Assertions.assertNotNull(fis); fis.close(); // Test with invalid path - Assert.assertNull(Profile.createPorfileFileInputStream("/invalid/path")); + Assertions.assertNull(Profile.createPorfileFileInputStream("/invalid/path")); // Test with directory - Assert.assertNull(Profile.createPorfileFileInputStream(tempDir.toString())); + Assertions.assertNull(Profile.createPorfileFileInputStream(tempDir.toString())); // Clean up profile.deleteFromStorage(); @@ -253,7 +253,7 @@ public void testGetOnStorageProfile() throws IOException { // First get profile content before storage StringBuilder beforeStorage = new StringBuilder(); beforeStorage.append(profile.getProfileByLevel()); - Assert.assertFalse(Strings.isNullOrEmpty(beforeStorage.toString())); + Assertions.assertFalse(Strings.isNullOrEmpty(beforeStorage.toString())); // Write to storage profile.writeToStorage(tempDir.toString()); @@ -261,17 +261,17 @@ public void testGetOnStorageProfile() throws IOException { // Test getOnStorageProfile StringBuilder afterStorage = new StringBuilder(); afterStorage.append(profile.getProfileByLevel()); - Assert.assertFalse(Strings.isNullOrEmpty(afterStorage.toString())); + Assertions.assertFalse(Strings.isNullOrEmpty(afterStorage.toString())); // Content should be same - Assert.assertEquals(beforeStorage.toString().trim(), afterStorage.toString().trim()); + Assertions.assertEquals(beforeStorage.toString().trim(), afterStorage.toString().trim()); // Test with corrupted file File profileFile = new File(profile.getProfileStoragePath()); FileUtils.writeStringToFile(profileFile, "corrupted content", StandardCharsets.UTF_8); SafeStringBuilder corruptedContent = new SafeStringBuilder(); profile.getOnStorageProfile(corruptedContent); - Assert.assertTrue(corruptedContent.toString().contains("Failed to read profile")); + Assertions.assertTrue(corruptedContent.toString().contains("Failed to read profile")); // Clean up profile.deleteFromStorage(); @@ -292,19 +292,19 @@ public void testProfileRead() throws IOException { // Test read with valid path Profile readProfile = Profile.read(profile.getProfileStoragePath()); - Assert.assertNotNull(readProfile); - Assert.assertEquals(profile.getId(), readProfile.getId()); + Assertions.assertNotNull(readProfile); + Assertions.assertEquals(profile.getId(), readProfile.getId()); // Test read with invalid path - Assert.assertNull(Profile.read("/invalid/path")); + Assertions.assertNull(Profile.read("/invalid/path")); // Test read with directory - Assert.assertNull(Profile.read(tempDir.toString())); + Assertions.assertNull(Profile.read(tempDir.toString())); // Test read with corrupted file File profileFile = new File(profile.getProfileStoragePath()); FileUtils.writeStringToFile(profileFile, "corrupted", StandardCharsets.UTF_8); - Assert.assertNull(Profile.read(profile.getProfileStoragePath())); + Assertions.assertNull(Profile.read(profile.getProfileStoragePath())); // Clean up profile.deleteFromStorage(); @@ -322,18 +322,18 @@ public void testwriteToStorage() throws IOException { try { // Test writeToStorage profile.writeToStorage(tempDir.toString()); - Assert.assertFalse(Strings.isNullOrEmpty(profile.getProfileStoragePath())); - Assert.assertTrue(new File(profile.getProfileStoragePath()).exists()); - Assert.assertTrue(profile.getProfileStoragePath().endsWith(".zip")); + Assertions.assertFalse(Strings.isNullOrEmpty(profile.getProfileStoragePath())); + Assertions.assertTrue(new File(profile.getProfileStoragePath()).exists()); + Assertions.assertTrue(profile.getProfileStoragePath().endsWith(".zip")); // Test write with empty id Profile emptyProfile = new Profile(); emptyProfile.writeToStorage(tempDir.toString()); - Assert.assertTrue(Strings.isNullOrEmpty(emptyProfile.getProfileStoragePath())); + Assertions.assertTrue(Strings.isNullOrEmpty(emptyProfile.getProfileStoragePath())); // Test write already stored profile profile.writeToStorage(tempDir.toString()); - Assert.assertTrue(profile.getProfileStoragePath().endsWith(".zip")); + Assertions.assertTrue(profile.getProfileStoragePath().endsWith(".zip")); // Clean up profile.deleteFromStorage(); @@ -355,15 +355,15 @@ public void testCreateProfileFileInputStreamWithCorruptedFiles() throws IOExcept // Test with empty file File emptyFile = new File(tempDir.toString(), "empty_1234567_abcdef.zip"); emptyFile.createNewFile(); - Assert.assertNull(Profile.createPorfileFileInputStream(emptyFile.getAbsolutePath())); + Assertions.assertNull(Profile.createPorfileFileInputStream(emptyFile.getAbsolutePath())); // Test with invalid filename format File invalidFile = new File(tempDir.toString(), "invalid_name.zip"); invalidFile.createNewFile(); - Assert.assertNull(Profile.createPorfileFileInputStream(invalidFile.getAbsolutePath())); + Assertions.assertNull(Profile.createPorfileFileInputStream(invalidFile.getAbsolutePath())); // Test with non-existing file - Assert.assertNull(Profile.createPorfileFileInputStream(tempDir + "/non_existing.zip")); + Assertions.assertNull(Profile.createPorfileFileInputStream(tempDir + "/non_existing.zip")); // Clean up profile.deleteFromStorage(); @@ -392,7 +392,7 @@ public void testGetOnStorageProfileComprehensive() throws IOException { Profile nonStoredProfile = constructRandomProfile(1); SafeStringBuilder nonStoredBuilder = new SafeStringBuilder(); nonStoredProfile.getOnStorageProfile(nonStoredBuilder); - Assert.assertEquals("", nonStoredBuilder.toString()); + Assertions.assertEquals("", nonStoredBuilder.toString()); // Test with invalid zip entry File profileFile = new File(profile.getProfileStoragePath()); @@ -406,7 +406,7 @@ public void testGetOnStorageProfileComprehensive() throws IOException { SafeStringBuilder invalidBuilder = new SafeStringBuilder(); profile.getOnStorageProfile(invalidBuilder); - Assert.assertTrue(invalidBuilder.toString().contains("Failed to read profile")); + Assertions.assertTrue(invalidBuilder.toString().contains("Failed to read profile")); // Clean up profile.deleteFromStorage(); @@ -430,15 +430,15 @@ public void testProfileReadComprehensive() throws IOException { FileOutputStream fos = new FileOutputStream(profileFile); ZipOutputStream zos = new ZipOutputStream(fos); zos.close(); - Assert.assertNull(Profile.read(profileFile.getAbsolutePath())); + Assertions.assertNull(Profile.read(profileFile.getAbsolutePath())); // Test read with corrupted zip FileUtils.writeStringToFile(profileFile, "not a zip file", StandardCharsets.UTF_8); - Assert.assertNull(Profile.read(profileFile.getAbsolutePath())); + Assertions.assertNull(Profile.read(profileFile.getAbsolutePath())); // Test read with empty file FileUtils.writeStringToFile(profileFile, "", StandardCharsets.UTF_8); - Assert.assertNull(Profile.read(profileFile.getAbsolutePath())); + Assertions.assertNull(Profile.read(profileFile.getAbsolutePath())); // Clean up profile.deleteFromStorage(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileStructureTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileStructureTest.java index 0ec0dc1e3f0246..9a6af35b9ea810 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileStructureTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileStructureTest.java @@ -24,8 +24,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; @@ -43,11 +43,11 @@ public void testToString() { String result = profile.toString(); // Verify the structure of the output - Assert.assertTrue("Should contain DetailProfile", result.contains("DetailProfile")); - Assert.assertTrue("Should contain Fragments section", result.contains(" Fragments:")); - Assert.assertTrue("Should contain Fragment 0", result.contains(" Fragment 0:")); - Assert.assertTrue("Should contain Fragment 1", result.contains(" Fragment 1:")); - Assert.assertTrue("Should contain LoadChannels section", result.contains(" LoadChannels:")); + Assertions.assertTrue(result.contains("DetailProfile"), "Should contain DetailProfile"); + Assertions.assertTrue(result.contains(" Fragments:"), "Should contain Fragments section"); + Assertions.assertTrue(result.contains(" Fragment 0:"), "Should contain Fragment 0"); + Assertions.assertTrue(result.contains(" Fragment 1:"), "Should contain Fragment 1"); + Assertions.assertTrue(result.contains(" LoadChannels:"), "Should contain LoadChannels section"); } @Test @@ -59,10 +59,10 @@ public void testPrettyPrint() { profile.prettyPrint(sb, " "); String result = sb.toString(); - Assert.assertTrue("Should contain proper indentation", result.contains(" Fragments:")); - Assert.assertTrue("Should contain Fragment 0 with indentation", result.contains(" Fragment 0:")); - Assert.assertTrue("Should contain Fragment 1 with indentation", result.contains(" Fragment 1:")); - Assert.assertTrue("Should contain LoadChannels with indentation", result.contains(" LoadChannels:")); + Assertions.assertTrue(result.contains(" Fragments:"), "Should contain proper indentation"); + Assertions.assertTrue(result.contains(" Fragment 0:"), "Should contain Fragment 0 with indentation"); + Assertions.assertTrue(result.contains(" Fragment 1:"), "Should contain Fragment 1 with indentation"); + Assertions.assertTrue(result.contains(" LoadChannels:"), "Should contain LoadChannels with indentation"); } @Test @@ -107,25 +107,23 @@ public void testGetPipelineAggregatedProfile() { RuntimeProfile result = profile.getPipelineAggregatedProfile(Maps.newHashMap()); // Verify root structure - Assert.assertEquals("Fragments", result.getName()); + Assertions.assertEquals("Fragments", result.getName()); List> fragments = result.getChildList(); - Assert.assertEquals(1, fragments.size()); + Assertions.assertEquals(1, fragments.size()); // Verify Fragment structure RuntimeProfile fragment0 = fragments.get(0).first; - Assert.assertEquals("Fragment 0", fragment0.getName()); + Assertions.assertEquals("Fragment 0", fragment0.getName()); // Verify Pipeline structure List> pipelines = fragment0.getChildList(); - Assert.assertEquals(2, pipelines.size()); + Assertions.assertEquals(2, pipelines.size()); // Verify pipeline names and instance counts RuntimeProfile pipeline0 = pipelines.get(0).first; RuntimeProfile pipeline1 = pipelines.get(1).first; - Assert.assertTrue("Pipeline 0 should contain instance count", - pipeline0.getName().contains("Pipeline 0(instance_num=4)")); - Assert.assertTrue("Pipeline 1 should contain instance count", - pipeline1.getName().contains("Pipeline 1(instance_num=4)")); + Assertions.assertTrue(pipeline0.getName().contains("Pipeline 0(instance_num=4)"), "Pipeline 0 should contain instance count"); + Assertions.assertTrue(pipeline1.getName().contains("Pipeline 1(instance_num=4)"), "Pipeline 1 should contain instance count"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileTest.java index a9f3714526f251..ed231e65d30a4b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/ProfileTest.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.File; @@ -38,7 +37,6 @@ import java.util.UUID; public class ProfileTest { - public TemporaryFolder tempFolder = new TemporaryFolder(); private Profile profile; private File tempDir; diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileMergeTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileMergeTest.java index d61713181915ce..a7768592934a5b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileMergeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileMergeTest.java @@ -27,8 +27,8 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import java.util.ArrayList; @@ -71,10 +71,10 @@ public void testMergeCounter() { * */ LOG.info("Profile1:\n{}", mergeProfile.toString()); - Assert.assertTrue(mergeProfile.getCounterMap().get("Counter1") instanceof AggCounter); + Assertions.assertTrue(mergeProfile.getCounterMap().get("Counter1") instanceof AggCounter); AggCounter aggCounter = (AggCounter) mergeProfile.getCounterMap().get("Counter1"); - Assert.assertEquals(aggCounter.sum.getValue(), 202); - Assert.assertEquals(aggCounter.number, 2); + Assertions.assertEquals(aggCounter.sum.getValue(), 202); + Assertions.assertEquals(aggCounter.number, 2); } @Test @@ -169,13 +169,13 @@ public void testMergeProfileNormal() { mergedProfile.prettyPrint(builder, "\t"); LOG.info("Merged profile:\n{}", builder.toString()); - Assert.assertEquals(mergedProfile.getChildList().size(), 2); - Assert.assertTrue( + Assertions.assertEquals(mergedProfile.getChildList().size(), 2); + Assertions.assertTrue( mergedProfile.getChildList().get(0).first.getCounterMap().get("Counter1") instanceof AggCounter); AggCounter aggCounterNode1 = (AggCounter) mergedProfile.getChildList().get(0).first.getCounterMap() .get("Counter1"); - Assert.assertEquals(aggCounterNode1.sum.getValue(), 3); - Assert.assertEquals(aggCounterNode1.number, 3); + Assertions.assertEquals(aggCounterNode1.sum.getValue(), 3); + Assertions.assertEquals(aggCounterNode1.number, 3); } // Test the case where counter of RuntimeProfile has different structure. diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileTest.java index 7e40c7f146f30e..18e42f297af3aa 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/profile/RuntimeProfileTest.java @@ -28,8 +28,8 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -59,21 +59,21 @@ public void testSortChildren() { long time1 = profile.getChildList().get(1).first.getCounterTotalTime().getValue(); long time2 = profile.getChildList().get(2).first.getCounterTotalTime().getValue(); - Assert.assertEquals(3, time0); - Assert.assertEquals(2, time1); - Assert.assertEquals(1, time2); + Assertions.assertEquals(3, time0); + Assertions.assertEquals(2, time1); + Assertions.assertEquals(1, time2); } @Test public void testInfoStrings() { RuntimeProfile profile = new RuntimeProfile("profileName"); - Assert.assertEquals("", profile.getInfoString("key")); + Assertions.assertEquals("", profile.getInfoString("key")); // normal add and get profile.addInfoString("key", "value"); String value = profile.getInfoString("key"); - Assert.assertNotNull(value); - Assert.assertEquals(value, "value"); + Assertions.assertNotNull(value); + Assertions.assertEquals(value, "value"); // from thrift to profile and first update TRuntimeProfileTree tprofileTree = new TRuntimeProfileTree(); TRuntimeProfileNode tnode = new TRuntimeProfileNode(); @@ -86,17 +86,17 @@ public void testInfoStrings() { tnode.info_strings_display_order.add("key3"); profile.update(tprofileTree); - Assert.assertEquals(profile.getInfoString("key"), "value2"); - Assert.assertEquals(profile.getInfoString("key3"), "value3"); + Assertions.assertEquals(profile.getInfoString("key"), "value2"); + Assertions.assertEquals(profile.getInfoString("key3"), "value3"); // second update tnode.info_strings.put("key", "value4"); profile.update(tprofileTree); - Assert.assertEquals(profile.getInfoString("key"), "value4"); + Assertions.assertEquals(profile.getInfoString("key"), "value4"); SafeStringBuilder builder = new SafeStringBuilder(); profile.prettyPrint(builder, ""); - Assert.assertEquals(builder.toString(), + Assertions.assertEquals(builder.toString(), "profileName:\n - key: value4\n - key3: value3\n"); } @@ -104,10 +104,10 @@ public void testInfoStrings() { public void testCounter() { RuntimeProfile profile = new RuntimeProfile("test counter"); profile.addCounter("key", TUnit.UNIT, ""); - Assert.assertNotNull(profile.getCounterMap().get("key")); - Assert.assertNull(profile.getCounterMap().get("key2")); + Assertions.assertNotNull(profile.getCounterMap().get("key")); + Assertions.assertNull(profile.getCounterMap().get("key2")); profile.getCounterMap().get("key").setValue(TUnit.TIME_NS, 1); - Assert.assertEquals(profile.getCounterMap().get("key").getValue(), 1); + Assertions.assertEquals(profile.getCounterMap().get("key").getValue(), 1); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/AutoBucketUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/AutoBucketUtilsTest.java index 506f1e5835f3b6..e254770e8d9ac8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/AutoBucketUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/AutoBucketUtilsTest.java @@ -31,11 +31,11 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -106,7 +106,7 @@ private void expectations(MockedStatic mockedEnv, Env env, EditLog editLog, Mockito.when(env.getEditLog()).thenReturn(editLog); } - @Before + @BeforeEach public void setUp() throws Exception { FeConstants.runningUnitTest = true; FeConstants.default_scheduler_interval_millisecond = 100; @@ -116,7 +116,7 @@ public void setUp() throws Exception { Config.autobucket_partition_size_per_bucket_gb = 1; } - @After + @AfterEach public void tearDown() { try { Env.getCurrentEnv().clear(); @@ -158,7 +158,7 @@ private static String genCreateTableSql(String estimatePartitionSize) { // It works on Mac and development machine, but it reports an error on CI pipeline. I don't know what it is, // so @Ignore - @Ignore + @Disabled @Test public void test100MB() throws Exception { Env env = Mockito.mock(Env.class); @@ -168,11 +168,11 @@ public void test100MB() throws Exception { ImmutableMap backends = createBackends(10, 3, 2000000000); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(1, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(1, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test500MB() throws Exception { Env env = Mockito.mock(Env.class); @@ -182,11 +182,11 @@ public void test500MB() throws Exception { ImmutableMap backends = createBackends(10, 3, 2000000000); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(1, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(1, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test1G() throws Exception { Env env = Mockito.mock(Env.class); @@ -196,11 +196,11 @@ public void test1G() throws Exception { ImmutableMap backends = createBackends(3, 2, 500 * AutoBucketUtils.SIZE_1GB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(2, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(2, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test100G() throws Exception { Env env = Mockito.mock(Env.class); @@ -210,11 +210,11 @@ public void test100G() throws Exception { ImmutableMap backends = createBackends(3, 2, 500 * AutoBucketUtils.SIZE_1GB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(20, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(20, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test500G_0() throws Exception { Env env = Mockito.mock(Env.class); @@ -224,11 +224,11 @@ public void test500G_0() throws Exception { ImmutableMap backends = createBackends(3, 1, AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(63, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(63, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test500G_1() throws Exception { Env env = Mockito.mock(Env.class); @@ -238,11 +238,11 @@ public void test500G_1() throws Exception { ImmutableMap backends = createBackends(10, 3, 2 * AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(100, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(100, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test500G_2() throws Exception { Env env = Mockito.mock(Env.class); @@ -252,11 +252,11 @@ public void test500G_2() throws Exception { ImmutableMap backends = createBackends(1, 1, 100 * AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(100, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(100, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test1T_0() throws Exception { Env env = Mockito.mock(Env.class); @@ -266,11 +266,11 @@ public void test1T_0() throws Exception { ImmutableMap backends = createBackends(10, 3, 2 * AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(128, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(128, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test1T_1() throws Exception { Env env = Mockito.mock(Env.class); @@ -280,11 +280,11 @@ public void test1T_1() throws Exception { ImmutableMap backends = createBackends(200, 7, 4 * AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(128, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(128, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } - @Ignore + @Disabled @Test public void test1T_1_In_Cloud() throws Exception { Env env = Mockito.mock(Env.class); @@ -296,7 +296,7 @@ public void test1T_1_In_Cloud() throws Exception { ImmutableMap backends = createBackends(10, 7, 4 * AutoBucketUtils.SIZE_1TB); try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { expectations(mockedEnv, env, editLog, systemInfoService, backends); - Assert.assertEquals(41, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); + Assertions.assertEquals(41, AutoBucketUtils.getBucketsNum(estimatePartitionSize)); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/BrokerUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/BrokerUtilTest.java index 43614db3034761..25fa2206182373 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/BrokerUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/BrokerUtilTest.java @@ -21,8 +21,8 @@ import org.apache.doris.datasource.scan.FilePartitionUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -34,16 +34,16 @@ public void parseColumnsFromPath() { String path = "/path/to/dir/k1=v1/xxx.csv"; try { List columns = FilePartitionUtils.parseColumnsFromPath(path, Collections.singletonList("k1")); - Assert.assertEquals(1, columns.size()); - Assert.assertEquals(Collections.singletonList("v1"), columns); + Assertions.assertEquals(1, columns.size()); + Assertions.assertEquals(Collections.singletonList("v1"), columns); } catch (UserException e) { - Assert.fail(); + Assertions.fail(); } path = "/path/to/dir/k1/xxx.csv"; try { FilePartitionUtils.parseColumnsFromPath(path, Collections.singletonList("k1")); - Assert.fail(); + Assertions.fail(); } catch (UserException ignored) { // CHECKSTYLE IGNORE THIS LINE } @@ -51,7 +51,7 @@ public void parseColumnsFromPath() { path = "/path/to/dir/k1=v1/xxx.csv"; try { FilePartitionUtils.parseColumnsFromPath(path, Collections.singletonList("k2")); - Assert.fail(); + Assertions.fail(); } catch (UserException ignored) { // CHECKSTYLE IGNORE THIS LINE } @@ -59,25 +59,25 @@ public void parseColumnsFromPath() { path = "/path/to/dir/k1=v2/k1=v1/xxx.csv"; try { List columns = FilePartitionUtils.parseColumnsFromPath(path, Collections.singletonList("k1")); - Assert.assertEquals(1, columns.size()); - Assert.assertEquals(Collections.singletonList("v1"), columns); + Assertions.assertEquals(1, columns.size()); + Assertions.assertEquals(Collections.singletonList("v1"), columns); } catch (UserException e) { - Assert.fail(); + Assertions.fail(); } path = "/path/to/dir/k2=v2/k1=v1/xxx.csv"; try { List columns = FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2")); - Assert.assertEquals(2, columns.size()); - Assert.assertEquals(Lists.newArrayList("v1", "v2"), columns); + Assertions.assertEquals(2, columns.size()); + Assertions.assertEquals(Lists.newArrayList("v1", "v2"), columns); } catch (UserException e) { - Assert.fail(); + Assertions.fail(); } path = "/path/to/dir/k2=v2/a/k1=v1/xxx.csv"; try { FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2")); - Assert.fail(); + Assertions.fail(); } catch (UserException ignored) { // CHECKSTYLE IGNORE THIS LINE } @@ -85,7 +85,7 @@ public void parseColumnsFromPath() { path = "/path/to/dir/k2=v2/k1=v1/xxx.csv"; try { FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2", "k3")); - Assert.fail(); + Assertions.fail(); } catch (UserException ignored) { // CHECKSTYLE IGNORE THIS LINE } @@ -93,25 +93,25 @@ public void parseColumnsFromPath() { path = "/path/to/dir/k2=v2//k1=v1//xxx.csv"; try { List columns = FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2")); - Assert.assertEquals(2, columns.size()); - Assert.assertEquals(Lists.newArrayList("v1", "v2"), columns); + Assertions.assertEquals(2, columns.size()); + Assertions.assertEquals(Lists.newArrayList("v1", "v2"), columns); } catch (UserException e) { - Assert.fail(); + Assertions.fail(); } path = "/path/to/dir/k2==v2=//k1=v1//xxx.csv"; try { List columns = FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2")); - Assert.assertEquals(2, columns.size()); - Assert.assertEquals(Lists.newArrayList("v1", "=v2="), columns); + Assertions.assertEquals(2, columns.size()); + Assertions.assertEquals(Lists.newArrayList("v1", "=v2="), columns); } catch (UserException e) { - Assert.fail(); + Assertions.fail(); } path = "/path/to/dir/k2==v2=//k1=v1/"; try { FilePartitionUtils.parseColumnsFromPath(path, Lists.newArrayList("k1", "k2")); - Assert.fail(); + Assertions.fail(); } catch (UserException ignored) { // CHECKSTYLE IGNORE THIS LINE } @@ -120,7 +120,7 @@ public void parseColumnsFromPath() { try { FilePartitionUtils.parseColumnsFromPath(path, Collections.singletonList("k1")); } catch (UserException ignored) { - Assert.fail(); + Assertions.fail(); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugPointUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugPointUtilTest.java index 0a68885bf26e56..d675fb86b4606e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugPointUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugPointUtilTest.java @@ -24,8 +24,8 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class DebugPointUtilTest extends DorisHttpTestCase { @@ -33,45 +33,45 @@ public class DebugPointUtilTest extends DorisHttpTestCase { public void testDebugPoint() throws Exception { Config.enable_debug_points = true; - Assert.assertFalse(DebugPointUtil.isEnable("dbug1")); + Assertions.assertFalse(DebugPointUtil.isEnable("dbug1")); sendRequest("/api/debug_point/add/dbug1"); - Assert.assertTrue(DebugPointUtil.isEnable("dbug1")); + Assertions.assertTrue(DebugPointUtil.isEnable("dbug1")); sendRequest("/api/debug_point/remove/dbug1"); - Assert.assertFalse(DebugPointUtil.isEnable("dbug1")); + Assertions.assertFalse(DebugPointUtil.isEnable("dbug1")); sendRequest("/api/debug_point/add/dbug2"); - Assert.assertTrue(DebugPointUtil.isEnable("dbug2")); + Assertions.assertTrue(DebugPointUtil.isEnable("dbug2")); sendRequest("/api/debug_point/clear"); - Assert.assertFalse(DebugPointUtil.isEnable("dbug2")); + Assertions.assertFalse(DebugPointUtil.isEnable("dbug2")); sendRequest("/api/debug_point/add/dbug3?execute=3"); for (int i = 0; i < 3; i++) { - Assert.assertTrue(DebugPointUtil.isEnable("dbug3")); + Assertions.assertTrue(DebugPointUtil.isEnable("dbug3")); } - Assert.assertFalse(DebugPointUtil.isEnable("dbug3")); + Assertions.assertFalse(DebugPointUtil.isEnable("dbug3")); sendRequest("/api/debug_point/add/dbug4?timeout=1"); Thread.sleep(200); - Assert.assertTrue(DebugPointUtil.isEnable("dbug4")); + Assertions.assertTrue(DebugPointUtil.isEnable("dbug4")); Thread.sleep(1000); - Assert.assertFalse(DebugPointUtil.isEnable("dbug4")); + Assertions.assertFalse(DebugPointUtil.isEnable("dbug4")); sendRequest("/api/debug_point/add/dbug5?v1=1&v2=a&v3=1.2&v4=true&v5=false"); - Assert.assertTrue(DebugPointUtil.isEnable("dbug5")); + Assertions.assertTrue(DebugPointUtil.isEnable("dbug5")); DebugPoint debugPoint = DebugPointUtil.getDebugPoint("dbug5"); - Assert.assertNotNull(debugPoint); - Assert.assertEquals(1, (int) debugPoint.param("v1", 0)); - Assert.assertEquals("a", debugPoint.param("v2", "")); - Assert.assertEquals(1.2, debugPoint.param("v3", 0.0), 1e-6); - Assert.assertTrue(debugPoint.param("v4", false)); - Assert.assertFalse(debugPoint.param("v5", false)); - Assert.assertEquals(123L, (long) debugPoint.param("v_no_exist", 123L)); + Assertions.assertNotNull(debugPoint); + Assertions.assertEquals(1, (int) debugPoint.param("v1", 0)); + Assertions.assertEquals("a", debugPoint.param("v2", "")); + Assertions.assertEquals(1.2, debugPoint.param("v3", 0.0), 1e-6); + Assertions.assertTrue(debugPoint.param("v4", false)); + Assertions.assertFalse(debugPoint.param("v5", false)); + Assertions.assertEquals(123L, (long) debugPoint.param("v_no_exist", 123L)); - Assert.assertEquals(1, (int) DebugPointUtil.getDebugParamOrDefault("dbug5", "v1", 0)); - Assert.assertEquals(100, (int) DebugPointUtil.getDebugParamOrDefault("point_not_exists", "v1", 100)); + Assertions.assertEquals(1, (int) DebugPointUtil.getDebugParamOrDefault("dbug5", "v1", 0)); + Assertions.assertEquals(100, (int) DebugPointUtil.getDebugParamOrDefault("point_not_exists", "v1", 100)); sendRequest("/api/debug_point/add/dbug6?value=100"); - Assert.assertEquals(100, (int) DebugPointUtil.getDebugParamOrDefault("dbug6", 0)); + Assertions.assertEquals(100, (int) DebugPointUtil.getDebugParamOrDefault("dbug6", 0)); } private void sendRequest(String uri) throws Exception { @@ -82,7 +82,7 @@ private void sendRequest(String uri) throws Exception { .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); - Assert.assertEquals(200, response.code()); + Assertions.assertNotNull(response.body()); + Assertions.assertEquals(200, response.code()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugUtilTest.java index aa599783f182f5..ec44bb6fcc57dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/DebugUtilTest.java @@ -21,8 +21,8 @@ import org.apache.doris.common.Pair; import org.apache.doris.thrift.TUniqueId; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.UUID; @@ -31,59 +31,59 @@ public class DebugUtilTest { public void testGetUint() { Pair result; result = DebugUtil.getUint(2000000000L); - Assert.assertEquals(Double.valueOf(2.0), result.first); - Assert.assertEquals(result.second, "B"); + Assertions.assertEquals(Double.valueOf(2.0), result.first); + Assertions.assertEquals(result.second, "B"); result = DebugUtil.getUint(1234567L); - Assert.assertEquals(result.first, Double.valueOf(1.234567)); - Assert.assertEquals(result.second, "M"); + Assertions.assertEquals(result.first, Double.valueOf(1.234567)); + Assertions.assertEquals(result.second, "M"); result = DebugUtil.getUint(1234L); - Assert.assertEquals(result.first, Double.valueOf(1.234)); - Assert.assertEquals(result.second, "K"); + Assertions.assertEquals(result.first, Double.valueOf(1.234)); + Assertions.assertEquals(result.second, "K"); result = DebugUtil.getUint(123L); - Assert.assertEquals(result.first, Double.valueOf(123.0)); - Assert.assertEquals(result.second, ""); + Assertions.assertEquals(result.first, Double.valueOf(123.0)); + Assertions.assertEquals(result.second, ""); } @Test public void testGetPrettyStringMs() { // 6hour1min - Assert.assertEquals("6hour1min", DebugUtil.getPrettyStringMs(21660222)); + Assertions.assertEquals("6hour1min", DebugUtil.getPrettyStringMs(21660222)); // 1min222ms - Assert.assertEquals("1min", DebugUtil.getPrettyStringMs(60222)); + Assertions.assertEquals("1min", DebugUtil.getPrettyStringMs(60222)); // 2s222ms - Assert.assertEquals("2sec222ms", DebugUtil.getPrettyStringMs(2222)); + Assertions.assertEquals("2sec222ms", DebugUtil.getPrettyStringMs(2222)); // 22ms - Assert.assertEquals("22ms", DebugUtil.getPrettyStringMs(22)); + Assertions.assertEquals("22ms", DebugUtil.getPrettyStringMs(22)); } @Test public void testGetByteUint() { Pair result; result = DebugUtil.getByteUint(0); - Assert.assertEquals(result.first, Double.valueOf(0.0)); - Assert.assertEquals(result.second, ""); + Assertions.assertEquals(result.first, Double.valueOf(0.0)); + Assertions.assertEquals(result.second, ""); result = DebugUtil.getByteUint(123); // B - Assert.assertEquals(result.first, Double.valueOf(123.0)); - Assert.assertEquals(result.second, "B"); + Assertions.assertEquals(result.first, Double.valueOf(123.0)); + Assertions.assertEquals(result.second, "B"); result = DebugUtil.getByteUint(123456); // K - Assert.assertEquals(result.first, Double.valueOf(120.5625)); - Assert.assertEquals(result.second, "KB"); + Assertions.assertEquals(result.first, Double.valueOf(120.5625)); + Assertions.assertEquals(result.second, "KB"); result = DebugUtil.getByteUint(1234567); // M - Assert.assertEquals(result.first, Double.valueOf(1.1773748397827148)); - Assert.assertEquals(result.second, "MB"); + Assertions.assertEquals(result.first, Double.valueOf(1.1773748397827148)); + Assertions.assertEquals(result.second, "MB"); result = DebugUtil.getByteUint(1234567890L); // G - Assert.assertEquals(result.first, Double.valueOf(1.1497809458523989)); - Assert.assertEquals(result.second, "GB"); + Assertions.assertEquals(result.first, Double.valueOf(1.1497809458523989)); + Assertions.assertEquals(result.second, "GB"); } @Test @@ -92,13 +92,13 @@ public void testUtilGetStackTrace() { DdlException e2 = new DdlException("exception2", e1); e2.printStackTrace(); System.out.println(Util.getRootCauseStack(e2)); - Assert.assertTrue(Util.getRootCauseStack(e2).contains("java.lang.Exception: exception1")); + Assertions.assertTrue(Util.getRootCauseStack(e2).contains("java.lang.Exception: exception1")); DdlException e3 = new DdlException("only one exception"); System.out.println(Util.getRootCauseStack(e3)); - Assert.assertTrue(Util.getRootCauseStack(e3) + Assertions.assertTrue(Util.getRootCauseStack(e3) .contains("org.apache.doris.common.DdlException: errCode = 2, detailMessage = only one exception")); - Assert.assertEquals("unknown", Util.getRootCauseStack(null)); + Assertions.assertEquals("unknown", Util.getRootCauseStack(null)); } @Test @@ -108,26 +108,26 @@ public void testParseIdFromString() { try { nullTUniqueId = DebugUtil.parseTUniqueIdFromString(null); } catch (NumberFormatException e) { - Assert.assertTrue("invalid query id".equals(e.getMessage())); + Assertions.assertTrue("invalid query id".equals(e.getMessage())); } - Assert.assertTrue(nullTUniqueId == null); + Assertions.assertTrue(nullTUniqueId == null); try { nullTUniqueId = DebugUtil.parseTUniqueIdFromString(""); } catch (NumberFormatException e) { - Assert.assertTrue("invalid query id".equals(e.getMessage())); + Assertions.assertTrue("invalid query id".equals(e.getMessage())); } - Assert.assertTrue(nullTUniqueId == null); + Assertions.assertTrue(nullTUniqueId == null); - Assert.assertEquals(new TUniqueId(), DebugUtil.parseTUniqueIdFromString("0-0")); + Assertions.assertEquals(new TUniqueId(), DebugUtil.parseTUniqueIdFromString("0-0")); try { nullTUniqueId = DebugUtil.parseTUniqueIdFromString("INVALID-STRING"); } catch (NumberFormatException e) { - Assert.assertTrue(e.getMessage().contains("For input string")); + Assertions.assertTrue(e.getMessage().contains("For input string")); } - Assert.assertTrue(nullTUniqueId == null); + Assertions.assertTrue(nullTUniqueId == null); for (int i = 0; i < 100; i++) { UUID uuid = UUID.randomUUID(); @@ -137,9 +137,9 @@ public void testParseIdFromString() { TUniqueId convertedTQueryId = DebugUtil.parseTUniqueIdFromString(originStrQueryId); String convertedStrQueryId = DebugUtil.printId(convertedTQueryId); - Assert.assertTrue(originTQueryId.hi == convertedTQueryId.hi); - Assert.assertTrue(originTQueryId.lo == convertedTQueryId.lo); - Assert.assertTrue(originStrQueryId.equals(convertedStrQueryId)); + Assertions.assertTrue(originTQueryId.hi == convertedTQueryId.hi); + Assertions.assertTrue(originTQueryId.lo == convertedTQueryId.lo); + Assertions.assertTrue(originStrQueryId.equals(convertedStrQueryId)); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/DynamicPartitionUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/DynamicPartitionUtilTest.java index 18ebaf6851aa28..4169975b86a22b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/DynamicPartitionUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/DynamicPartitionUtilTest.java @@ -25,8 +25,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.time.DateTimeException; import java.time.LocalDate; @@ -77,141 +77,141 @@ public void testGetPartitionRangeString() throws DateTimeException { DynamicPartitionProperty property = new DynamicPartitionProperty(getDynamProp("DAY", -3, 3, -1, -1)); String res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), -7, FORMAT); - Assert.assertEquals("2020-05-18", res); + Assertions.assertEquals("2020-05-18", res); String partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "DAY"); - Assert.assertEquals("20200518", partName); + Assertions.assertEquals("20200518", partName); // 2. 2020-05-25, offset 0 res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 0, FORMAT); - Assert.assertEquals("2020-05-25", res); + Assertions.assertEquals("2020-05-25", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "DAY"); - Assert.assertEquals("20200525", partName); + Assertions.assertEquals("20200525", partName); // 3. 2020-05-25, offset 7 res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 7, FORMAT); - Assert.assertEquals("2020-06-01", res); + Assertions.assertEquals("2020-06-01", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "DAY"); - Assert.assertEquals("20200601", partName); + Assertions.assertEquals("20200601", partName); // 4. 2020-02-28, offset 3 res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-28"), 3, FORMAT); - Assert.assertEquals("2020-03-02", res); + Assertions.assertEquals("2020-03-02", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "DAY"); - Assert.assertEquals("20200302", partName); + Assertions.assertEquals("20200302", partName); // TimeUnit: WEEK // 1. 2020-05-25, start day: MONDAY, offset 0 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 1, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 0, FORMAT); - Assert.assertEquals("2020-05-25", res); + Assertions.assertEquals("2020-05-25", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_22", partName); + Assertions.assertEquals("2020_22", partName); // 2. 2020-05-28, start day: MONDAY, offset 0 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 1, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-28"), 0, FORMAT); - Assert.assertEquals("2020-05-25", res); + Assertions.assertEquals("2020-05-25", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_22", partName); + Assertions.assertEquals("2020_22", partName); // 3. 2020-05-25, start day: SUNDAY, offset 0 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 7, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 0, FORMAT); - Assert.assertEquals("2020-05-31", res); + Assertions.assertEquals("2020-05-31", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_23", partName); + Assertions.assertEquals("2020_23", partName); // 4. 2020-05-25, start day: MONDAY, offset -2 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 1, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), -2, FORMAT); - Assert.assertEquals("2020-05-11", res); + Assertions.assertEquals("2020-05-11", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_20", partName); + Assertions.assertEquals("2020_20", partName); // 5. 2020-02-29, start day: WED, offset 0 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 3, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-29"), 0, FORMAT); - Assert.assertEquals("2020-02-26", res); + Assertions.assertEquals("2020-02-26", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_09", partName); + Assertions.assertEquals("2020_09", partName); // 6. 2020-02-29, start day: TUS, offset 1 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 2, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-29"), 1, FORMAT); - Assert.assertEquals("2020-03-03", res); + Assertions.assertEquals("2020-03-03", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2020_10", partName); + Assertions.assertEquals("2020_10", partName); // 6. 2020-01-01, start day: MONDAY, offset -1 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 1, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-01-01"), -1, FORMAT); - Assert.assertEquals("2019-12-23", res); + Assertions.assertEquals("2019-12-23", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2019_52", partName); + Assertions.assertEquals("2019_52", partName); // 6. 2020-01-01, start day: MONDAY, offset 0 property = new DynamicPartitionProperty(getDynamProp("WEEK", -3, 3, 1, -1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-01-01"), 0, FORMAT); - Assert.assertEquals("2019-12-30", res); + Assertions.assertEquals("2019-12-30", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "WEEK"); - Assert.assertEquals("2019_53", partName); + Assertions.assertEquals("2019_53", partName); // TimeUnit: MONTH // 1. 2020-05-25, start day: 1, offset 0 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 1)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 0, FORMAT); - Assert.assertEquals("2020-05-01", res); + Assertions.assertEquals("2020-05-01", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("202005", partName); + Assertions.assertEquals("202005", partName); // 2. 2020-05-25, start day: 26, offset 0 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 26)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), 0, FORMAT); - Assert.assertEquals("2020-04-26", res); + Assertions.assertEquals("2020-04-26", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("202004", partName); + Assertions.assertEquals("202004", partName); // 3. 2020-05-25, start day: 26, offset -1 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 26)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-05-25"), -1, FORMAT); - Assert.assertEquals("2020-03-26", res); + Assertions.assertEquals("2020-03-26", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("202003", partName); + Assertions.assertEquals("202003", partName); // 4. 2020-02-29, start day: 26, offset 3 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 26)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-29"), 3, FORMAT); - Assert.assertEquals("2020-05-26", res); + Assertions.assertEquals("2020-05-26", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("202005", partName); + Assertions.assertEquals("202005", partName); // 5. 2020-02-29, start day: 27, offset 0 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 27)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-29"), 0, FORMAT); - Assert.assertEquals("2020-02-27", res); + Assertions.assertEquals("2020-02-27", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("202002", partName); + Assertions.assertEquals("202002", partName); // 6. 2020-02-29, start day: 27, offset -3 property = new DynamicPartitionProperty(getDynamProp("MONTH", -3, 3, -1, 27)); res = DynamicPartitionUtil.getPartitionRangeString(property, getZonedDateTimeFromStr("2020-02-29"), -3, FORMAT); - Assert.assertEquals("2019-11-27", res); + Assertions.assertEquals("2019-11-27", res); partName = DynamicPartitionUtil.getFormattedPartitionName(getCTSTimeZone(), res, "MONTH"); - Assert.assertEquals("201911", partName); + Assertions.assertEquals("201911", partName); } @Test @@ -225,7 +225,7 @@ public void testCheckTimeUnit() { Deencapsulation.setField(rangePartitionInfo, "partitionColumns", partitionColumnList); try { Deencapsulation.invoke(dynamicPartitionUtil, "checkTimeUnit", "HOUR", rangePartitionInfo); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { System.out.print(e.getMessage()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/HttpURLUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/HttpURLUtilTest.java index 5d2099c5c61d0e..0e9ccc9be18207 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/HttpURLUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/HttpURLUtilTest.java @@ -22,9 +22,9 @@ import org.apache.doris.httpv2.meta.MetaBaseAction; import org.apache.doris.system.SystemInfoService.HostInfo; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -33,7 +33,7 @@ public class HttpURLUtilTest { - @After + @AfterEach public void tearDown() { Config.enable_https = false; Config.http_port = 8030; @@ -52,9 +52,9 @@ public void testNodeIdentHeadersIncludeClusterToken() throws Exception { Map headers = HttpURLUtil.getNodeIdentHeaders(); - Assert.assertEquals("127.0.0.1", headers.get(Env.CLIENT_NODE_HOST_KEY)); - Assert.assertEquals("9010", headers.get(Env.CLIENT_NODE_PORT_KEY)); - Assert.assertEquals("cluster-token", headers.get(MetaBaseAction.TOKEN)); + Assertions.assertEquals("127.0.0.1", headers.get(Env.CLIENT_NODE_HOST_KEY)); + Assertions.assertEquals("9010", headers.get(Env.CLIENT_NODE_PORT_KEY)); + Assertions.assertEquals("cluster-token", headers.get(MetaBaseAction.TOKEN)); } } @@ -69,8 +69,8 @@ public void testNodeIdentHeadersOmitTokenWhenNotConfigured() throws Exception { Map headers = HttpURLUtil.getNodeIdentHeaders(); - Assert.assertEquals("127.0.0.1", headers.get(Env.CLIENT_NODE_HOST_KEY)); - Assert.assertFalse(headers.containsKey(MetaBaseAction.TOKEN)); + Assertions.assertEquals("127.0.0.1", headers.get(Env.CLIENT_NODE_HOST_KEY)); + Assertions.assertFalse(headers.containsKey(MetaBaseAction.TOKEN)); } } @@ -85,9 +85,9 @@ public void testNodeIdentConnectionIncludesClusterToken() throws Exception { HttpURLConnection connection = HttpURLUtil.getConnectionWithNodeIdent("http://127.0.0.1:8030/info"); - Assert.assertEquals("127.0.0.1", connection.getRequestProperty(Env.CLIENT_NODE_HOST_KEY)); - Assert.assertEquals("9010", connection.getRequestProperty(Env.CLIENT_NODE_PORT_KEY)); - Assert.assertEquals("cluster-token", connection.getRequestProperty(MetaBaseAction.TOKEN)); + Assertions.assertEquals("127.0.0.1", connection.getRequestProperty(Env.CLIENT_NODE_HOST_KEY)); + Assertions.assertEquals("9010", connection.getRequestProperty(Env.CLIENT_NODE_PORT_KEY)); + Assertions.assertEquals("cluster-token", connection.getRequestProperty(MetaBaseAction.TOKEN)); } } @@ -97,7 +97,7 @@ public void testBuildInternalFeUrlHttp() { Config.http_port = 8030; String url = HttpURLUtil.buildInternalFeUrl("192.168.1.10", "/put", "version=123&port=8030"); - Assert.assertEquals("http://192.168.1.10:8030/put?version=123&port=8030", url); + Assertions.assertEquals("http://192.168.1.10:8030/put?version=123&port=8030", url); } @Test @@ -106,7 +106,7 @@ public void testBuildInternalFeUrlHttps() { Config.https_port = 8050; String url = HttpURLUtil.buildInternalFeUrl("192.168.1.10", "/put", "version=123&port=8050"); - Assert.assertEquals("https://192.168.1.10:8050/put?version=123&port=8050", url); + Assertions.assertEquals("https://192.168.1.10:8050/put?version=123&port=8050", url); } @Test @@ -115,7 +115,7 @@ public void testBuildInternalFeUrlNoQueryParams() { Config.http_port = 8030; String url = HttpURLUtil.buildInternalFeUrl("192.168.1.10", "/journal_id", null); - Assert.assertEquals("http://192.168.1.10:8030/journal_id", url); + Assertions.assertEquals("http://192.168.1.10:8030/journal_id", url); } @Test @@ -124,7 +124,7 @@ public void testBuildInternalFeUrlEmptyQueryParams() { Config.http_port = 8030; String url = HttpURLUtil.buildInternalFeUrl("192.168.1.10", "/version", ""); - Assert.assertEquals("http://192.168.1.10:8030/version", url); + Assertions.assertEquals("http://192.168.1.10:8030/version", url); } @Test @@ -133,7 +133,7 @@ public void testBuildInternalFeUrlHttpsWithIPv6() { Config.https_port = 8050; String url = HttpURLUtil.buildInternalFeUrl("fe80::1", "/role", "host=fe80::2&port=9010"); - Assert.assertTrue(url.startsWith("https://")); - Assert.assertTrue(url.contains("/role?host=fe80::2&port=9010")); + Assertions.assertTrue(url.startsWith("https://")); + Assertions.assertTrue(url.contains("/role?host=fe80::2&port=9010")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/InternalHttpsUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/InternalHttpsUtilsTest.java index d082420d8397e4..160335ae802686 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/InternalHttpsUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/InternalHttpsUtilsTest.java @@ -19,10 +19,10 @@ import org.apache.doris.common.Config; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; @@ -30,14 +30,14 @@ public class InternalHttpsUtilsTest { private String originalKeyStorePath; - @Before + @BeforeEach public void setUp() throws Exception { originalKeyStorePath = Config.key_store_path; // Reset the cached SSLContext before each test so tests are independent. resetCachedSslContext(); } - @After + @AfterEach public void tearDown() throws Exception { Config.key_store_path = originalKeyStorePath; resetCachedSslContext(); @@ -54,12 +54,11 @@ public void testGetSslContextThrowsWhenCertMissing() { Config.key_store_path = "/non/existent/path/doris_ssl_certificate.keystore"; try { InternalHttpsUtils.getSslContext(); - Assert.fail("Expected RuntimeException when cert file does not exist"); + Assertions.fail("Expected RuntimeException when cert file does not exist"); } catch (RuntimeException e) { // Error message must mention the cert path so operators know what to fix. - Assert.assertTrue("Error message should contain cert path", - e.getMessage() != null - && e.getMessage().contains("/non/existent/path/doris_ssl_certificate.keystore")); + Assertions.assertTrue(e.getMessage() != null + && e.getMessage().contains("/non/existent/path/doris_ssl_certificate.keystore"), "Error message should contain cert path"); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/ListComparatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/ListComparatorTest.java index 7cbca7a93d15d2..5a7c5a65004a69 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/ListComparatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/ListComparatorTest.java @@ -17,9 +17,9 @@ package org.apache.doris.common.util; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.LinkedList; @@ -29,7 +29,7 @@ public class ListComparatorTest { List> listCollection; - @Before + @BeforeEach public void setUp() { listCollection = new LinkedList>(); } @@ -69,7 +69,7 @@ public void test_1() { Collections.sort(listCollection, comparator); printCollection(); - Assert.assertEquals(list2, listCollection.get(0)); + Assertions.assertEquals(list2, listCollection.get(0)); } @Test @@ -95,33 +95,35 @@ public void test_2() { new OrderByPair(2, false)); Collections.sort(listCollection, comparator); printCollection(); - Assert.assertEquals(list2, listCollection.get(0)); + Assertions.assertEquals(list2, listCollection.get(0)); } - @Test(expected = ClassCastException.class) + @Test public void test_3() { - // 1, 200, "abc", 2000 - // 1, 200, "abc", "bcd" - List list1 = new LinkedList(); - list1.add(new Long(1)); - list1.add(new Long(200)); - list1.add("abc"); - list1.add(new Long(2000)); - listCollection.add(list1); - - List list2 = new LinkedList(); - list2.add(new Long(1)); - list2.add(new Long(200)); - list2.add("abc"); - list2.add("bcd"); - listCollection.add(list2); - - printCollection(); - - ListComparator> comparator = new ListComparator<>(new OrderByPair(1, false), - new OrderByPair(3, false)); - Collections.sort(listCollection, comparator); - Assert.fail(); + Assertions.assertThrows(ClassCastException.class, () -> { + // 1, 200, "abc", 2000 + // 1, 200, "abc", "bcd" + List list1 = new LinkedList(); + list1.add(new Long(1)); + list1.add(new Long(200)); + list1.add("abc"); + list1.add(new Long(2000)); + listCollection.add(list1); + + List list2 = new LinkedList(); + list2.add(new Long(1)); + list2.add(new Long(200)); + list2.add("abc"); + list2.add("bcd"); + listCollection.add(list2); + + printCollection(); + + ListComparator> comparator = new ListComparator<>(new OrderByPair(1, false), + new OrderByPair(3, false)); + Collections.sort(listCollection, comparator); + Assertions.fail(); + }); } @Test @@ -147,7 +149,7 @@ public void test_4() { new OrderByPair(1, false)); Collections.sort(listCollection, comparator); printCollection(); - Assert.assertEquals(list2, listCollection.get(0)); + Assertions.assertEquals(list2, listCollection.get(0)); } @Test @@ -180,7 +182,7 @@ public void test_5() { new OrderByPair(1, true)); Collections.sort(listCollection, comparator); printCollection(); - Assert.assertEquals(list3, listCollection.get(0)); + Assertions.assertEquals(list3, listCollection.get(0)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/ListUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/ListUtilTest.java index 21652d4f186194..cf730164160359 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/ListUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/ListUtilTest.java @@ -27,11 +27,9 @@ import org.apache.doris.common.DdlException; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -46,7 +44,7 @@ public class ListUtilTest { private static List listB = new ArrayList<>(); private static List listC = new ArrayList<>(); - @BeforeClass + @BeforeAll public static void setUp() throws AnalysisException { Column charString = new Column("char", PrimitiveType.CHAR); Column varchar = new Column("varchar", PrimitiveType.VARCHAR); @@ -65,9 +63,6 @@ public static void setUp() throws AnalysisException { listC.add(pk3); } - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - @Test public void testSplitBySizeNormal() { List lists = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7); @@ -75,10 +70,10 @@ public void testSplitBySizeNormal() { List> splitLists = ListUtil.splitBySize(lists, expectSize); - Assert.assertEquals(splitLists.size(), 3); - Assert.assertEquals(splitLists.get(0).size(), 3); - Assert.assertEquals(splitLists.get(1).size(), 2); - Assert.assertEquals(splitLists.get(2).size(), 2); + Assertions.assertEquals(splitLists.size(), 3); + Assertions.assertEquals(splitLists.get(0).size(), 3); + Assertions.assertEquals(splitLists.get(1).size(), 2); + Assertions.assertEquals(splitLists.get(2).size(), 2); } @Test @@ -88,8 +83,8 @@ public void testSplitBySizeNormal2() { List> splitLists = ListUtil.splitBySize(lists, expectSize); - Assert.assertEquals(splitLists.size(), 1); - Assert.assertEquals(lists, splitLists.get(0)); + Assertions.assertEquals(splitLists.size(), 1); + Assertions.assertEquals(lists, splitLists.get(0)); } @Test @@ -99,10 +94,10 @@ public void testSplitBySizeWithLargeExpectSize() { List> splitLists = ListUtil.splitBySize(lists, expectSize); - Assert.assertEquals(splitLists.size(), lists.size()); - Assert.assertEquals(1, (int) splitLists.get(0).get(0)); - Assert.assertEquals(2, (int) splitLists.get(1).get(0)); - Assert.assertEquals(3, (int) splitLists.get(2).get(0)); + Assertions.assertEquals(splitLists.size(), lists.size()); + Assertions.assertEquals(1, (int) splitLists.get(0).get(0)); + Assertions.assertEquals(2, (int) splitLists.get(1).get(0)); + Assertions.assertEquals(3, (int) splitLists.get(2).get(0)); } @Test @@ -112,7 +107,7 @@ public void testSplitBySizeWithEmptyList() { List> splitLists = ListUtil.splitBySize(lists, expectSize); - Assert.assertEquals(splitLists.size(), lists.size()); + Assertions.assertEquals(splitLists.size(), lists.size()); } @Test @@ -120,10 +115,11 @@ public void testSplitBySizeWithNullList() { List lists = null; int expectSize = 10; - expectedEx.expect(NullPointerException.class); - expectedEx.expectMessage("list must not be null"); - - ListUtil.splitBySize(lists, expectSize); + NullPointerException e = Assertions.assertThrows(NullPointerException.class, () -> { + ListUtil.splitBySize(lists, expectSize); + }); + Assertions.assertTrue(e.getMessage().contains("list must not be null"), + "unexpected message: " + e.getMessage()); } @Test @@ -131,10 +127,11 @@ public void testSplitBySizeWithNegativeSize() { List lists = Lists.newArrayList(1, 2, 3); int expectSize = -1; - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage("expectedSize must larger than 0"); - - ListUtil.splitBySize(lists, expectSize); + IllegalArgumentException e = Assertions.assertThrows(IllegalArgumentException.class, () -> { + ListUtil.splitBySize(lists, expectSize); + }); + Assertions.assertTrue(e.getMessage().contains("expectedSize must larger than 0"), + "unexpected message: " + e.getMessage()); } @Test @@ -147,20 +144,24 @@ public void testListsMatchNormal() throws DdlException { } - @Test(expected = DdlException.class) + @Test public void testListsMatchSameSize() throws DdlException { - List list1 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB)); - List list2 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listC)); + Assertions.assertThrows(DdlException.class, () -> { + List list1 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB)); + List list2 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listC)); - ListUtil.checkPartitionKeyListsMatch(list1, list2); + ListUtil.checkPartitionKeyListsMatch(list1, list2); + }); } - @Test(expected = DdlException.class) + @Test public void testListMatchDiffSize() throws DdlException { - List list1 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB)); - List list2 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB), - new ListPartitionItem(listC)); + Assertions.assertThrows(DdlException.class, () -> { + List list1 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB)); + List list2 = Arrays.asList(new ListPartitionItem(listA), new ListPartitionItem(listB), + new ListPartitionItem(listC)); - ListUtil.checkPartitionKeyListsMatch(list1, list2); + ListUtil.checkPartitionKeyListsMatch(list1, list2); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/MetaLockUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/MetaLockUtilsTest.java index 1669038913dea5..8faa5916ea88ba 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/MetaLockUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/MetaLockUtilsTest.java @@ -24,10 +24,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.TimeUnit; @@ -37,18 +35,15 @@ public class MetaLockUtilsTest { List
tableList = ImmutableList.of(TableTest.newOlapTable(0, "test1", 0), TableTest.newOlapTable(1, "test2", 0)); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void testReadLockDatabases() { List databaseList = Lists.newArrayList(new Database(), new Database()); MetaLockUtils.readLockDatabases(databaseList); - Assert.assertFalse(databaseList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); - Assert.assertFalse(databaseList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertFalse(databaseList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertFalse(databaseList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); MetaLockUtils.readUnlockDatabases(databaseList); - Assert.assertTrue(databaseList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); - Assert.assertTrue(databaseList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(databaseList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(databaseList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); databaseList.get(0).writeUnlock(); databaseList.get(1).writeUnlock(); } @@ -56,11 +51,11 @@ public void testReadLockDatabases() { @Test public void testReadLockTables() { MetaLockUtils.readLockTables(tableList); - Assert.assertFalse(tableList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); - Assert.assertFalse(tableList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertFalse(tableList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertFalse(tableList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); MetaLockUtils.readUnlockTables(tableList); - Assert.assertTrue(tableList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); - Assert.assertTrue(tableList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(tableList.get(0).tryWriteLock(1, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(tableList.get(1).tryWriteLock(1, TimeUnit.MILLISECONDS)); tableList.get(0).writeUnlock(); tableList.get(1).writeUnlock(); } @@ -68,57 +63,61 @@ public void testReadLockTables() { @Test public void testWriteLockTables() throws MetaNotFoundException { MetaLockUtils.writeLockTables(tableList); - Assert.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); MetaLockUtils.writeUnlockTables(tableList); - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); - Assert.assertTrue(MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1, TimeUnit.MILLISECONDS)); - Assert.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); MetaLockUtils.writeUnlockTables(tableList); tableList.get(1).readLock(); - Assert.assertFalse(MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1, TimeUnit.MILLISECONDS)); - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1, TimeUnit.MILLISECONDS)); + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); tableList.get(1).readUnlock(); } @Test public void testWriteLockTablesWithMetaNotFoundException() throws MetaNotFoundException { MetaLockUtils.writeLockTablesOrMetaException(tableList); - Assert.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); MetaLockUtils.writeUnlockTables(tableList); - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); tableList.get(1).markDropped(); - expectedException.expect(MetaNotFoundException.class); - expectedException.expectMessage("errCode = 7, detailMessage = unknown table, tableName=test2"); - try { - MetaLockUtils.writeLockTablesOrMetaException(tableList); - } finally { - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); - } + MetaNotFoundException e = Assertions.assertThrows(MetaNotFoundException.class, () -> { + try { + MetaLockUtils.writeLockTablesOrMetaException(tableList); + } finally { + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + } + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 7, detailMessage = unknown table, tableName=test2"), + "unexpected message: " + e.getMessage()); } @Test public void testTryWriteLockTablesWithMetaNotFoundException() throws MetaNotFoundException { MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1000, TimeUnit.MILLISECONDS); - Assert.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertTrue(tableList.get(1).isWriteLockHeldByCurrentThread()); MetaLockUtils.writeUnlockTables(tableList); - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); tableList.get(1).markDropped(); - expectedException.expect(MetaNotFoundException.class); - expectedException.expectMessage("errCode = 7, detailMessage = unknown table, tableName=test2"); - try { - MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1000, TimeUnit.MILLISECONDS); - } finally { - Assert.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); - Assert.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); - } + MetaNotFoundException e = Assertions.assertThrows(MetaNotFoundException.class, () -> { + try { + MetaLockUtils.tryWriteLockTablesOrMetaException(tableList, 1000, TimeUnit.MILLISECONDS); + } finally { + Assertions.assertFalse(tableList.get(0).isWriteLockHeldByCurrentThread()); + Assertions.assertFalse(tableList.get(1).isWriteLockHeldByCurrentThread()); + } + }); + Assertions.assertTrue(e.getMessage().contains("errCode = 7, detailMessage = unknown table, tableName=test2"), + "unexpected message: " + e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/NetUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/NetUtilsTest.java index 4b23a13832b2cb..3150e4564face9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/NetUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/NetUtilsTest.java @@ -18,8 +18,8 @@ package org.apache.doris.common.util; import com.google.common.net.InetAddresses; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.net.Inet4Address; import java.net.InetAddress; @@ -30,10 +30,10 @@ public class NetUtilsTest { public void testConvertIp() throws Exception { long ipValue = 3232235786L; InetAddress ip = InetAddress.getByName("192.168.1.10"); - Assert.assertTrue(ip instanceof Inet4Address); - Assert.assertEquals(ipValue, NetUtils.inet4AddressToLong((Inet4Address) ip)); + Assertions.assertTrue(ip instanceof Inet4Address); + Assertions.assertEquals(ipValue, NetUtils.inet4AddressToLong((Inet4Address) ip)); Inet4Address convertIp = NetUtils.longToInet4Address(ipValue); - Assert.assertEquals(ip, convertIp); + Assertions.assertEquals(ip, convertIp); System.out.println(InetAddresses.forString("192.168.1.10").toString()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/QueryableReentrantLockTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/QueryableReentrantLockTest.java index 1608b1d6efa3e5..034a5bbd4b433b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/QueryableReentrantLockTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/QueryableReentrantLockTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.lock.MonitoredReentrantLock; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -59,7 +59,7 @@ public void run() { try { if (!lock.tryLock(1000, TimeUnit.MILLISECONDS)) { Thread owner = lock.getOwner(); - Assert.assertEquals("thread1", owner.getName()); + Assertions.assertEquals("thread1", owner.getName()); System.out.println(Util.dumpThread(owner, 10)); diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/S3URITest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/S3URITest.java index 5cfd889ab97f90..e00af5432b9908 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/S3URITest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/S3URITest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.UserException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Optional; @@ -32,11 +32,11 @@ public void testLocationParsing() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("path/to/file", uri1.getKey()); - Assert.assertEquals(Optional.empty(), uri1.getRegion()); - Assert.assertEquals(Optional.empty(), uri1.getEndpoint()); - Assert.assertEquals(Optional.empty(), uri1.getQueryParams()); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("path/to/file", uri1.getKey()); + Assertions.assertEquals(Optional.empty(), uri1.getRegion()); + Assertions.assertEquals(Optional.empty(), uri1.getEndpoint()); + Assertions.assertEquals(Optional.empty(), uri1.getQueryParams()); } @Test @@ -46,14 +46,14 @@ public void testVirtualHostStyleParsing() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("resources/doc.txt", uri1.getKey()); - Assert.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); - Assert.assertEquals("us-west-1", uri1.getRegion().get()); - Assert.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); - Assert.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("resources/doc.txt", uri1.getKey()); + Assertions.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); + Assertions.assertEquals("us-west-1", uri1.getRegion().get()); + Assertions.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); + Assertions.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); } @Test @@ -63,14 +63,14 @@ public void testPathStyleParsing() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("resources/doc.txt", uri1.getKey()); - Assert.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); - Assert.assertEquals("us-west-1", uri1.getRegion().get()); - Assert.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); - Assert.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("resources/doc.txt", uri1.getKey()); + Assertions.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); + Assertions.assertEquals("us-west-1", uri1.getRegion().get()); + Assertions.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); + Assertions.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); } @Test @@ -78,19 +78,19 @@ public void testForceParsingStandardUri() throws UserException { String p1 = "s3://my-bucket.s3.us-west-1.amazonaws.com/path/to/file"; S3URI uri1 = S3URI.create(p1, false, true); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("path/to/file", uri1.getKey()); - Assert.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); - Assert.assertEquals("us-west-1", uri1.getRegion().get()); - Assert.assertEquals(Optional.empty(), uri1.getQueryParams()); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("path/to/file", uri1.getKey()); + Assertions.assertEquals("s3.us-west-1.amazonaws.com", uri1.getEndpoint().get()); + Assertions.assertEquals("us-west-1", uri1.getRegion().get()); + Assertions.assertEquals(Optional.empty(), uri1.getQueryParams()); String p2 = "s3://s3.us-west-1.amazonaws.com/my-bucket/path/to/file"; S3URI uri2 = S3URI.create(p2, true, true); - Assert.assertEquals("my-bucket", uri2.getBucket()); - Assert.assertEquals("path/to/file", uri2.getKey()); - Assert.assertEquals("s3.us-west-1.amazonaws.com", uri2.getEndpoint().get()); - Assert.assertEquals(Optional.empty(), uri1.getQueryParams()); + Assertions.assertEquals("my-bucket", uri2.getBucket()); + Assertions.assertEquals("path/to/file", uri2.getKey()); + Assertions.assertEquals("s3.us-west-1.amazonaws.com", uri2.getEndpoint().get()); + Assertions.assertEquals(Optional.empty(), uri1.getQueryParams()); } @Test @@ -100,14 +100,14 @@ public void testOSSVirtualHostStyle() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("resources/doc.txt", uri1.getKey()); - Assert.assertEquals("oss-cn-bejing.aliyuncs.com", uri1.getEndpoint().get()); - Assert.assertEquals("oss-cn-bejing", uri1.getRegion().get()); - Assert.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); - Assert.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("resources/doc.txt", uri1.getKey()); + Assertions.assertEquals("oss-cn-bejing.aliyuncs.com", uri1.getEndpoint().get()); + Assertions.assertEquals("oss-cn-bejing", uri1.getRegion().get()); + Assertions.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); + Assertions.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); } @Test @@ -117,14 +117,14 @@ public void testOSSPathStyle() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("resources/doc.txt", uri1.getKey()); - Assert.assertEquals("oss-cn-bejing.aliyuncs.com", uri1.getEndpoint().get()); - Assert.assertEquals("oss-cn-bejing", uri1.getRegion().get()); - Assert.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); - Assert.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("resources/doc.txt", uri1.getKey()); + Assertions.assertEquals("oss-cn-bejing.aliyuncs.com", uri1.getEndpoint().get()); + Assertions.assertEquals("oss-cn-bejing", uri1.getRegion().get()); + Assertions.assertEquals("abc123", uri1.getQueryParams().get().get("versionId").get(0)); + Assertions.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); } @Test @@ -134,10 +134,10 @@ public void testCOSVirtualHostStyle() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("resources/doc.txt", uri1.getKey()); - Assert.assertEquals("cos.ap-beijing.myqcloud.com", uri1.getEndpoint().get()); - Assert.assertEquals("ap-beijing", uri1.getRegion().get()); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("resources/doc.txt", uri1.getKey()); + Assertions.assertEquals("cos.ap-beijing.myqcloud.com", uri1.getEndpoint().get()); + Assertions.assertEquals("ap-beijing", uri1.getRegion().get()); } @Test @@ -147,10 +147,10 @@ public void testOBSVirtualHostStyle() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("my-bucket", uri1.getBucket()); - Assert.assertEquals("test_obs/000000_0", uri1.getKey()); - Assert.assertEquals("obs.cn-north-4.myhuaweicloud.com", uri1.getEndpoint().get()); - Assert.assertEquals("cn-north-4", uri1.getRegion().get()); + Assertions.assertEquals("my-bucket", uri1.getBucket()); + Assertions.assertEquals("test_obs/000000_0", uri1.getKey()); + Assertions.assertEquals("obs.cn-north-4.myhuaweicloud.com", uri1.getEndpoint().get()); + Assertions.assertEquals("cn-north-4", uri1.getRegion().get()); } @Test @@ -160,14 +160,14 @@ public void testEncodedString() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("bucket", uri1.getBucket()); - Assert.assertEquals("path%20to%20file", uri1.getKey()); - Assert.assertEquals(Optional.empty(), uri1.getEndpoint()); - Assert.assertEquals(Optional.empty(), uri1.getRegion()); - Assert.assertEquals("hello%20world", uri1.getQueryParams().get().get("txt").get(0)); - Assert.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); - Assert.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); + Assertions.assertEquals("bucket", uri1.getBucket()); + Assertions.assertEquals("path%20to%20file", uri1.getKey()); + Assertions.assertEquals(Optional.empty(), uri1.getEndpoint()); + Assertions.assertEquals(Optional.empty(), uri1.getRegion()); + Assertions.assertEquals("hello%20world", uri1.getQueryParams().get().get("txt").get(0)); + Assertions.assertEquals(2, uri1.getQueryParams().get().get("partNumber").size()); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("77")); + Assertions.assertTrue(uri1.getQueryParams().get().get("partNumber").contains("88")); } @Test @@ -177,30 +177,38 @@ public void testHadoopEncodedString() throws UserException { boolean forceParsingStandardUri = false; S3URI uri1 = S3URI.create(p1, isPathStyle, forceParsingStandardUri); - Assert.assertEquals("bucket", uri1.getBucket()); - Assert.assertEquals("path%20to%20file/abc%3Aqqq=xyz%2Fyyy zzz", uri1.getKey()); - Assert.assertEquals(Optional.empty(), uri1.getEndpoint()); - Assert.assertEquals(Optional.empty(), uri1.getRegion()); + Assertions.assertEquals("bucket", uri1.getBucket()); + Assertions.assertEquals("path%20to%20file/abc%3Aqqq=xyz%2Fyyy zzz", uri1.getKey()); + Assertions.assertEquals(Optional.empty(), uri1.getEndpoint()); + Assertions.assertEquals(Optional.empty(), uri1.getRegion()); } - @Test(expected = UserException.class) + @Test public void missingBucket() throws UserException { - S3URI.create("https:///"); + Assertions.assertThrows(UserException.class, () -> { + S3URI.create("https:///"); + }); } - @Test(expected = UserException.class) + @Test public void missingKey() throws UserException { - S3URI.create("https://bucket/"); + Assertions.assertThrows(UserException.class, () -> { + S3URI.create("https://bucket/"); + }); } - @Test(expected = UserException.class) + @Test public void relativePathing() throws UserException { - S3URI.create("/path/to/file"); + Assertions.assertThrows(UserException.class, () -> { + S3URI.create("/path/to/file"); + }); } - @Test(expected = UserException.class) + @Test public void invalidScheme() throws UserException { - S3URI.create("ftp://bucket/"); + Assertions.assertThrows(UserException.class, () -> { + S3URI.create("ftp://bucket/"); + }); } @Test @@ -208,11 +216,11 @@ public void testQueryAndFragment() throws UserException { String p1 = "s3://bucket/path/to/file?query=foo#bar"; S3URI uri1 = S3URI.create(p1); - Assert.assertEquals("bucket", uri1.getBucket()); - Assert.assertEquals("path/to/file", uri1.getKey()); - Assert.assertEquals(Optional.empty(), uri1.getEndpoint()); - Assert.assertEquals(Optional.empty(), uri1.getRegion()); - Assert.assertEquals("foo", uri1.getQueryParams().get().get("query").get(0)); + Assertions.assertEquals("bucket", uri1.getBucket()); + Assertions.assertEquals("path/to/file", uri1.getKey()); + Assertions.assertEquals(Optional.empty(), uri1.getEndpoint()); + Assertions.assertEquals(Optional.empty(), uri1.getRegion()); + Assertions.assertEquals("foo", uri1.getQueryParams().get().get("query").get(0)); } @@ -220,44 +228,44 @@ public void testQueryAndFragment() throws UserException { public void testS3DirectoryBucket() throws UserException { // Valid directory bucket String validDirBucket = "my-bucket--usw2-az1--x-s3"; - Assert.assertTrue(S3URI.isS3DirectoryBucket(validDirBucket)); + Assertions.assertTrue(S3URI.isS3DirectoryBucket(validDirBucket)); S3URI uriWithDirBucket = S3URI.create("s3://" + validDirBucket + "/some/file.csv"); - Assert.assertTrue(uriWithDirBucket.useS3DirectoryBucket()); - Assert.assertEquals(validDirBucket, uriWithDirBucket.getBucket()); + Assertions.assertTrue(uriWithDirBucket.useS3DirectoryBucket()); + Assertions.assertEquals(validDirBucket, uriWithDirBucket.getBucket()); // Another valid one String validDirBucket2 = "another-bucket--use1-az4--x-s3"; - Assert.assertTrue(S3URI.isS3DirectoryBucket(validDirBucket2)); + Assertions.assertTrue(S3URI.isS3DirectoryBucket(validDirBucket2)); // Invalid directory buckets - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket")); // regular bucket - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--x-s3")); // missing azid - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--usw2-az1--x-s4")); // wrong suffix - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket-usw2-az1--x-s3")); // incorrect format - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--usw2az1--x-s3")); // azid without hyphen - Assert.assertFalse(S3URI.isS3DirectoryBucket("my-bucket---x-s3")); // empty azid - Assert.assertFalse(S3URI.isS3DirectoryBucket(null)); - Assert.assertFalse(S3URI.isS3DirectoryBucket("")); + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket")); // regular bucket + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--x-s3")); // missing azid + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--usw2-az1--x-s4")); // wrong suffix + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket-usw2-az1--x-s3")); // incorrect format + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket--usw2az1--x-s3")); // azid without hyphen + Assertions.assertFalse(S3URI.isS3DirectoryBucket("my-bucket---x-s3")); // empty azid + Assertions.assertFalse(S3URI.isS3DirectoryBucket(null)); + Assertions.assertFalse(S3URI.isS3DirectoryBucket("")); S3URI uriWithRegularBucket = S3URI.create("s3://my-bucket/some/file.csv"); - Assert.assertFalse(uriWithRegularBucket.useS3DirectoryBucket()); + Assertions.assertFalse(uriWithRegularBucket.useS3DirectoryBucket()); } @Test public void testGetDirectoryPrefixForGlob() { // Case 1: Standard glob prefix - Assert.assertEquals("path/to/", S3URI.getDirectoryPrefixForGlob("path/to/file.csv")); + Assertions.assertEquals("path/to/", S3URI.getDirectoryPrefixForGlob("path/to/file.csv")); // Case 2: Prefix already ends with a slash - Assert.assertEquals("path/to/", S3URI.getDirectoryPrefixForGlob("path/to/")); + Assertions.assertEquals("path/to/", S3URI.getDirectoryPrefixForGlob("path/to/")); // Case 3: No slashes in prefix - Assert.assertEquals("", S3URI.getDirectoryPrefixForGlob("file.csv")); + Assertions.assertEquals("", S3URI.getDirectoryPrefixForGlob("file.csv")); // Case 4: Empty prefix - Assert.assertEquals("", S3URI.getDirectoryPrefixForGlob("")); + Assertions.assertEquals("", S3URI.getDirectoryPrefixForGlob("")); // Case 5: Null prefix - Assert.assertNull(S3URI.getDirectoryPrefixForGlob(null)); + Assertions.assertNull(S3URI.getDirectoryPrefixForGlob(null)); // Case 6: Prefix is just a slash - Assert.assertEquals("/", S3URI.getDirectoryPrefixForGlob("/")); + Assertions.assertEquals("/", S3URI.getDirectoryPrefixForGlob("/")); // Case 7: Starts with slash - Assert.assertEquals("/path/to/", S3URI.getDirectoryPrefixForGlob("/path/to/file.csv")); + Assertions.assertEquals("/path/to/", S3URI.getDirectoryPrefixForGlob("/path/to/file.csv")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/S3UtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/S3UtilTest.java index ff155a0b1f8fe1..ae82034f9afa40 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/S3UtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/S3UtilTest.java @@ -19,10 +19,10 @@ import org.apache.doris.common.Config; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.services.s3.S3Client; @@ -34,12 +34,12 @@ public class S3UtilTest { private String originalS3ClientHttpScheme; - @Before + @BeforeEach public void setUp() { originalS3ClientHttpScheme = Config.s3_client_http_scheme; } - @After + @AfterEach public void tearDown() { Config.s3_client_http_scheme = originalS3ClientHttpScheme; } @@ -47,25 +47,25 @@ public void tearDown() { @Test public void testBuildEndpointUrlDefaultsToHttps() { Config.s3_client_http_scheme = "https"; - Assert.assertEquals("https://s3.us-east-1.amazonaws.com", + Assertions.assertEquals("https://s3.us-east-1.amazonaws.com", S3Util.buildEndpointUrl("s3.us-east-1.amazonaws.com")); } @Test public void testBuildEndpointUrlUsesConfiguredHttpScheme() { Config.s3_client_http_scheme = "http"; - Assert.assertEquals("http://127.0.0.1:9000", + Assertions.assertEquals("http://127.0.0.1:9000", S3Util.buildEndpointUrl("127.0.0.1:9000")); } @Test public void testBuildEndpointUrlPreservesExplicitSchemes() { Config.s3_client_http_scheme = "https"; - Assert.assertEquals("http://127.0.0.1:9000", + Assertions.assertEquals("http://127.0.0.1:9000", S3Util.buildEndpointUrl("http://127.0.0.1:9000")); Config.s3_client_http_scheme = "http"; - Assert.assertEquals("https://s3.us-east-1.amazonaws.com", + Assertions.assertEquals("https://s3.us-east-1.amazonaws.com", S3Util.buildEndpointUrl("https://s3.us-east-1.amazonaws.com")); } @@ -77,7 +77,7 @@ public void testBuildS3ClientAppliesDefaultSchemeAtClientCreation() { "us-east-1", true, StaticCredentialsProvider.create(AwsBasicCredentials.create("ak", "sk")))) { - Assert.assertEquals(URI.create("https://127.0.0.1:9000"), + Assertions.assertEquals(URI.create("https://127.0.0.1:9000"), client.serviceClientConfiguration().endpointOverride().orElseThrow()); } } @@ -88,7 +88,7 @@ public void testExtendGlobNumberRange_simpleRange() { String input = "file_{1..3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -97,7 +97,7 @@ public void testExtendGlobNumberRange_reverseRange() { String input = "file_{3..1}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -106,7 +106,7 @@ public void testExtendGlobNumberRange_singleNumber() { String input = "file_{2..2}.csv"; String expected = "file_{2}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -115,7 +115,7 @@ public void testExtendGlobNumberRange_mixedRangeAndValues() { String input = "file_{1..2,3,1..3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -124,7 +124,7 @@ public void testExtendGlobNumberRange_multipleRanges() { String input = "file_{1..2}_{1..2}.csv"; String expected = "file_{1,2}_{1,2}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -133,7 +133,7 @@ public void testExtendGlobNumberRange_largeRange() { String input = "file_{0..9}.csv"; String expected = "file_{0,1,2,3,4,5,6,7,8,9}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -142,7 +142,7 @@ public void testExtendGlobNumberRange_negativeNumbersFiltered() { String input = "file_{-1..2}.csv"; String expected = "file_{-1..2}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -151,7 +151,7 @@ public void testExtendGlobNumberRange_allNegativeRange() { String input = "file_{-3..-1}.csv"; String expected = "file_{-3..-1}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -160,7 +160,7 @@ public void testExtendGlobNumberRange_mixedWithNegative() { String input = "file_{-1..2,1..3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -169,7 +169,7 @@ public void testExtendGlobNumberRange_invalidCharacters() { String input = "file_{Refrain,1..3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -178,7 +178,7 @@ public void testExtendGlobNumberRange_mixedInvalidAndValid() { String input = "file_{3..1,2,1..2}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -187,7 +187,7 @@ public void testExtendGlobNumberRange_noRange() { String input = "file_123.csv"; String expected = "file_123.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -196,7 +196,7 @@ public void testExtendGlobNumberRange_noNumericRange() { String input = "file_{a..z}.csv"; String expected = "file_{a..z}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -205,7 +205,7 @@ public void testExtendGlobNumberRange_emptyBraces() { String input = "file_{}.csv"; String expected = "file_{}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -214,7 +214,7 @@ public void testExtendGlobNumberRange_singleValue() { String input = "file_{5}.csv"; String expected = "file_{5}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -223,7 +223,7 @@ public void testExtendGlobNumberRange_multipleValues() { String input = "file_{1,2,3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -232,7 +232,7 @@ public void testExtendGlobNumberRange_duplicateRemoval() { String input = "file_{1..3,2..4}.csv"; String expected = "file_{1,2,3,4}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -241,7 +241,7 @@ public void testExtendGlobNumberRange_largeNumbers() { String input = "file_{100..103}.csv"; String expected = "file_{100,101,102,103}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -251,7 +251,7 @@ public void testExtendGlobNumberRange_zeroPadding() { String input = "file_{01..03}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -260,7 +260,7 @@ public void testExtendGlobNumberRange_complexPath() { String input = "s3://bucket/data_{0..9}/file_{1..3}.csv"; String expected = "s3://bucket/data_{0,1,2,3,4,5,6,7,8,9}/file_{1,2,3}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -269,7 +269,7 @@ public void testExtendGlobNumberRange_noBraces() { String input = "s3://bucket/data.csv"; String expected = "s3://bucket/data.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -278,7 +278,7 @@ public void testExtendGlobNumberRange_specialCase() { String input = "data_{2..4,6}.csv"; String expected = "data_{2,3,4,6}.csv"; String result = S3Util.extendGlobNumberRange(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } @Test @@ -287,17 +287,17 @@ public void testGetLongestPrefix_withGlobPattern() { String input1 = "s3://bucket/path/to/file_{1..3}.csv"; String expected1 = "s3://bucket/path/to/file_"; String result1 = S3Util.getLongestPrefix(input1); - Assert.assertEquals(expected1, result1); + Assertions.assertEquals(expected1, result1); String input2 = "s3://bucket/path/*/file.csv"; String expected2 = "s3://bucket/path/"; String result2 = S3Util.getLongestPrefix(input2); - Assert.assertEquals(expected2, result2); + Assertions.assertEquals(expected2, result2); String input3 = "s3://bucket/path/file.csv"; String expected3 = "s3://bucket/path/file.csv"; String result3 = S3Util.getLongestPrefix(input3); - Assert.assertEquals(expected3, result3); + Assertions.assertEquals(expected3, result3); } @Test @@ -306,7 +306,7 @@ public void testExtendGlobs() { String input = "file_{1..3}.csv"; String expected = "file_{1,2,3}.csv"; String result = S3Util.extendGlobs(input); - Assert.assertEquals(expected, result); + Assertions.assertEquals(expected, result); } // Tests for isDeterministicPattern @@ -314,62 +314,62 @@ public void testExtendGlobs() { @Test public void testIsDeterministicPattern_simpleFile() { // Simple file path without any patterns - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file.csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file.csv")); } @Test public void testIsDeterministicPattern_withBraces() { // Path with brace pattern (deterministic - can be expanded) - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file{1,2,3}.csv")); - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file{1..3}.csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file{1,2,3}.csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file{1..3}.csv")); } @Test public void testIsDeterministicPattern_withAsterisk() { // Path with asterisk wildcard (not deterministic) - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/*.csv")); - Assert.assertFalse(S3Util.isDeterministicPattern("path/*/file.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/*.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/*/file.csv")); } @Test public void testIsDeterministicPattern_withQuestionMark() { // Path with question mark wildcard (not deterministic) - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file?.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file?.csv")); } @Test public void testIsDeterministicPattern_withBrackets() { // Non-negated bracket patterns are deterministic (can be expanded) - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file[0-9].csv")); - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file[abc].csv")); - Assert.assertTrue(S3Util.isDeterministicPattern("path/to/file[a-zA-Z].csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file[0-9].csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file[abc].csv")); + Assertions.assertTrue(S3Util.isDeterministicPattern("path/to/file[a-zA-Z].csv")); } @Test public void testIsDeterministicPattern_withNegatedBrackets() { // Negated bracket patterns are NOT deterministic - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file[!abc].csv")); - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file[^0-9].csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file[!abc].csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file[^0-9].csv")); } @Test public void testIsDeterministicPattern_withMalformedBrackets() { // Malformed brackets (no closing ]) are NOT deterministic - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file[abc.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file[abc.csv")); // Empty brackets [] are NOT deterministic - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file[].csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file[].csv")); } @Test public void testIsDeterministicPattern_withEscape() { // Path with escape character (not deterministic - complex pattern) - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file\\*.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file\\*.csv")); } @Test public void testIsDeterministicPattern_mixed() { // Path with both braces and wildcards - Assert.assertFalse(S3Util.isDeterministicPattern("path/to/file{1,2}/*.csv")); + Assertions.assertFalse(S3Util.isDeterministicPattern("path/to/file{1,2}/*.csv")); } // Tests for expandBracePatterns @@ -378,21 +378,21 @@ public void testIsDeterministicPattern_mixed() { public void testExpandBracePatterns_noBraces() { // No braces - returns single path List result = S3Util.expandBracePatterns("path/to/file.csv"); - Assert.assertEquals(Arrays.asList("path/to/file.csv"), result); + Assertions.assertEquals(Arrays.asList("path/to/file.csv"), result); } @Test public void testExpandBracePatterns_simpleBrace() { // Simple brace expansion List result = S3Util.expandBracePatterns("file{1,2,3}.csv"); - Assert.assertEquals(Arrays.asList("file1.csv", "file2.csv", "file3.csv"), result); + Assertions.assertEquals(Arrays.asList("file1.csv", "file2.csv", "file3.csv"), result); } @Test public void testExpandBracePatterns_multipleBraces() { // Multiple brace expansions List result = S3Util.expandBracePatterns("dir{a,b}/file{1,2}.csv"); - Assert.assertEquals(Arrays.asList( + Assertions.assertEquals(Arrays.asList( "dira/file1.csv", "dira/file2.csv", "dirb/file1.csv", "dirb/file2.csv"), result); } @@ -401,25 +401,25 @@ public void testExpandBracePatterns_multipleBraces() { public void testExpandBracePatterns_emptyBrace() { // Empty brace content List result = S3Util.expandBracePatterns("file{}.csv"); - Assert.assertEquals(Arrays.asList("file.csv"), result); + Assertions.assertEquals(Arrays.asList("file.csv"), result); } @Test public void testExpandBracePatterns_singleValue() { // Single value in brace List result = S3Util.expandBracePatterns("file{1}.csv"); - Assert.assertEquals(Arrays.asList("file1.csv"), result); + Assertions.assertEquals(Arrays.asList("file1.csv"), result); } @Test public void testExpandBracePatterns_withPath() { // Full path with braces: 2 years × 2 months = 4 paths List result = S3Util.expandBracePatterns("data/year{2023,2024}/month{01,02}/file.csv"); - Assert.assertEquals(4, result.size()); - Assert.assertTrue(result.contains("data/year2023/month01/file.csv")); - Assert.assertTrue(result.contains("data/year2023/month02/file.csv")); - Assert.assertTrue(result.contains("data/year2024/month01/file.csv")); - Assert.assertTrue(result.contains("data/year2024/month02/file.csv")); + Assertions.assertEquals(4, result.size()); + Assertions.assertTrue(result.contains("data/year2023/month01/file.csv")); + Assertions.assertTrue(result.contains("data/year2023/month02/file.csv")); + Assertions.assertTrue(result.contains("data/year2024/month01/file.csv")); + Assertions.assertTrue(result.contains("data/year2024/month02/file.csv")); } @Test @@ -427,21 +427,21 @@ public void testExpandBracePatterns_extendedRange() { // Test with extended range (after extendGlobs processing) String expanded = S3Util.extendGlobs("file{1..3}.csv"); List result = S3Util.expandBracePatterns(expanded); - Assert.assertEquals(Arrays.asList("file1.csv", "file2.csv", "file3.csv"), result); + Assertions.assertEquals(Arrays.asList("file1.csv", "file2.csv", "file3.csv"), result); } @Test public void testExpandBracePatterns_malformedBrace() { // Malformed brace pattern (no closing }) - treated as literal List result = S3Util.expandBracePatterns("file{1,2.csv"); - Assert.assertEquals(Arrays.asList("file{1,2.csv"), result); + Assertions.assertEquals(Arrays.asList("file{1,2.csv"), result); } @Test public void testExpandBracePatterns_malformedBraceWithDots() { // Malformed range-like pattern (no closing }) - treated as literal List result = S3Util.expandBracePatterns("file{1..csv"); - Assert.assertEquals(Arrays.asList("file{1..csv"), result); + Assertions.assertEquals(Arrays.asList("file{1..csv"), result); } // Tests for expandBracketPatterns @@ -449,31 +449,31 @@ public void testExpandBracePatterns_malformedBraceWithDots() { @Test public void testExpandBracketPatterns_noBrackets() { // No brackets - returns unchanged - Assert.assertEquals("path/to/file.csv", S3Util.expandBracketPatterns("path/to/file.csv")); + Assertions.assertEquals("path/to/file.csv", S3Util.expandBracketPatterns("path/to/file.csv")); } @Test public void testExpandBracketPatterns_simpleCharList() { // [abc] => {a,b,c} - Assert.assertEquals("file{a,b,c}.csv", S3Util.expandBracketPatterns("file[abc].csv")); + Assertions.assertEquals("file{a,b,c}.csv", S3Util.expandBracketPatterns("file[abc].csv")); } @Test public void testExpandBracketPatterns_charRange() { // [0-3] => {0,1,2,3} - Assert.assertEquals("file{0,1,2,3}.csv", S3Util.expandBracketPatterns("file[0-3].csv")); + Assertions.assertEquals("file{0,1,2,3}.csv", S3Util.expandBracketPatterns("file[0-3].csv")); } @Test public void testExpandBracketPatterns_mixedRangeAndChars() { // [a-cX] => {a,b,c,X} - Assert.assertEquals("file{a,b,c,X}.csv", S3Util.expandBracketPatterns("file[a-cX].csv")); + Assertions.assertEquals("file{a,b,c,X}.csv", S3Util.expandBracketPatterns("file[a-cX].csv")); } @Test public void testExpandBracketPatterns_multipleRanges() { // [a-c0-2] => {a,b,c,0,1,2} - Assert.assertEquals("file{a,b,c,0,1,2}.csv", S3Util.expandBracketPatterns("file[a-c0-2].csv")); + Assertions.assertEquals("file{a,b,c,0,1,2}.csv", S3Util.expandBracketPatterns("file[a-c0-2].csv")); } @Test @@ -483,7 +483,7 @@ public void testExpandBracketPatterns_fullPipeline() { String bracketExpanded = S3Util.expandBracketPatterns("file[abc].csv"); String globExpanded = S3Util.extendGlobs(bracketExpanded); List result = S3Util.expandBracePatterns(globExpanded); - Assert.assertEquals(Arrays.asList("filea.csv", "fileb.csv", "filec.csv"), result); + Assertions.assertEquals(Arrays.asList("filea.csv", "fileb.csv", "filec.csv"), result); } @Test @@ -491,9 +491,9 @@ public void testExpandBracketPatterns_withBracesAndBrackets() { // Mixed brackets and braces: dir[ab]/file{1,2}.csv // => dir{a,b}/file{1,2}.csv => [dira/file1.csv, dira/file2.csv, dirb/file1.csv, dirb/file2.csv] String bracketExpanded = S3Util.expandBracketPatterns("dir[ab]/file{1,2}.csv"); - Assert.assertEquals("dir{a,b}/file{1,2}.csv", bracketExpanded); + Assertions.assertEquals("dir{a,b}/file{1,2}.csv", bracketExpanded); List result = S3Util.expandBracePatterns(bracketExpanded); - Assert.assertEquals(Arrays.asList( + Assertions.assertEquals(Arrays.asList( "dira/file1.csv", "dira/file2.csv", "dirb/file1.csv", "dirb/file2.csv"), result); } @@ -503,14 +503,14 @@ public void testExpandBracketPatterns_digitRange() { // [0-9] => {0,1,2,3,4,5,6,7,8,9} String expanded = S3Util.expandBracketPatterns("part[0-9].dat"); List result = S3Util.expandBracePatterns(expanded); - Assert.assertEquals(10, result.size()); - Assert.assertTrue(result.contains("part0.dat")); - Assert.assertTrue(result.contains("part9.dat")); + Assertions.assertEquals(10, result.size()); + Assertions.assertTrue(result.contains("part0.dat")); + Assertions.assertTrue(result.contains("part9.dat")); } @Test public void testExpandBracketPatterns_malformedBracket() { // Malformed bracket (no closing ]) - [ kept as literal - Assert.assertEquals("file[abc.csv", S3Util.expandBracketPatterns("file[abc.csv")); + Assertions.assertEquals("file[abc.csv", S3Util.expandBracketPatterns("file[abc.csv")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/SafeStringBuilderTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/SafeStringBuilderTest.java index cfd4b67dff7ad8..41c41b850d511b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/SafeStringBuilderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/SafeStringBuilderTest.java @@ -17,16 +17,16 @@ package org.apache.doris.common.util; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SafeStringBuilderTest { private SafeStringBuilder builder; private final int testMaxCapacity = 100; - @Before + @BeforeEach public void setUp() { builder = new SafeStringBuilder(testMaxCapacity); } @@ -34,28 +34,28 @@ public void setUp() { @Test public void testDefaultConstructor() { SafeStringBuilder defaultBuilder = new SafeStringBuilder(); - Assert.assertEquals(Integer.MAX_VALUE - 16, defaultBuilder.getMaxCapacity()); + Assertions.assertEquals(Integer.MAX_VALUE - 16, defaultBuilder.getMaxCapacity()); } @Test public void testConstructorWithSmallCapacity() { SafeStringBuilder smallBuilder = new SafeStringBuilder(10); - Assert.assertEquals(0, smallBuilder.getMaxCapacity()); + Assertions.assertEquals(0, smallBuilder.getMaxCapacity()); } @Test public void testAppendStringWithinCapacity() { String testString = "Hello"; builder.append(testString); - Assert.assertEquals(testString, builder.toString()); - Assert.assertFalse(builder.isTruncated()); + Assertions.assertEquals(testString, builder.toString()); + Assertions.assertFalse(builder.isTruncated()); } @Test public void testMultipleAppendsWithinCapacity() { builder.append("Hello").append(" ").append("World"); - Assert.assertEquals("Hello World", builder.toString()); - Assert.assertFalse(builder.isTruncated()); + Assertions.assertEquals("Hello World", builder.toString()); + Assertions.assertFalse(builder.isTruncated()); } @Test @@ -67,9 +67,9 @@ public void testAppendStringExceedingCapacity() { builder.append(exceedString); // Should be truncated to exactly max capacity - Assert.assertEquals(testMaxCapacity - 16, builder.length()); - Assert.assertTrue(builder.isTruncated()); - Assert.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); + Assertions.assertEquals(testMaxCapacity - 16, builder.length()); + Assertions.assertTrue(builder.isTruncated()); + Assertions.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); } @Test @@ -81,47 +81,47 @@ public String toString() { } }; builder.append(testObj); - Assert.assertEquals("TestObject", builder.toString()); + Assertions.assertEquals("TestObject", builder.toString()); } @Test public void testLength() { - Assert.assertEquals(0, builder.length()); + Assertions.assertEquals(0, builder.length()); builder.append("123"); - Assert.assertEquals(3, builder.length()); + Assertions.assertEquals(3, builder.length()); } @Test public void testToStringNotTruncated() { builder.append("Normal string"); - Assert.assertEquals("Normal string", builder.toString()); + Assertions.assertEquals("Normal string", builder.toString()); } @Test public void testToStringTruncated() { // Force truncation builder.append(repeat('X', testMaxCapacity - 5)); - Assert.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); + Assertions.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); } @Test public void testAppendAfterTruncation() { // First append that causes truncation builder.append(repeat('X', testMaxCapacity + 1)); - Assert.assertTrue(builder.isTruncated()); + Assertions.assertTrue(builder.isTruncated()); // Subsequent append should be ignored builder.append("This should not appear"); - Assert.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); - Assert.assertFalse(builder.toString().contains("This should not appear")); + Assertions.assertTrue(builder.toString().endsWith("...[TRUNCATED]")); + Assertions.assertFalse(builder.toString().contains("This should not appear")); } @Test public void testExactCapacity() { String exactString = repeat('X', testMaxCapacity - 16); builder.append(exactString); - Assert.assertEquals(exactString, builder.toString()); - Assert.assertFalse(builder.isTruncated()); + Assertions.assertEquals(exactString, builder.toString()); + Assertions.assertFalse(builder.isTruncated()); } private String repeat(char c, int count) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/SortAndLimitTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/SortAndLimitTest.java index 0b72552d72ece4..abf42e85530271 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/SortAndLimitTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/SortAndLimitTest.java @@ -19,8 +19,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -49,7 +49,7 @@ private static List firstColumnOf(List> rows) { public void testEmptyLimitKeepsEveryRow() { List> sorted = SortAndLimit.sortAndLimit(rows(3L, 1L, 2L), BY_FIRST_COLUMN, Optional.empty()); - Assert.assertEquals(Lists.newArrayList(1L, 2L, 3L), firstColumnOf(sorted)); + Assertions.assertEquals(Lists.newArrayList(1L, 2L, 3L), firstColumnOf(sorted)); } @Test @@ -57,14 +57,14 @@ public void testLimitAppliesToTheSortedResult() { // the two smallest values, not the first two rows of the input List> sorted = SortAndLimit.sortAndLimit(rows(3L, 1L, 2L), BY_FIRST_COLUMN, Optional.of(2)); - Assert.assertEquals(Lists.newArrayList(1L, 2L), firstColumnOf(sorted)); + Assertions.assertEquals(Lists.newArrayList(1L, 2L), firstColumnOf(sorted)); } @Test public void testLimitLargerThanInputIsClamped() { List> sorted = SortAndLimit.sortAndLimit(rows(3L, 1L), BY_FIRST_COLUMN, Optional.of(100)); - Assert.assertEquals(Lists.newArrayList(1L, 3L), firstColumnOf(sorted)); + Assertions.assertEquals(Lists.newArrayList(1L, 3L), firstColumnOf(sorted)); } @Test @@ -73,7 +73,7 @@ public void testInputIsNotModified() { ImmutableList.of(3L), ImmutableList.of(1L)); List> sorted = SortAndLimit.sortAndLimit(input, BY_FIRST_COLUMN, Optional.of(1)); - Assert.assertEquals(Lists.newArrayList(1L), firstColumnOf(sorted)); - Assert.assertEquals(Lists.newArrayList(3L, 1L), firstColumnOf(input)); + Assertions.assertEquals(Lists.newArrayList(1L), firstColumnOf(sorted)); + Assertions.assertEquals(Lists.newArrayList(3L, 1L), firstColumnOf(input)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/SymmetricEncryptionTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/SymmetricEncryptionTest.java index fc8a53b7ce9909..f7c2101863e3cf 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/SymmetricEncryptionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/SymmetricEncryptionTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SymmetricEncryptionTest { @@ -34,6 +34,6 @@ private void testEncryptionAndDecryption(String password) { byte[] iv = SymmetricEncryption.generateIv(); String passwdEncrypted = SymmetricEncryption.encrypt(password, key, iv); String passwdDecrypted = SymmetricEncryption.decrypt(passwdEncrypted, key, iv); - Assert.assertEquals(password, passwdDecrypted); + Assertions.assertEquals(password, passwdDecrypted); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/TimeUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/TimeUtilsTest.java index 30fb368e6617ec..f69ab124c1fe77 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/TimeUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/TimeUtilsTest.java @@ -25,10 +25,10 @@ import org.apache.doris.common.ExceptionChecker; import org.apache.doris.common.FeConstants; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -44,14 +44,14 @@ public class TimeUtilsTest { private MockedStatic mockedTimeUtils; - @Before + @BeforeEach public void setUp() { TimeZone tz = TimeZone.getTimeZone(ZoneId.of("Asia/Shanghai")); mockedTimeUtils = Mockito.mockStatic(TimeUtils.class, Mockito.CALLS_REAL_METHODS); mockedTimeUtils.when(TimeUtils::getTimeZone).thenReturn(tz); } - @After + @AfterEach public void tearDown() { if (mockedTimeUtils != null) { mockedTimeUtils.close(); @@ -60,9 +60,9 @@ public void tearDown() { @Test public void testNormal() { - Assert.assertNotNull(TimeUtils.getCurrentFormatTime()); - Assert.assertNotNull(TimeUtils.getStartTimeMs()); - Assert.assertTrue(TimeUtils.getElapsedTimeMs(0L) > 0); + Assertions.assertNotNull(TimeUtils.getCurrentFormatTime()); + Assertions.assertNotNull(TimeUtils.getStartTimeMs()); + Assertions.assertTrue(TimeUtils.getElapsedTimeMs(0L) > 0); } @Test @@ -83,7 +83,7 @@ public void testDateParse() { } catch (AnalysisException e) { e.printStackTrace(); System.out.println(validDate); - Assert.fail(); + Assertions.fail(); } } @@ -98,9 +98,9 @@ public void testDateParse() { for (String invalidDate : invalidDateList) { try { TimeUtils.parseDate(invalidDate, PrimitiveType.DATE); - Assert.fail(); + Assertions.fail(); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Invalid")); + Assertions.assertTrue(e.getMessage().contains("Invalid")); } } @@ -122,7 +122,7 @@ public void testDateParse() { } catch (AnalysisException e) { e.printStackTrace(); System.out.println(validDateTime); - Assert.fail(); + Assertions.fail(); } } @@ -138,46 +138,46 @@ public void testDateParse() { for (String invalidDateTime : invalidDateTimeList) { try { TimeUtils.parseDate(invalidDateTime, PrimitiveType.DATETIME); - Assert.fail(); + Assertions.fail(); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Invalid")); + Assertions.assertTrue(e.getMessage().contains("Invalid")); } } } @Test public void testDateTrans() throws AnalysisException { - Assert.assertEquals(FeConstants.null_string, TimeUtils.longToTimeString(-2L)); + Assertions.assertEquals(FeConstants.null_string, TimeUtils.longToTimeString(-2L)); long timestamp = 1426125600000L; - Assert.assertEquals("2015-03-12 10:00:00", TimeUtils.longToTimeString(timestamp)); + Assertions.assertEquals("2015-03-12 10:00:00", TimeUtils.longToTimeString(timestamp)); DateLiteral date = new DateLiteral(2015, 3, 1, ScalarType.DATE); - Assert.assertEquals(1031777L, date.getRealValue()); + Assertions.assertEquals(1031777L, date.getRealValue()); DateLiteral datetime = new DateLiteral(2015, 3, 1, 12, 0, 0, ScalarType.DATETIME); - Assert.assertEquals(20150301120000L, datetime.getRealValue()); + Assertions.assertEquals(20150301120000L, datetime.getRealValue()); } @Test public void testTimezone() throws AnalysisException { try { - Assert.assertEquals("CST", TimeUtils.checkTimeZoneValidAndStandardize("CST")); - Assert.assertEquals("EST", TimeUtils.checkTimeZoneValidAndStandardize("EST")); - Assert.assertEquals("GMT+08:00", TimeUtils.checkTimeZoneValidAndStandardize("GMT+8:00")); - Assert.assertEquals("UTC+08:00", TimeUtils.checkTimeZoneValidAndStandardize("UTC+8:00")); - Assert.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("+08:00")); - Assert.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("+8:00")); - Assert.assertEquals("-08:00", TimeUtils.checkTimeZoneValidAndStandardize("-8:00")); - Assert.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("8:00")); + Assertions.assertEquals("CST", TimeUtils.checkTimeZoneValidAndStandardize("CST")); + Assertions.assertEquals("EST", TimeUtils.checkTimeZoneValidAndStandardize("EST")); + Assertions.assertEquals("GMT+08:00", TimeUtils.checkTimeZoneValidAndStandardize("GMT+8:00")); + Assertions.assertEquals("UTC+08:00", TimeUtils.checkTimeZoneValidAndStandardize("UTC+8:00")); + Assertions.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("+08:00")); + Assertions.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("+8:00")); + Assertions.assertEquals("-08:00", TimeUtils.checkTimeZoneValidAndStandardize("-8:00")); + Assertions.assertEquals("+08:00", TimeUtils.checkTimeZoneValidAndStandardize("8:00")); } catch (DdlException ex) { - Assert.assertTrue(ex.getMessage(), false); + Assertions.assertTrue(false, ex.getMessage()); } try { TimeUtils.checkTimeZoneValidAndStandardize("FOO"); - Assert.fail(); + Assertions.fail(); } catch (DdlException ex) { - Assert.assertTrue(ex.getMessage().contains("Unknown or incorrect time zone: 'FOO'")); + Assertions.assertTrue(ex.getMessage().contains("Unknown or incorrect time zone: 'FOO'")); } } @@ -186,36 +186,36 @@ public void testGetHourAsDate() { Calendar calendar = Calendar.getInstance(); Date date = TimeUtils.getHourAsDate("1"); calendar.setTime(date); - Assert.assertEquals(1, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertEquals(1, calendar.get(Calendar.HOUR_OF_DAY)); date = TimeUtils.getHourAsDate("10"); calendar.setTime(date); - Assert.assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertEquals(10, calendar.get(Calendar.HOUR_OF_DAY)); date = TimeUtils.getHourAsDate("24"); calendar.setTime(date); - Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); date = TimeUtils.getHourAsDate("05"); calendar.setTime(date); - Assert.assertEquals(5, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertEquals(5, calendar.get(Calendar.HOUR_OF_DAY)); date = TimeUtils.getHourAsDate("0"); calendar.setTime(date); - Assert.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); date = TimeUtils.getHourAsDate("13"); calendar.setTime(date); - Assert.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); - Assert.assertNull(TimeUtils.getHourAsDate("111")); - Assert.assertNull(TimeUtils.getHourAsDate("-1")); + Assertions.assertEquals(13, calendar.get(Calendar.HOUR_OF_DAY)); + Assertions.assertNull(TimeUtils.getHourAsDate("111")); + Assertions.assertNull(TimeUtils.getHourAsDate("-1")); } @Test public void testConvertToBEDateType() { long result = TimeUtils.convertStringToDateV2("2021-01-01"); - Assert.assertEquals(1034785, result); + Assertions.assertEquals(1034785, result); result = TimeUtils.convertStringToDateV2("1900-01-01"); - Assert.assertEquals(972833, result); + Assertions.assertEquals(972833, result); result = TimeUtils.convertStringToDateV2("1899-12-31"); - Assert.assertEquals(972703, result); + Assertions.assertEquals(972703, result); result = TimeUtils.convertStringToDateV2("9999-12-31"); - Assert.assertEquals(5119903, result); + Assertions.assertEquals(5119903, result); ExceptionChecker.expectThrows(DateTimeParseException.class, () -> TimeUtils.convertStringToDateV2("2021-1-1")); ExceptionChecker.expectThrows(DateTimeParseException.class, () -> TimeUtils.convertStringToDateV2("1900-01-1")); @@ -229,13 +229,13 @@ public void testConvertToBEDateType() { @Test public void testConvertToBEDatetimeV2Type() { long result = TimeUtils.convertStringToDateTimeV2("2021-01-01 10:10:10", 0); - Assert.assertEquals(142219811099770880L, result); + Assertions.assertEquals(142219811099770880L, result); result = TimeUtils.convertStringToDateTimeV2("1900-01-01 00:00:00.12", 2); - Assert.assertEquals(133705149423146176L, result); + Assertions.assertEquals(133705149423146176L, result); result = TimeUtils.convertStringToDateTimeV2("1899-12-31 23:59:59.000", 3); - Assert.assertEquals(133687385164611584L, result); + Assertions.assertEquals(133687385164611584L, result); result = TimeUtils.convertStringToDateTimeV2("9999-12-31 23:59:59.123456", 6); - Assert.assertEquals(703674213003812984L, result); + Assertions.assertEquals(703674213003812984L, result); ExceptionChecker.expectThrows(DateTimeParseException.class, () -> TimeUtils.convertStringToDateTimeV2("2021-1-1", 0)); @@ -258,29 +258,29 @@ public void testConvertToBEDatetimeV2Type() { @Test public void testLongToTimeStringWithTimeZoneAndOffset() { // null/zero/negative → null_string - Assert.assertEquals(FeConstants.null_string, + Assertions.assertEquals(FeConstants.null_string, TimeUtils.longToTimeStringWithTimeZoneAndOffset(null, "UTC")); - Assert.assertEquals(FeConstants.null_string, + Assertions.assertEquals(FeConstants.null_string, TimeUtils.longToTimeStringWithTimeZoneAndOffset(0L, "UTC")); - Assert.assertEquals(FeConstants.null_string, + Assertions.assertEquals(FeConstants.null_string, TimeUtils.longToTimeStringWithTimeZoneAndOffset(-1L, "Asia/Shanghai")); long ts = org.apache.doris.catalog.DataProperty.MAX_COOLDOWN_TIME_MS; // UTC → "9999-12-31 15:59:59Z" String utcResult = TimeUtils.longToTimeStringWithTimeZoneAndOffset(ts, "UTC"); - Assert.assertEquals("9999-12-31 15:59:59Z", utcResult); + Assertions.assertEquals("9999-12-31 15:59:59Z", utcResult); // Asia/Shanghai (+08:00) → "9999-12-31 23:59:59+08:00" String shanghaiResult = TimeUtils.longToTimeStringWithTimeZoneAndOffset(ts, "Asia/Shanghai"); - Assert.assertEquals("9999-12-31 23:59:59+08:00", shanghaiResult); + Assertions.assertEquals("9999-12-31 23:59:59+08:00", shanghaiResult); // America/New_York (-05:00) → "9999-12-31 10:59:59-05:00" String nyResult = TimeUtils.longToTimeStringWithTimeZoneAndOffset(ts, "America/New_York"); - Assert.assertEquals("9999-12-31 10:59:59-05:00", nyResult); + Assertions.assertEquals("9999-12-31 10:59:59-05:00", nyResult); // America/Chicago (-06:00) → "9999-12-31 09:59:59-06:00" String chicagoResult = TimeUtils.longToTimeStringWithTimeZoneAndOffset(ts, "America/Chicago"); - Assert.assertEquals("9999-12-31 09:59:59-06:00", chicagoResult); + Assertions.assertEquals("9999-12-31 09:59:59-06:00", chicagoResult); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/URITest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/URITest.java index 235880cf635895..ef2b888745f9dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/URITest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/URITest.java @@ -19,21 +19,21 @@ import org.apache.doris.common.UserException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.net.URISyntaxException; public class URITest { private void check(java.net.URI javaURI, URI myURI) { - Assert.assertEquals(javaURI.getAuthority(), myURI.getAuthority()); - Assert.assertEquals(javaURI.getPath(), myURI.getPath()); - Assert.assertEquals(javaURI.getHost(), myURI.getHost()); - Assert.assertEquals(javaURI.getPort(), myURI.getPort()); - Assert.assertEquals(javaURI.getScheme(), myURI.getScheme()); - Assert.assertEquals(javaURI.getQuery(), myURI.getQuery()); - Assert.assertEquals(javaURI.getFragment(), myURI.getFragment()); - Assert.assertEquals(javaURI.getUserInfo(), myURI.getUserInfo()); + Assertions.assertEquals(javaURI.getAuthority(), myURI.getAuthority()); + Assertions.assertEquals(javaURI.getPath(), myURI.getPath()); + Assertions.assertEquals(javaURI.getHost(), myURI.getHost()); + Assertions.assertEquals(javaURI.getPort(), myURI.getPort()); + Assertions.assertEquals(javaURI.getScheme(), myURI.getScheme()); + Assertions.assertEquals(javaURI.getQuery(), myURI.getQuery()); + Assertions.assertEquals(javaURI.getFragment(), myURI.getFragment()); + Assertions.assertEquals(javaURI.getUserInfo(), myURI.getUserInfo()); } @Test @@ -42,33 +42,33 @@ public void testNormal() throws UserException, URISyntaxException { java.net.URI javaURI1 = new java.net.URI(str1); URI myURI1 = URI.create(str1); check(javaURI1, myURI1); - Assert.assertEquals(myURI1.getUserName(), "username"); - Assert.assertEquals(myURI1.getPassWord(), "password"); - Assert.assertEquals(myURI1.getQueryMap().get("type"), "animal"); + Assertions.assertEquals(myURI1.getUserName(), "username"); + Assertions.assertEquals(myURI1.getPassWord(), "password"); + Assertions.assertEquals(myURI1.getQueryMap().get("type"), "animal"); String str2 = "foo://example.com/over/there/index.dtb#nose"; java.net.URI javaURI2 = new java.net.URI(str2); URI myURI2 = URI.create(str2); check(javaURI2, myURI2); - Assert.assertEquals(myURI2.getFragment(), "nose"); + Assertions.assertEquals(myURI2.getFragment(), "nose"); String str3 = "foo://example.com/over/there/index.dtb?type=animal"; java.net.URI javaURI3 = new java.net.URI(str3); URI myURI3 = URI.create(str3); check(javaURI3, myURI3); - Assert.assertEquals(myURI3.getQueryMap().get("type"), "animal"); + Assertions.assertEquals(myURI3.getQueryMap().get("type"), "animal"); String str4 = "foo://:password@example.com/over/there/index.dtb?type=animal"; java.net.URI javaURI4 = new java.net.URI(str4); URI myURI4 = URI.create(str4); check(javaURI4, myURI4); - Assert.assertEquals(myURI4.getQueryMap().get("type"), "animal"); + Assertions.assertEquals(myURI4.getQueryMap().get("type"), "animal"); String str5 = "foo://password@example.com/over/there/index.dtb?type=animal"; java.net.URI javaURI5 = new java.net.URI(str5); URI myURI5 = URI.create(str5); check(javaURI5, myURI5); - Assert.assertEquals(myURI5.getQueryMap().get("type"), "animal"); + Assertions.assertEquals(myURI5.getQueryMap().get("type"), "animal"); String str6 = "foo://example.com"; java.net.URI javaURI6 = new java.net.URI(str6); @@ -86,13 +86,13 @@ public void testNormal() throws UserException, URISyntaxException { check(javaURI8, myURI8); URI myURI9 = URI.create("hdfs://ip:12/test/test/data/{20220131,20220201}/*"); - Assert.assertEquals(myURI9.getScheme(), "hdfs"); - Assert.assertEquals(myURI9.getPath(), "/test/test/data/{20220131,20220201}/*"); - Assert.assertEquals(myURI9.getHost(), "ip"); - Assert.assertEquals(myURI9.getPort(), 12); - Assert.assertEquals(myURI9.getAuthority(), "ip:12"); + Assertions.assertEquals(myURI9.getScheme(), "hdfs"); + Assertions.assertEquals(myURI9.getPath(), "/test/test/data/{20220131,20220201}/*"); + Assertions.assertEquals(myURI9.getHost(), "ip"); + Assertions.assertEquals(myURI9.getPort(), 12); + Assertions.assertEquals(myURI9.getAuthority(), "ip:12"); URI myURI10 = URI.create("hdfs"); - Assert.assertEquals(myURI10.getPath(), "hdfs"); + Assertions.assertEquals(myURI10.getPath(), "hdfs"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/UnitTestUtil.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/UnitTestUtil.java index a26e472d22e681..96a63cd4b1fc7b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/UnitTestUtil.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/UnitTestUtil.java @@ -45,7 +45,7 @@ import org.apache.doris.thrift.TStorageType; import org.apache.doris.thrift.TTabletType; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import java.lang.reflect.Method; import java.util.ArrayList; @@ -153,7 +153,7 @@ public static Method getPrivateMethod(Class c, String methodName, Class[] params method = c.getDeclaredMethod(methodName, params); method.setAccessible(true); } catch (NoSuchMethodException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } return method; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/common/util/VersionTest.java b/fe/fe-core/src/test/java/org/apache/doris/common/util/VersionTest.java index df0d7f30cd012c..2017c925334b54 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/common/util/VersionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/common/util/VersionTest.java @@ -17,8 +17,8 @@ package org.apache.doris.common.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class VersionTest { @@ -27,24 +27,24 @@ public void testVersion() { DigitalVersion v = new DigitalVersion(1100000); System.out.println(v); - Assert.assertEquals(1, v.major); - Assert.assertEquals(10, v.minor); - Assert.assertEquals(0, v.revision); + Assertions.assertEquals(1, v.major); + Assertions.assertEquals(10, v.minor); + Assertions.assertEquals(0, v.revision); DigitalVersion s = new DigitalVersion((byte) 50, (byte) 2, (byte) 3); - Assert.assertEquals(50020300, s.id); + Assertions.assertEquals(50020300, s.id); - Assert.assertTrue(s.onOrAfter(v)); - Assert.assertFalse(s.before(v)); + Assertions.assertTrue(s.onOrAfter(v)); + Assertions.assertFalse(s.before(v)); DigitalVersion vs = new DigitalVersion((byte) 1, (byte) 10, (byte) 0); - Assert.assertEquals(vs, v); + Assertions.assertEquals(vs, v); } @Test public void testFromString() { try { - Assert.assertEquals(1060000, DigitalVersion.fromString("1.6.0.123.123").id); + Assertions.assertEquals(1060000, DigitalVersion.fromString("1.6.0.123.123").id); } catch (IllegalArgumentException e) { e.printStackTrace(); } @@ -52,22 +52,22 @@ public void testFromString() { try { DigitalVersion.fromString(""); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - Assert.assertTrue(e.getMessage().contains("Illegal empty version")); + Assertions.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e.getMessage().contains("Illegal empty version")); } try { DigitalVersion.fromString("1.6123123.123"); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - Assert.assertTrue(e.getMessage().contains("Illegal version format")); + Assertions.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e.getMessage().contains("Illegal version format")); } try { DigitalVersion.fromString("a.b.c"); } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - Assert.assertTrue(e.getMessage().contains("Illegal version format")); + Assertions.assertTrue(e instanceof IllegalArgumentException); + Assertions.assertTrue(e.getMessage().contains("Illegal version format")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/cooldown/CooldownConfHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/cooldown/CooldownConfHandlerTest.java index 6868000f425a50..d8c863e4b156e3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/cooldown/CooldownConfHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/cooldown/CooldownConfHandlerTest.java @@ -41,7 +41,7 @@ import com.google.common.collect.Lists; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.LinkedList; @@ -121,7 +121,7 @@ public void updateCooldownConf() { break; } } - Assert.assertTrue(matched); - Assert.assertEquals(101, cooldownTerm); + Assertions.assertTrue(matched); + Assertions.assertEquals(101, cooldownTerm); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogFactoryTest.java index c03f9c4ade77c1..f18366d9b4821a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogFactoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogFactoryTest.java @@ -23,8 +23,8 @@ import org.apache.doris.connector.spi.Connector; import org.apache.doris.datasource.plugin.PluginDrivenExternalCatalog; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.HashMap; @@ -38,10 +38,10 @@ public void testCloseCatalogWhenCreateValidationFails() throws Exception { 1L, "failed_catalog", null, new HashMap<>(), "", connector)); Mockito.doThrow(new DdlException("validation failed")).when(catalog).checkWhenCreating(); - DdlException exception = Assert.assertThrows( + DdlException exception = Assertions.assertThrows( DdlException.class, () -> CatalogFactory.finishCatalogCreation(catalog, false)); - Assert.assertTrue(exception.getMessage().endsWith("validation failed")); + Assertions.assertTrue(exception.getMessage().endsWith("validation failed")); Mockito.verify(connector).close(); } @@ -57,10 +57,10 @@ public void checkWhenCreating() throws DdlException { } }; - DdlException exception = Assert.assertThrows( + DdlException exception = Assertions.assertThrows( DdlException.class, () -> CatalogFactory.finishCatalogCreation(catalog, false)); - Assert.assertTrue(exception.getMessage().endsWith("primary validation failure")); + Assertions.assertTrue(exception.getMessage().endsWith("primary validation failure")); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogPropertyTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogPropertyTest.java index 6a47944748e4ed..73c2862e5e213b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogPropertyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/CatalogPropertyTest.java @@ -20,8 +20,8 @@ import org.apache.doris.datasource.storage.StorageAdapter; import org.apache.doris.datasource.storage.StorageTypeId; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; @@ -53,18 +53,17 @@ public void testStorageAdaptersArePublishedAfterInitialization() throws Exceptio try { Future> initializer = executor.submit(catalogProperty::getStorageAdaptersMap); - Assert.assertTrue(initializationStarted.await(5, TimeUnit.SECONDS)); + Assertions.assertTrue(initializationStarted.await(5, TimeUnit.SECONDS)); concurrentReader.start(); - Assert.assertTrue(waitUntilBlockedOrTerminated(concurrentReader, 5, TimeUnit.SECONDS)); - Assert.assertEquals("The reader must block until initialization publishes the completed map", - Thread.State.BLOCKED, concurrentReader.getState()); + Assertions.assertTrue(waitUntilBlockedOrTerminated(concurrentReader, 5, TimeUnit.SECONDS)); + Assertions.assertEquals(Thread.State.BLOCKED, concurrentReader.getState(), "The reader must block until initialization publishes the completed map"); allowInitialization.countDown(); Map initialized = initializer.get(5, TimeUnit.SECONDS); concurrentReader.join(TimeUnit.SECONDS.toMillis(5)); - Assert.assertFalse(concurrentReader.isAlive()); - Assert.assertSame(initialized, readerResult.get()); + Assertions.assertFalse(concurrentReader.isAlive()); + Assertions.assertSame(initialized, readerResult.get()); } finally { allowInitialization.countDown(); concurrentReader.interrupt(); @@ -79,7 +78,7 @@ public void testStorageAdaptersCacheIsImmutable() { catalogProperty.setPluginDerivedStorageDefaultsSupplier(Collections::emptyMap); Map storageAdapters = catalogProperty.getStorageAdaptersMap(); - Assert.assertThrows(UnsupportedOperationException.class, storageAdapters::clear); + Assertions.assertThrows(UnsupportedOperationException.class, storageAdapters::clear); } private static boolean waitUntilBlockedOrTerminated(Thread thread, long timeout, TimeUnit timeUnit) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/ColumnPrivTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/ColumnPrivTest.java index b4e7fce9e7b422..1d7052cf2b4bb7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/ColumnPrivTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/ColumnPrivTest.java @@ -35,7 +35,6 @@ import org.apache.doris.qe.StmtExecutor; import org.apache.doris.utframe.TestWithFeService; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -134,13 +133,13 @@ protected void runBeforeAll() throws Exception { protected void runAfterAll() throws Exception { super.runAfterAll(); rootCtx.setThreadLocalInfo(); - Assert.assertTrue(env.getAccessManager().checkIfAccessControllerExist("test1")); + Assertions.assertTrue(env.getAccessManager().checkIfAccessControllerExist("test1")); NereidsParser nereidsParser = new NereidsParser(); LogicalPlan logicalPlan = nereidsParser.parseSingle("drop catalog test1"); if (logicalPlan instanceof DropCatalogCommand) { ((DropCatalogCommand) logicalPlan).run(rootCtx, null); } - Assert.assertFalse(env.getAccessManager().checkIfAccessControllerExist("test1")); + Assertions.assertFalse(env.getAccessManager().checkIfAccessControllerExist("test1")); } @Test @@ -166,6 +165,6 @@ public void testShowTableStatusPrivs() throws Exception { ConnectContext userCtx = createCtx(user, "127.0.0.1"); ShowTableStatusCommand command = new ShowTableStatusCommand("db1", "test2", "%tbl%", null); ShowResultSet resultSet = command.doRun(userCtx, new StmtExecutor(userCtx, "")); - Assert.assertEquals(2, resultSet.getResultRows().size()); + Assertions.assertEquals(2, resultSet.getResultRows().size()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalEqualsTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalEqualsTest.java index 2e36a222cfe3de..4b1707a35a0f32 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalEqualsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalEqualsTest.java @@ -21,8 +21,8 @@ import org.apache.doris.datasource.test.TestExternalDatabase; import org.apache.doris.datasource.test.TestExternalTable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class ExternalEqualsTest { @@ -35,16 +35,16 @@ public void testEquals() { TestExternalDatabase db2 = new TestExternalDatabase(ctl2, 1L, "db2", null); TestExternalDatabase db3 = new TestExternalDatabase(ctl1, 1L, "db2", null); TestExternalDatabase db11 = new TestExternalDatabase(ctl1, 1L, "db1", null); - Assert.assertNotEquals(db1, db2); - Assert.assertNotEquals(db1, db3); - Assert.assertEquals(db1, db11); + Assertions.assertNotEquals(db1, db2); + Assertions.assertNotEquals(db1, db3); + Assertions.assertEquals(db1, db11); TestExternalTable t1 = new TestExternalTable(1L, "t1", null, ctl1, db1); TestExternalTable t2 = new TestExternalTable(2L, "t2", null, ctl2, db2); TestExternalTable t3 = new TestExternalTable(3L, "t3", null, ctl1, db1); TestExternalTable t11 = new TestExternalTable(4L, "t1", null, ctl1, db1); - Assert.assertNotEquals(t1, t2); - Assert.assertNotEquals(t1, t3); - Assert.assertEquals(t1, t11); + Assertions.assertNotEquals(t1, t2); + Assertions.assertNotEquals(t1, t3); + Assertions.assertEquals(t1, t11); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalTableSchemaCacheDelegationTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalTableSchemaCacheDelegationTest.java index c14f8f3765e0ce..0b3e3afacb8a67 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalTableSchemaCacheDelegationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/ExternalTableSchemaCacheDelegationTest.java @@ -21,8 +21,8 @@ import org.apache.doris.catalog.PrimitiveType; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -34,13 +34,13 @@ public class ExternalTableSchemaCacheDelegationTest { public void testGetFullSchemaDelegatesToGetSchemaCacheValue() { List schema = Lists.newArrayList(new Column("c1", PrimitiveType.INT)); ExternalTable table = new DelegatingExternalTable(Optional.of(new SchemaCacheValue(schema))); - Assert.assertEquals(schema, table.getFullSchema()); + Assertions.assertEquals(schema, table.getFullSchema()); } @Test public void testGetFullSchemaReturnsNullWhenSchemaCacheMissing() { ExternalTable table = new DelegatingExternalTable(Optional.empty()); - Assert.assertNull(table.getFullSchema()); + Assertions.assertNull(table.getFullSchema()); } @Test @@ -56,10 +56,9 @@ public void getSchemaCacheValueBypassesSharedCacheUnderSessionUser() { BypassProbeTable table = new BypassProbeTable(catalog, live); Optional result = table.getSchemaCacheValue(); - Assert.assertTrue(result.isPresent()); - Assert.assertEquals(live, result.get().getSchema()); - Assert.assertEquals("schema was read live, once, through initSchema (not the shared cache)", - 1, table.initSchemaCalls); + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(live, result.get().getSchema()); + Assertions.assertEquals(1, table.initSchemaCalls, "schema was read live, once, through initSchema (not the shared cache)"); } private static final class BypassProbeTable extends ExternalTable { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/FileCacheAdmissionRuleRefresherTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/FileCacheAdmissionRuleRefresherTest.java index d17b1092a39952..7f42b76be03026 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/FileCacheAdmissionRuleRefresherTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/FileCacheAdmissionRuleRefresherTest.java @@ -23,10 +23,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.awaitility.Awaitility; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -45,7 +45,7 @@ public class FileCacheAdmissionRuleRefresherTest { private static FileCacheAdmissionManager manager; - @BeforeClass + @BeforeAll public static void setUpClass() throws Exception { Path currentDir = Paths.get("").toAbsolutePath(); Path jsonFileDir = currentDir.resolve("jsonFileDir-test"); @@ -65,13 +65,13 @@ public static void setUpClass() throws Exception { public void testJsonFileCreated() throws Exception { AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_1", "catalog_1", "database_1", "table_1", reason1); - Assert.assertFalse(result1); - Assert.assertEquals("default rule", reason1.get()); + Assertions.assertFalse(result1); + Assertions.assertEquals("default rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_2", "catalog_2", "database_2", "table_2", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("default rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("default rule", reason2.get()); List rules = new ArrayList<>(); long createdTime = 0; @@ -100,13 +100,13 @@ public void testJsonFileCreated() throws Exception { Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_1", "catalog_1", "database_1", "table_1", reason3); - Assert.assertTrue(result3); - Assert.assertEquals("user table-level whitelist rule", reason3.get()); + Assertions.assertTrue(result3); + Assertions.assertEquals("user table-level whitelist rule", reason3.get()); AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_2", "catalog_2", "database_2", "table_2", reason4); - Assert.assertTrue(result4); - Assert.assertEquals("user table-level whitelist rule", reason4.get()); + Assertions.assertTrue(result4); + Assertions.assertEquals("user table-level whitelist rule", reason4.get()); }); } @@ -139,27 +139,27 @@ public void testJsonFileDeleted() throws Exception { Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_3", "catalog_3", "database_3", "table_3", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("user table-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("user table-level whitelist rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_4", "catalog_4", "database_4", "table_4", reason2); - Assert.assertTrue(result2); - Assert.assertEquals("user table-level whitelist rule", reason2.get()); + Assertions.assertTrue(result2); + Assertions.assertEquals("user table-level whitelist rule", reason2.get()); }); - Assert.assertTrue(jsonFile4.delete()); + Assertions.assertTrue(jsonFile4.delete()); Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_3", "catalog_3", "database_3", "table_3", reason3); - Assert.assertTrue(result3); - Assert.assertEquals("user table-level whitelist rule", reason3.get()); + Assertions.assertTrue(result3); + Assertions.assertEquals("user table-level whitelist rule", reason3.get()); AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_4", "catalog_4", "database_4", "table_4", reason4); - Assert.assertFalse(result4); - Assert.assertEquals("default rule", reason4.get()); + Assertions.assertFalse(result4); + Assertions.assertEquals("default rule", reason4.get()); }); } @@ -183,13 +183,13 @@ public void testJsonFileModified() throws Exception { Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_5", "catalog_5", "database_5", "table_5", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("user table-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("user table-level whitelist rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_6", "catalog_6", "database_6", "table_6", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("default rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("default rule", reason2.get()); }); rules.clear(); @@ -203,13 +203,13 @@ public void testJsonFileModified() throws Exception { Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_5", "catalog_5", "database_5", "table_5", reason3); - Assert.assertFalse(result3); - Assert.assertEquals("default rule", reason3.get()); + Assertions.assertFalse(result3); + Assertions.assertEquals("default rule", reason3.get()); AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_6", "catalog_6", "database_6", "table_6", reason4); - Assert.assertTrue(result4); - Assert.assertEquals("user table-level whitelist rule", reason4.get()); + Assertions.assertTrue(result4); + Assertions.assertEquals("user table-level whitelist rule", reason4.get()); }); } @@ -236,7 +236,7 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOEx }); } - @AfterClass + @AfterAll public static void deleteJsonFile() throws Exception { Path currentDir = Paths.get("").toAbsolutePath(); Path jsonFileDir = currentDir.resolve("jsonFileDir-test"); diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/InternalCatalogTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/InternalCatalogTest.java index 1e6096567ef77c..ff1f1d230ef98b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/InternalCatalogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/InternalCatalogTest.java @@ -62,10 +62,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Range; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -88,7 +88,7 @@ public class InternalCatalogTest { private FailingCommitInternalCatalog catalog; private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() throws Exception { fakeEnv = new FakeEnv(); Env env = new TestingEnv(); @@ -98,7 +98,7 @@ public void setUp() throws Exception { catalog = new FailingCommitInternalCatalog(); } - @After + @AfterEach public void tearDown() { fakeEnv.close(); } @@ -106,19 +106,19 @@ public void tearDown() { @Test public void testAddPartitionRollbackPartitionInfoOnCommitFailure() throws Exception { AddPartitionOp addPartitionOp = createAddPartitionOp(); - DdlException exception = Assert.assertThrows(DdlException.class, + DdlException exception = Assertions.assertThrows(DdlException.class, () -> catalog.addPartition(db, TABLE_NAME, addPartitionOp, false, 0, true, null)); - Assert.assertTrue(exception.getMessage().contains("injected commit failure")); + Assertions.assertTrue(exception.getMessage().contains("injected commit failure")); long newPartitionId = catalog.getCommittedPartitionId(); OlapTable table = (OlapTable) db.getTableOrDdlException(TABLE_NAME); - Assert.assertNull(table.getPartition(NEW_PARTITION_NAME)); - Assert.assertNull(table.getPartition(newPartitionId)); + Assertions.assertNull(table.getPartition(NEW_PARTITION_NAME)); + Assertions.assertNull(table.getPartition(newPartitionId)); PartitionInfo partitionInfo = table.getPartitionInfo(); - Assert.assertNull(partitionInfo.getItem(newPartitionId)); - Assert.assertNull(partitionInfo.getDataProperty(newPartitionId)); - Assert.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, partitionInfo.getReplicaAllocation(newPartitionId)); + Assertions.assertNull(partitionInfo.getItem(newPartitionId)); + Assertions.assertNull(partitionInfo.getDataProperty(newPartitionId)); + Assertions.assertEquals(ReplicaAllocation.DEFAULT_ALLOCATION, partitionInfo.getReplicaAllocation(newPartitionId)); } private AddPartitionOp createAddPartitionOp() { @@ -206,8 +206,8 @@ protected Partition createPartitionWithIndices(long dbId, OlapTable tbl, long pa @Override public void afterCreatePartitions(long dbId, long tableId, List partitionIds, List indexIds, boolean isCreateTable, boolean isBatchCommit, OlapTable olapTable) throws DdlException { - Assert.assertEquals(TABLE_ID, tableId); - Assert.assertEquals(1, partitionIds.size()); + Assertions.assertEquals(TABLE_ID, tableId); + Assertions.assertEquals(1, partitionIds.size()); committedPartitionId = partitionIds.get(0); throw new DdlException("injected commit failure"); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/RoundRobinCreateTabletTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/RoundRobinCreateTabletTest.java index 25a23885074eca..29cfd8920ab367 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/RoundRobinCreateTabletTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/RoundRobinCreateTabletTest.java @@ -33,10 +33,10 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.ImmutableMap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; @@ -49,7 +49,7 @@ public class RoundRobinCreateTabletTest { private Backend backend3; private Backend backend4; - @Before + @BeforeEach public void setUp() { backend1 = new Backend(1L, "192.168.1.1", 9050); backend2 = new Backend(2L, "192.168.1.2", 9050); @@ -82,7 +82,7 @@ public void setUp() { Env.getCurrentSystemInfo().addBackend(backend4); } - @After + @AfterEach public void tearDown() { Config.enable_round_robin_create_tablet = true; Config.disable_storage_medium_check = true; @@ -122,7 +122,7 @@ public void testCreateTablets() { int beNum = 4; for (Tablet tablet : index.getTablets()) { for (Replica replica : tablet.getReplicas()) { - Assert.assertEquals((i++ % beNum) + 1, replica.getBackendIdWithoutException()); + Assertions.assertEquals((i++ % beNum) + 1, replica.getBackendIdWithoutException()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/WriteConstraintExtractorTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/WriteConstraintExtractorTest.java index 1e65f3a5f03477..911131f9f13cd8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/WriteConstraintExtractorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/WriteConstraintExtractorTest.java @@ -40,9 +40,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Optional; @@ -66,7 +66,7 @@ public class WriteConstraintExtractorTest { private TableIf targetTable; - @Before + @BeforeEach public void setUp() { targetTable = Mockito.mock(TableIf.class); Mockito.when(targetTable.getId()).thenReturn(TARGET_ID); @@ -90,12 +90,12 @@ public void targetOnlyPredicateIsKept() { Optional result = WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION); - Assert.assertTrue(result.isPresent()); + Assertions.assertTrue(result.isPresent()); ConnectorExpression expr = result.get().getExpression(); - Assert.assertTrue(expr instanceof ConnectorComparison); + Assertions.assertTrue(expr instanceof ConnectorComparison); ConnectorComparison cmp = (ConnectorComparison) expr; - Assert.assertEquals(ConnectorComparison.Operator.EQ, cmp.getOperator()); - Assert.assertEquals("id", ((ConnectorColumnRef) cmp.getLeft()).getColumnName()); + Assertions.assertEquals(ConnectorComparison.Operator.EQ, cmp.getOperator()); + Assertions.assertEquals("id", ((ConnectorColumnRef) cmp.getLeft()).getColumnName()); } @Test @@ -105,7 +105,7 @@ public void crossTablePredicateIsDropped() { SlotReference slot = slot(other, "id", ScalarType.INT); Plan plan = filterOver(ImmutableSet.of(new EqualTo(slot, new IntegerLiteral(1))), slot); - Assert.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); } @Test @@ -121,9 +121,9 @@ public void mixedConjunctsKeepOnlyTargetArm() { Optional result = WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION); - Assert.assertTrue(result.isPresent()); + Assertions.assertTrue(result.isPresent()); // only the single target-arm survives -> a lone comparison, not an AND of both - Assert.assertTrue(result.get().getExpression() instanceof ConnectorComparison); + Assertions.assertTrue(result.get().getExpression() instanceof ConnectorComparison); } @Test @@ -137,9 +137,9 @@ public void multipleTargetConjunctsAreAnded() { Optional result = WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION); - Assert.assertTrue(result.isPresent()); - Assert.assertTrue(result.get().getExpression() instanceof ConnectorAnd); - Assert.assertEquals(2, ((ConnectorAnd) result.get().getExpression()).getConjuncts().size()); + Assertions.assertTrue(result.isPresent()); + Assertions.assertTrue(result.get().getExpression() instanceof ConnectorAnd); + Assertions.assertEquals(2, ((ConnectorAnd) result.get().getExpression()).getConjuncts().size()); } @Test @@ -150,12 +150,10 @@ public void injectedExclusionDropsSyntheticColumnConjunct() { SlotReference synthetic = slot(targetTable, "rowid_col", ScalarType.INT); Plan plan = filterOver(ImmutableSet.of(new EqualTo(synthetic, new IntegerLiteral(1))), synthetic); - Assert.assertTrue("without exclusion the synthetic-column conjunct slips through", - WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertTrue(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent(), "without exclusion the synthetic-column conjunct slips through"); Predicate excludeRowId = s -> "rowid_col".equalsIgnoreCase(s.getName()); - Assert.assertFalse("the injected exclusion predicate must drop the synthetic-column conjunct", - WriteConstraintExtractor.extract(plan, TARGET_ID, excludeRowId).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, excludeRowId).isPresent(), "the injected exclusion predicate must drop the synthetic-column conjunct"); } @Test @@ -165,7 +163,7 @@ public void targetConjunctUnrepresentableByConverterIsDropped() { SlotReference b = slot(targetTable, "v", ScalarType.INT); Plan plan = filterOver(ImmutableSet.of(new EqualTo(a, b)), a); - Assert.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); } @Test @@ -185,10 +183,9 @@ public void targetConjunctsDropOnlyTheUnconvertibleArm() { Optional result = WriteConstraintExtractor.extract(filterOver(conjuncts, id), TARGET_ID, NO_EXCLUSION); - Assert.assertTrue("the convertible target conjunct survives", result.isPresent()); - Assert.assertTrue("only the convertible arm remains -> a lone comparison, not an AND of one", - result.get().getExpression() instanceof ConnectorComparison); - Assert.assertEquals("id", + Assertions.assertTrue(result.isPresent(), "the convertible target conjunct survives"); + Assertions.assertTrue(result.get().getExpression() instanceof ConnectorComparison, "only the convertible arm remains -> a lone comparison, not an AND of one"); + Assertions.assertEquals("id", ((ConnectorColumnRef) ((ConnectorComparison) result.get().getExpression()).getLeft()) .getColumnName()); } @@ -198,7 +195,7 @@ public void conjunctWithoutInputSlotsIsDropped() { SlotReference slot = slot(targetTable, "id", ScalarType.INT); Plan plan = filterOver(ImmutableSet.of(BooleanLiteral.of(true)), slot); - Assert.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); } @Test @@ -213,9 +210,9 @@ public void recursesIntoChildFilters() { Optional result = WriteConstraintExtractor.extract(outer, TARGET_ID, NO_EXCLUSION); - Assert.assertTrue(result.isPresent()); - Assert.assertTrue(result.get().getExpression() instanceof ConnectorAnd); - Assert.assertEquals(2, ((ConnectorAnd) result.get().getExpression()).getConjuncts().size()); + Assertions.assertTrue(result.isPresent()); + Assertions.assertTrue(result.get().getExpression() instanceof ConnectorAnd); + Assertions.assertEquals(2, ((ConnectorAnd) result.get().getExpression()).getConjuncts().size()); } @Test @@ -223,11 +220,11 @@ public void planWithoutFilterReturnsEmpty() { SlotReference slot = slot(targetTable, "id", ScalarType.INT); Plan plan = new LogicalEmptyRelation(new RelationId(0), ImmutableList.of((NamedExpression) slot)); - Assert.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(plan, TARGET_ID, NO_EXCLUSION).isPresent()); } @Test public void nullPlanReturnsEmpty() { - Assert.assertFalse(WriteConstraintExtractor.extract(null, TARGET_ID, NO_EXCLUSION).isPresent()); + Assertions.assertFalse(WriteConstraintExtractor.extract(null, TARGET_ID, NO_EXCLUSION).isPresent()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/DorisExternalMetaCacheTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/DorisExternalMetaCacheTest.java index 26f845171716aa..5ece32e7a77f74 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/DorisExternalMetaCacheTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/DorisExternalMetaCacheTest.java @@ -20,8 +20,8 @@ import org.apache.doris.connector.cache.MetaCache; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.concurrent.ExecutorService; @@ -43,11 +43,11 @@ public void testInvalidateBackendCacheUsesSingletonEntryKey() { String.class, DorisExternalMetaCacheTestSupport.backendMapClass()); backendsEntry.put("backends", ImmutableMap.of()); - Assert.assertNotNull(backendsEntry.getIfPresent("backends")); + Assertions.assertNotNull(backendsEntry.getIfPresent("backends")); cache.invalidateBackendCache(catalogId); - Assert.assertNull(backendsEntry.getIfPresent("backends")); + Assertions.assertNull(backendsEntry.getIfPresent("backends")); } finally { executor.shutdownNow(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisCompatibleRestClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisCompatibleRestClientTest.java index 58423e6ac2759c..266be31e169fa6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisCompatibleRestClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisCompatibleRestClientTest.java @@ -26,8 +26,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import okhttp3.Request; import okhttp3.Response; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -56,7 +56,7 @@ public void testGetColumns() throws Exception { columns.add(k1); columns.add(k2); - Assert.assertArrayEquals(columns.toArray(), res.toArray()); + Assertions.assertArrayEquals(columns.toArray(), res.toArray()); } private String execute(String url) throws IOException { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisRestClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisRestClientTest.java index 14fb6bcc63daf3..68794c0b541a97 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisRestClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/doris/RemoteDorisRestClientTest.java @@ -23,8 +23,8 @@ import okhttp3.Request; import okhttp3.Response; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -35,42 +35,42 @@ public class RemoteDorisRestClientTest extends DorisHttpTestCase { public void testGetDatabaseNameList() throws Exception { List res = RemoteDorisRestClient.parseStringLists( execute("api/meta/namespaces/default_cluster/databases")); - Assert.assertArrayEquals(new String[]{DB_NAME}, res.toArray()); + Assertions.assertArrayEquals(new String[]{DB_NAME}, res.toArray()); } @Test public void testGetTablesNameList() throws Exception { List res = RemoteDorisRestClient.parseStringLists( execute("api/meta/namespaces/default_cluster/databases/" + DB_NAME + "/tables")); - Assert.assertArrayEquals(new String[]{"testTbl1"}, res.toArray()); + Assertions.assertArrayEquals(new String[]{"testTbl1"}, res.toArray()); } @Test public void testGetTablesNameListByErrorDb() throws Exception { List res = RemoteDorisRestClient.parseStringLists( execute("api/meta/namespaces/default_cluster/databases/not_" + DB_NAME + "/tables")); - Assert.assertEquals(0, res.size()); + Assertions.assertEquals(0, res.size()); } @Test public void testTableExist() throws Exception { boolean res = RemoteDorisRestClient.parseSuccessResponse( execute("api/" + DB_NAME + "/" + TABLE_NAME + "/_schema")); - Assert.assertTrue(res); + Assertions.assertTrue(res); } @Test public void testTableNotExist() throws Exception { boolean res = RemoteDorisRestClient.parseSuccessResponse( execute("api/" + DB_NAME + "/not_" + TABLE_NAME + "/_schema")); - Assert.assertFalse(res); + Assertions.assertFalse(res); } @Test public void testHealth() throws Exception { int res = RemoteDorisRestClient.parseOnlineBeNum( execute("api/health")); - Assert.assertEquals(3, res); + Assertions.assertEquals(3, res); } @Test @@ -84,7 +84,7 @@ public void testGetColumns() throws Exception { columns.add(k1); columns.add(k2); - Assert.assertArrayEquals(columns.toArray(), res.toArray()); + Assertions.assertArrayEquals(columns.toArray(), res.toArray()); } @Test @@ -92,7 +92,7 @@ public void testGetRowCount() throws Exception { long res = RemoteDorisRestClient.parseRowCount( execute("api/rowcount?db=" + DB_NAME + "&table=" + TABLE_NAME)); - Assert.assertEquals(2000L, res); + Assertions.assertEquals(2000L, res); } private String execute(String url) throws IOException { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClickHouseClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClickHouseClientTest.java index a76319d108f7cc..dafb7ade3c7d2a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClickHouseClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClickHouseClientTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.jdbc.client; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.Mockito; @@ -32,19 +32,19 @@ public void testDatabaseTermFollowsDriverMetadata() throws Exception { DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class); Mockito.when(databaseMetaData.supportsCatalogsInDataManipulation()).thenReturn(false); - Assert.assertFalse(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.9.8")); + Assertions.assertFalse(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.9.8")); Mockito.when(databaseMetaData.supportsCatalogsInDataManipulation()).thenReturn(true); - Assert.assertTrue(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.7.1")); + Assertions.assertTrue(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.7.1")); - Assert.assertFalse(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.4.2")); + Assertions.assertFalse(JdbcClickHouseClient.isDatabaseTermCatalog(databaseMetaData, "0.4.2")); } @Test public void testClickHouseSpecificTableTypesAreVisible() { JdbcClickHouseClient client = Mockito.mock(JdbcClickHouseClient.class, Answers.CALLS_REAL_METHODS); - Assert.assertArrayEquals( + Assertions.assertArrayEquals( new String[] {"TABLE", "VIEW", "SYSTEM TABLE", "REMOTE TABLE", "MATERIALIZED VIEW"}, client.getTableTypes()); } @@ -56,37 +56,37 @@ public void testIsNewClickHouseDriver() { method.setAccessible(true); // Valid test cases - Assert.assertTrue((boolean) method.invoke(null, "0.5.0")); // Major version 0, Minor version 5 - Assert.assertTrue((boolean) method.invoke(null, "1.0.0")); // Major version 1 - Assert.assertTrue((boolean) method.invoke(null, "0.6.3 (revision: a6a8a22)")); // Major version 0, Minor version 6 - Assert.assertFalse((boolean) method.invoke(null, "0.4.2 (revision: 1513b27)")); // Major version 0, Minor version 4 + Assertions.assertTrue((boolean) method.invoke(null, "0.5.0")); // Major version 0, Minor version 5 + Assertions.assertTrue((boolean) method.invoke(null, "1.0.0")); // Major version 1 + Assertions.assertTrue((boolean) method.invoke(null, "0.6.3 (revision: a6a8a22)")); // Major version 0, Minor version 6 + Assertions.assertFalse((boolean) method.invoke(null, "0.4.2 (revision: 1513b27)")); // Major version 0, Minor version 4 // Invalid version formats try { method.invoke(null, "invalid.version"); // Invalid version format - Assert.fail("Expected JdbcClientException for invalid version 'invalid.version'"); + Assertions.fail("Expected JdbcClientException for invalid version 'invalid.version'"); } catch (Exception e) { - Assert.assertTrue(e.getCause() instanceof JdbcClientException); - Assert.assertTrue(e.getCause().getMessage().contains("Invalid clickhouse driver version format")); + Assertions.assertTrue(e.getCause() instanceof JdbcClientException); + Assertions.assertTrue(e.getCause().getMessage().contains("Invalid clickhouse driver version format")); } try { method.invoke(null, ""); // Empty version - Assert.fail("Expected JdbcClientException for empty version"); + Assertions.fail("Expected JdbcClientException for empty version"); } catch (Exception e) { - Assert.assertTrue(e.getCause() instanceof JdbcClientException); - Assert.assertTrue(e.getCause().getMessage().contains("Invalid clickhouse driver version format")); + Assertions.assertTrue(e.getCause() instanceof JdbcClientException); + Assertions.assertTrue(e.getCause().getMessage().contains("Invalid clickhouse driver version format")); } try { method.invoke(null, (Object) null); // Null version - Assert.fail("Expected JdbcClientException for null version"); + Assertions.fail("Expected JdbcClientException for null version"); } catch (Exception e) { - Assert.assertTrue(e.getCause() instanceof JdbcClientException); - Assert.assertTrue(e.getCause().getMessage().contains("Driver version cannot be null")); + Assertions.assertTrue(e.getCause() instanceof JdbcClientException); + Assertions.assertTrue(e.getCause().getMessage().contains("Driver version cannot be null")); } } catch (Exception e) { - Assert.fail("Exception occurred while testing isNewClickHouseDriver: " + e.getMessage()); + Assertions.fail("Exception occurred while testing isNewClickHouseDriver: " + e.getMessage()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClientExceptionTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClientExceptionTest.java index c99f2bcfe26dbc..040d4e9109f8cc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClientExceptionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcClientExceptionTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.jdbc.client; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class JdbcClientExceptionTest { @@ -27,8 +27,8 @@ public void testExceptionWithoutArgs() { String message = "An error occurred."; JdbcClientException exception = new JdbcClientException(message); - Assert.assertEquals(message, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(message, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -39,8 +39,8 @@ public void testExceptionWithFormattingArgs() { JdbcClientException exception = new JdbcClientException(format, errorCode, errorMsg); String expectedMessage = String.format(format, errorCode, errorMsg); - Assert.assertEquals(expectedMessage, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(expectedMessage, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -50,8 +50,8 @@ public void testExceptionWithPercentInFormatString() { JdbcClientException exception = new JdbcClientException(format, threshold); String expectedMessage = String.format(format, threshold); - Assert.assertEquals(expectedMessage, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(expectedMessage, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -61,8 +61,8 @@ public void testExceptionWithPercentInArgs() { JdbcClientException exception = new JdbcClientException(format, input); String expectedMessage = String.format(format, input.replace("%", "%%")); - Assert.assertEquals(expectedMessage, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(expectedMessage, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -71,8 +71,8 @@ public void testExceptionWithCause() { Exception cause = new Exception("Timeout occurred"); JdbcClientException exception = new JdbcClientException(message, cause); - Assert.assertEquals(message, exception.getMessage()); - Assert.assertEquals(cause, exception.getCause()); + Assertions.assertEquals(message, exception.getMessage()); + Assertions.assertEquals(cause, exception.getCause()); } @Test @@ -83,8 +83,8 @@ public void testExceptionWithFormattingArgsAndCause() { JdbcClientException exception = new JdbcClientException(format, cause, query); String expectedMessage = String.format(format, query); - Assert.assertEquals(expectedMessage, exception.getMessage()); - Assert.assertEquals(cause, exception.getCause()); + Assertions.assertEquals(expectedMessage, exception.getMessage()); + Assertions.assertEquals(cause, exception.getCause()); } @Test @@ -95,8 +95,8 @@ public void testExceptionWithPercentInArgsAndCause() { JdbcClientException exception = new JdbcClientException(format, cause, filePath); String expectedMessage = String.format(format, filePath.replace("%", "%%")); - Assert.assertEquals(expectedMessage, exception.getMessage()); - Assert.assertEquals(cause, exception.getCause()); + Assertions.assertEquals(expectedMessage, exception.getMessage()); + Assertions.assertEquals(cause, exception.getCause()); } @Test @@ -104,8 +104,8 @@ public void testExceptionWithNoFormattingNeeded() { String message = "Simple error message."; JdbcClientException exception = new JdbcClientException(message, (Object[]) null); - Assert.assertEquals(message, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(message, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -114,8 +114,8 @@ public void testExceptionWithNullArgs() { JdbcClientException exception = new JdbcClientException(format, (Object[]) null); // Since args are null, message should remain unformatted - Assert.assertEquals(format, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(format, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } @Test @@ -124,7 +124,7 @@ public void testExceptionWithEmptyArgs() { JdbcClientException exception = new JdbcClientException(format, new Object[]{}); // Since args are empty, message should remain unformatted - Assert.assertEquals(format, exception.getMessage()); - Assert.assertNull(exception.getCause()); + Assertions.assertEquals(format, exception.getMessage()); + Assertions.assertNull(exception.getCause()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcMySQLClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcMySQLClientTest.java index 010181b52e6174..6379c0db52aae2 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcMySQLClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcMySQLClientTest.java @@ -17,21 +17,21 @@ package org.apache.doris.datasource.jdbc.client; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class JdbcMySQLClientTest { @Test public void testIsDorisCompatibleVersionComment() { - Assert.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("Apache Doris version 3.1.0")); - Assert.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("SelectDB Cloud version 4.0.5")); - Assert.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("VeloDB version 2.1.0")); - Assert.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment( + Assertions.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("Apache Doris version 3.1.0")); + Assertions.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("SelectDB Cloud version 4.0.5")); + Assertions.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment("VeloDB version 2.1.0")); + Assertions.assertTrue(JdbcMySQLClient.isDorisCompatibleVersionComment( "enterprise version enterprise-4.0.5-rc01-0724569463d (Cloud Mode)")); - Assert.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment("MySQL Community Server - GPL")); - Assert.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment("")); - Assert.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment(null)); + Assertions.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment("MySQL Community Server - GPL")); + Assertions.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment("")); + Assertions.assertFalse(JdbcMySQLClient.isDorisCompatibleVersionComment(null)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcOceanBaseClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcOceanBaseClientTest.java index b2632b8fc104e8..4addc9caaa2b1d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcOceanBaseClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/client/JdbcOceanBaseClientTest.java @@ -18,9 +18,9 @@ package org.apache.doris.datasource.jdbc.client; import com.zaxxer.hikari.HikariDataSource; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.mockito.MockedConstruction; import org.mockito.Mockito; @@ -34,7 +34,7 @@ public class JdbcOceanBaseClientTest { private Statement statement; private ResultSet resultSet; - @Before + @BeforeEach public void setUp() throws Exception { connection = Mockito.mock(Connection.class); statement = Mockito.mock(Statement.class); @@ -52,8 +52,8 @@ public void testCloseTemporaryDataSourceAfterCreatingClient() throws Exception { JdbcOceanBaseClient oceanBaseClient = new JdbcOceanBaseClient(createConfig()); JdbcClient client = oceanBaseClient.createClient(createConfig()); - Assert.assertTrue(client instanceof JdbcMySQLClient); - Assert.assertEquals(2, mockedDataSources.constructed().size()); + Assertions.assertTrue(client instanceof JdbcMySQLClient); + Assertions.assertEquals(2, mockedDataSources.constructed().size()); HikariDataSource temporaryDataSource = mockedDataSources.constructed().get(0); HikariDataSource clientDataSource = mockedDataSources.constructed().get(1); assertTemporaryResourcesClosed(temporaryDataSource); @@ -71,11 +71,11 @@ public void testCloseTemporaryDataSourceWhenCompatibilityModeIsMissing() throws try (MockedConstruction mockedDataSources = mockDataSources()) { JdbcOceanBaseClient oceanBaseClient = new JdbcOceanBaseClient(createConfig()); - JdbcClientException exception = Assert.assertThrows( + JdbcClientException exception = Assertions.assertThrows( JdbcClientException.class, () -> oceanBaseClient.createClient(createConfig())); - Assert.assertEquals("Failed to determine OceanBase compatibility mode", exception.getMessage()); - Assert.assertEquals(1, mockedDataSources.constructed().size()); + Assertions.assertEquals("Failed to determine OceanBase compatibility mode", exception.getMessage()); + Assertions.assertEquals(1, mockedDataSources.constructed().size()); assertTemporaryResourcesClosed(mockedDataSources.constructed().get(0)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/util/JdbcFieldSchemaTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/util/JdbcFieldSchemaTest.java index 955608226fad67..bed0faf9f3dd67 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/util/JdbcFieldSchemaTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/jdbc/util/JdbcFieldSchemaTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.jdbc.util; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.sql.ResultSetMetaData; @@ -38,7 +38,7 @@ public void testUseColumnLabelForQueryAlias() throws Exception { JdbcFieldSchema schema = new JdbcFieldSchema(metaData, 1); - Assert.assertEquals("t1", schema.getColumnName()); + Assertions.assertEquals("t1", schema.getColumnName()); } @Test @@ -52,6 +52,6 @@ public void testFallbackToColumnNameWhenLabelMissing() throws Exception { JdbcFieldSchema schema = new JdbcFieldSchema(metaData, 1); - Assert.assertEquals("username", schema.getColumnName()); + Assertions.assertEquals("username", schema.getColumnName()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/kafka/KafkaUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/kafka/KafkaUtilTest.java index 1036ff938343cf..08a2ba0e895c51 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/kafka/KafkaUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/kafka/KafkaUtilTest.java @@ -25,8 +25,8 @@ import org.apache.doris.system.Backend; import org.apache.doris.system.SystemInfoService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -40,9 +40,9 @@ public class KafkaUtilTest { @Test public void testGetInfoFailureMessageIncludesComputeGroup() { - Assert.assertEquals("failed to get info: no alive backends, compute group: routine-load-compute-group,", + Assertions.assertEquals("failed to get info: no alive backends, compute group: routine-load-compute-group,", KafkaUtil.getInfoFailureMessage("no alive backends", "routine-load-compute-group")); - Assert.assertEquals("failed to get info: no alive backends,", + Assertions.assertEquals("failed to get info: no alive backends,", KafkaUtil.getInfoFailureMessage("no alive backends", null)); } @@ -63,7 +63,7 @@ public void testGetBackendIdsForMetaRequestUsesRoutineLoadComputeGroup() throws List backendIds = KafkaUtil.getBackendIdsForMetaRequest("routine-load-compute-group"); - Assert.assertEquals(Collections.singletonList(routineLoadBackend.getId()), backendIds); + Assertions.assertEquals(Collections.singletonList(routineLoadBackend.getId()), backendIds); Mockito.verify(systemInfoService).getBackendsByClusterName("routine-load-compute-group"); Mockito.verify(systemInfoService, Mockito.never()).getAllBackendIds(true); } finally { @@ -97,7 +97,7 @@ public void testGetAvailableBackendIdsForMetaRequestKeepsBlacklistFallbackInComp List backendIds = KafkaUtil.getAvailableBackendIdsForMetaRequest( Collections.singletonList(routineLoadBackendId), new HashSet<>()); - Assert.assertEquals(Collections.singletonList(routineLoadBackendId), backendIds); + Assertions.assertEquals(Collections.singletonList(routineLoadBackendId), backendIds); Mockito.verify(systemInfoService, Mockito.never()).getBackend(otherComputeGroupBackendId); } } @@ -111,13 +111,13 @@ public void testGetBackendIdsForMetaRequestRejectsMissingCloudComputeGroup() { Config.cloud_unique_id = "test-cloud"; envStatic.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); - LoadException nullException = Assert.assertThrows( + LoadException nullException = Assertions.assertThrows( LoadException.class, () -> KafkaUtil.getBackendIdsForMetaRequest(null)); - LoadException emptyException = Assert.assertThrows( + LoadException emptyException = Assertions.assertThrows( LoadException.class, () -> KafkaUtil.getBackendIdsForMetaRequest("")); - Assert.assertEquals("compute group is empty when getting kafka meta", nullException.getDetailMessage()); - Assert.assertEquals("compute group is empty when getting kafka meta", emptyException.getDetailMessage()); + Assertions.assertEquals("compute group is empty when getting kafka meta", nullException.getDetailMessage()); + Assertions.assertEquals("compute group is empty when getting kafka meta", emptyException.getDetailMessage()); Mockito.verifyNoInteractions(systemInfoService); } finally { Config.cloud_unique_id = originalCloudUniqueId; @@ -135,7 +135,7 @@ public void testGetBackendIdsForMetaRequestPreservesNonCloudSelection() throws E Config.cloud_unique_id = ""; envStatic.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); - Assert.assertEquals(allBackendIds, KafkaUtil.getBackendIdsForMetaRequest(null)); + Assertions.assertEquals(allBackendIds, KafkaUtil.getBackendIdsForMetaRequest(null)); Mockito.verify(systemInfoService).getAllBackendIds(true); } finally { Config.cloud_unique_id = originalCloudUniqueId; diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/CacheSpecTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/CacheSpecTest.java index 178e30650eade2..5e195a22a59e99 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/CacheSpecTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/CacheSpecTest.java @@ -20,8 +20,8 @@ import org.apache.doris.connector.cache.CacheSpec; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.OptionalLong; @@ -41,9 +41,9 @@ public void testFromPropertiesWithExplicitKeys() { "k.ttl", CacheSpec.CACHE_NO_TTL, "k.capacity", 100); - Assert.assertFalse(spec.isEnable()); - Assert.assertEquals(123, spec.getTtlSecond()); - Assert.assertEquals(456, spec.getCapacity()); + Assertions.assertFalse(spec.isEnable()); + Assertions.assertEquals(123, spec.getTtlSecond()); + Assertions.assertEquals(456, spec.getCapacity()); } @Test @@ -59,9 +59,9 @@ public void testFromPropertiesWithPropertySpecBuilder() { .capacity("k.capacity", 100) .build()); - Assert.assertFalse(spec.isEnable()); - Assert.assertEquals(123, spec.getTtlSecond()); - Assert.assertEquals(456, spec.getCapacity()); + Assertions.assertFalse(spec.isEnable()); + Assertions.assertEquals(123, spec.getTtlSecond()); + Assertions.assertEquals(456, spec.getCapacity()); } @Test @@ -76,9 +76,9 @@ public void testFromPropertiesWithEngineEntryKeys() { "capacity", 100); CacheSpec spec = CacheSpec.fromProperties(properties, "hive", "schema", defaultSpec); - Assert.assertTrue(spec.isEnable()); - Assert.assertEquals(0, spec.getTtlSecond()); - Assert.assertEquals(100, spec.getCapacity()); + Assertions.assertTrue(spec.isEnable()); + Assertions.assertEquals(0, spec.getTtlSecond()); + Assertions.assertEquals(100, spec.getCapacity()); } @Test @@ -95,29 +95,29 @@ public void testApplyCompatibilityMap() { Map mapped = CacheSpec.applyCompatibilityMap(properties, compatibilityMap); // New key keeps precedence if already present. - Assert.assertEquals("20", mapped.get("new.ttl")); + Assertions.assertEquals("20", mapped.get("new.ttl")); // Missing new key is copied from legacy key. - Assert.assertEquals("30", mapped.get("new.capacity")); + Assertions.assertEquals("30", mapped.get("new.capacity")); // Original map is not modified. - Assert.assertFalse(properties.containsKey("new.capacity")); + Assertions.assertFalse(properties.containsKey("new.capacity")); } @Test public void testOfSemantics() { CacheSpec enabled = CacheSpec.of(true, 60, 100); - Assert.assertTrue(enabled.isEnable()); - Assert.assertEquals(60, enabled.getTtlSecond()); - Assert.assertEquals(100, enabled.getCapacity()); + Assertions.assertTrue(enabled.isEnable()); + Assertions.assertEquals(60, enabled.getTtlSecond()); + Assertions.assertEquals(100, enabled.getCapacity()); CacheSpec zeroTtl = CacheSpec.of(true, 0, 100); - Assert.assertTrue(zeroTtl.isEnable()); - Assert.assertEquals(0, zeroTtl.getTtlSecond()); - Assert.assertEquals(100, zeroTtl.getCapacity()); + Assertions.assertTrue(zeroTtl.isEnable()); + Assertions.assertEquals(0, zeroTtl.getTtlSecond()); + Assertions.assertEquals(100, zeroTtl.getCapacity()); CacheSpec disabled = CacheSpec.of(false, 60, 100); - Assert.assertFalse(disabled.isEnable()); - Assert.assertEquals(60, disabled.getTtlSecond()); - Assert.assertEquals(100, disabled.getCapacity()); + Assertions.assertFalse(disabled.isEnable()); + Assertions.assertEquals(60, disabled.getTtlSecond()); + Assertions.assertEquals(100, disabled.getCapacity()); } @Test @@ -127,43 +127,43 @@ public void testPropertyValidationHelpers() throws Exception { try { CacheSpec.checkBooleanProperty("on", "k.enable"); - Assert.fail("expected IllegalArgumentException"); + Assertions.fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - Assert.assertTrue(e.getMessage().contains("k.enable")); + Assertions.assertTrue(e.getMessage().contains("k.enable")); } CacheSpec.checkLongProperty("10", 0, "k.ttl"); try { CacheSpec.checkLongProperty("-1", 0, "k.ttl"); - Assert.fail("expected IllegalArgumentException"); + Assertions.fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - Assert.assertTrue(e.getMessage().contains("k.ttl")); + Assertions.assertTrue(e.getMessage().contains("k.ttl")); } } @Test public void testIsCacheEnabled() { - Assert.assertTrue(CacheSpec.isCacheEnabled(true, CacheSpec.CACHE_NO_TTL, 1)); - Assert.assertFalse(CacheSpec.isCacheEnabled(false, CacheSpec.CACHE_NO_TTL, 1)); - Assert.assertFalse(CacheSpec.isCacheEnabled(true, 0, 1)); - Assert.assertFalse(CacheSpec.isCacheEnabled(true, CacheSpec.CACHE_NO_TTL, 0)); + Assertions.assertTrue(CacheSpec.isCacheEnabled(true, CacheSpec.CACHE_NO_TTL, 1)); + Assertions.assertFalse(CacheSpec.isCacheEnabled(false, CacheSpec.CACHE_NO_TTL, 1)); + Assertions.assertFalse(CacheSpec.isCacheEnabled(true, 0, 1)); + Assertions.assertFalse(CacheSpec.isCacheEnabled(true, CacheSpec.CACHE_NO_TTL, 0)); } @Test public void testToExpireAfterAccess() { OptionalLong noTtl = CacheSpec.toExpireAfterAccess(CacheSpec.CACHE_NO_TTL); - Assert.assertFalse(noTtl.isPresent()); + Assertions.assertFalse(noTtl.isPresent()); OptionalLong disabled = CacheSpec.toExpireAfterAccess(0); - Assert.assertTrue(disabled.isPresent()); - Assert.assertEquals(0, disabled.getAsLong()); + Assertions.assertTrue(disabled.isPresent()); + Assertions.assertEquals(0, disabled.getAsLong()); OptionalLong positive = CacheSpec.toExpireAfterAccess(15); - Assert.assertTrue(positive.isPresent()); - Assert.assertEquals(15, positive.getAsLong()); + Assertions.assertTrue(positive.isPresent()); + Assertions.assertEquals(15, positive.getAsLong()); OptionalLong negativeOther = CacheSpec.toExpireAfterAccess(-2); - Assert.assertTrue(negativeOther.isPresent()); - Assert.assertEquals(0, negativeOther.getAsLong()); + Assertions.assertTrue(negativeOther.isPresent()); + Assertions.assertEquals(0, negativeOther.getAsLong()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/ExternalCatalogMetaCacheTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/ExternalCatalogMetaCacheTest.java index 5ba447411aaf8e..34b989380f3a72 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/ExternalCatalogMetaCacheTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/ExternalCatalogMetaCacheTest.java @@ -27,8 +27,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -41,11 +41,11 @@ public void testEntryRequiresExplicitInit() { ExecutorService refreshExecutor = Executors.newSingleThreadExecutor(); try { TestExternalMetaCache cache = new TestExternalMetaCache(refreshExecutor); - Assert.assertThrows(IllegalStateException.class, () -> cache.entry( + Assertions.assertThrows(IllegalStateException.class, () -> cache.entry( 1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class)); cache.initCatalog(1L, Maps.newHashMap()); - Assert.assertNotNull(cache.entry(1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class)); + Assertions.assertNotNull(cache.entry(1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class)); } finally { refreshExecutor.shutdownNow(); } @@ -59,14 +59,14 @@ public void testEngineEntriesDoNotInitializeMultiKeyStripeStatesEagerly() { cache.initCatalog(1L, Maps.newHashMap()); MetaCache enabledEntry = cache.entry( 1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class); - Assert.assertTrue(enabledEntry.isEnabled()); + Assertions.assertTrue(enabledEntry.isEnabled()); Map disabledProperties = Maps.newHashMap(); disabledProperties.put("meta.cache.test_engine.schema.ttl-second", "0"); cache.initCatalog(2L, disabledProperties); MetaCache disabledEntry = cache.entry( 2L, "schema", SchemaCacheKey.class, SchemaCacheValue.class); - Assert.assertFalse(disabledEntry.isEnabled()); + Assertions.assertFalse(disabledEntry.isEnabled()); } finally { refreshExecutor.shutdownNow(); } @@ -77,7 +77,7 @@ public void testCheckCatalogInitializedRequiresExplicitInit() { ExecutorService refreshExecutor = Executors.newSingleThreadExecutor(); try { TestExternalMetaCache cache = new TestExternalMetaCache(refreshExecutor); - Assert.assertThrows(IllegalStateException.class, () -> cache.checkCatalogInitialized(1L)); + Assertions.assertThrows(IllegalStateException.class, () -> cache.checkCatalogInitialized(1L)); cache.initCatalog(1L, Maps.newHashMap()); cache.checkCatalogInitialized(1L); } finally { @@ -95,10 +95,10 @@ public void testSchemaEntryValidatesDuplicateColumnsOnLoad() { MetaCache schemaEntry = cache.entry( 1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class); - IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException exception = Assertions.assertThrows( IllegalArgumentException.class, () -> schemaEntry.get(new SchemaCacheKey(NameMapping.createForTest(1L, "db1", "tbl1")))); - Assert.assertTrue(exception.getMessage().contains("Duplicate column name found")); + Assertions.assertTrue(exception.getMessage().contains("Duplicate column name found")); } finally { refreshExecutor.shutdownNow(); } @@ -112,10 +112,10 @@ public void testEntryFailsFastAfterCatalogRemoved() { cache.initCatalog(1L, Maps.newHashMap()); cache.invalidateCatalog(1L); - IllegalStateException exception = Assert.assertThrows(IllegalStateException.class, + IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, () -> cache.entry(1L, "schema", SchemaCacheKey.class, SchemaCacheValue.class)); - Assert.assertTrue(exception.getMessage().contains("not initialized")); - Assert.assertFalse(cache.isCatalogInitialized(1L)); + Assertions.assertTrue(exception.getMessage().contains("not initialized")); + Assertions.assertFalse(cache.isCatalogInitialized(1L)); } finally { refreshExecutor.shutdownNow(); } @@ -137,9 +137,9 @@ public void testEntryLevelInvalidationUsesRegisteredMatcher() { cache.invalidateTable(1L, "db1", "tbl1"); - Assert.assertNull(schemaEntry.getIfPresent(matched)); - Assert.assertNotNull(schemaEntry.getIfPresent(unmatched)); - Assert.assertTrue(cache.isCatalogInitialized(1L)); + Assertions.assertNull(schemaEntry.getIfPresent(matched)); + Assertions.assertNotNull(schemaEntry.getIfPresent(unmatched)); + Assertions.assertTrue(cache.isCatalogInitialized(1L)); } finally { refreshExecutor.shutdownNow(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/FeMetaCacheEntryTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/FeMetaCacheEntryTest.java index 843d4c518b7d6e..e76b9d35752ae6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/FeMetaCacheEntryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/FeMetaCacheEntryTest.java @@ -19,8 +19,8 @@ import org.apache.doris.connector.cache.CacheSpec; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashSet; @@ -46,19 +46,19 @@ public void testLoadMutationAndStatsUseSharedRuntime() { FeMetaCacheEntry entry = new FeMetaCacheEntry<>( "objects", key -> loads.incrementAndGet(), ENABLED, executor, false, 8); - Assert.assertEquals(Integer.valueOf(1), entry.get("key")); - Assert.assertEquals(Integer.valueOf(1), entry.get("key")); - Assert.assertEquals(1, loads.get()); - Assert.assertEquals(Integer.valueOf(2), entry.compute("key", (key, value) -> value + 1)); - Assert.assertEquals(Integer.valueOf(2), entry.getIfPresent("key")); + Assertions.assertEquals(Integer.valueOf(1), entry.get("key")); + Assertions.assertEquals(Integer.valueOf(1), entry.get("key")); + Assertions.assertEquals(1, loads.get()); + Assertions.assertEquals(Integer.valueOf(2), entry.compute("key", (key, value) -> value + 1)); + Assertions.assertEquals(Integer.valueOf(2), entry.getIfPresent("key")); entry.invalidateKey("key"); - Assert.assertNull(entry.getIfPresent("key")); + Assertions.assertNull(entry.getIfPresent("key")); MetaCacheEntryStats stats = entry.stats(); - Assert.assertTrue(stats.isEffectiveEnabled()); - Assert.assertEquals(1L, stats.getLoadSuccessCount()); - Assert.assertTrue(stats.getRequestCount() >= 4L); - Assert.assertTrue(stats.getInvalidateCount() >= 1L); + Assertions.assertTrue(stats.isEffectiveEnabled()); + Assertions.assertEquals(1L, stats.getLoadSuccessCount()); + Assertions.assertTrue(stats.getRequestCount() >= 4L); + Assertions.assertTrue(stats.getInvalidateCount() >= 1L); } finally { executor.shutdownNow(); } @@ -70,17 +70,17 @@ public void testContextualOnlyAndDisabledEntry() { try { FeMetaCacheEntry contextual = new FeMetaCacheEntry<>( "contextual", null, ENABLED, executor, false, true); - Assert.assertThrows(UnsupportedOperationException.class, () -> contextual.get("key")); - Assert.assertEquals(Integer.valueOf(3), contextual.get("key", String::length)); + Assertions.assertThrows(UnsupportedOperationException.class, () -> contextual.get("key")); + Assertions.assertEquals(Integer.valueOf(3), contextual.get("key", String::length)); CacheSpec disabledSpec = CacheSpec.of(false, CacheSpec.CACHE_NO_TTL, 100L); AtomicInteger actions = new AtomicInteger(); FeMetaCacheEntry disabled = new FeMetaCacheEntry<>( "disabled", String::length, disabledSpec, executor, false); - Assert.assertEquals(Integer.valueOf(3), disabled.getAndRunIfCurrent( + Assertions.assertEquals(Integer.valueOf(3), disabled.getAndRunIfCurrent( "key", (key, value) -> actions.incrementAndGet())); - Assert.assertEquals(1, actions.get()); - Assert.assertNull(disabled.getIfPresent("key")); + Assertions.assertEquals(1, actions.get()); + Assertions.assertNull(disabled.getIfPresent("key")); } finally { executor.shutdownNow(); } @@ -98,9 +98,9 @@ public void testDisabledEntryDoesNotRetireTheReturnedValue() { AtomicBoolean loaded = entry.get("db"); - Assert.assertSame(usable, loaded); - Assert.assertTrue(loaded.get()); - Assert.assertNull(entry.getIfPresent("db")); + Assertions.assertSame(usable, loaded); + Assertions.assertTrue(loaded.get()); + Assertions.assertNull(entry.getIfPresent("db")); } finally { executor.shutdownNow(); } @@ -130,9 +130,9 @@ void beforeManualCachePutForTest(String key, AtomicBoolean value) { continuePublication.countDown(); AtomicBoolean returned = load.get(3L, TimeUnit.SECONDS); - Assert.assertSame(usable, returned); - Assert.assertTrue(returned.get()); - Assert.assertNull(entry.getIfPresent("db")); + Assertions.assertSame(usable, returned); + Assertions.assertTrue(returned.get()); + Assertions.assertNull(entry.getIfPresent("db")); } finally { continuePublication.countDown(); worker.shutdownNow(); @@ -149,12 +149,12 @@ public void testMutationAndAuxiliaryIndexSharePublicationWindow() { "objects", String::length, ENABLED, executor, false); entry.computeAndRun("table", (key, value) -> 5, () -> index.add("table")); - Assert.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); - Assert.assertEquals(List.of("table"), index); + Assertions.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); + Assertions.assertEquals(List.of("table"), index); entry.invalidateKeyAndRun("table", index::clear); - Assert.assertNull(entry.getIfPresent("table")); - Assert.assertTrue(index.isEmpty()); + Assertions.assertNull(entry.getIfPresent("table")); + Assertions.assertTrue(index.isEmpty()); } finally { executor.shutdownNow(); } @@ -168,13 +168,13 @@ public void testFailedFinalValidationDoesNotModifyCachedObject() { "objects", String::length, ENABLED, executor, false); entry.put("table", 1); - Assert.assertThrows(IllegalStateException.class, + Assertions.assertThrows(IllegalStateException.class, () -> entry.computeWithCommitAction( "table", (key, value) -> 2, () -> { throw new IllegalStateException("identity conflict"); })); - Assert.assertEquals(Integer.valueOf(1), entry.getIfPresent("table")); + Assertions.assertEquals(Integer.valueOf(1), entry.getIfPresent("table")); } finally { executor.shutdownNow(); } @@ -195,18 +195,18 @@ public void testConcurrentIdentityConflictPublishesOneConsistentPair() throws Ex entry, index, 1L, prechecksComplete, startPublication)); Future second = workers.submit(() -> publishIdentity( entry, index, 2L, prechecksComplete, startPublication)); - Assert.assertTrue(prechecksComplete.await(3L, TimeUnit.SECONDS)); + Assertions.assertTrue(prechecksComplete.await(3L, TimeUnit.SECONDS)); startPublication.countDown(); Long firstResult = resultOrNull(first); Long secondResult = resultOrNull(second); - Assert.assertTrue((firstResult == null) != (secondResult == null)); + Assertions.assertTrue((firstResult == null) != (secondResult == null)); long winner = firstResult == null ? secondResult : firstResult; long loser = winner == 1L ? 2L : 1L; - Assert.assertEquals(Long.valueOf(winner), entry.getIfPresent("table")); - Assert.assertEquals("table", index.getName(winner)); - Assert.assertNull(index.getName(loser)); + Assertions.assertEquals(Long.valueOf(winner), entry.getIfPresent("table")); + Assertions.assertEquals("table", index.getName(winner)); + Assertions.assertNull(index.getName(loser)); } finally { startPublication.countDown(); workers.shutdownNow(); @@ -233,14 +233,14 @@ protected void beforeCurrentValueActionForTest(String key, Integer value) { Future load = worker.submit(() -> entry.getAndRunIfCurrent( "table", (key, value) -> actions.incrementAndGet())); - Assert.assertTrue(valueLoaded.await(3L, TimeUnit.SECONDS)); + Assertions.assertTrue(valueLoaded.await(3L, TimeUnit.SECONDS)); entry.invalidateKey("table"); continueAction.countDown(); - Assert.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); - Assert.assertEquals(0, actions.get()); - Assert.assertNull(entry.getIfPresent("table")); - Assert.assertEquals(0, entry.activeActionReferenceCountForTest()); + Assertions.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); + Assertions.assertEquals(0, actions.get()); + Assertions.assertNull(entry.getIfPresent("table")); + Assertions.assertEquals(0, entry.activeActionReferenceCountForTest()); } finally { continueAction.countDown(); worker.shutdownNow(); @@ -287,14 +287,14 @@ protected void beforeCurrentValueActionForTest(String key, Integer value) { releaseLoader.countDown(); await(publicationReady); - Assert.assertNull(entry.getIfPresent("table")); - Assert.assertTrue(index.isEmpty()); + Assertions.assertNull(entry.getIfPresent("table")); + Assertions.assertTrue(index.isEmpty()); releaseStripe.countDown(); - Assert.assertEquals(Integer.valueOf(1), blocker.get(3L, TimeUnit.SECONDS)); - Assert.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); - Assert.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); - Assert.assertEquals(List.of("table"), index); + Assertions.assertEquals(Integer.valueOf(1), blocker.get(3L, TimeUnit.SECONDS)); + Assertions.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); + Assertions.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); + Assertions.assertEquals(List.of("table"), index); } finally { releaseLoader.countDown(); releaseStripe.countDown(); @@ -353,7 +353,7 @@ void beforePublicMutationWriteForTest(String key) { "db", (key, current) -> database, () -> { }))); await(firstObjectPublished); - Assert.assertSame(database, objects.getIfPresent("db")); + Assertions.assertSame(database, objects.getIfPresent("db")); objectInitialized.set(true); // Model an auto-refresh replacing the outer name snapshot after the first nested object publish. @@ -361,12 +361,12 @@ void beforePublicMutationWriteForTest(String key) { names.putSharedForTest("names", Set.of("initial", "refreshed")); continueNamePublication.countDown(); - Assert.assertEquals(Set.of("initial", "refreshed", "incremental"), + Assertions.assertEquals(Set.of("initial", "refreshed", "incremental"), update.get(3L, TimeUnit.SECONDS)); - Assert.assertSame(database, objects.getIfPresent("db")); - Assert.assertTrue(objectInitialized.get()); - Assert.assertEquals(0, objectRemovals.get()); - Assert.assertEquals(2, nameAttempts.get()); + Assertions.assertSame(database, objects.getIfPresent("db")); + Assertions.assertTrue(objectInitialized.get()); + Assertions.assertEquals(0, objectRemovals.get()); + Assertions.assertEquals(2, nameAttempts.get()); } finally { continueNamePublication.countDown(); worker.shutdownNow(); @@ -417,17 +417,17 @@ void beforePublicMutationWriteForTest(String key) { objectEntryUpdated.set(true); })); await(firstObjectCommitFinished); - Assert.assertEquals("database", index.getName(1L)); + Assertions.assertEquals("database", index.getName(1L)); names.putSharedForTest("names", Set.of("database")); - Assert.assertSame(queryDatabase, objects.get("database")); + Assertions.assertSame(queryDatabase, objects.get("database")); continueNamePublication.countDown(); - Assert.assertEquals(Set.of("database"), update.get(3L, TimeUnit.SECONDS)); - Assert.assertSame(queryDatabase, objects.getIfPresent("database")); - Assert.assertTrue(queryDatabase.get()); - Assert.assertEquals(0, objectRemovals.get()); - Assert.assertEquals(2, nameAttempts.get()); + Assertions.assertEquals(Set.of("database"), update.get(3L, TimeUnit.SECONDS)); + Assertions.assertSame(queryDatabase, objects.getIfPresent("database")); + Assertions.assertTrue(queryDatabase.get()); + Assertions.assertEquals(0, objectRemovals.get()); + Assertions.assertEquals(2, nameAttempts.get()); } finally { continueNamePublication.countDown(); worker.shutdownNow(); @@ -468,11 +468,11 @@ void beforePublicMutationWriteForTest(String key) { objects.putSharedForTest("database", queryDatabase); continueObjectPublication.countDown(); - Assert.assertSame(eventDatabase, update.get(3L, TimeUnit.SECONDS)); - Assert.assertSame(eventDatabase, objects.getIfPresent("database")); - Assert.assertFalse(queryDatabase.get()); - Assert.assertEquals(1, objectRemovals.get()); - Assert.assertEquals(2, attempts.get()); + Assertions.assertSame(eventDatabase, update.get(3L, TimeUnit.SECONDS)); + Assertions.assertSame(eventDatabase, objects.getIfPresent("database")); + Assertions.assertFalse(queryDatabase.get()); + Assertions.assertEquals(1, objectRemovals.get()); + Assertions.assertEquals(2, attempts.get()); } finally { continueObjectPublication.countDown(); worker.shutdownNow(); @@ -523,19 +523,19 @@ void beforePublicMutationWriteForTest(String key) { objectEntryUpdated.set(true); })); await(firstObjectCommitFinished); - Assert.assertSame(eventDatabase, objects.getIfPresent("database")); + Assertions.assertSame(eventDatabase, objects.getIfPresent("database")); names.putSharedForTest("names", Set.of("database")); objects.invalidateKey("database"); - Assert.assertFalse(eventDatabase.get()); - Assert.assertSame(queryDatabase, objects.get("database")); + Assertions.assertFalse(eventDatabase.get()); + Assertions.assertSame(queryDatabase, objects.get("database")); continueNamePublication.countDown(); - Assert.assertEquals(Set.of("database"), update.get(3L, TimeUnit.SECONDS)); - Assert.assertSame(queryDatabase, objects.getIfPresent("database")); - Assert.assertTrue(queryDatabase.get()); - Assert.assertEquals(2, objectRemovals.get()); - Assert.assertEquals(2, nameAttempts.get()); + Assertions.assertEquals(Set.of("database"), update.get(3L, TimeUnit.SECONDS)); + Assertions.assertSame(queryDatabase, objects.getIfPresent("database")); + Assertions.assertTrue(queryDatabase.get()); + Assertions.assertEquals(2, objectRemovals.get()); + Assertions.assertEquals(2, nameAttempts.get()); } finally { continueNamePublication.countDown(); worker.shutdownNow(); @@ -562,17 +562,17 @@ protected void beforeCurrentValueActionForTest(String key, Integer value) { Future load = worker.submit(() -> entry.getAndRunIfCurrent( "table", (key, value) -> actions.incrementAndGet())); - Assert.assertTrue(valueLoaded.await(3L, TimeUnit.SECONDS)); - Assert.assertThrows(IllegalStateException.class, + Assertions.assertTrue(valueLoaded.await(3L, TimeUnit.SECONDS)); + Assertions.assertThrows(IllegalStateException.class, () -> entry.computeAfterValidation( "table", (key, value) -> 6, () -> { throw new IllegalStateException("identity conflict"); })); continueAction.countDown(); - Assert.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); - Assert.assertEquals(1, actions.get()); - Assert.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); + Assertions.assertEquals(Integer.valueOf(5), load.get(3L, TimeUnit.SECONDS)); + Assertions.assertEquals(1, actions.get()); + Assertions.assertEquals(Integer.valueOf(5), entry.getIfPresent("table")); } finally { continueAction.countDown(); worker.shutdownNow(); @@ -588,11 +588,11 @@ public void testRemovalListenerAndLazyStripeAllocation() { FeMetaCacheEntry entry = FeMetaCacheEntry.withSyncRemovalListener( "objects", String::length, ENABLED, executor, 8, (key, value, cause) -> removals.add(key + "=" + value)); - Assert.assertEquals(0, entry.initializedStripeCountForTest()); + Assertions.assertEquals(0, entry.initializedStripeCountForTest()); entry.put("table", 5); - Assert.assertEquals(1, entry.initializedStripeCountForTest()); + Assertions.assertEquals(1, entry.initializedStripeCountForTest()); entry.invalidateAll(); - Assert.assertEquals(List.of("table=5"), removals); + Assertions.assertEquals(List.of("table=5"), removals); } finally { executor.shutdownNow(); } @@ -638,9 +638,9 @@ void beforePublicMutationWriteForTest(String key) { continuePublication.countDown(); Set expected = Set.of("initial", "refreshed", "incremental"); - Assert.assertEquals(expected, remap.get(3L, TimeUnit.SECONDS)); - Assert.assertEquals(expected, entry.getIfPresent("names")); - Assert.assertEquals(2, attempts.get()); + Assertions.assertEquals(expected, remap.get(3L, TimeUnit.SECONDS)); + Assertions.assertEquals(expected, entry.getIfPresent("names")); + Assertions.assertEquals(2, attempts.get()); } finally { continuePublication.countDown(); worker.shutdownNow(); @@ -660,7 +660,7 @@ private static Long resultOrNull(Future future) throws Exception { try { return future.get(3L, TimeUnit.SECONDS); } catch (ExecutionException e) { - Assert.assertTrue(e.getCause() instanceof IllegalStateException); + Assertions.assertTrue(e.getCause() instanceof IllegalStateException); return null; } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/IdNameIndexTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/IdNameIndexTest.java index 53d1771924d98a..4ea6773e24db34 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/IdNameIndexTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/IdNameIndexTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.metacache; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -36,9 +36,9 @@ public void testPutAndIdempotentPut() { index.checkCanPut(1L, "db1"); index.put(1L, "db1"); - Assert.assertEquals("db1", index.getName(1L)); - Assert.assertTrue(index.containsMappingForTest(1L, "db1")); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertEquals("db1", index.getName(1L)); + Assertions.assertTrue(index.containsMappingForTest(1L, "db1")); + Assertions.assertEquals(1, index.sizeForTest()); } @Test @@ -46,12 +46,12 @@ public void testCheckCanPutRejectsConflictWithoutPublishing() { IdNameIndex index = new IdNameIndex("test database"); index.put(1L, "db1"); - Assert.assertThrows(IllegalStateException.class, () -> index.checkCanPut(2L, "db1")); - Assert.assertThrows(IllegalStateException.class, () -> index.checkCanPut(1L, "db2")); + Assertions.assertThrows(IllegalStateException.class, () -> index.checkCanPut(2L, "db1")); + Assertions.assertThrows(IllegalStateException.class, () -> index.checkCanPut(1L, "db2")); - Assert.assertTrue(index.containsMappingForTest(1L, "db1")); - Assert.assertNull(index.getName(2L)); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertTrue(index.containsMappingForTest(1L, "db1")); + Assertions.assertNull(index.getName(2L)); + Assertions.assertEquals(1, index.sizeForTest()); } @Test @@ -74,15 +74,15 @@ public void testRejectsSameNameWithDifferentIdWithoutPartialUpdate() { IdNameIndex index = new IdNameIndex("test database"); index.put(1L, "db1"); - IllegalStateException exception = Assert.assertThrows( + IllegalStateException exception = Assertions.assertThrows( IllegalStateException.class, () -> index.put(2L, "db1")); - Assert.assertTrue(exception.getMessage().contains("test database")); - Assert.assertTrue(exception.getMessage().contains("id 1")); - Assert.assertTrue(exception.getMessage().contains("id 2")); - Assert.assertTrue(index.containsMappingForTest(1L, "db1")); - Assert.assertNull(index.getName(2L)); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertTrue(exception.getMessage().contains("test database")); + Assertions.assertTrue(exception.getMessage().contains("id 1")); + Assertions.assertTrue(exception.getMessage().contains("id 2")); + Assertions.assertTrue(index.containsMappingForTest(1L, "db1")); + Assertions.assertNull(index.getName(2L)); + Assertions.assertEquals(1, index.sizeForTest()); } @Test @@ -90,14 +90,14 @@ public void testRejectsSameIdWithDifferentNameWithoutPartialUpdate() { IdNameIndex index = new IdNameIndex("test table"); index.put(1L, "tbl1"); - IllegalStateException exception = Assert.assertThrows( + IllegalStateException exception = Assertions.assertThrows( IllegalStateException.class, () -> index.put(1L, "tbl2")); - Assert.assertTrue(exception.getMessage().contains("test table")); - Assert.assertTrue(exception.getMessage().contains("tbl1")); - Assert.assertTrue(exception.getMessage().contains("tbl2")); - Assert.assertTrue(index.containsMappingForTest(1L, "tbl1")); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertTrue(exception.getMessage().contains("test table")); + Assertions.assertTrue(exception.getMessage().contains("tbl1")); + Assertions.assertTrue(exception.getMessage().contains("tbl2")); + Assertions.assertTrue(index.containsMappingForTest(1L, "tbl1")); + Assertions.assertEquals(1, index.sizeForTest()); } @Test @@ -109,9 +109,9 @@ public void testRemoveNameAndMissingRemovalAreIdempotent() { index.removeName("tbl1"); index.removeName("tbl1"); - Assert.assertNull(index.getName(1L)); - Assert.assertEquals("tbl2", index.getName(2L)); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertNull(index.getName(1L)); + Assertions.assertEquals("tbl2", index.getName(2L)); + Assertions.assertEquals(1, index.sizeForTest()); } @Test @@ -122,11 +122,11 @@ public void testClearRemovesBothDirections() { index.clear(); - Assert.assertNull(index.getName(1L)); - Assert.assertNull(index.getName(2L)); - Assert.assertEquals(0, index.sizeForTest()); + Assertions.assertNull(index.getName(1L)); + Assertions.assertNull(index.getName(2L)); + Assertions.assertEquals(0, index.sizeForTest()); index.put(3L, "tbl1"); - Assert.assertTrue(index.containsMappingForTest(3L, "tbl1")); + Assertions.assertTrue(index.containsMappingForTest(3L, "tbl1")); } @Test @@ -134,9 +134,9 @@ public void testCaseInsensitiveFallbackDoesNotChangeExactIdentity() { IdNameIndex index = new IdNameIndex("test table"); index.put(1L, "MixedTable"); - Assert.assertEquals("MixedTable", index.findNameIgnoreCase("mixedtable")); - Assert.assertNull(index.findNameIgnoreCase("missing")); - Assert.assertTrue(index.containsMappingForTest(1L, "MixedTable")); + Assertions.assertEquals("MixedTable", index.findNameIgnoreCase("mixedtable")); + Assertions.assertNull(index.findNameIgnoreCase("missing")); + Assertions.assertTrue(index.containsMappingForTest(1L, "MixedTable")); } @Test @@ -149,11 +149,11 @@ public void testConcurrentConflictingPublicationKeepsOneCompleteMapping() throws Future second = executor.submit(() -> putAfterStart(index, start, 2L, "db")); start.countDown(); - Assert.assertNotEquals(first.get(), second.get()); - Assert.assertEquals(1, index.sizeForTest()); + Assertions.assertNotEquals(first.get(), second.get()); + Assertions.assertEquals(1, index.sizeForTest()); String firstName = index.getName(1L); String secondName = index.getName(2L); - Assert.assertTrue(("db".equals(firstName) && secondName == null) + Assertions.assertTrue(("db".equals(firstName) && secondName == null) || (firstName == null && "db".equals(secondName))); } finally { executor.shutdownNow(); @@ -181,7 +181,7 @@ private static void assertCheckDoesNotWaitForMutationMonitor( started.countDown(); check.run(); }); - Assert.assertTrue(started.await(3L, TimeUnit.SECONDS)); + Assertions.assertTrue(started.await(3L, TimeUnit.SECONDS)); result.get(3L, TimeUnit.SECONDS); } } finally { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/MetaCacheDeadlockTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/MetaCacheDeadlockTest.java index 56aafafac02dfb..eed53e15390809 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/MetaCacheDeadlockTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/MetaCacheDeadlockTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.ThreadPoolManager; import org.apache.doris.connector.cache.CacheSpec; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -85,7 +85,6 @@ public void testNestedInvalidateAllWithBoundedExecutor() throws InterruptedExcep executor.shutdown(); boolean terminated = executor.awaitTermination(1, TimeUnit.SECONDS); - Assert.assertTrue("FeMetaCacheEntry deadlock detected. Ensure sync removal listeners use direct execution.", - completed && terminated); + Assertions.assertTrue(completed && terminated, "FeMetaCacheEntry deadlock detected. Ensure sync removal listeners use direct execution."); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/NameCacheValueTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/NameCacheValueTest.java index 401959c88899d8..8cb3fb719676c6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/NameCacheValueTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/metacache/NameCacheValueTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.Pair; import com.google.common.collect.ImmutableList; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class NameCacheValueTest { @@ -30,9 +30,9 @@ public void testCopyOnWriteKeepsOriginalSnapshot() { NameCacheValue original = NameCacheValue.of(ImmutableList.of(Pair.of("RemoteA", "LocalA"))); NameCacheValue updated = original.withName("RemoteB", "LocalB"); - Assert.assertEquals("RemoteA", original.remoteNameOfLocalName("LocalA")); - Assert.assertNull(original.remoteNameOfLocalName("LocalB")); - Assert.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalB")); + Assertions.assertEquals("RemoteA", original.remoteNameOfLocalName("LocalA")); + Assertions.assertNull(original.remoteNameOfLocalName("LocalB")); + Assertions.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalB")); } @Test @@ -41,8 +41,8 @@ public void testCaseInsensitiveLookupReturnsRemoteName() { Pair.of("RemoteA", "LocalA"), Pair.of("RemoteB", "RemoteB"))); - Assert.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); - Assert.assertEquals("RemoteB", names.remoteNameForCaseInsensitiveLookup("REMOTEB")); + Assertions.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); + Assertions.assertEquals("RemoteB", names.remoteNameForCaseInsensitiveLookup("REMOTEB")); } @Test @@ -54,9 +54,9 @@ public void testSourcePairMutationDoesNotChangeSnapshot() { pair.first = "RemoteB"; pair.second = "LocalB"; - Assert.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); - Assert.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); - Assert.assertNull(names.remoteNameOfLocalName("LocalB")); + Assertions.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); + Assertions.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); + Assertions.assertNull(names.remoteNameOfLocalName("LocalB")); } @Test @@ -68,9 +68,9 @@ public void testReturnedPairMutationDoesNotChangeSnapshot() { returned.first = "RemoteB"; returned.second = "LocalB"; - Assert.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); - Assert.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); - Assert.assertNull(names.remoteNameOfLocalName("LocalB")); + Assertions.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); + Assertions.assertEquals("RemoteA", names.remoteNameForCaseInsensitiveLookup("remotea")); + Assertions.assertNull(names.remoteNameOfLocalName("LocalB")); } @Test @@ -79,10 +79,10 @@ public void testLocalNamesExposeImmutableReadOnlyView() { Pair.of("RemoteA", "LocalA"), Pair.of("RemoteB", "LocalB"))); - Assert.assertEquals(ImmutableList.of("LocalA", "LocalB"), names.localNames()); - Assert.assertSame(names.localNames(), names.localNames()); - Assert.assertTrue(names.containsLocalName("LocalA")); - Assert.assertThrows(UnsupportedOperationException.class, () -> names.localNames().add("LocalC")); + Assertions.assertEquals(ImmutableList.of("LocalA", "LocalB"), names.localNames()); + Assertions.assertSame(names.localNames(), names.localNames()); + Assertions.assertTrue(names.containsLocalName("LocalA")); + Assertions.assertThrows(UnsupportedOperationException.class, () -> names.localNames().add("LocalC")); } @Test @@ -91,35 +91,35 @@ public void testIdenticalMappingIsIdempotent() { Pair.of("RemoteA", "LocalA"), Pair.of("RemoteA", "LocalA"))); - Assert.assertEquals(ImmutableList.of("LocalA"), names.localNames()); - Assert.assertEquals(1, names.names().size()); - Assert.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); + Assertions.assertEquals(ImmutableList.of("LocalA"), names.localNames()); + Assertions.assertEquals(1, names.names().size()); + Assertions.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); } @Test public void testRejectsConflictingRemoteNamesForSameLocalName() { - IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException exception = Assertions.assertThrows( IllegalArgumentException.class, () -> NameCacheValue.of(ImmutableList.of( Pair.of("RemoteA", "LocalX"), Pair.of("RemoteB", "LocalX")))); - Assert.assertTrue(exception.getMessage().contains("LocalX")); - Assert.assertTrue(exception.getMessage().contains("RemoteA")); - Assert.assertTrue(exception.getMessage().contains("RemoteB")); + Assertions.assertTrue(exception.getMessage().contains("LocalX")); + Assertions.assertTrue(exception.getMessage().contains("RemoteA")); + Assertions.assertTrue(exception.getMessage().contains("RemoteB")); } @Test public void testRejectsConflictingLocalNamesForSameRemoteName() { - IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException exception = Assertions.assertThrows( IllegalArgumentException.class, () -> NameCacheValue.of(ImmutableList.of( Pair.of("RemoteA", "LocalX"), Pair.of("RemoteA", "LocalY")))); - Assert.assertTrue(exception.getMessage().contains("RemoteA")); - Assert.assertTrue(exception.getMessage().contains("LocalX")); - Assert.assertTrue(exception.getMessage().contains("LocalY")); + Assertions.assertTrue(exception.getMessage().contains("RemoteA")); + Assertions.assertTrue(exception.getMessage().contains("LocalX")); + Assertions.assertTrue(exception.getMessage().contains("LocalY")); } @Test @@ -129,18 +129,18 @@ public void testCaseSensitiveNamesCanShareLowerCaseKey() { Pair.of("Foo", "Foo"), Pair.of("foo", "foo"))); - Assert.assertEquals("Foo", names.remoteNameOfLocalName("Foo")); - Assert.assertEquals("foo", names.remoteNameOfLocalName("foo")); - Assert.assertEquals("foo", names.remoteNameForCaseInsensitiveLookup("FOO")); + Assertions.assertEquals("Foo", names.remoteNameOfLocalName("Foo")); + Assertions.assertEquals("foo", names.remoteNameOfLocalName("foo")); + Assertions.assertEquals("foo", names.remoteNameForCaseInsensitiveLookup("FOO")); } @Test public void testWithNameRejectsRemoteNameConflict() { NameCacheValue names = NameCacheValue.of(ImmutableList.of(Pair.of("RemoteA", "LocalA"))); - IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException exception = Assertions.assertThrows( IllegalArgumentException.class, () -> names.withName("RemoteA", "LocalB")); - Assert.assertTrue(exception.getMessage().contains("remote name already maps")); + Assertions.assertTrue(exception.getMessage().contains("remote name already maps")); } @Test @@ -151,8 +151,8 @@ public void testWithSameNameIsIdempotent() { NameCacheValue updated = names.withName("RemoteA", "LocalA"); - Assert.assertSame(names, updated); - Assert.assertEquals(ImmutableList.of("LocalA", "LocalB"), updated.localNames()); + Assertions.assertSame(names, updated); + Assertions.assertEquals(ImmutableList.of("LocalA", "LocalB"), updated.localNames()); } @Test @@ -161,9 +161,9 @@ public void testWithNameReplacesRemoteNameForExistingLocalName() { NameCacheValue updated = names.withName("RemoteB", "LocalA"); - Assert.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); - Assert.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalA")); - Assert.assertEquals(ImmutableList.of("LocalA"), updated.localNames()); + Assertions.assertEquals("RemoteA", names.remoteNameOfLocalName("LocalA")); + Assertions.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalA")); + Assertions.assertEquals(ImmutableList.of("LocalA"), updated.localNames()); } @Test @@ -173,7 +173,7 @@ public void testWithoutLocalNameRemovesMapping() { Pair.of("RemoteB", "LocalB"))); NameCacheValue updated = names.withoutLocalName("LocalA"); - Assert.assertFalse(updated.containsLocalName("LocalA")); - Assert.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalB")); + Assertions.assertFalse(updated.containsLocalName("LocalA")); + Assertions.assertEquals("RemoteB", updated.remoteNameOfLocalName("LocalB")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/AvroFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/AvroFileFormatPropertiesTest.java index a7fc534e0de5cc..03323d8e159432 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/AvroFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/AvroFileFormatPropertiesTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.property.fileformat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -28,7 +28,7 @@ public class AvroFileFormatPropertiesTest { private AvroFileFormatProperties avroFileFormatProperties; - @Before + @BeforeEach public void setUp() { avroFileFormatProperties = new AvroFileFormatProperties(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/CsvFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/CsvFileFormatPropertiesTest.java index 1482c84055daee..9333bdd02eebda 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/CsvFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/CsvFileFormatPropertiesTest.java @@ -21,9 +21,9 @@ import org.apache.doris.nereids.exceptions.AnalysisException; import org.apache.doris.thrift.TFileCompressType; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -32,7 +32,7 @@ public class CsvFileFormatPropertiesTest { private CsvFileFormatProperties csvFileFormatProperties; - @Before + @BeforeEach public void setUp() { csvFileFormatProperties = new CsvFileFormatProperties("csv"); } @@ -46,9 +46,9 @@ public void testAnalyzeFileFormatPropertiesValid() throws AnalysisException { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(",", csvFileFormatProperties.getColumnSeparator()); - Assert.assertEquals("\n", csvFileFormatProperties.getLineDelimiter()); - Assert.assertEquals(1, csvFileFormatProperties.getSkipLines()); + Assertions.assertEquals(",", csvFileFormatProperties.getColumnSeparator()); + Assertions.assertEquals("\n", csvFileFormatProperties.getLineDelimiter()); + Assertions.assertEquals(1, csvFileFormatProperties.getSkipLines()); } @Test @@ -56,7 +56,7 @@ public void testAnalyzeFileFormatPropertiesInvalidSeparator() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_COLUMN_SEPARATOR, ""); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -66,7 +66,7 @@ public void testAnalyzeFileFormatPropertiesInvalidLineDelimiter() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_LINE_DELIMITER, ""); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -76,7 +76,7 @@ public void testAnalyzeFileFormatPropertiesInvalidEnclose() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_ENCLOSE, "invalid"); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -87,7 +87,7 @@ public void testAnalyzeFileFormatPropertiesValidEnclose() throws AnalysisExcepti properties.put(CsvFileFormatProperties.PROP_ENCLOSE, "\""); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals((byte) '"', csvFileFormatProperties.getEnclose()); + Assertions.assertEquals((byte) '"', csvFileFormatProperties.getEnclose()); } @Test @@ -95,7 +95,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesNegative() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_SKIP_LINES, "-1"); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -106,7 +106,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesLargeValue() throws Analysis properties.put(CsvFileFormatProperties.PROP_SKIP_LINES, "1000"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(1000, csvFileFormatProperties.getSkipLines()); + Assertions.assertEquals(1000, csvFileFormatProperties.getSkipLines()); } @Test @@ -115,7 +115,7 @@ public void testAnalyzeFileFormatPropertiesTrimDoubleQuotesTrue() throws Analysi properties.put(CsvFileFormatProperties.PROP_TRIM_DOUBLE_QUOTES, "true"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, csvFileFormatProperties.isTrimDoubleQuotes()); + Assertions.assertEquals(true, csvFileFormatProperties.isTrimDoubleQuotes()); } @Test @@ -124,7 +124,7 @@ public void testAnalyzeFileFormatPropertiesTrimDoubleQuotesFalse() throws Analys properties.put(CsvFileFormatProperties.PROP_TRIM_DOUBLE_QUOTES, "false"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, csvFileFormatProperties.isTrimDoubleQuotes()); + Assertions.assertEquals(false, csvFileFormatProperties.isTrimDoubleQuotes()); } @Test @@ -141,7 +141,7 @@ public void testAnalyzeFileFormatPropertiesValidCompressType() throws AnalysisEx Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_COMPRESS_TYPE, "gz"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.GZ, csvFileFormatProperties.getCompressionType()); + Assertions.assertEquals(TFileCompressType.GZ, csvFileFormatProperties.getCompressionType()); ExceptionChecker.expectThrowsNoException(() -> csvFileFormatProperties.checkSupportedCompressionType(true)); } @@ -157,7 +157,7 @@ public void testAnalyzeFileFormatPropertiesValidEncloseMultipleCharacters() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_ENCLOSE, "\"\""); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -168,7 +168,7 @@ public void testAnalyzeFileFormatPropertiesValidEncloseEmpty() { properties.put(CsvFileFormatProperties.PROP_ENCLOSE, ""); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(0, csvFileFormatProperties.getEnclose()); + Assertions.assertEquals(0, csvFileFormatProperties.getEnclose()); } @Test @@ -176,7 +176,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesAsString() { Map properties = new HashMap<>(); properties.put(CsvFileFormatProperties.PROP_SKIP_LINES, "abc"); - Assert.assertThrows(NumberFormatException.class, () -> { + Assertions.assertThrows(NumberFormatException.class, () -> { csvFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -187,7 +187,7 @@ public void testAnalyzeFileFormatPropertiesValidColumnSeparator() throws Analysi properties.put(CsvFileFormatProperties.PROP_COLUMN_SEPARATOR, ";"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(";", csvFileFormatProperties.getColumnSeparator()); + Assertions.assertEquals(";", csvFileFormatProperties.getColumnSeparator()); } @Test @@ -203,7 +203,7 @@ public void testAnalyzeFileFormatPropertiesValidLineDelimiter() throws AnalysisE properties.put(CsvFileFormatProperties.PROP_LINE_DELIMITER, "\r\n"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("\r\n", csvFileFormatProperties.getLineDelimiter()); + Assertions.assertEquals("\r\n", csvFileFormatProperties.getLineDelimiter()); } @Test @@ -212,7 +212,7 @@ public void testAnalyzeFileFormatPropertiesValidTrimDoubleQuotes() throws Analys properties.put(CsvFileFormatProperties.PROP_TRIM_DOUBLE_QUOTES, "true"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, csvFileFormatProperties.isTrimDoubleQuotes()); + Assertions.assertEquals(true, csvFileFormatProperties.isTrimDoubleQuotes()); } @Test @@ -221,6 +221,6 @@ public void testAnalyzeFileFormatPropertiesInvalidTrimDoubleQuotes() { properties.put(CsvFileFormatProperties.PROP_TRIM_DOUBLE_QUOTES, "invalid"); csvFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, csvFileFormatProperties.isTrimDoubleQuotes()); + Assertions.assertEquals(false, csvFileFormatProperties.isTrimDoubleQuotes()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/FileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/FileFormatPropertiesTest.java index 74d8d0db2ad19b..d420bb8bdd6e5e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/FileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/FileFormatPropertiesTest.java @@ -19,15 +19,15 @@ import org.apache.doris.nereids.exceptions.AnalysisException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class FileFormatPropertiesTest { @Test public void testCreateFileFormatPropertiesInvalidFormat() { - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { FileFormatProperties.createFileFormatProperties("invalid_format"); }); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/JsonFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/JsonFileFormatPropertiesTest.java index 1f1e1b2447eb74..b92226989cf3e8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/JsonFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/JsonFileFormatPropertiesTest.java @@ -19,9 +19,9 @@ import org.apache.doris.nereids.exceptions.AnalysisException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,7 @@ public class JsonFileFormatPropertiesTest { private JsonFileFormatProperties jsonFileFormatProperties; - @Before + @BeforeEach public void setUp() { jsonFileFormatProperties = new JsonFileFormatProperties(); } @@ -40,13 +40,13 @@ public void testAnalyzeFileFormatPropertiesEmpty() throws AnalysisException { Map properties = new HashMap<>(); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("", jsonFileFormatProperties.getJsonRoot()); - Assert.assertEquals("", jsonFileFormatProperties.getJsonPaths()); - Assert.assertEquals(false, jsonFileFormatProperties.isStripOuterArray()); - Assert.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); - Assert.assertEquals(false, jsonFileFormatProperties.isNumAsString()); - Assert.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); - Assert.assertEquals(CsvFileFormatProperties.DEFAULT_LINE_DELIMITER, + Assertions.assertEquals("", jsonFileFormatProperties.getJsonRoot()); + Assertions.assertEquals("", jsonFileFormatProperties.getJsonPaths()); + Assertions.assertEquals(false, jsonFileFormatProperties.isStripOuterArray()); + Assertions.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); + Assertions.assertEquals(false, jsonFileFormatProperties.isNumAsString()); + Assertions.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); + Assertions.assertEquals(CsvFileFormatProperties.DEFAULT_LINE_DELIMITER, jsonFileFormatProperties.getLineDelimiter()); } @@ -56,7 +56,7 @@ public void testAnalyzeFileFormatPropertiesValidJsonRoot() throws AnalysisExcept properties.put(JsonFileFormatProperties.PROP_JSON_ROOT, "data.items"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("data.items", jsonFileFormatProperties.getJsonRoot()); + Assertions.assertEquals("data.items", jsonFileFormatProperties.getJsonRoot()); } @Test @@ -66,7 +66,7 @@ public void testAnalyzeFileFormatPropertiesValidJsonPaths() throws AnalysisExcep "[\"$.name\", \"$.age\", \"$.city\"]"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("[\"$.name\", \"$.age\", \"$.city\"]", jsonFileFormatProperties.getJsonPaths()); + Assertions.assertEquals("[\"$.name\", \"$.age\", \"$.city\"]", jsonFileFormatProperties.getJsonPaths()); } @Test @@ -75,7 +75,7 @@ public void testAnalyzeFileFormatPropertiesStripOuterArrayTrue() throws Analysis properties.put(JsonFileFormatProperties.PROP_STRIP_OUTER_ARRAY, "true"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, jsonFileFormatProperties.isStripOuterArray()); + Assertions.assertEquals(true, jsonFileFormatProperties.isStripOuterArray()); } @Test @@ -84,7 +84,7 @@ public void testAnalyzeFileFormatPropertiesStripOuterArrayFalse() throws Analysi properties.put(JsonFileFormatProperties.PROP_STRIP_OUTER_ARRAY, "false"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, jsonFileFormatProperties.isStripOuterArray()); + Assertions.assertEquals(false, jsonFileFormatProperties.isStripOuterArray()); } @Test @@ -93,7 +93,7 @@ public void testAnalyzeFileFormatPropertiesReadJsonByLineTrue() throws AnalysisE properties.put(JsonFileFormatProperties.PROP_READ_JSON_BY_LINE, "true"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); + Assertions.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); } @Test @@ -102,7 +102,7 @@ public void testAnalyzeFileFormatPropertiesReadJsonByLineFalse() throws Analysis properties.put(JsonFileFormatProperties.PROP_READ_JSON_BY_LINE, "false"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, jsonFileFormatProperties.isReadJsonByLine()); + Assertions.assertEquals(false, jsonFileFormatProperties.isReadJsonByLine()); } @Test @@ -111,7 +111,7 @@ public void testAnalyzeFileFormatPropertiesNumAsStringTrue() throws AnalysisExce properties.put(JsonFileFormatProperties.PROP_NUM_AS_STRING, "true"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, jsonFileFormatProperties.isNumAsString()); + Assertions.assertEquals(true, jsonFileFormatProperties.isNumAsString()); } @Test @@ -120,7 +120,7 @@ public void testAnalyzeFileFormatPropertiesNumAsStringFalse() throws AnalysisExc properties.put(JsonFileFormatProperties.PROP_NUM_AS_STRING, "false"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, jsonFileFormatProperties.isNumAsString()); + Assertions.assertEquals(false, jsonFileFormatProperties.isNumAsString()); } @Test @@ -129,7 +129,7 @@ public void testAnalyzeFileFormatPropertiesFuzzyParseTrue() throws AnalysisExcep properties.put(JsonFileFormatProperties.PROP_FUZZY_PARSE, "true"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(true, jsonFileFormatProperties.isFuzzyParse()); + Assertions.assertEquals(true, jsonFileFormatProperties.isFuzzyParse()); } @Test @@ -138,7 +138,7 @@ public void testAnalyzeFileFormatPropertiesFuzzyParseFalse() throws AnalysisExce properties.put(JsonFileFormatProperties.PROP_FUZZY_PARSE, "false"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); + Assertions.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); } @Test @@ -147,7 +147,7 @@ public void testAnalyzeFileFormatPropertiesInvalidBooleanValue() throws Analysis properties.put(JsonFileFormatProperties.PROP_FUZZY_PARSE, "invalid"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); + Assertions.assertEquals(false, jsonFileFormatProperties.isFuzzyParse()); } @Test @@ -162,12 +162,12 @@ public void testAnalyzeFileFormatPropertiesAllProperties() throws AnalysisExcept jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("data.records", jsonFileFormatProperties.getJsonRoot()); - Assert.assertEquals("[\"$.id\", \"$.name\"]", jsonFileFormatProperties.getJsonPaths()); - Assert.assertEquals(true, jsonFileFormatProperties.isStripOuterArray()); - Assert.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); - Assert.assertEquals(true, jsonFileFormatProperties.isNumAsString()); - Assert.assertEquals(true, jsonFileFormatProperties.isFuzzyParse()); + Assertions.assertEquals("data.records", jsonFileFormatProperties.getJsonRoot()); + Assertions.assertEquals("[\"$.id\", \"$.name\"]", jsonFileFormatProperties.getJsonPaths()); + Assertions.assertEquals(true, jsonFileFormatProperties.isStripOuterArray()); + Assertions.assertEquals(true, jsonFileFormatProperties.isReadJsonByLine()); + Assertions.assertEquals(true, jsonFileFormatProperties.isNumAsString()); + Assertions.assertEquals(true, jsonFileFormatProperties.isFuzzyParse()); } @Test @@ -176,7 +176,7 @@ public void testAnalyzeFileFormatPropertiesSpecialCharactersInJsonRoot() throws properties.put(JsonFileFormatProperties.PROP_JSON_ROOT, "data.special@#$%^&*()"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("data.special@#$%^&*()", jsonFileFormatProperties.getJsonRoot()); + Assertions.assertEquals("data.special@#$%^&*()", jsonFileFormatProperties.getJsonRoot()); } @Test @@ -186,7 +186,7 @@ public void testAnalyzeFileFormatPropertiesComplexJsonPaths() throws AnalysisExc "[\"$.deeply.nested[0].array[*].field\", \"$.complex.path[?(@.type=='value')]\"]"); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("[\"$.deeply.nested[0].array[*].field\", \"$.complex.path[?(@.type=='value')]\"]", + Assertions.assertEquals("[\"$.deeply.nested[0].array[*].field\", \"$.complex.path[?(@.type=='value')]\"]", jsonFileFormatProperties.getJsonPaths()); } @@ -196,6 +196,6 @@ public void testAnalyzeFileFormatPropertiesEmptyJsonPaths() throws AnalysisExcep properties.put(JsonFileFormatProperties.PROP_JSON_PATHS, ""); jsonFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("", jsonFileFormatProperties.getJsonPaths()); + Assertions.assertEquals("", jsonFileFormatProperties.getJsonPaths()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/OrcFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/OrcFileFormatPropertiesTest.java index 0a63d0cec69b6f..6d466baa0a6a83 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/OrcFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/OrcFileFormatPropertiesTest.java @@ -21,9 +21,9 @@ import org.apache.doris.thrift.TFileCompressType; import org.apache.doris.thrift.TResultFileSinkOptions; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -32,7 +32,7 @@ public class OrcFileFormatPropertiesTest { private OrcFileFormatProperties orcFileFormatProperties; - @Before + @BeforeEach public void setUp() { orcFileFormatProperties = new OrcFileFormatProperties(); } @@ -42,7 +42,7 @@ public void testAnalyzeFileFormatProperties() { Map properties = new HashMap<>(); // Add properties if needed orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.ZLIB, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.ZLIB, orcFileFormatProperties.getOrcCompressionType()); } @Test @@ -50,19 +50,19 @@ public void testSupportedCompressionTypes() { Map properties = new HashMap<>(); properties.put("compress_type", "plain"); orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.PLAIN, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.PLAIN, orcFileFormatProperties.getOrcCompressionType()); properties.put("compress_type", "snappy"); orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.SNAPPYBLOCK, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.SNAPPYBLOCK, orcFileFormatProperties.getOrcCompressionType()); properties.put("compress_type", "zlib"); orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.ZLIB, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.ZLIB, orcFileFormatProperties.getOrcCompressionType()); properties.put("compress_type", "zstd"); orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.ZSTD, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.ZSTD, orcFileFormatProperties.getOrcCompressionType()); } @Test @@ -70,28 +70,30 @@ public void testCompressionTypeCaseInsensitive() { Map properties = new HashMap<>(); properties.put("compress_type", "SNAPPY"); orcFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.SNAPPYBLOCK, orcFileFormatProperties.getOrcCompressionType()); + Assertions.assertEquals(TFileCompressType.SNAPPYBLOCK, orcFileFormatProperties.getOrcCompressionType()); } - @Test(expected = org.apache.doris.nereids.exceptions.AnalysisException.class) + @Test public void testInvalidCompressionType() { - Map properties = new HashMap<>(); - properties.put("compress_type", "invalid_type"); - orcFileFormatProperties.analyzeFileFormatProperties(properties, true); + Assertions.assertThrows(org.apache.doris.nereids.exceptions.AnalysisException.class, () -> { + Map properties = new HashMap<>(); + properties.put("compress_type", "invalid_type"); + orcFileFormatProperties.analyzeFileFormatProperties(properties, true); + }); } @Test public void testFullTResultFileSinkOptions() { TResultFileSinkOptions sinkOptions = new TResultFileSinkOptions(); orcFileFormatProperties.fullTResultFileSinkOptions(sinkOptions); - Assert.assertEquals(orcFileFormatProperties.getOrcCompressionType(), sinkOptions.getOrcCompressionType()); - Assert.assertEquals(1, sinkOptions.getOrcWriterVersion()); + Assertions.assertEquals(orcFileFormatProperties.getOrcCompressionType(), sinkOptions.getOrcCompressionType()); + Assertions.assertEquals(1, sinkOptions.getOrcWriterVersion()); } @Test public void testToTFileAttributes() { TFileAttributes attrs = orcFileFormatProperties.toTFileAttributes(); - Assert.assertNotNull(attrs); - Assert.assertNotNull(attrs.getTextParams()); + Assertions.assertNotNull(attrs); + Assertions.assertNotNull(attrs.getTextParams()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/ParquetFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/ParquetFileFormatPropertiesTest.java index 0a8831585de4d0..7d41adae26de6a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/ParquetFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/ParquetFileFormatPropertiesTest.java @@ -23,9 +23,9 @@ import org.apache.doris.thrift.TParquetVersion; import org.apache.doris.thrift.TResultFileSinkOptions; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -34,7 +34,7 @@ public class ParquetFileFormatPropertiesTest { private ParquetFileFormatProperties parquetFileFormatProperties; - @Before + @BeforeEach public void setUp() { parquetFileFormatProperties = new ParquetFileFormatProperties(); } @@ -45,9 +45,9 @@ public void testAnalyzeFileFormatProperties() { // Add properties if needed parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TParquetCompressionType.SNAPPY, parquetFileFormatProperties.getParquetCompressionType()); - Assert.assertEquals(false, parquetFileFormatProperties.isParquetDisableDictionary()); - Assert.assertFalse(parquetFileFormatProperties.isEnableInt96Timestamps()); + Assertions.assertEquals(TParquetCompressionType.SNAPPY, parquetFileFormatProperties.getParquetCompressionType()); + Assertions.assertEquals(false, parquetFileFormatProperties.isParquetDisableDictionary()); + Assertions.assertFalse(parquetFileFormatProperties.isEnableInt96Timestamps()); } @Test @@ -65,7 +65,7 @@ public void testSupportedCompressionTypes() { for (int i = 0; i < types.length; i++) { properties.put("compress_type", types[i]); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(expected[i], parquetFileFormatProperties.getParquetCompressionType()); + Assertions.assertEquals(expected[i], parquetFileFormatProperties.getParquetCompressionType()); } } @@ -74,14 +74,16 @@ public void testCompressionTypeCaseInsensitive() { Map properties = new HashMap<>(); properties.put("compress_type", "SNAPPY"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TParquetCompressionType.SNAPPY, parquetFileFormatProperties.getParquetCompressionType()); + Assertions.assertEquals(TParquetCompressionType.SNAPPY, parquetFileFormatProperties.getParquetCompressionType()); } - @Test(expected = AnalysisException.class) + @Test public void testInvalidCompressionType() { - Map properties = new HashMap<>(); - properties.put("compress_type", "invalid_type"); - parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); + Assertions.assertThrows(AnalysisException.class, () -> { + Map properties = new HashMap<>(); + properties.put("compress_type", "invalid_type"); + parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); + }); } @Test @@ -89,10 +91,10 @@ public void testParquetDisableDictionary() { Map properties = new HashMap<>(); properties.put("parquet.disable_dictionary", "true"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertTrue(parquetFileFormatProperties.isParquetDisableDictionary()); + Assertions.assertTrue(parquetFileFormatProperties.isParquetDisableDictionary()); properties.put("parquet.disable_dictionary", "false"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertFalse(parquetFileFormatProperties.isParquetDisableDictionary()); + Assertions.assertFalse(parquetFileFormatProperties.isParquetDisableDictionary()); } @Test @@ -100,10 +102,10 @@ public void testEnableInt96Timestamps() { Map properties = new HashMap<>(); properties.put("enable_int96_timestamps", "true"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertTrue(parquetFileFormatProperties.isEnableInt96Timestamps()); + Assertions.assertTrue(parquetFileFormatProperties.isEnableInt96Timestamps()); properties.put("enable_int96_timestamps", "false"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertFalse(parquetFileFormatProperties.isEnableInt96Timestamps()); + Assertions.assertFalse(parquetFileFormatProperties.isEnableInt96Timestamps()); } @Test @@ -113,9 +115,9 @@ public void testEnableInt96TimestampsRejectsInvalidBoolean() { properties.put("enable_int96_timestamps", value); try { parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.fail("Expected invalid boolean value to be rejected: " + value); + Assertions.fail("Expected invalid boolean value to be rejected: " + value); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("enable_int96_timestamps")); + Assertions.assertTrue(e.getMessage().contains("enable_int96_timestamps")); } } } @@ -128,13 +130,13 @@ public void testParquetVersion() { TResultFileSinkOptions sinkOptions = new TResultFileSinkOptions(); parquetFileFormatProperties.fullTResultFileSinkOptions(sinkOptions); - Assert.assertEquals(TParquetVersion.PARQUET_1_0, sinkOptions.getParquetVersion()); + Assertions.assertEquals(TParquetVersion.PARQUET_1_0, sinkOptions.getParquetVersion()); properties.put("parquet.version", "latest"); parquetFileFormatProperties.analyzeFileFormatProperties(properties, true); sinkOptions = new TResultFileSinkOptions(); parquetFileFormatProperties.fullTResultFileSinkOptions(sinkOptions); - Assert.assertEquals(TParquetVersion.PARQUET_2_LATEST, sinkOptions.getParquetVersion()); + Assertions.assertEquals(TParquetVersion.PARQUET_2_LATEST, sinkOptions.getParquetVersion()); } @Test @@ -145,22 +147,22 @@ public void testParquetVersionInvalid() { TResultFileSinkOptions sinkOptions = new TResultFileSinkOptions(); parquetFileFormatProperties.fullTResultFileSinkOptions(sinkOptions); - Assert.assertEquals(TParquetVersion.PARQUET_1_0, sinkOptions.getParquetVersion()); + Assertions.assertEquals(TParquetVersion.PARQUET_1_0, sinkOptions.getParquetVersion()); } @Test public void testFullTResultFileSinkOptions() { TResultFileSinkOptions sinkOptions = new TResultFileSinkOptions(); parquetFileFormatProperties.fullTResultFileSinkOptions(sinkOptions); - Assert.assertEquals(parquetFileFormatProperties.getParquetCompressionType(), sinkOptions.getParquetCompressionType()); - Assert.assertEquals(parquetFileFormatProperties.isParquetDisableDictionary(), sinkOptions.isParquetDisableDictionary()); - Assert.assertEquals(parquetFileFormatProperties.isEnableInt96Timestamps(), sinkOptions.isEnableInt96Timestamps()); + Assertions.assertEquals(parquetFileFormatProperties.getParquetCompressionType(), sinkOptions.getParquetCompressionType()); + Assertions.assertEquals(parquetFileFormatProperties.isParquetDisableDictionary(), sinkOptions.isParquetDisableDictionary()); + Assertions.assertEquals(parquetFileFormatProperties.isEnableInt96Timestamps(), sinkOptions.isEnableInt96Timestamps()); } @Test public void testToTFileAttributes() { TFileAttributes attrs = parquetFileFormatProperties.toTFileAttributes(); - Assert.assertNotNull(attrs); - Assert.assertNotNull(attrs.getTextParams()); + Assertions.assertNotNull(attrs); + Assertions.assertNotNull(attrs.getTextParams()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/TextFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/TextFileFormatPropertiesTest.java index 2ed04c234b715e..55d62cb7c1bd26 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/TextFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/TextFileFormatPropertiesTest.java @@ -21,9 +21,9 @@ import org.apache.doris.nereids.exceptions.AnalysisException; import org.apache.doris.thrift.TFileCompressType; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -32,7 +32,7 @@ public class TextFileFormatPropertiesTest { private TextFileFormatProperties textFileFormatProperties; - @Before + @BeforeEach public void setUp() { textFileFormatProperties = new TextFileFormatProperties(); } @@ -46,9 +46,9 @@ public void testAnalyzeFileFormatPropertiesValid() throws AnalysisException { textFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(",", textFileFormatProperties.getColumnSeparator()); - Assert.assertEquals("\n", textFileFormatProperties.getLineDelimiter()); - Assert.assertEquals(1, textFileFormatProperties.getSkipLines()); + Assertions.assertEquals(",", textFileFormatProperties.getColumnSeparator()); + Assertions.assertEquals("\n", textFileFormatProperties.getLineDelimiter()); + Assertions.assertEquals(1, textFileFormatProperties.getSkipLines()); } @Test @@ -56,7 +56,7 @@ public void testAnalyzeFileFormatPropertiesInvalidSeparator() { Map properties = new HashMap<>(); properties.put(TextFileFormatProperties.PROP_COLUMN_SEPARATOR, ""); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { textFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -66,7 +66,7 @@ public void testAnalyzeFileFormatPropertiesInvalidLineDelimiter() { Map properties = new HashMap<>(); properties.put(TextFileFormatProperties.PROP_LINE_DELIMITER, ""); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { textFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -76,7 +76,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesNegative() { Map properties = new HashMap<>(); properties.put(TextFileFormatProperties.PROP_SKIP_LINES, "-1"); - Assert.assertThrows(AnalysisException.class, () -> { + Assertions.assertThrows(AnalysisException.class, () -> { textFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -87,7 +87,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesLargeValue() throws Analysis properties.put(TextFileFormatProperties.PROP_SKIP_LINES, "1000"); textFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(1000, textFileFormatProperties.getSkipLines()); + Assertions.assertEquals(1000, textFileFormatProperties.getSkipLines()); } @Test @@ -104,7 +104,7 @@ public void testAnalyzeFileFormatPropertiesValidCompressType() throws AnalysisEx properties.put(TextFileFormatProperties.PROP_COMPRESS_TYPE, "gz"); textFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(TFileCompressType.GZ, textFileFormatProperties.getCompressionType()); + Assertions.assertEquals(TFileCompressType.GZ, textFileFormatProperties.getCompressionType()); } @Test @@ -112,7 +112,7 @@ public void testAnalyzeFileFormatPropertiesSkipLinesAsString() { Map properties = new HashMap<>(); properties.put(TextFileFormatProperties.PROP_SKIP_LINES, "abc"); - Assert.assertThrows(NumberFormatException.class, () -> { + Assertions.assertThrows(NumberFormatException.class, () -> { textFileFormatProperties.analyzeFileFormatProperties(properties, true); }); } @@ -123,7 +123,7 @@ public void testAnalyzeFileFormatPropertiesValidColumnSeparator() throws Analysi properties.put(TextFileFormatProperties.PROP_COLUMN_SEPARATOR, ";"); textFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals(";", textFileFormatProperties.getColumnSeparator()); + Assertions.assertEquals(";", textFileFormatProperties.getColumnSeparator()); } @Test @@ -139,6 +139,6 @@ public void testAnalyzeFileFormatPropertiesValidLineDelimiter() throws AnalysisE properties.put(TextFileFormatProperties.PROP_LINE_DELIMITER, "\r\n"); textFileFormatProperties.analyzeFileFormatProperties(properties, true); - Assert.assertEquals("\r\n", textFileFormatProperties.getLineDelimiter()); + Assertions.assertEquals("\r\n", textFileFormatProperties.getLineDelimiter()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/WalFileFormatPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/WalFileFormatPropertiesTest.java index d94b49aca978f4..ed9cc2fe8036d3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/WalFileFormatPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/property/fileformat/WalFileFormatPropertiesTest.java @@ -17,8 +17,8 @@ package org.apache.doris.datasource.property.fileformat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -27,7 +27,7 @@ public class WalFileFormatPropertiesTest { private WalFileFormatProperties walFileFormatProperties; - @Before + @BeforeEach public void setUp() { walFileFormatProperties = new WalFileFormatProperties(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileCacheAdmissionManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileCacheAdmissionManagerTest.java index b75cd880a2200f..4c5c6c7bb905ad 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileCacheAdmissionManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileCacheAdmissionManagerTest.java @@ -19,14 +19,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import org.junit.AfterClass; -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.AfterAll; +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.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; @@ -35,10 +36,10 @@ public class FileCacheAdmissionManagerTest { private FileCacheAdmissionManager manager; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + public Path tempFolder; - @Before + @BeforeEach public void setUp() { manager = new FileCacheAdmissionManager(); } @@ -47,16 +48,16 @@ public void setUp() { public void testEmptyUserIdentity() { AtomicReference reason = new AtomicReference<>(); boolean result = manager.isAdmittedAtTableLevel("", "catalog", "database", "table", reason); - Assert.assertFalse(result); - Assert.assertEquals("empty user_identity", reason.get()); + Assertions.assertFalse(result); + Assertions.assertEquals("empty user_identity", reason.get()); } @Test public void testInvalidUserIdentity() { AtomicReference reason = new AtomicReference<>(); boolean result = manager.isAdmittedAtTableLevel("123user", "catalog", "database", "table", reason); - Assert.assertFalse(result); - Assert.assertEquals("invalid user_identity", reason.get()); + Assertions.assertFalse(result); + Assertions.assertEquals("invalid user_identity", reason.get()); } @Test @@ -80,25 +81,25 @@ public void testCommonRule() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-common.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-common.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user", "catalog_1", "database", "table", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("common catalog-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("common catalog-level whitelist rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user", "catalog_2", "database_1", "table", reason2); - Assert.assertTrue(result2); - Assert.assertEquals("common database-level whitelist rule", reason2.get()); + Assertions.assertTrue(result2); + Assertions.assertEquals("common database-level whitelist rule", reason2.get()); AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user", "catalog_3", "database_2", "table_1", reason3); - Assert.assertTrue(result3); - Assert.assertEquals("common table-level whitelist rule", reason3.get()); + Assertions.assertTrue(result3); + Assertions.assertEquals("common table-level whitelist rule", reason3.get()); } @Test @@ -122,25 +123,25 @@ public void testRuleEnabled() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-enabled.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-enabled.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user", "catalog_1", "database", "table", reason1); - Assert.assertFalse(result1); - Assert.assertEquals("default rule", reason1.get()); + Assertions.assertFalse(result1); + Assertions.assertEquals("default rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user", "catalog_2", "database_1", "table", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("default rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("default rule", reason2.get()); AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user", "catalog_3", "database_2", "table_1", reason3); - Assert.assertFalse(result3); - Assert.assertEquals("default rule", reason3.get()); + Assertions.assertFalse(result3); + Assertions.assertEquals("default rule", reason3.get()); } @Test @@ -164,37 +165,37 @@ public void testUserRule() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-user.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-user.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_1", "catalog_4", "database", "table", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("user catalog-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("user catalog-level whitelist rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_2", "catalog_4", "database", "table", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("default rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("default rule", reason2.get()); AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_1", "catalog_5", "database_4", "table", reason3); - Assert.assertTrue(result3); - Assert.assertEquals("user database-level whitelist rule", reason3.get()); + Assertions.assertTrue(result3); + Assertions.assertEquals("user database-level whitelist rule", reason3.get()); AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_2", "catalog_5", "database_4", "table", reason4); - Assert.assertFalse(result4); - Assert.assertEquals("default rule", reason4.get()); + Assertions.assertFalse(result4); + Assertions.assertEquals("default rule", reason4.get()); AtomicReference reason5 = new AtomicReference<>(); boolean result5 = manager.isAdmittedAtTableLevel("user_1", "catalog_6", "database_5", "table_4", reason5); - Assert.assertTrue(result5); - Assert.assertEquals("user table-level whitelist rule", reason5.get()); + Assertions.assertTrue(result5); + Assertions.assertEquals("user table-level whitelist rule", reason5.get()); AtomicReference reason6 = new AtomicReference<>(); boolean result6 = manager.isAdmittedAtTableLevel("user_2", "catalog_6", "database_5", "table_4", reason6); - Assert.assertFalse(result6); - Assert.assertEquals("default rule", reason6.get()); + Assertions.assertFalse(result6); + Assertions.assertEquals("default rule", reason6.get()); } @Test @@ -210,15 +211,15 @@ public void testRuleLevelPriority() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-priority.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-priority.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_3", "catalog", "database", "table", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("user global-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("user global-level whitelist rule", reason1.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 8L, "user_3", "catalog", "", "", "", @@ -231,8 +232,8 @@ public void testRuleLevelPriority() throws Exception { AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_3", "catalog", "database", "table", reason2); - Assert.assertTrue(result2); - Assert.assertEquals("user catalog-level whitelist rule", reason2.get()); + Assertions.assertTrue(result2); + Assertions.assertEquals("user catalog-level whitelist rule", reason2.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 9L, "user_3", "catalog", "database", "", "", @@ -245,8 +246,8 @@ public void testRuleLevelPriority() throws Exception { AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_3", "catalog", "database", "table", reason3); - Assert.assertTrue(result3); - Assert.assertEquals("user database-level whitelist rule", reason3.get()); + Assertions.assertTrue(result3); + Assertions.assertEquals("user database-level whitelist rule", reason3.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 10L, "user_3", "catalog", "database", "table", "", @@ -259,8 +260,8 @@ public void testRuleLevelPriority() throws Exception { AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_3", "catalog", "database", "table", reason4); - Assert.assertTrue(result4); - Assert.assertEquals("user table-level whitelist rule", reason4.get()); + Assertions.assertTrue(result4); + Assertions.assertEquals("user table-level whitelist rule", reason4.get()); } @Test @@ -280,15 +281,15 @@ public void testRuleTypePriority() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-type-priority.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-type-priority.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_4", "catalog", "database", "table", reason1); - Assert.assertFalse(result1); - Assert.assertEquals("user global-level blacklist rule", reason1.get()); + Assertions.assertFalse(result1); + Assertions.assertEquals("user global-level blacklist rule", reason1.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 13L, "user_4", "catalog", "", "", "", @@ -305,8 +306,8 @@ public void testRuleTypePriority() throws Exception { AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_4", "catalog", "database", "table", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("user catalog-level blacklist rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("user catalog-level blacklist rule", reason2.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 15L, "user_4", "catalog", "database", "", "", @@ -323,8 +324,8 @@ public void testRuleTypePriority() throws Exception { AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_4", "catalog", "database", "table", reason3); - Assert.assertFalse(result3); - Assert.assertEquals("user database-level blacklist rule", reason3.get()); + Assertions.assertFalse(result3); + Assertions.assertEquals("user database-level blacklist rule", reason3.get()); rules.add(new FileCacheAdmissionManager.AdmissionRule( 17L, "user_4", "catalog", "database", "table", "", @@ -341,8 +342,8 @@ public void testRuleTypePriority() throws Exception { AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_4", "catalog", "database", "table", reason4); - Assert.assertFalse(result4); - Assert.assertEquals("user table-level blacklist rule", reason4.get()); + Assertions.assertFalse(result4); + Assertions.assertEquals("user table-level blacklist rule", reason4.get()); } @Test @@ -389,49 +390,49 @@ public void testNestedRulePriorities() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); - File jsonFile = tempFolder.newFile("rules-test-nested.json"); + File jsonFile = Files.createFile(tempFolder.resolve("rules-test-nested.json")).toFile(); objectMapper.writeValue(jsonFile, rules); manager.loadRules(jsonFile.getAbsolutePath()); AtomicReference reason1 = new AtomicReference<>(); boolean result1 = manager.isAdmittedAtTableLevel("user_5", "catalog", "database", "table", reason1); - Assert.assertTrue(result1); - Assert.assertEquals("user database-level whitelist rule", reason1.get()); + Assertions.assertTrue(result1); + Assertions.assertEquals("user database-level whitelist rule", reason1.get()); AtomicReference reason2 = new AtomicReference<>(); boolean result2 = manager.isAdmittedAtTableLevel("user_5", "catalog", "otherDatabase", "table", reason2); - Assert.assertFalse(result2); - Assert.assertEquals("user catalog-level blacklist rule", reason2.get()); + Assertions.assertFalse(result2); + Assertions.assertEquals("user catalog-level blacklist rule", reason2.get()); AtomicReference reason3 = new AtomicReference<>(); boolean result3 = manager.isAdmittedAtTableLevel("user_6", "catalog", "database", "table", reason3); - Assert.assertFalse(result3); - Assert.assertEquals("user database-level blacklist rule", reason3.get()); + Assertions.assertFalse(result3); + Assertions.assertEquals("user database-level blacklist rule", reason3.get()); AtomicReference reason4 = new AtomicReference<>(); boolean result4 = manager.isAdmittedAtTableLevel("user_6", "catalog", "otherDatabase", "table", reason4); - Assert.assertTrue(result4); - Assert.assertEquals("user catalog-level whitelist rule", reason4.get()); + Assertions.assertTrue(result4); + Assertions.assertEquals("user catalog-level whitelist rule", reason4.get()); AtomicReference reason5 = new AtomicReference<>(); boolean result5 = manager.isAdmittedAtTableLevel("user_7", "catalog", "database", "table", reason5); - Assert.assertTrue(result5); - Assert.assertEquals("user table-level whitelist rule", reason5.get()); + Assertions.assertTrue(result5); + Assertions.assertEquals("user table-level whitelist rule", reason5.get()); AtomicReference reason6 = new AtomicReference<>(); boolean result6 = manager.isAdmittedAtTableLevel("user_7", "catalog", "database", "otherTable", reason6); - Assert.assertFalse(result6); - Assert.assertEquals("user database-level blacklist rule", reason6.get()); + Assertions.assertFalse(result6); + Assertions.assertEquals("user database-level blacklist rule", reason6.get()); AtomicReference reason7 = new AtomicReference<>(); boolean result7 = manager.isAdmittedAtTableLevel("user_8", "catalog", "database", "table", reason7); - Assert.assertFalse(result7); - Assert.assertEquals("user table-level blacklist rule", reason7.get()); + Assertions.assertFalse(result7); + Assertions.assertEquals("user table-level blacklist rule", reason7.get()); AtomicReference reason8 = new AtomicReference<>(); boolean result8 = manager.isAdmittedAtTableLevel("user_8", "catalog", "database", "otherTable", reason8); - Assert.assertTrue(result8); - Assert.assertEquals("user database-level whitelist rule", reason8.get()); + Assertions.assertTrue(result8); + Assertions.assertEquals("user database-level whitelist rule", reason8.get()); } - @AfterClass + @AfterAll public static void deleteJsonFile() throws Exception { } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileQueryScanNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileQueryScanNodeTest.java index 8d06c56459f288..5f608d7349785f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileQueryScanNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/FileQueryScanNodeTest.java @@ -42,9 +42,9 @@ import org.apache.doris.thrift.TFileScanRangeParams; import org.apache.doris.thrift.TFileScanSlotInfo; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Method; @@ -109,7 +109,7 @@ protected Map getLocationProperties() throws UserException { } } - @Before + @BeforeEach public void setUp() { table = Mockito.mock(TableIf.class); Mockito.when(table.getName()).thenReturn("test_table"); @@ -121,7 +121,7 @@ public void testApplyMaxFileSplitNumLimitRaisesTargetSize() { sv.setMaxFileSplitNum(100); TestFileQueryScanNode node = new TestFileQueryScanNode(sv); long target = node.applyMaxFileSplitNumLimit(32 * MB, 10_000L * MB); - Assert.assertEquals(100 * MB, target); + Assertions.assertEquals(100 * MB, target); } @Test @@ -130,7 +130,7 @@ public void testApplyMaxFileSplitNumLimitKeepsTargetSizeWhenSmall() { sv.setMaxFileSplitNum(100); TestFileQueryScanNode node = new TestFileQueryScanNode(sv); long target = node.applyMaxFileSplitNumLimit(32 * MB, 500L * MB); - Assert.assertEquals(32 * MB, target); + Assertions.assertEquals(32 * MB, target); } @Test @@ -139,7 +139,7 @@ public void testApplyMaxFileSplitNumLimitDisabled() { sv.setMaxFileSplitNum(0); TestFileQueryScanNode node = new TestFileQueryScanNode(sv); long target = node.applyMaxFileSplitNumLimit(32 * MB, 10_000L * MB); - Assert.assertEquals(32 * MB, target); + Assertions.assertEquals(32 * MB, target); } @Test @@ -156,8 +156,8 @@ public void testHiveParquetTimezoneOverridesDifferentSessionTimezoneInScanParams node.initSchemaParamsForTest(); - Assert.assertEquals("+08:00", node.getFileScanRangeParams().getHiveParquetTimeZone()); - Assert.assertNotEquals(sessionVariable.getTimeZone(), + Assertions.assertEquals("+08:00", node.getFileScanRangeParams().getHiveParquetTimeZone()); + Assertions.assertNotEquals(sessionVariable.getTimeZone(), node.getFileScanRangeParams().getHiveParquetTimeZone()); SessionVariable differentSessionVariable = new SessionVariable(); @@ -167,7 +167,7 @@ public void testHiveParquetTimezoneOverridesDifferentSessionTimezoneInScanParams nodeWithDifferentSession.getTupleDescriptor().setTable(hmsTable); nodeWithDifferentSession.initSchemaParamsForTest(); - Assert.assertEquals(node.getFileScanRangeParams().getHiveParquetTimeZone(), + Assertions.assertEquals(node.getFileScanRangeParams().getHiveParquetTimeZone(), nodeWithDifferentSession.getFileScanRangeParams().getHiveParquetTimeZone()); } @@ -183,7 +183,7 @@ public void testHiveParquetTimezoneIsNotSetForHmsIcebergTable() throws Exception node.getTupleDescriptor().setTable(hmsTable); node.initSchemaParamsForTest(); - Assert.assertFalse(node.getFileScanRangeParams().isSetHiveParquetTimeZone()); + Assertions.assertFalse(node.getFileScanRangeParams().isSetHiveParquetTimeZone()); } @Test @@ -198,7 +198,7 @@ public void testHiveParquetTimezoneIsSetForHmsHudiTable() throws Exception { node.getTupleDescriptor().setTable(hmsTable); node.initSchemaParamsForTest(); - Assert.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); + Assertions.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); } @Test @@ -216,7 +216,7 @@ public void testHiveParquetTimezoneComesFromTableValuedFunction() throws Excepti node.getTupleDescriptor().setTable(functionGenTable); node.initSchemaParamsForTest(); - Assert.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); + Assertions.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); } @Test @@ -243,7 +243,7 @@ public void testHiveParquetTimezoneComesFromFileTableValuedFunctionDelegate() th node.getTupleDescriptor().setTable(functionGenTable); node.initSchemaParamsForTest(); - Assert.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); + Assertions.assertEquals("Asia/Shanghai", node.getFileScanRangeParams().getHiveParquetTimeZone()); } finally { FeConstants.runningUnitTest = originalRunningUnitTest; } @@ -261,7 +261,7 @@ public void testHiveParquetTimezoneIgnoresPluginDrivenQueryTableValuedFunction() node.initSchemaParamsForTest(); - Assert.assertFalse(node.getFileScanRangeParams().isSetHiveParquetTimeZone()); + Assertions.assertFalse(node.getFileScanRangeParams().isSetHiveParquetTimeZone()); } @Test @@ -292,9 +292,9 @@ public void testUpdateRequiredSlotsPreservesInlineDefaultValueExpr() throws Exce UPDATE_REQUIRED_SLOTS_METHOD.invoke(node); TFileScanSlotInfo updatedSlotInfo = node.params.getRequiredSlots().get(0); - Assert.assertSame(slotInfo, updatedSlotInfo); - Assert.assertTrue(updatedSlotInfo.isSetDefaultValueExpr()); - Assert.assertSame(defaultExpr, updatedSlotInfo.getDefaultValueExpr()); + Assertions.assertSame(slotInfo, updatedSlotInfo); + Assertions.assertTrue(updatedSlotInfo.isSetDefaultValueExpr()); + Assertions.assertSame(defaultExpr, updatedSlotInfo.getDefaultValueExpr()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/PluginDrivenScanNodeCompatibilityTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/PluginDrivenScanNodeCompatibilityTest.java index 99344fa4760cdc..340a6128bdc6c9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/PluginDrivenScanNodeCompatibilityTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/scan/PluginDrivenScanNodeCompatibilityTest.java @@ -44,8 +44,8 @@ import org.apache.doris.thrift.TFileScanRangeParams; import org.apache.doris.thrift.TPushAggOp; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -110,10 +110,10 @@ public void computeVariantRejectsSmoothUpgradeSourceBackend() { Backend backend = new Backend(7L, "127.0.0.1", 9050); backend.setSmoothUpgradeSrc(true); - UserException exception = Assert.assertThrows(UserException.class, + UserException exception = Assertions.assertThrows(UserException.class, () -> PluginDrivenScanNode.checkVariantBackendCompatibility( true, Collections.singletonList(backend))); - Assert.assertTrue(exception.getMessage().contains("backend 7")); + Assertions.assertTrue(exception.getMessage().contains("backend 7")); } @Test @@ -132,10 +132,10 @@ public void computeVariantRejectsOldQueryWideExecutionVersion() { Config.be_exec_version = VARIANT_EXEC_VERSION - 1; Backend backend = new Backend(8L, "127.0.0.1", 9050); - UserException exception = Assert.assertThrows(UserException.class, + UserException exception = Assertions.assertThrows(UserException.class, () -> PluginDrivenScanNode.checkVariantBackendCompatibility( true, Collections.singletonList(backend))); - Assert.assertTrue(exception.getMessage().contains("execution version")); + Assertions.assertTrue(exception.getMessage().contains("execution version")); } finally { Config.be_exec_version = original; } @@ -155,8 +155,8 @@ public void translatedScanTuplePreservesNestedComputeVariantCarrier() { TupleDescriptor tuple = context.generateTupleDesc(); context.createSlotDesc(tuple, slot); - Assert.assertTrue(PluginDrivenScanNode.projectsComputeVariant(tuple)); - Assert.assertTrue(tuple.getSlots().get(0).getType().toThrift() + Assertions.assertTrue(PluginDrivenScanNode.projectsComputeVariant(tuple)); + Assertions.assertTrue(tuple.getSlots().get(0).getType().toThrift() .types.get(1).scalar_type.variant_is_v2); } finally { Config.enable_variant_v2 = originalEnableVariantV2; @@ -192,7 +192,7 @@ public Map getProperties() { true, true, Collections.singletonList(countRange)), backends); - Assert.assertThrows(UserException.class, + Assertions.assertThrows(UserException.class, () -> PluginDrivenScanNode.checkVariantBackendCompatibility( PluginDrivenScanNode.plannedScanDecodesVariant( true, true, Arrays.asList(countRange, dataRange)), @@ -211,7 +211,7 @@ public void sampledMetadataCountDefersVariantFenceToPlannedRanges() throws UserE node.checkVariantBackendCompatibilityForCurrentScan(Collections.singletonList(oldBackend())); - Assert.assertTrue((Boolean) Deencapsulation.getField(node, "variantCompatibilityDeferred")); + Assertions.assertTrue((Boolean) Deencapsulation.getField(node, "variantCompatibilityDeferred")); } @Test @@ -231,7 +231,7 @@ public void metadataCountProviderCannotEnterPartitionBatchBeforeRangeProof() thr node.checkVariantBackendCompatibilityForCurrentScan(Collections.singletonList(oldBackend())); - Assert.assertFalse(node.isBatchMode()); + Assertions.assertFalse(node.isBatchMode()); } private static ConnectorScanPlanProvider metadataCountProvider() { diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/split/FileSplitterTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/split/FileSplitterTest.java index fcfd336b476665..ed356ea42119eb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/split/FileSplitterTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/split/FileSplitterTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.util.LocationPath; import org.apache.doris.spi.Split; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -46,12 +46,12 @@ public void testNonSplittableCompressedFileProducesSingleSplit() throws Exceptio true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); Split s = splits.get(0); - Assert.assertEquals(10 * MB, ((org.apache.doris.datasource.split.FileSplit) s).getLength()); + Assertions.assertEquals(10 * MB, ((org.apache.doris.datasource.split.FileSplit) s).getLength()); // host should be preserved - Assert.assertArrayEquals(new String[]{"h1"}, ((org.apache.doris.datasource.split.FileSplit) s).getHosts()); - Assert.assertEquals(DEFAULT_INITIAL_SPLITS - 1, fileSplitter.getRemainingInitialSplitNum()); + Assertions.assertArrayEquals(new String[]{"h1"}, ((org.apache.doris.datasource.split.FileSplit) s).getHosts()); + Assertions.assertEquals(DEFAULT_INITIAL_SPLITS - 1, fileSplitter.getRemainingInitialSplitNum()); } @Test @@ -68,12 +68,12 @@ public void testEmptyBlockLocationsProducesSingleSplitAndNullHosts() throws Exce true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); org.apache.doris.datasource.split.FileSplit s = (org.apache.doris.datasource.split.FileSplit) splits.get(0); - Assert.assertEquals(5 * MB, s.getLength()); + Assertions.assertEquals(5 * MB, s.getLength()); // hosts should be empty array when passing null - Assert.assertNotNull(s.getHosts()); - Assert.assertEquals(0, s.getHosts().length); + Assertions.assertNotNull(s.getHosts()); + Assertions.assertEquals(0, s.getHosts().length); } @Test @@ -95,18 +95,18 @@ public void testSplittableSingleBigBlockProducesExpectedSplitsWithInitialSmallCh // expect splits sizes: 32MB, 32MB, 64MB, 36MB, 36MB -> sum is 200MB long[] expected = new long[]{32 * MB, 32 * MB, 64 * MB, 36 * MB, 36 * MB}; - Assert.assertEquals(expected.length, splits.size()); + Assertions.assertEquals(expected.length, splits.size()); long sum = 0L; for (int i = 0; i < expected.length; i++) { org.apache.doris.datasource.split.FileSplit s = (org.apache.doris.datasource.split.FileSplit) splits.get(i); - Assert.assertEquals(expected[i], s.getLength()); + Assertions.assertEquals(expected[i], s.getLength()); sum += s.getLength(); // ensure host preserved - Assert.assertArrayEquals(new String[]{"h1"}, s.getHosts()); + Assertions.assertArrayEquals(new String[]{"h1"}, s.getHosts()); } - Assert.assertEquals(length, sum); + Assertions.assertEquals(length, sum); // ensure the initial small-split counter is consumed for the two initial small splits - Assert.assertEquals(0, fileSplitter.getRemainingInitialSplitNum()); + Assertions.assertEquals(0, fileSplitter.getRemainingInitialSplitNum()); } @Test @@ -131,17 +131,17 @@ public void testNullBlockLocationsSplitLikeOneWholeFileBlock() throws Exception FileSplit.FileSplitCreator.DEFAULT); long[] expected = new long[]{32 * MB, 32 * MB, 64 * MB, 36 * MB, 36 * MB}; - Assert.assertEquals(expected.length, splits.size()); + Assertions.assertEquals(expected.length, splits.size()); long sum = 0L; for (int i = 0; i < expected.length; i++) { FileSplit s = (FileSplit) splits.get(i); - Assert.assertEquals(expected[i], s.getLength()); + Assertions.assertEquals(expected[i], s.getLength()); sum += s.getLength(); // No locality information is available, so no split may claim a host. - Assert.assertNotNull(s.getHosts()); - Assert.assertEquals(0, s.getHosts().length); + Assertions.assertNotNull(s.getHosts()); + Assertions.assertEquals(0, s.getHosts().length); } - Assert.assertEquals(length, sum); + Assertions.assertEquals(length, sum); } @Test @@ -162,13 +162,13 @@ public void testMultiBlockSplitsAndHostPreservation() throws Exception { true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(2, splits.size()); + Assertions.assertEquals(2, splits.size()); FileSplit s0 = (FileSplit) splits.get(0); FileSplit s1 = (FileSplit) splits.get(1); - Assert.assertEquals(48 * MB, s0.getLength()); - Assert.assertEquals(48 * MB, s1.getLength()); - Assert.assertArrayEquals(new String[]{"h1"}, s0.getHosts()); - Assert.assertArrayEquals(new String[]{"h2"}, s1.getHosts()); + Assertions.assertEquals(48 * MB, s0.getLength()); + Assertions.assertEquals(48 * MB, s1.getLength()); + Assertions.assertArrayEquals(new String[]{"h1"}, s0.getHosts()); + Assertions.assertArrayEquals(new String[]{"h2"}, s1.getHosts()); } @Test @@ -189,10 +189,10 @@ public void testZeroLengthBlockIsSkipped() throws Exception { true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); FileSplit s = (FileSplit) splits.get(0); - Assert.assertEquals(10 * MB, s.getLength()); - Assert.assertArrayEquals(new String[]{"h1"}, s.getHosts()); + Assertions.assertEquals(10 * MB, s.getLength()); + Assertions.assertArrayEquals(new String[]{"h1"}, s.getHosts()); } @Test @@ -209,7 +209,7 @@ public void testNonSplittableFlagDecrementsCounter() throws Exception { false, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); } @Test @@ -226,7 +226,7 @@ public void testNullRemainingInitialSplitIsAllowed() throws Exception { true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); } @Test @@ -238,19 +238,19 @@ public void testZeroLengthFileProducesNoSplits() throws Exception { List splits = fileSplitter.splitFile( loc, 0L, locations, 0L, 0L, false, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertTrue("Zero-length file should produce no splits", splits.isEmpty()); + Assertions.assertTrue(splits.isEmpty(), "Zero-length file should produce no splits"); // Splittable zero-length file splits = fileSplitter.splitFile( loc, 0L, locations, 0L, 0L, true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertTrue("Zero-length splittable file should produce no splits", splits.isEmpty()); + Assertions.assertTrue(splits.isEmpty(), "Zero-length splittable file should produce no splits"); // Null block locations with zero-length file splits = fileSplitter.splitFile( loc, 0L, null, 0L, 0L, true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertTrue("Zero-length file with null locations should produce no splits", splits.isEmpty()); + Assertions.assertTrue(splits.isEmpty(), "Zero-length file with null locations should produce no splits"); // Counter should not be decremented for skipped zero-length files - Assert.assertEquals(DEFAULT_INITIAL_SPLITS, fileSplitter.getRemainingInitialSplitNum()); + Assertions.assertEquals(DEFAULT_INITIAL_SPLITS, fileSplitter.getRemainingInitialSplitNum()); } @Test @@ -267,8 +267,8 @@ public void testSmallFileNoSplit() throws Exception { true, Collections.emptyList(), FileSplit.FileSplitCreator.DEFAULT); - Assert.assertEquals(1, splits.size()); + Assertions.assertEquals(1, splits.size()); FileSplit s = (FileSplit) splits.get(0); - Assert.assertEquals(2 * MB, s.getLength()); + Assertions.assertEquals(2 * MB, s.getLength()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/systable/SysTableTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/systable/SysTableTest.java index c12c5742abf8ac..d61058df3345d5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/systable/SysTableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/systable/SysTableTest.java @@ -21,8 +21,8 @@ import org.apache.doris.info.TableValuedFunctionRefInfo; import org.apache.doris.nereids.trees.expressions.functions.table.TableValuedFunction; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SysTableTest { // Mock implementation of TvfSysTable for testing @@ -47,44 +47,44 @@ public TableValuedFunctionRefInfo createFunctionRef( @Test public void testBasicProperties() { MockTvfSysTable sysTable = new MockTvfSysTable("test_table", "test_tvf"); - Assert.assertEquals("test_table", sysTable.getSysTableName()); - Assert.assertEquals("$test_table", sysTable.getSuffix()); - Assert.assertEquals("test_tvf", sysTable.getTvfName()); - Assert.assertFalse(sysTable.useNativeTablePath()); + Assertions.assertEquals("test_table", sysTable.getSysTableName()); + Assertions.assertEquals("$test_table", sysTable.getSuffix()); + Assertions.assertEquals("test_tvf", sysTable.getTvfName()); + Assertions.assertFalse(sysTable.useNativeTablePath()); } @Test public void testGetSourceTableName() { MockTvfSysTable sysTable = new MockTvfSysTable("partitions", "partition_values"); - Assert.assertEquals("mytable", sysTable.getSourceTableName("mytable$partitions")); - Assert.assertEquals("complex_table", sysTable.getSourceTableName("complex_table$partitions")); - Assert.assertEquals("table$with$dollar", sysTable.getSourceTableName("table$with$dollar$partitions")); + Assertions.assertEquals("mytable", sysTable.getSourceTableName("mytable$partitions")); + Assertions.assertEquals("complex_table", sysTable.getSourceTableName("complex_table$partitions")); + Assertions.assertEquals("table$with$dollar", sysTable.getSourceTableName("table$with$dollar$partitions")); } @Test public void testGetTableNameWithSysTableName() { // Test normal case Pair result1 = SysTable.getTableNameWithSysTableName("table$partitions"); - Assert.assertEquals("table", result1.first); - Assert.assertEquals("partitions", result1.second); + Assertions.assertEquals("table", result1.first); + Assertions.assertEquals("partitions", result1.second); // Test with multiple $ symbols Pair result2 = SysTable.getTableNameWithSysTableName("table$with$dollar$partitions"); - Assert.assertEquals("table$with$dollar", result2.first); - Assert.assertEquals("partitions", result2.second); + Assertions.assertEquals("table$with$dollar", result2.first); + Assertions.assertEquals("partitions", result2.second); // Test edge cases Pair result3 = SysTable.getTableNameWithSysTableName("table"); - Assert.assertEquals("table", result3.first); - Assert.assertEquals("", result3.second); + Assertions.assertEquals("table", result3.first); + Assertions.assertEquals("", result3.second); Pair result4 = SysTable.getTableNameWithSysTableName("$"); - Assert.assertEquals("$", result4.first); - Assert.assertEquals("", result4.second); + Assertions.assertEquals("$", result4.first); + Assertions.assertEquals("", result4.second); Pair result5 = SysTable.getTableNameWithSysTableName(""); - Assert.assertEquals("", result5.first); - Assert.assertEquals("", result5.second); + Assertions.assertEquals("", result5.first); + Assertions.assertEquals("", result5.second); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/MetadataScanNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/MetadataScanNodeTest.java index 4381777cf66a95..c9bf0cf22d6942 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/MetadataScanNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/MetadataScanNodeTest.java @@ -27,13 +27,12 @@ import org.apache.doris.thrift.TMetadataType; import org.apache.doris.thrift.TScanRangeLocations; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import java.lang.reflect.Field; import java.util.List; @@ -41,7 +40,6 @@ /** * Test for MetadataScanNode, focusing on initedScanRangeLocations logic */ -@RunWith(MockitoJUnitRunner.class) public class MetadataScanNodeTest { @Mock @@ -53,8 +51,9 @@ public class MetadataScanNodeTest { private TupleDescriptor tupleDescriptor; private PlanNodeId planNodeId; - @Before + @BeforeEach public void setUp() { + MockitoAnnotations.openMocks(this); tupleDescriptor = new TupleDescriptor(new TupleId(1)); planNodeId = new PlanNodeId(1); } @@ -71,7 +70,7 @@ public void testInitedScanRangeLocationsInitialState() throws Exception { field.setAccessible(true); boolean initedValue = (Boolean) field.get(scanNode); - Assert.assertFalse("initedScanRangeLocations should be false initially", initedValue); + Assertions.assertFalse(initedValue, "initedScanRangeLocations should be false initially"); } /** @@ -100,18 +99,16 @@ public void testInitedScanRangeLocationsAfterFirstCall() throws Exception { Field field = MetadataScanNode.class.getDeclaredField("initedScanRangeLocations"); field.setAccessible(true); - Assert.assertFalse("initedScanRangeLocations should be false initially", - (Boolean) field.get(scanNode)); + Assertions.assertFalse((Boolean) field.get(scanNode), "initedScanRangeLocations should be false initially"); // Call getScanRangeLocations for the first time List locations = scanNode.getScanRangeLocations(1000); // Check that initedScanRangeLocations is now true - Assert.assertTrue("initedScanRangeLocations should be true after first call", - (Boolean) field.get(scanNode)); + Assertions.assertTrue((Boolean) field.get(scanNode), "initedScanRangeLocations should be true after first call"); // Verify we got some scan range locations - Assert.assertNotNull("Scan range locations should not be null", locations); + Assertions.assertNotNull(locations, "Scan range locations should not be null"); } /** @@ -138,10 +135,8 @@ public void testMultipleCallsToGetScanRangeLocations() throws Exception { List locations3 = scanNode.getScanRangeLocations(1000); // All calls should return the same cached result - Assert.assertEquals("Multiple calls should return same result", - locations1.size(), locations2.size()); - Assert.assertEquals("Multiple calls should return same result", - locations1.size(), locations3.size()); + Assertions.assertEquals(locations1.size(), locations2.size(), "Multiple calls should return same result"); + Assertions.assertEquals(locations1.size(), locations3.size(), "Multiple calls should return same result"); // Verify that getMetaScanRange was only called once (during first call) Mockito.verify(mockTvf, Mockito.times(1)).getMetaScanRange(Mockito.anyList()); diff --git a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java index 8e7cf7e99ddb11..83ab587f0266fc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/datasource/tvf/source/TVFScanNodeTest.java @@ -32,8 +32,8 @@ import org.apache.doris.thrift.TFileType; import org.apache.doris.thrift.TPushAggOp; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Method; @@ -65,7 +65,7 @@ public void testCountColumnKeepsNormalFileSplitting() throws Exception { countColumnNode.setPushDownCountSlotIds(Collections.singletonList(new SlotId(7))); List countColumnSplits = countColumnNode.getSplits(1); - Assert.assertEquals(8, countColumnSplits.size()); + Assertions.assertEquals(8, countColumnSplits.size()); TVFScanNode countStarNode = new TVFScanNode( new PlanNodeId(1), desc, false, sv, ScanContext.EMPTY); @@ -74,7 +74,7 @@ public void testCountColumnKeepsNormalFileSplitting() throws Exception { countStarNode.setPushDownCountSlotIds(Collections.emptyList()); List countStarSplits = countStarNode.getSplits(1); - Assert.assertEquals(2, countStarSplits.size()); + Assertions.assertEquals(2, countStarSplits.size()); } @Test @@ -95,7 +95,7 @@ public void testDetermineTargetFileSplitSizeHonorsMaxFileSplitNum() throws Excep Method method = TVFScanNode.class.getDeclaredMethod("determineTargetFileSplitSize", List.class); method.setAccessible(true); long target = (long) method.invoke(node, statuses); - Assert.assertEquals(100 * MB, target); + Assertions.assertEquals(100 * MB, target); } private static TBrokerFileStatus splittableFile(String path, long size) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/dictionary/DictionaryManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/dictionary/DictionaryManagerTest.java index 4fdb9a4ee38202..ae15318a5ace37 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/dictionary/DictionaryManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/dictionary/DictionaryManagerTest.java @@ -23,8 +23,8 @@ import org.apache.doris.persist.DropDictionaryPersistInfo; import org.apache.doris.persist.gson.GsonUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Tests for dictionary version journal replay robustness. @@ -72,7 +72,7 @@ public void testReplayDecreaseVersionAfterDrop() throws Exception { // journal order CREATE -> INC -> DROP -> DEC, DEC must be a no-op, not an exception manager.replayDecreaseVersion(new DictionaryDecreaseVersionInfo(dict)); - Assert.assertNull(manager.getDictionary(1001)); + Assertions.assertNull(manager.getDictionary(1001)); } @Test @@ -86,8 +86,8 @@ public void testReplayDecreaseVersionAbA() throws Exception { // DEC of the dropped dictionary must not affect the recreated same-name dictionary manager.replayDecreaseVersion(new DictionaryDecreaseVersionInfo(oldDict)); - Assert.assertEquals(1, newDict.getVersion()); - Assert.assertEquals(1, manager.getDictionary(1002).getVersion()); + Assertions.assertEquals(1, newDict.getVersion()); + Assertions.assertEquals(1, manager.getDictionary(1002).getVersion()); } @Test @@ -97,7 +97,7 @@ public void testReplayDecreaseVersionNormal() throws Exception { manager.replayCreateDictionary(new CreateDictionaryPersistInfo(dict)); manager.replayDecreaseVersion(new DictionaryDecreaseVersionInfo(dict)); - Assert.assertEquals(1, manager.getDictionary(1001).getVersion()); + Assertions.assertEquals(1, manager.getDictionary(1001).getVersion()); } @Test @@ -107,6 +107,6 @@ public void testReplayIncreaseVersionNormal() throws Exception { manager.replayCreateDictionary(new CreateDictionaryPersistInfo(dict)); manager.replayIncreaseVersion(new DictionaryIncreaseVersionInfo(dict)); - Assert.assertEquals(2, manager.getDictionary(1001).getVersion()); + Assertions.assertEquals(2, manager.getDictionary(1001).getVersion()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/fs/FileSystemCacheTest.java b/fe/fe-core/src/test/java/org/apache/doris/fs/FileSystemCacheTest.java index 21934f46069a65..20419c73f34cdb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/fs/FileSystemCacheTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/fs/FileSystemCacheTest.java @@ -19,8 +19,8 @@ import org.apache.doris.datasource.storage.StorageAdapter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.OptionalLong; @@ -39,20 +39,20 @@ public void testEvictedFileSystemClosesAfterLastLeaseIsReleased() { FileSystemCache.FileSystemCacheKey firstKey = key("hdfs://ns1"); FileSystemCache.FileSystemLease firstLease = cache.getFileSystem(firstKey); - Assert.assertSame(first, firstLease.fileSystem()); + Assertions.assertSame(first, firstLease.fileSystem()); FileSystemCache.FileSystemLease secondLease = cache.getFileSystem(key("hdfs://ns2")); cache.cleanUp(); - Assert.assertEquals(0, first.getCloseCount()); - Assert.assertEquals(0, second.getCloseCount()); + Assertions.assertEquals(0, first.getCloseCount()); + Assertions.assertEquals(0, second.getCloseCount()); firstLease.close(); - Assert.assertEquals(1, first.getCloseCount()); - Assert.assertEquals(0, second.getCloseCount()); + Assertions.assertEquals(1, first.getCloseCount()); + Assertions.assertEquals(0, second.getCloseCount()); secondLease.close(); - Assert.assertEquals(0, second.getCloseCount()); + Assertions.assertEquals(0, second.getCloseCount()); } @Test @@ -61,11 +61,11 @@ public void testUncachedFileSystemClosesWhenLeaseIsReleased() { FileSystemCache cache = new FileSystemCache(0L, OptionalLong.empty(), key -> fileSystem); FileSystemCache.FileSystemLease lease = cache.getFileSystem(key("hdfs://ns1")); - Assert.assertSame(fileSystem, lease.fileSystem()); - Assert.assertEquals(0, fileSystem.getCloseCount()); + Assertions.assertSame(fileSystem, lease.fileSystem()); + Assertions.assertEquals(0, fileSystem.getCloseCount()); lease.close(); - Assert.assertEquals(1, fileSystem.getCloseCount()); + Assertions.assertEquals(1, fileSystem.getCloseCount()); } @Test @@ -78,7 +78,7 @@ public void testLeaseCloseIsConcurrentIdempotent() throws InterruptedException { cache.cleanUp(); closeConcurrently(lease); - Assert.assertEquals(1, fileSystem.getCloseCount()); + Assertions.assertEquals(1, fileSystem.getCloseCount()); evictingLease.close(); } @@ -90,7 +90,7 @@ public void testUncachedLeaseCloseIsConcurrentIdempotent() throws InterruptedExc closeConcurrently(cache.getFileSystem(key("hdfs://ns1"))); - Assert.assertEquals(1, fileSystem.getCloseCount()); + Assertions.assertEquals(1, fileSystem.getCloseCount()); } private static void closeConcurrently(FileSystemCache.FileSystemLease lease) throws InterruptedException { diff --git a/fe/fe-core/src/test/java/org/apache/doris/fs/MemoryFileSystemTest.java b/fe/fe-core/src/test/java/org/apache/doris/fs/MemoryFileSystemTest.java index 05e9c30fe6cbe2..10267dba51befe 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/fs/MemoryFileSystemTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/fs/MemoryFileSystemTest.java @@ -21,9 +21,9 @@ import org.apache.doris.filesystem.FileIterator; import org.apache.doris.filesystem.Location; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.OutputStream; @@ -36,7 +36,7 @@ public class MemoryFileSystemTest { private MemoryFileSystem fs; - @Before + @BeforeEach public void setUp() { fs = new MemoryFileSystem(); } @@ -45,20 +45,20 @@ public void setUp() { @Test public void testExistsReturnsFalseForMissingFile() throws IOException { - Assert.assertFalse(fs.exists(Location.of("memory://bucket/missing.txt"))); + Assertions.assertFalse(fs.exists(Location.of("memory://bucket/missing.txt"))); } @Test public void testExistsReturnsTrueAfterPut() throws IOException { Location loc = Location.of("memory://bucket/file.txt"); fs.put(loc, "hello".getBytes(StandardCharsets.UTF_8)); - Assert.assertTrue(fs.exists(loc)); + Assertions.assertTrue(fs.exists(loc)); } @Test public void testExistsReturnsTrueForDirectoryViaChild() throws IOException { fs.put(Location.of("memory://bucket/dir/child.txt"), new byte[0]); - Assert.assertTrue(fs.exists(Location.of("memory://bucket/dir"))); + Assertions.assertTrue(fs.exists(Location.of("memory://bucket/dir"))); } // ─────────────────────────── newOutputFile / newInputFile ─────────────────────────── @@ -73,7 +73,7 @@ public void testCreateAndRead() throws IOException { } byte[] stored = fs.get(loc); - Assert.assertArrayEquals(data, stored); + Assertions.assertArrayEquals(data, stored); } @Test @@ -84,10 +84,10 @@ public void testCreateFailsIfFileExists() throws IOException { try (OutputStream out = fs.newOutputFile(loc).create()) { out.write(1); } catch (IOException e) { - Assert.assertTrue(e.getMessage().contains("already exists")); + Assertions.assertTrue(e.getMessage().contains("already exists")); return; } - Assert.fail("Expected IOException for overwriting existing file via create()"); + Assertions.fail("Expected IOException for overwriting existing file via create()"); } @Test @@ -99,7 +99,7 @@ public void testCreateOrOverwriteReplacesExistingFile() throws IOException { out.write("new".getBytes(StandardCharsets.UTF_8)); } - Assert.assertArrayEquals("new".getBytes(StandardCharsets.UTF_8), fs.get(loc)); + Assertions.assertArrayEquals("new".getBytes(StandardCharsets.UTF_8), fs.get(loc)); } @Test @@ -108,7 +108,7 @@ public void testInputFileLength() throws IOException { byte[] data = new byte[42]; fs.put(loc, data); - Assert.assertEquals(42L, fs.newInputFile(loc).length()); + Assertions.assertEquals(42L, fs.newInputFile(loc).length()); } @Test @@ -116,7 +116,7 @@ public void testInputFileLengthHintSkipsLookup() throws IOException { Location loc = Location.of("memory://bucket/hinted.bin"); fs.put(loc, new byte[10]); - Assert.assertEquals(99L, fs.newInputFile(loc, 99L).length()); + Assertions.assertEquals(99L, fs.newInputFile(loc, 99L).length()); } @Test @@ -125,20 +125,20 @@ public void testInputFileExistsAndNotExists() throws IOException { Location absent = Location.of("memory://bucket/absent.txt"); fs.put(present, new byte[0]); - Assert.assertTrue(fs.newInputFile(present).exists()); - Assert.assertFalse(fs.newInputFile(absent).exists()); + Assertions.assertTrue(fs.newInputFile(present).exists()); + Assertions.assertFalse(fs.newInputFile(absent).exists()); } @Test public void testInputFileLocationRoundtrip() throws IOException { Location loc = Location.of("memory://bucket/path/file.txt"); - Assert.assertEquals(loc, fs.newInputFile(loc).location()); + Assertions.assertEquals(loc, fs.newInputFile(loc).location()); } @Test public void testOutputFileLocationRoundtrip() throws IOException { Location loc = Location.of("memory://bucket/path/out.txt"); - Assert.assertEquals(loc, fs.newOutputFile(loc).location()); + Assertions.assertEquals(loc, fs.newOutputFile(loc).location()); } // ─────────────────────────── deleteFile ─────────────────────────── @@ -148,16 +148,16 @@ public void testDeleteFile() throws IOException { Location loc = Location.of("memory://bucket/del.txt"); fs.put(loc, new byte[1]); fs.delete(loc, false); - Assert.assertFalse(fs.exists(loc)); + Assertions.assertFalse(fs.exists(loc)); } @Test public void testDeleteFileMissingThrows() { try { fs.delete(Location.of("memory://bucket/ghost.txt"), false); - Assert.fail("Expected IOException"); + Assertions.fail("Expected IOException"); } catch (IOException e) { - Assert.assertTrue(e.getMessage().contains("not found")); + Assertions.assertTrue(e.getMessage().contains("not found")); } } @@ -172,8 +172,8 @@ public void testRenameFile() throws IOException { fs.rename(src, dst); - Assert.assertFalse(fs.exists(src)); - Assert.assertArrayEquals(data, fs.get(dst)); + Assertions.assertFalse(fs.exists(src)); + Assertions.assertArrayEquals(data, fs.get(dst)); } @Test @@ -182,9 +182,9 @@ public void testRenameMissingSourceThrows() { fs.rename( Location.of("memory://bucket/missing.txt"), Location.of("memory://bucket/target.txt")); - Assert.fail("Expected IOException"); + Assertions.fail("Expected IOException"); } catch (IOException e) { - Assert.assertTrue(e.getMessage().contains("not found")); + Assertions.assertTrue(e.getMessage().contains("not found")); } } @@ -198,9 +198,9 @@ public void testDeleteDirectory() throws IOException { fs.delete(Location.of("memory://bucket/dirA"), true); - Assert.assertFalse(fs.exists(Location.of("memory://bucket/dirA/f1.txt"))); - Assert.assertFalse(fs.exists(Location.of("memory://bucket/dirA/f2.txt"))); - Assert.assertTrue(fs.exists(Location.of("memory://bucket/dirB/f3.txt"))); + Assertions.assertFalse(fs.exists(Location.of("memory://bucket/dirA/f1.txt"))); + Assertions.assertFalse(fs.exists(Location.of("memory://bucket/dirA/f2.txt"))); + Assertions.assertTrue(fs.exists(Location.of("memory://bucket/dirB/f3.txt"))); } // ─────────────────────────── createDirectory ─────────────────────────── @@ -209,7 +209,7 @@ public void testDeleteDirectory() throws IOException { public void testCreateDirectory() throws IOException { Location dir = Location.of("memory://bucket/newdir"); fs.mkdirs(dir); - Assert.assertTrue(fs.exists(dir)); + Assertions.assertTrue(fs.exists(dir)); } // ─────────────────────────── renameDirectory ─────────────────────────── @@ -223,10 +223,10 @@ public void testRenameDirectory() throws IOException { Location.of("memory://bucket/src"), Location.of("memory://bucket/dst")); - Assert.assertFalse(fs.exists(Location.of("memory://bucket/src/a.txt"))); - Assert.assertArrayEquals("a".getBytes(StandardCharsets.UTF_8), + Assertions.assertFalse(fs.exists(Location.of("memory://bucket/src/a.txt"))); + Assertions.assertArrayEquals("a".getBytes(StandardCharsets.UTF_8), fs.get(Location.of("memory://bucket/dst/a.txt"))); - Assert.assertArrayEquals("b".getBytes(StandardCharsets.UTF_8), + Assertions.assertArrayEquals("b".getBytes(StandardCharsets.UTF_8), fs.get(Location.of("memory://bucket/dst/b.txt"))); } @@ -236,9 +236,9 @@ public void testRenameMissingDirectoryThrows() { fs.rename( Location.of("memory://bucket/nosuchdir"), Location.of("memory://bucket/target")); - Assert.fail("Expected IOException"); + Assertions.fail("Expected IOException"); } catch (IOException e) { - Assert.assertTrue(e.getMessage().contains("not found")); + Assertions.assertTrue(e.getMessage().contains("not found")); } } @@ -259,12 +259,11 @@ public void testListFilesNonRecursive() throws IOException { names.add(e.name()); } } - Assert.assertTrue(names.contains("a.txt")); - Assert.assertTrue(names.contains("b.txt")); + Assertions.assertTrue(names.contains("a.txt")); + Assertions.assertTrue(names.contains("b.txt")); for (FileEntry e : entries) { if (e.isFile()) { - Assert.assertFalse("sub/c.txt must not appear at top level", - e.name().equals("c.txt")); + Assertions.assertFalse(e.name().equals("c.txt"), "sub/c.txt must not appear at top level"); } } } @@ -283,23 +282,23 @@ public void testListFilesRecursive() throws IOException { fileNames.add(e.name()); } } - Assert.assertTrue(fileNames.contains("a.txt")); - Assert.assertTrue(fileNames.contains("b.txt")); - Assert.assertTrue(fileNames.contains("c.txt")); + Assertions.assertTrue(fileNames.contains("a.txt")); + Assertions.assertTrue(fileNames.contains("b.txt")); + Assertions.assertTrue(fileNames.contains("c.txt")); } @Test public void testListFilesEmptyDirectory() throws IOException { fs.mkdirs(Location.of("memory://bucket/empty")); List entries = drain(fs.list(Location.of("memory://bucket/empty"))); - Assert.assertTrue(entries.isEmpty()); + Assertions.assertTrue(entries.isEmpty()); } @Test public void testListFilesCloseable() throws IOException { fs.put(Location.of("memory://bucket/closeable/x.txt"), new byte[0]); try (FileIterator it = fs.list(Location.of("memory://bucket/closeable"))) { - Assert.assertTrue(it.hasNext()); + Assertions.assertTrue(it.hasNext()); } // no exception on close } @@ -313,7 +312,7 @@ public void testListDirectories() throws IOException { Set dirs = fs.listDirectories(Location.of("memory://bucket/parent")); - Assert.assertEquals(2, dirs.size()); + Assertions.assertEquals(2, dirs.size()); boolean hasA = false; boolean hasB = false; for (String d : dirs) { @@ -324,15 +323,15 @@ public void testListDirectories() throws IOException { hasB = true; } } - Assert.assertTrue(hasA); - Assert.assertTrue(hasB); + Assertions.assertTrue(hasA); + Assertions.assertTrue(hasB); } @Test public void testListDirectoriesEmptyParent() throws IOException { fs.mkdirs(Location.of("memory://bucket/leafdir")); Set dirs = fs.listDirectories(Location.of("memory://bucket/leafdir")); - Assert.assertTrue(dirs.isEmpty()); + Assertions.assertTrue(dirs.isEmpty()); } // ─────────────────────────── deleteFiles (default batch) ─────────────────────────── @@ -349,8 +348,8 @@ public void testDeleteFilesMultiple() throws IOException { toDelete.add(b); fs.deleteFiles(toDelete); - Assert.assertFalse(fs.exists(a)); - Assert.assertFalse(fs.exists(b)); + Assertions.assertFalse(fs.exists(a)); + Assertions.assertFalse(fs.exists(b)); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/fs/SpiSwitchingFileSystemTest.java b/fe/fe-core/src/test/java/org/apache/doris/fs/SpiSwitchingFileSystemTest.java index 750f2f1d1ef032..dda45dbe03bed2 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/fs/SpiSwitchingFileSystemTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/fs/SpiSwitchingFileSystemTest.java @@ -28,8 +28,8 @@ import org.apache.doris.filesystem.Location; import org.apache.doris.filesystem.properties.FileSystemProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -88,12 +88,12 @@ public void testForPathPropagatesIOExceptionNotRuntimeException() { SpiSwitchingFileSystem spiFs = new SpiSwitchingFileSystem(Collections.emptyMap()); try { spiFs.forPath("broker://host/path"); - Assert.fail("Expected IOException but no exception was thrown"); + Assertions.fail("Expected IOException but no exception was thrown"); } catch (IOException e) { // Correct: IOException propagated as-is. - Assert.assertSame("forPath() must rethrow the original IOException", rootCause, e); + Assertions.assertSame(rootCause, e, "forPath() must rethrow the original IOException"); } catch (RuntimeException e) { - Assert.fail("forPath() wrapped IOException in RuntimeException: " + Assertions.fail("forPath() wrapped IOException in RuntimeException: " + e.getClass().getName()); } } @@ -107,7 +107,7 @@ public void testForPathPropagatesIOExceptionNotRuntimeException() { public void testForPathWithTestDelegateBypasses() throws IOException { SpiSwitchingFileSystem spiFs = new SpiSwitchingFileSystem(mockDelegate); FileSystem result = spiFs.forPath("s3://bucket/key"); - Assert.assertSame("Test-delegate constructor must return the injected delegate", mockDelegate, result); + Assertions.assertSame(mockDelegate, result, "Test-delegate constructor must return the injected delegate"); } // ----------------------------------------------------------------------- @@ -145,7 +145,7 @@ public void close() throws IOException { spiFs.close(); - Assert.assertEquals("close() must have been called once per cached FileSystem", 2, closeCount.get()); + Assertions.assertEquals(2, closeCount.get(), "close() must have been called once per cached FileSystem"); } /** @@ -168,7 +168,7 @@ public void close() throws IOException { spiFs.close(); // first close — should close the cached FS spiFs.close(); // second close — must be a no-op - Assert.assertEquals("second close() must not close FileSystems again", 1, closeCount.get()); + Assertions.assertEquals(1, closeCount.get(), "second close() must not close FileSystems again"); } /** @@ -201,20 +201,18 @@ public void close() throws IOException { try { spiFs.close(); - Assert.fail("Expected IOException from close()"); + Assertions.fail("Expected IOException from close()"); } catch (IOException thrown) { // The thrown exception must be one of the two, and the other must be suppressed. boolean firstIsThrown = thrown == ex1; boolean secondIsThrown = thrown == ex2; - Assert.assertTrue("Thrown exception must be one of the two IOExceptions", - firstIsThrown || secondIsThrown); - Assert.assertEquals("Exactly one exception must be suppressed", 1, - thrown.getSuppressed().length); + Assertions.assertTrue(firstIsThrown || secondIsThrown, "Thrown exception must be one of the two IOExceptions"); + Assertions.assertEquals(1, thrown.getSuppressed().length, "Exactly one exception must be suppressed"); Throwable suppressed = thrown.getSuppressed()[0]; if (firstIsThrown) { - Assert.assertSame("Second exception must be suppressed", ex2, suppressed); + Assertions.assertSame(ex2, suppressed, "Second exception must be suppressed"); } else { - Assert.assertSame("First exception must be suppressed", ex1, suppressed); + Assertions.assertSame(ex1, suppressed, "First exception must be suppressed"); } } } @@ -257,30 +255,30 @@ public void testCompatFallbackTranslatesUrisBothWays() throws Exception { // Inbound: single-location operations are translated to the native scheme. spiFs.exists(Location.of("cos://bucket/dir/file1")); - Assert.assertEquals("s3://bucket/dir/file1", fake.lastUri); + Assertions.assertEquals("s3://bucket/dir/file1", fake.lastUri); // Inbound: rename translates both endpoints. spiFs.rename(Location.of("cos://bucket/dir/a"), Location.of("cos://bucket/dir/b")); - Assert.assertEquals("s3://bucket/dir/a", fake.lastRenameSrc); - Assert.assertEquals("s3://bucket/dir/b", fake.lastRenameDst); + Assertions.assertEquals("s3://bucket/dir/a", fake.lastRenameSrc); + Assertions.assertEquals("s3://bucket/dir/b", fake.lastRenameDst); // Outbound: listing results are translated back to the caller's scheme. fake.entries = List.of( new FileEntry(Location.of("s3://bucket/dir/f1"), 1, false, 0, null), new FileEntry(Location.of("s3://bucket/dir/sub/"), 0, true, 0, null)); List files = spiFs.listFiles(Location.of("cos://bucket/dir")); - Assert.assertEquals("s3://bucket/dir", fake.lastUri); - Assert.assertEquals(1, files.size()); - Assert.assertEquals("cos://bucket/dir/f1", files.get(0).location().uri()); + Assertions.assertEquals("s3://bucket/dir", fake.lastUri); + Assertions.assertEquals(1, files.size()); + Assertions.assertEquals("cos://bucket/dir/f1", files.get(0).location().uri()); Set dirs = spiFs.listDirectories(Location.of("cos://bucket/dir")); - Assert.assertEquals(Collections.singleton("cos://bucket/dir/sub/"), dirs); + Assertions.assertEquals(Collections.singleton("cos://bucket/dir/sub/"), dirs); // Outbound: newInputFile reports the caller's location, while the delegate // was opened with the native scheme. DorisInputFile inputFile = spiFs.newInputFile(Location.of("cos://bucket/dir/f1")); - Assert.assertEquals("s3://bucket/dir/f1", fake.lastUri); - Assert.assertEquals("cos://bucket/dir/f1", inputFile.location().uri()); + Assertions.assertEquals("s3://bucket/dir/f1", fake.lastUri); + Assertions.assertEquals("cos://bucket/dir/f1", inputFile.location().uri()); } } @@ -312,7 +310,7 @@ public void testDirectMatchSkipsTranslation() throws Exception { SpiSwitchingFileSystem spiFs = new SpiSwitchingFileSystem(Collections.emptyMap()); spiFs.exists(Location.of("cos://bucket/dir/file1")); - Assert.assertEquals("cos://bucket/dir/file1", fake.lastUri); + Assertions.assertEquals("cos://bucket/dir/file1", fake.lastUri); } } @@ -342,7 +340,7 @@ public void testSameSchemeFallbackSkipsTranslation() throws Exception { SpiSwitchingFileSystem spiFs = new SpiSwitchingFileSystem(Collections.emptyMap()); spiFs.exists(Location.of("s3://bucket/key")); - Assert.assertEquals("s3://bucket/key", fake.lastUri); + Assertions.assertEquals("s3://bucket/key", fake.lastUri); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/DorisHttpTestCase.java b/fe/fe-core/src/test/java/org/apache/doris/http/DorisHttpTestCase.java index de882032ad3ea8..17d0e7c83a7051 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/DorisHttpTestCase.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/DorisHttpTestCase.java @@ -59,14 +59,13 @@ import com.google.common.base.Strings; import com.google.common.collect.Lists; -import junit.framework.AssertionFailedError; import okhttp3.Credentials; import okhttp3.MediaType; import okhttp3.OkHttpClient; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import java.io.File; @@ -236,7 +235,7 @@ private static void assignBackends() { Env.getCurrentSystemInfo().addBackend(backend3); } - @BeforeClass + @BeforeAll public static void initHttpServer() throws IllegalArgException, InterruptedException { ServerSocket socket = null; try { @@ -267,13 +266,13 @@ public static void initHttpServer() throws IllegalArgException, InterruptedExcep httpServer.start(); } - @AfterClass + @AfterAll public static void afterClass() { File file = new File(DORIS_HOME); file.delete(); } - @Before + @BeforeEach public void setUp() { Env env = newDelegateCatalog(); SystemInfoService systemInfoService = new SystemInfoService(); @@ -296,7 +295,7 @@ public void setUp() { doSetUp(); } - @After + @AfterEach public void tearDown() { if (originalEnvInstance != null) { try { @@ -339,7 +338,7 @@ public void expectThrowsNoException(ThrowingRunnable runnable) { try { runnable.run(); } catch (Throwable e) { - throw new AssertionFailedError(e.getMessage()); + throw new AssertionError(e.getMessage()); } } @@ -360,10 +359,10 @@ public static T expectThrows(Class expectedType, String if (expectedType.isInstance(e)) { return expectedType.cast(e); } - AssertionFailedError assertion = new AssertionFailedError("Unexpected exception type, expected " + expectedType.getSimpleName() + " but got " + e); + AssertionError assertion = new AssertionError("Unexpected exception type, expected " + expectedType.getSimpleName() + " but got " + e); assertion.initCause(e); throw assertion; } - throw new AssertionFailedError(noExceptionMessage); + throw new AssertionError(noExceptionMessage); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/ForwardToMasterTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/ForwardToMasterTest.java index 85d523270d60f9..83e12e73d97212 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/ForwardToMasterTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/ForwardToMasterTest.java @@ -26,8 +26,8 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ForwardToMasterTest extends DorisHttpTestCase { @Test @@ -44,8 +44,8 @@ public void testAddBeDropBe() throws Exception { .url(url) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); @@ -60,7 +60,7 @@ public void testAddBeDropBe() throws Exception { existsbe++; } } - Assert.assertEquals(0, existsbe); + Assertions.assertEquals(0, existsbe); } { @@ -81,7 +81,7 @@ public void testAddBeDropBe() throws Exception { .post(RequestBody.create(jsonBody, MediaType.parse("application/json"))) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); + Assertions.assertTrue(response.isSuccessful()); } { @@ -94,8 +94,8 @@ public void testAddBeDropBe() throws Exception { .url(url) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); @@ -110,7 +110,7 @@ public void testAddBeDropBe() throws Exception { existsbe++; } } - Assert.assertEquals(1, existsbe); + Assertions.assertEquals(1, existsbe); } { @@ -132,7 +132,7 @@ public void testAddBeDropBe() throws Exception { .post(RequestBody.create(jsonBody, MediaType.parse("application/json"))) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); + Assertions.assertTrue(response.isSuccessful()); } { @@ -145,8 +145,8 @@ public void testAddBeDropBe() throws Exception { .url(url) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); @@ -161,7 +161,7 @@ public void testAddBeDropBe() throws Exception { existsbe++; } } - Assert.assertEquals(0, existsbe); + Assertions.assertEquals(0, existsbe); } } @@ -177,13 +177,13 @@ public void testPost1() throws Exception { .post(emptyBody) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); String data = (String) object.get("data"); - Assert.assertTrue(data.contains("does not exist")); + Assertions.assertTrue(data.contains("does not exist")); } @Test @@ -202,13 +202,13 @@ public void testPost2() throws Exception { .addHeader("Authorization", rootAuth) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); String data = (String) object.get("data"); - Assert.assertTrue(data.contains("the group 99999999.18888 isn't exist")); + Assertions.assertTrue(data.contains("the group 99999999.18888 isn't exist")); } @Test @@ -222,12 +222,12 @@ public void testGet1() throws Exception { .url(url) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); - Assert.assertNotNull(response.body()); + Assertions.assertTrue(response.isSuccessful()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject object = (JSONObject) JSONValue.parse(respStr); JSONObject data = (JSONObject) object.get("data"); - Assert.assertTrue(data.toString().contains("diskOccupancy")); + Assertions.assertTrue(data.toString().contains("diskOccupancy")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/HttpAuthManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/HttpAuthManagerTest.java index 34526fb9385ecb..26b2c51bce645d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/HttpAuthManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/HttpAuthManagerTest.java @@ -20,8 +20,8 @@ import org.apache.doris.analysis.UserIdentity; import org.apache.doris.httpv2.HttpAuthManager; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -37,20 +37,20 @@ public void testNormal() { HttpAuthManager.SessionValue sessionValue = new HttpAuthManager.SessionValue(); sessionValue.currentUser = UserIdentity.createAnalyzedUserIdentWithIp(username, "%"); authMgr.addSessionValue(sessionId, sessionValue); - Assert.assertEquals(1, authMgr.getAuthSessions().size()); - Assert.assertNotNull(sessionValue.csrfToken); - Assert.assertFalse(sessionValue.csrfToken.isEmpty()); + Assertions.assertEquals(1, authMgr.getAuthSessions().size()); + Assertions.assertNotNull(sessionValue.csrfToken); + Assertions.assertFalse(sessionValue.csrfToken.isEmpty()); List sessionIds = new ArrayList<>(); sessionIds.add(sessionId); System.out.println("username in test: " + authMgr.getSessionValue(sessionIds).currentUser); - Assert.assertEquals(username, authMgr.getSessionValue(sessionIds).currentUser.getQualifiedUser()); + Assertions.assertEquals(username, authMgr.getSessionValue(sessionIds).currentUser.getQualifiedUser()); String noExistSession = "no-exist-session-id"; sessionIds.clear(); sessionIds.add(noExistSession); - Assert.assertNull(authMgr.getSessionValue(sessionIds)); - Assert.assertEquals(1, authMgr.getAuthSessions().size()); + Assertions.assertNull(authMgr.getSessionValue(sessionIds)); + Assertions.assertEquals(1, authMgr.getAuthSessions().size()); authMgr.removeSession(sessionId); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/MimeTypeTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/MimeTypeTest.java index 9ff5c7cb2d6a01..5ca8bf92ce5c53 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/MimeTypeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/MimeTypeTest.java @@ -17,8 +17,8 @@ package org.apache.doris.http; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import javax.activation.MimetypesFileTypeMap; @@ -30,9 +30,9 @@ public void test() { mimeTypesMap.addMimeTypes("text/html html htm"); mimeTypesMap.addMimeTypes("application/javascript js"); mimeTypesMap.addMimeTypes("text/css css"); - Assert.assertEquals("text/css", mimeTypesMap.getContentType("/fe/webroot/static/datatables_bootstrap.css")); - Assert.assertEquals("application/javascript", mimeTypesMap.getContentType("/fe/webroot/static/web.js")); - Assert.assertEquals("text/html", mimeTypesMap.getContentType("/fe/webroot/index.html")); - Assert.assertEquals("text/html", mimeTypesMap.getContentType("/fe/webroot/index.htm")); + Assertions.assertEquals("text/css", mimeTypesMap.getContentType("/fe/webroot/static/datatables_bootstrap.css")); + Assertions.assertEquals("application/javascript", mimeTypesMap.getContentType("/fe/webroot/static/web.js")); + Assertions.assertEquals("text/html", mimeTypesMap.getContentType("/fe/webroot/index.html")); + Assertions.assertEquals("text/html", mimeTypesMap.getContentType("/fe/webroot/index.htm")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/TableQueryPlanActionTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/TableQueryPlanActionTest.java index 037765ef3b971b..c2cc760ff04db3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/TableQueryPlanActionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/TableQueryPlanActionTest.java @@ -27,8 +27,8 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Base64; @@ -47,21 +47,21 @@ public void testQueryPlanAction() throws IOException, TException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); + Assertions.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); JSONObject partitionsObject = (JSONObject) ((JSONObject) jsonObject.get("data")).get("partitions"); - Assert.assertNotNull(partitionsObject); + Assertions.assertNotNull(partitionsObject); for (Object tabletKey : partitionsObject.keySet()) { JSONObject tabletObject = (JSONObject) partitionsObject.get(tabletKey); - Assert.assertNotNull(tabletObject.get("routings")); - Assert.assertEquals(3, ((JSONArray) tabletObject.get("routings")).size()); - Assert.assertEquals(testStartVersion, (long) tabletObject.get("version")); + Assertions.assertNotNull(tabletObject.get("routings")); + Assertions.assertEquals(3, ((JSONArray) tabletObject.get("routings")).size()); + Assertions.assertEquals(testStartVersion, (long) tabletObject.get("version")); } String queryPlan = (String) ((JSONObject) jsonObject.get("data")).get("opaqued_query_plan"); - Assert.assertNotNull(queryPlan); + Assertions.assertNotNull(queryPlan); byte[] binaryPlanInfo = Base64.getDecoder().decode(queryPlan); TDeserializer deserializer = new TDeserializer(); TQueryPlanInfo tQueryPlanInfo = new TQueryPlanInfo(); @@ -80,21 +80,21 @@ public void testQueryPlanActionEmptyRelation() throws IOException, TException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); + Assertions.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); JSONObject partitionsObject = (JSONObject) ((JSONObject) jsonObject.get("data")).get("partitions"); - Assert.assertNotNull(partitionsObject); + Assertions.assertNotNull(partitionsObject); for (Object tabletKey : partitionsObject.keySet()) { JSONObject tabletObject = (JSONObject) partitionsObject.get(tabletKey); - Assert.assertNotNull(tabletObject.get("routings")); - Assert.assertEquals(3, ((JSONArray) tabletObject.get("routings")).size()); - Assert.assertEquals(testStartVersion, (long) tabletObject.get("version")); + Assertions.assertNotNull(tabletObject.get("routings")); + Assertions.assertEquals(3, ((JSONArray) tabletObject.get("routings")).size()); + Assertions.assertEquals(testStartVersion, (long) tabletObject.get("version")); } String queryPlan = (String) ((JSONObject) jsonObject.get("data")).get("opaqued_query_plan"); - Assert.assertNotNull(queryPlan); + Assertions.assertNotNull(queryPlan); byte[] binaryPlanInfo = Base64.getDecoder().decode(queryPlan); TDeserializer deserializer = new TDeserializer(); TQueryPlanInfo tQueryPlanInfo = new TQueryPlanInfo(); @@ -112,13 +112,13 @@ public void testNoSqlFailure() throws IOException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(403, (long) jsonObject.get("code")); + Assertions.assertEquals(403, (long) jsonObject.get("code")); String exception = (String) jsonObject.get("data"); - Assert.assertNotNull(exception); - Assert.assertEquals("POST body must contains [sql] root object", exception); + Assertions.assertNotNull(exception); + Assertions.assertEquals("POST body must contains [sql] root object", exception); } @Test @@ -130,14 +130,14 @@ public void testEmptySqlFailure() throws IOException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); - Assert.assertNotNull(respStr); + Assertions.assertNotNull(respStr); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(403, (long) jsonObject.get("code")); + Assertions.assertEquals(403, (long) jsonObject.get("code")); String exception = (String) jsonObject.get("data"); - Assert.assertNotNull(exception); - Assert.assertEquals("POST body must contains [sql] root object", exception); + Assertions.assertNotNull(exception); + Assertions.assertEquals("POST body must contains [sql] root object", exception); } @Test @@ -150,14 +150,14 @@ public void testInconsistentResource() throws IOException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); - Assert.assertNotNull(respStr); + Assertions.assertNotNull(respStr); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(400, (long) ((JSONObject) jsonObject.get("data")).get("status")); + Assertions.assertEquals(400, (long) ((JSONObject) jsonObject.get("data")).get("status")); String exception = (String) ((JSONObject) jsonObject.get("data")).get("exception"); - Assert.assertNotNull(exception); - Assert.assertTrue(exception.startsWith("requested database and table must consistent with sql")); + Assertions.assertNotNull(exception); + Assertions.assertTrue(exception.startsWith("requested database and table must consistent with sql")); } @Test @@ -171,12 +171,12 @@ public void testMalformedJson() throws IOException { .build(); Response response = networkClient.newCall(request).execute(); String respStr = response.body().string(); - Assert.assertNotNull(respStr); + Assertions.assertNotNull(respStr); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(403, (long) jsonObject.get("code")); + Assertions.assertEquals(403, (long) jsonObject.get("code")); String exception = (String) jsonObject.get("data"); - Assert.assertNotNull(exception); - Assert.assertTrue(exception.startsWith("malformed json")); + Assertions.assertNotNull(exception); + Assertions.assertTrue(exception.startsWith("malformed json")); } @@ -191,11 +191,11 @@ public void testHasAggFailure() throws IOException { .url(URI + PATH_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); - Assert.assertNotNull(respStr); + Assertions.assertNotNull(respStr); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); String exception = jsonObject.get("data").toString(); - Assert.assertTrue(exception.contains("only support single table filter-prune-scan")); + Assertions.assertTrue(exception.contains("only support single table filter-prune-scan")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/TableRowCountActionTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/TableRowCountActionTest.java index 44b174b12d7ec7..5fbf07223af2a5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/TableRowCountActionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/TableRowCountActionTest.java @@ -21,8 +21,8 @@ import okhttp3.Response; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -39,10 +39,10 @@ public void testTableCount() throws IOException { .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String res = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(res); - Assert.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); - Assert.assertEquals(2000, (long) ((JSONObject) jsonObject.get("data")).get("size")); + Assertions.assertEquals(200, (long) ((JSONObject) jsonObject.get("data")).get("status")); + Assertions.assertEquals(2000, (long) ((JSONObject) jsonObject.get("data")).get("size")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/http/TableSchemaActionTest.java b/fe/fe-core/src/test/java/org/apache/doris/http/TableSchemaActionTest.java index 7e2347f61f4d1f..5d7e7703a9b0a4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/http/TableSchemaActionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/http/TableSchemaActionTest.java @@ -22,8 +22,8 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -39,13 +39,13 @@ public void testGetTableSchema() throws IOException { .url(URI + QUERY_PLAN_URI) .build(); Response response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.isSuccessful()); + Assertions.assertTrue(response.isSuccessful()); String respStr = response.body().string(); - Assert.assertNotNull(respStr); + Assertions.assertNotNull(respStr); JSONObject object = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(200, (long) ((JSONObject) object.get("data")).get("status")); + Assertions.assertEquals(200, (long) ((JSONObject) object.get("data")).get("status")); JSONArray propArray = (JSONArray) ((JSONObject) object.get("data")).get("properties"); // k1, k2 - Assert.assertEquals(2, propArray.size()); + Assertions.assertEquals(2, propArray.size()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/httpv2/meta/MetaServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/httpv2/meta/MetaServiceTest.java index 90bb54de6b9e43..5eb7c571db30fa 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/httpv2/meta/MetaServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/httpv2/meta/MetaServiceTest.java @@ -33,18 +33,19 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -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.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.http.ResponseEntity; import java.io.File; import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; public class MetaServiceTest { // Value configured via Config.fe_meta_auth_token -- the cluster meta auth token. @@ -56,8 +57,8 @@ public class MetaServiceTest { private static final String FE_HOST = "127.0.0.1"; private static final int FE_EDIT_LOG_PORT = 9010; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public Path temporaryFolder; private String oldMetaAuthToken; private boolean oldEnableAllHttpAuth; @@ -67,7 +68,7 @@ public class MetaServiceTest { private Env env; private MockedStatic envStatic; - @Before + @BeforeEach public void setUp() { oldMetaAuthToken = Config.fe_meta_auth_token; oldEnableAllHttpAuth = Config.enable_all_http_auth; @@ -87,10 +88,10 @@ public void setUp() { Frontend frontend = new Frontend(FrontendNodeType.FOLLOWER, "fe1", FE_HOST, FE_EDIT_LOG_PORT); Mockito.when(env.checkFeExist(FE_HOST, FE_EDIT_LOG_PORT)).thenReturn(frontend); - Mockito.when(env.getImageDir()).thenReturn(temporaryFolder.getRoot().getAbsolutePath()); + Mockito.when(env.getImageDir()).thenReturn(temporaryFolder.toFile().getAbsolutePath()); } - @After + @AfterEach public void tearDown() { Config.fe_meta_auth_token = oldMetaAuthToken; Config.enable_all_http_auth = oldEnableAllHttpAuth; @@ -112,7 +113,7 @@ public void testMatchingTokenAllowsMetaRequestFromProxyAddress() throws Exceptio Object result = service.role(request, response); - Assert.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); + Assertions.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); Mockito.verify(response).setHeader("role", FrontendNodeType.FOLLOWER.name()); } @@ -127,7 +128,7 @@ public void testNoTokenRequiredWhenTokenNotConfigured() throws Exception { Object result = service.role(request, response); - Assert.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); + Assertions.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); Mockito.verify(response).setHeader("role", FrontendNodeType.FOLLOWER.name()); } @@ -141,7 +142,7 @@ public void testCheckReturnsStorageTokenWhenAuthPasses() throws Exception { Object result = service.check(request, response); - Assert.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); + Assertions.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); Mockito.verify(response).setHeader(MetaBaseAction.TOKEN, STORAGE_TOKEN); } @@ -152,7 +153,7 @@ public void testWrongTokenRejected() { HttpServletRequest request = newRequest(FE_HOST, FE_HOST, BAD_TOKEN); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Assert.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); + Assertions.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); } // A missing token is rejected when a cluster token is configured. @@ -162,7 +163,7 @@ public void testMissingTokenRejectedWhenConfigured() { HttpServletRequest request = newRequest(FE_HOST, FE_HOST, null); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Assert.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); + Assertions.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); } // The node-host check is always enforced: an unknown FE host is rejected even with a @@ -173,7 +174,7 @@ public void testUnknownHostRejectedEvenWithValidToken() { HttpServletRequest request = newRequest("192.0.2.99", "192.0.2.99", META_TOKEN); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Assert.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); + Assertions.assertThrows(UnauthorizedException.class, () -> service.role(request, response)); } @Test @@ -185,13 +186,13 @@ public void testPutRejectsUnexpectedHttpPort() throws Exception { Mockito.when(request.getParameter("port")).thenReturn(Integer.toString(Config.http_port + 1)); try (MockedStatic metaHelper = Mockito.mockStatic(MetaHelper.class)) { - File partialFile = temporaryFolder.newFile("image.100.part"); + File partialFile = Files.createFile(temporaryFolder.resolve("image.100.part")).toFile(); metaHelper.when(() -> MetaHelper.getFile(Mockito.anyString(), Mockito.any(File.class))) .thenReturn(partialFile); Object result = service.put(request, response); - Assert.assertEquals(RestApiStatusCode.BAD_REQUEST.code, responseCode(result)); + Assertions.assertEquals(RestApiStatusCode.BAD_REQUEST.code, responseCode(result)); metaHelper.verify(() -> MetaHelper.getRemoteFile(Mockito.anyString(), Mockito.anyInt(), Mockito.any(File.class)), Mockito.never()); } @@ -209,14 +210,14 @@ public void testPutAcceptsHttpsPortWhenHttpsEnabled() throws Exception { Mockito.when(request.getParameter("port")).thenReturn(Integer.toString(Config.https_port)); try (MockedStatic metaHelper = Mockito.mockStatic(MetaHelper.class)) { - File partialFile = temporaryFolder.newFile("image.100.part"); + File partialFile = Files.createFile(temporaryFolder.resolve("image.100.part")).toFile(); metaHelper.when(() -> MetaHelper.getFile(Mockito.anyString(), Mockito.any(File.class))) .thenReturn(partialFile); Object result = service.put(request, response); // Passes the port check and proceeds to fetch the remote image (no BAD_REQUEST). - Assert.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); + Assertions.assertEquals(RestApiStatusCode.OK.code, responseCode(result)); metaHelper.verify(() -> MetaHelper.getRemoteFile(Mockito.anyString(), Mockito.anyInt(), Mockito.any(File.class)), Mockito.times(1)); } @@ -253,7 +254,7 @@ public void testDumpRejectsNonAdmin() throws Exception { Mockito.when(env.getAccessManager()).thenReturn(accessManager); Mockito.when(accessManager.checkGlobalPriv(nonAdmin, PrivPredicate.ADMIN)).thenReturn(false); - Assert.assertThrows(UnauthorizedException.class, () -> service.dump(request, response)); + Assertions.assertThrows(UnauthorizedException.class, () -> service.dump(request, response)); Mockito.verify(env, Mockito.never()).dumpImage(); } @@ -264,7 +265,7 @@ private static BaseController.ActionAuthorizationInfo authInfo(UserIdentity user } private MetaService serviceWithImageDir() throws Exception { - File imageDir = temporaryFolder.newFolder("image"); + File imageDir = Files.createDirectories(temporaryFolder.resolve("image")).toFile(); Storage storage = new Storage(12345, STORAGE_TOKEN, imageDir.getAbsolutePath()); storage.writeClusterIdAndToken(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/CopyIntoTest.java b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/CopyIntoTest.java index 6ab624cd9436a1..6b41ec70c24bae 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/CopyIntoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/CopyIntoTest.java @@ -34,10 +34,10 @@ import okhttp3.Response; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; @@ -55,13 +55,13 @@ public class CopyIntoTest extends DorisHttpTestCase { protected String rootAuth = Credentials.basic("root", ""); - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { MetricRepo.init(); port = UtFrameUtils.createMetaServer(MockedMetaServerFactory.METASERVER_DEFAULT_IP); } - @Ignore + @Disabled @Test public void testUpload() throws IOException { FeConstants.runningUnitTest = true; @@ -70,12 +70,12 @@ public void testUpload() throws IOException { .addHeader("Authorization", rootAuth) .addHeader("Content-Type", "text/plain; charset=UTF-8").url(CloudURI + UPDATE_URI).build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(403, (long) jsonObject.get("code")); + Assertions.assertEquals(403, (long) jsonObject.get("code")); String exception = (String) jsonObject.get("data"); - Assert.assertTrue(exception.contains("http header must have filename entry")); + Assertions.assertTrue(exception.contains("http header must have filename entry")); // case 1 request = new Request.Builder() @@ -87,7 +87,7 @@ public void testUpload() throws IOException { Config.cloud_unique_id = "Internal-MetaServiceCode.OK"; Config.meta_service_endpoint = MockedMetaServerFactory.METASERVER_DEFAULT_IP + ":" + port; response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.internal.com/ut-test/test.csv")); + Assertions.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.internal.com/ut-test/test.csv")); // case 2 add header endpointHeader, __USE_ENDPOINT__ request = new Request.Builder() @@ -100,7 +100,7 @@ public void testUpload() throws IOException { Config.cloud_unique_id = "Internal-MetaServiceCode.OK"; Config.meta_service_endpoint = MockedMetaServerFactory.METASERVER_DEFAULT_IP + ":" + port; response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.internal.com/ut-test/test.csv")); + Assertions.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.internal.com/ut-test/test.csv")); // case 3 add header endpointHeader, __USE_ENDPOINT__ request = new Request.Builder() @@ -113,7 +113,7 @@ public void testUpload() throws IOException { Config.cloud_unique_id = "Internal-MetaServiceCode.OK"; Config.meta_service_endpoint = MockedMetaServerFactory.METASERVER_DEFAULT_IP + ":" + port; response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.com/ut-test/test.csv")); + Assertions.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.com/ut-test/test.csv")); // case 4 add header endpointHeader, host request = new Request.Builder() @@ -126,7 +126,7 @@ public void testUpload() throws IOException { Config.cloud_unique_id = "Internal-MetaServiceCode.OK"; Config.meta_service_endpoint = MockedMetaServerFactory.METASERVER_DEFAULT_IP + ":" + port; response = networkClient.newCall(request).execute(); - Assert.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.com/ut-test/test.csv")); + Assertions.assertTrue(response.request().url().toString().contains("http://bucketbucket.cos.ap-beijing.myqcloud.com/ut-test/test.csv")); } @Test @@ -135,12 +135,12 @@ public void testQuery() throws IOException, ExecutionException, InterruptedExcep Request request = new Request.Builder().post(RequestBody.create(emptySql.getBytes())).addHeader("Authorization", rootAuth) .addHeader("Content-Type", "application/json").url(CloudURI + QUERY_URI).build(); Response response = networkClient.newCall(request).execute(); - Assert.assertNotNull(response.body()); + Assertions.assertNotNull(response.body()); String respStr = response.body().string(); JSONObject jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(403, (long) jsonObject.get("code")); + Assertions.assertEquals(403, (long) jsonObject.get("code")); String exception = (String) jsonObject.get("data"); - Assert.assertTrue(exception.contains("POST body must contain [sql] root object")); + Assertions.assertTrue(exception.contains("POST body must contain [sql] root object")); HashMap om = new HashMap<>(); HashMap im = new HashMap<>(); @@ -173,10 +173,10 @@ public void testQuery() throws IOException, ExecutionException, InterruptedExcep // {"msg":"success","code":0,"data":{"result":{"copyId":"copy_1296997def6d4887_9e7ff31a7f3842cc","msg":"","loadedRows":"","state":"CANCELLED","type":"LOAD_RUN_FAIL","filterRows":"","unselectRows":"","url":null}},"count":0} System.out.println(respStr); jsonObject = (JSONObject) JSONValue.parse(respStr); - Assert.assertEquals(0, (long) jsonObject.get("code")); + Assertions.assertEquals(0, (long) jsonObject.get("code")); JSONObject data = (JSONObject) jsonObject.get("data"); JSONObject result = (JSONObject) data.get("result"); String copyId = (String) result.get("copyId"); - Assert.assertEquals(copyId, "copy_1296997def6d4887_9e7ff31a7f3842cc"); + Assertions.assertEquals(copyId, "copy_1296997def6d4887_9e7ff31a7f3842cc"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/HttpApiAuthTest.java b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/HttpApiAuthTest.java index b3c319fd46bdce..94377a23761274 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/HttpApiAuthTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/HttpApiAuthTest.java @@ -23,10 +23,10 @@ import org.apache.doris.httpv2.exception.UnauthorizedException; import org.apache.doris.mysql.privilege.PrivPredicate; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests for HTTP API authentication and authorization. @@ -39,13 +39,13 @@ public class HttpApiAuthTest { private boolean originalEnableAllHttpAuth; - @Before + @BeforeEach public void setUp() { // Save original config originalEnableAllHttpAuth = Config.enable_all_http_auth; } - @After + @AfterEach public void tearDown() { // Restore original config Config.enable_all_http_auth = originalEnableAllHttpAuth; @@ -64,8 +64,8 @@ public void testActionAuthorizationInfoHasUserIdentity() { userIdentity.setIsAnalyzed(); authInfo.userIdentity = userIdentity; - Assert.assertNotNull("userIdentity field should exist", authInfo.userIdentity); - Assert.assertEquals("root", authInfo.userIdentity.getQualifiedUser()); + Assertions.assertNotNull(authInfo.userIdentity, "userIdentity field should exist"); + Assertions.assertEquals("root", authInfo.userIdentity.getQualifiedUser()); } @Test @@ -82,7 +82,7 @@ public void testCheckAdminAuthWhenDisabled() { controller.checkAdminAuth(normalUser); // Success - no exception thrown } catch (UnauthorizedException e) { - Assert.fail("checkAdminAuth should not check privilege when enable_all_http_auth=false"); + Assertions.fail("checkAdminAuth should not check privilege when enable_all_http_auth=false"); } } @@ -101,7 +101,7 @@ public void testCheckAdminAuthWithAdminUser() { controller.checkAdminAuth(adminUser); // Success - no exception thrown } catch (UnauthorizedException e) { - Assert.fail("Admin user should pass checkAdminAuth: " + e.getMessage()); + Assertions.fail("Admin user should pass checkAdminAuth: " + e.getMessage()); } } @@ -118,12 +118,11 @@ public void testCheckAdminAuthWithNormalUser() { try { controller.checkAdminAuth(normalUser); - Assert.fail("Normal user should not pass checkAdminAuth"); + Assertions.fail("Normal user should not pass checkAdminAuth"); } catch (UnauthorizedException e) { // Expected exception - Assert.assertTrue("Error message should mention privilege", - e.getMessage().toLowerCase().contains("privilege") - || e.getMessage().toLowerCase().contains("permission")); + Assertions.assertTrue(e.getMessage().toLowerCase().contains("privilege") + || e.getMessage().toLowerCase().contains("permission"), "Error message should mention privilege"); } } @@ -133,7 +132,7 @@ public void testCheckAdminAuthMethodExists() { TestRestController controller = new TestRestController(); // This test passes if the method exists and compiles - Assert.assertNotNull("RestBaseController should have checkAdminAuth method", controller); + Assertions.assertNotNull(controller, "RestBaseController should have checkAdminAuth method"); } /** diff --git a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/RestBaseControllerTest.java b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/RestBaseControllerTest.java index a42a389c911959..ad7113706b478f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/RestBaseControllerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/RestBaseControllerTest.java @@ -20,8 +20,8 @@ import org.apache.doris.thrift.TNetworkAddress; import jakarta.servlet.http.HttpServletRequest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class RestBaseControllerTest { @@ -37,7 +37,7 @@ public void testBuildRedirectUrlPreservesEncodedPath() { String redirectUrl = controller.buildRedirectUrlForTest(request, new TNetworkAddress("be-host", 8040), "/api/db%2Ftbl/_stream_load", "k=a%2Bb"); - Assert.assertEquals("http://be-host:8040/api/db%2Ftbl/_stream_load?k=a%2Bb", redirectUrl); + Assertions.assertEquals("http://be-host:8040/api/db%2Ftbl/_stream_load?k=a%2Bb", redirectUrl); } @Test @@ -51,7 +51,7 @@ public void testBuildRedirectUrlWithoutQueryString() { String redirectUrl = controller.buildRedirectUrlForTest(request, new TNetworkAddress("be-host", 8040), "/api/db%2Ftbl/_stream_load", null); - Assert.assertEquals("http://be-host:8040/api/db%2Ftbl/_stream_load", redirectUrl); + Assertions.assertEquals("http://be-host:8040/api/db%2Ftbl/_stream_load", redirectUrl); } @Test @@ -65,7 +65,7 @@ public void testBuildRedirectUrlToBackendForcesHttpEvenWhenRequestIsHttps() { String redirectUrl = controller.buildRedirectUrlToBackendForTest(request, new TNetworkAddress("be-host", 8040), "/api/db/tbl/_stream_load", "k=v"); - Assert.assertEquals("http://be-host:8040/api/db/tbl/_stream_load?k=v", redirectUrl); + Assertions.assertEquals("http://be-host:8040/api/db/tbl/_stream_load?k=v", redirectUrl); } // Expose the protected helper so the redirect URL can be verified directly. diff --git a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/manager/HttpUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/manager/HttpUtilsTest.java index 2efaf4ca7bad16..24fe7958e3d173 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/manager/HttpUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/httpv2/rest/manager/HttpUtilsTest.java @@ -20,10 +20,10 @@ import org.apache.doris.common.Config; import org.apache.doris.common.util.InternalHttpsUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.reflect.Field; @@ -37,14 +37,14 @@ public class HttpUtilsTest { private boolean originalEnableHttps; private String originalKeyStorePath; - @Before + @BeforeEach public void setUp() throws Exception { originalEnableHttps = Config.enable_https; originalKeyStorePath = Config.key_store_path; resetCachedSslContext(); } - @After + @AfterEach public void tearDown() throws Exception { Config.enable_https = originalEnableHttps; Config.key_store_path = originalKeyStorePath; @@ -65,9 +65,9 @@ public void testExecuteRequestUsesPlainClientForHttpUrlEvenWhenHttpsEnabled() th try { HttpUtils.doGet(REFUSED_PORT_URL_HTTP, null); - Assert.fail("Expected a connection failure against the refused port"); + Assertions.fail("Expected a connection failure against the refused port"); } catch (RuntimeException e) { - Assert.fail("Should not have attempted to build the HTTPS client for an http:// URL: " + Assertions.fail("Should not have attempted to build the HTTPS client for an http:// URL: " + e.getMessage()); } catch (IOException expected) { // Plain client hit the network and failed there, never touching the broken keystore. @@ -82,12 +82,11 @@ public void testExecuteRequestUsesHttpsClientForHttpsUrl() throws Exception { try { HttpUtils.doGet(REFUSED_PORT_URL_HTTPS, null); - Assert.fail("Expected SSLContext build failure before any connection attempt"); + Assertions.fail("Expected SSLContext build failure before any connection attempt"); } catch (RuntimeException e) { - Assert.assertTrue("Failure should come from the missing keystore, not an unrelated error", - e.getMessage() != null && e.getMessage().contains("doris_ssl_certificate.keystore")); + Assertions.assertTrue(e.getMessage() != null && e.getMessage().contains("doris_ssl_certificate.keystore"), "Failure should come from the missing keystore, not an unrelated error"); } catch (IOException e) { - Assert.fail("Expected the HTTPS client's keystore failure, not a network-level error: " + Assertions.fail("Expected the HTTPS client's keystore failure, not a network-level error: " + e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteManagerTest.java index d071163021bd88..8b02f59c507ed2 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteManagerTest.java @@ -24,9 +24,9 @@ import org.apache.doris.common.DdlException; import org.apache.doris.common.MetaNotFoundException; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class InsertOverwriteManagerTest { @@ -36,7 +36,7 @@ public class InsertOverwriteManagerTest { private MTMV mtmv = Mockito.mock(MTMV.class); - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException, DdlException, MetaNotFoundException { diff --git a/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteUtilTest.java index 947e876c53c8b5..7e532611bda453 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/insertoverwrite/InsertOverwriteUtilTest.java @@ -18,8 +18,8 @@ package org.apache.doris.insertoverwrite; import com.google.common.collect.Lists; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/InsertTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/InsertTaskTest.java index 4ea2f4fba701f4..9722b5f2310313 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/InsertTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/InsertTaskTest.java @@ -19,13 +19,13 @@ import org.apache.doris.qe.ConnectContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class InsertTaskTest { @Test public void testMakeConnection() { ConnectContext ctx = InsertTask.makeConnectContext(null, null); - Assert.assertTrue(ctx.getState().isNereids()); + Assertions.assertTrue(ctx.getState().isNereids()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/DataSourceConfigValidatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/DataSourceConfigValidatorTest.java index 3765fd1018933e..231c7210e7d727 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/DataSourceConfigValidatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/DataSourceConfigValidatorTest.java @@ -23,8 +23,8 @@ import org.apache.doris.job.exception.JobException; import org.apache.doris.job.util.StreamingJobUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -113,7 +113,7 @@ public void testDisableWithoutRootcertPasses() { private static void assertReject(Map input) { try { DataSourceConfigValidator.validateSource(input, DataSourceType.MYSQL.name()); - Assert.fail("expected IllegalArgumentException for input: " + input); + Assertions.fail("expected IllegalArgumentException for input: " + input); } catch (IllegalArgumentException ignored) { // expected } @@ -140,15 +140,15 @@ public void testSlotNameAndPublicationNameNotRequired() { @Test public void testDefaultSlotNameFormat() { String slotName = DataSourceConfigKeys.defaultSlotName("12345"); - Assert.assertEquals("doris_cdc_12345", slotName); - Assert.assertTrue(slotName.length() <= PG_MAX_IDENTIFIER_LENGTH); + Assertions.assertEquals("doris_cdc_12345", slotName); + Assertions.assertTrue(slotName.length() <= PG_MAX_IDENTIFIER_LENGTH); } @Test public void testDefaultPublicationNameFormat() { String pubName = DataSourceConfigKeys.defaultPublicationName("12345"); - Assert.assertEquals("doris_pub_12345", pubName); - Assert.assertTrue(pubName.length() <= PG_MAX_IDENTIFIER_LENGTH); + Assertions.assertEquals("doris_pub_12345", pubName); + Assertions.assertTrue(pubName.length() <= PG_MAX_IDENTIFIER_LENGTH); } @Test @@ -156,10 +156,8 @@ public void testDefaultNamesWithLargeJobId() { String maxJobId = String.valueOf(Long.MAX_VALUE); String slotName = DataSourceConfigKeys.defaultSlotName(maxJobId); String pubName = DataSourceConfigKeys.defaultPublicationName(maxJobId); - Assert.assertTrue("Slot name should not exceed PG limit, actual: " + slotName.length(), - slotName.length() <= PG_MAX_IDENTIFIER_LENGTH); - Assert.assertTrue("Publication name should not exceed PG limit, actual: " + pubName.length(), - pubName.length() <= PG_MAX_IDENTIFIER_LENGTH); + Assertions.assertTrue(slotName.length() <= PG_MAX_IDENTIFIER_LENGTH, "Slot name should not exceed PG limit, actual: " + slotName.length()); + Assertions.assertTrue(pubName.length() <= PG_MAX_IDENTIFIER_LENGTH, "Publication name should not exceed PG limit, actual: " + pubName.length()); } @Test @@ -181,7 +179,7 @@ public void testSlotNameRejectsInvalidPgIdentifiers() { props.put(DataSourceConfigKeys.SLOT_NAME, invalid); try { DataSourceConfigValidator.validateSource(props, DataSourceType.POSTGRES.name()); - Assert.fail("Expected IllegalArgumentException for slot_name='" + invalid + "'"); + Assertions.fail("Expected IllegalArgumentException for slot_name='" + invalid + "'"); } catch (IllegalArgumentException expected) { // ok } @@ -197,7 +195,7 @@ public void testPublicationNameRejectsInvalidPgIdentifiers() { props.put(DataSourceConfigKeys.PUBLICATION_NAME, invalid); try { DataSourceConfigValidator.validateSource(props, DataSourceType.POSTGRES.name()); - Assert.fail("Expected IllegalArgumentException for publication_name='" + invalid + "'"); + Assertions.fail("Expected IllegalArgumentException for publication_name='" + invalid + "'"); } catch (IllegalArgumentException expected) { // ok } @@ -215,7 +213,7 @@ public void testSlotNameRejectsOverlongIdentifier() { props.put(DataSourceConfigKeys.SLOT_NAME, sb.toString()); try { DataSourceConfigValidator.validateSource(props, DataSourceType.POSTGRES.name()); - Assert.fail("Expected IllegalArgumentException for slot_name exceeding " + Assertions.fail("Expected IllegalArgumentException for slot_name exceeding " + PG_MAX_IDENTIFIER_LENGTH + " chars"); } catch (IllegalArgumentException expected) { // ok @@ -326,11 +324,9 @@ public void testServerIdRejectsMalformed() { try { DataSourceConfigValidator.validateSource( serverIdInput(invalid), DataSourceType.MYSQL.name()); - Assert.fail("Expected IllegalArgumentException for server_id='" + invalid + "'"); + Assertions.fail("Expected IllegalArgumentException for server_id='" + invalid + "'"); } catch (IllegalArgumentException expected) { - Assert.assertTrue( - "Error message should reference server_id, got: " + expected.getMessage(), - expected.getMessage().contains("server_id")); + Assertions.assertTrue(expected.getMessage().contains("server_id"), "Error message should reference server_id, got: " + expected.getMessage()); } } } @@ -339,9 +335,9 @@ public void testServerIdRejectsMalformed() { public void testServerIdRejectsZero() { try { DataSourceConfigValidator.validateSource(serverIdInput("0"), DataSourceType.MYSQL.name()); - Assert.fail("Expected IllegalArgumentException for server_id='0'"); + Assertions.fail("Expected IllegalArgumentException for server_id='0'"); } catch (IllegalArgumentException expected) { - Assert.assertTrue(expected.getMessage().contains("server_id")); + Assertions.assertTrue(expected.getMessage().contains("server_id")); } } @@ -350,9 +346,9 @@ public void testServerIdRejectsBackwardRange() { try { DataSourceConfigValidator.validateSource( serverIdInput("5408-5400"), DataSourceType.MYSQL.name()); - Assert.fail("Expected IllegalArgumentException for server_id='5408-5400'"); + Assertions.fail("Expected IllegalArgumentException for server_id='5408-5400'"); } catch (IllegalArgumentException expected) { - Assert.assertTrue(expected.getMessage().contains("server_id")); + Assertions.assertTrue(expected.getMessage().contains("server_id")); } } @@ -360,9 +356,9 @@ public void testServerIdRejectsBackwardRange() { public void testServerIdRejectsNegative() { try { DataSourceConfigValidator.validateSource(serverIdInput("-5"), DataSourceType.MYSQL.name()); - Assert.fail("Expected IllegalArgumentException for server_id='-5'"); + Assertions.fail("Expected IllegalArgumentException for server_id='-5'"); } catch (IllegalArgumentException expected) { - Assert.assertTrue(expected.getMessage().contains("server_id")); + Assertions.assertTrue(expected.getMessage().contains("server_id")); } } @@ -373,13 +369,11 @@ public void testServerIdCrossFieldWidthRejected() { props.put(DataSourceConfigKeys.SNAPSHOT_PARALLELISM, "8"); try { DataSourceConfigValidator.validateSource(props, DataSourceType.MYSQL.name()); - Assert.fail("Expected IllegalArgumentException for range size 3 < parallelism 8"); + Assertions.fail("Expected IllegalArgumentException for range size 3 < parallelism 8"); } catch (IllegalArgumentException expected) { String msg = expected.getMessage(); - Assert.assertTrue("Message should reference snapshot_parallelism: " + msg, - msg.contains("snapshot_parallelism")); - Assert.assertTrue("Message should reference server_id: " + msg, - msg.contains("server_id")); + Assertions.assertTrue(msg.contains("snapshot_parallelism"), "Message should reference snapshot_parallelism: " + msg); + Assertions.assertTrue(msg.contains("server_id"), "Message should reference server_id: " + msg); } } @@ -428,11 +422,11 @@ public void testOceanBaseRejectsNonMysqlJdbcUrl() { Map props = new HashMap<>(); props.put(DataSourceConfigKeys.JDBC_URL, "jdbc:oceanbase://localhost:2883/test_db"); - IllegalArgumentException exception = Assert.assertThrows(IllegalArgumentException.class, + IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> DataSourceConfigValidator.validateSource( props, DataSourceType.OCEANBASE.name())); - Assert.assertTrue(exception.getMessage().contains("jdbc:mysql://")); + Assertions.assertTrue(exception.getMessage().contains("jdbc:mysql://")); } @Test @@ -444,11 +438,11 @@ public void testOceanBaseRejectsPostgresProperties() { Map props = new HashMap<>(); props.put(key, "value"); - IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException exception = Assertions.assertThrows( IllegalArgumentException.class, () -> DataSourceConfigValidator.validateSource( props, DataSourceType.OCEANBASE.name())); - Assert.assertTrue(exception.getMessage().contains(key)); + Assertions.assertTrue(exception.getMessage().contains(key)); } } @@ -457,18 +451,18 @@ public void testOceanBaseDoesNotExposeSchemaChangeEnabled() { Map props = new HashMap<>(); props.put(DataSourceConfigKeys.SCHEMA_CHANGE_ENABLED, "false"); - IllegalArgumentException exception = Assert.assertThrows(IllegalArgumentException.class, + IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> DataSourceConfigValidator.validateSource( props, DataSourceType.OCEANBASE.name())); - Assert.assertTrue(exception.getMessage().contains(DataSourceConfigKeys.SCHEMA_CHANGE_ENABLED)); + Assertions.assertTrue(exception.getMessage().contains(DataSourceConfigKeys.SCHEMA_CHANGE_ENABLED)); } @Test public void testOceanBaseSupportsEarliestOffset() { - Assert.assertTrue(DataSourceConfigValidator.isValidOffset( + Assertions.assertTrue(DataSourceConfigValidator.isValidOffset( DataSourceConfigKeys.OFFSET_EARLIEST, DataSourceType.OCEANBASE.name())); - Assert.assertFalse(DataSourceConfigValidator.isValidOffset( + Assertions.assertFalse(DataSourceConfigValidator.isValidOffset( DataSourceConfigKeys.OFFSET_EARLIEST, DataSourceType.POSTGRES.name())); } @@ -505,10 +499,10 @@ public void testOceanBaseOracleCompatibilityModeIsRejected() throws Exception { Mockito.eq(DataSourceType.OCEANBASE), Mockito.anyMap())) .thenReturn(jdbcClient); - JobException exception = Assert.assertThrows(JobException.class, + JobException exception = Assertions.assertThrows(JobException.class, () -> DataSourceConfigValidator.validateSourceBeforeTableCreation( DataSourceType.OCEANBASE, new HashMap<>())); - Assert.assertTrue(exception.getMessage().contains("Oracle compatibility mode")); + Assertions.assertTrue(exception.getMessage().contains("Oracle compatibility mode")); } Mockito.verify(jdbcClient).closeClient(); @@ -523,10 +517,10 @@ public void testOceanBaseUnknownCompatibilityModeIsRejected() throws Exception { Mockito.eq(DataSourceType.OCEANBASE), Mockito.anyMap())) .thenReturn(jdbcClient); - JobException exception = Assert.assertThrows(JobException.class, + JobException exception = Assertions.assertThrows(JobException.class, () -> DataSourceConfigValidator.validateSourceBeforeTableCreation( DataSourceType.OCEANBASE, new HashMap<>())); - Assert.assertTrue(exception.getMessage().contains("UNKNOWN")); + Assertions.assertTrue(exception.getMessage().contains("UNKNOWN")); } Mockito.verify(jdbcClient).closeClient(); @@ -541,10 +535,10 @@ public void testOceanBaseEmptyCompatibilityModeResultIsRejected() throws Excepti Mockito.eq(DataSourceType.OCEANBASE), Mockito.anyMap())) .thenReturn(jdbcClient); - JobException exception = Assert.assertThrows(JobException.class, + JobException exception = Assertions.assertThrows(JobException.class, () -> DataSourceConfigValidator.validateSourceBeforeTableCreation( DataSourceType.OCEANBASE, new HashMap<>())); - Assert.assertTrue(exception.getMessage().contains("Failed to determine")); + Assertions.assertTrue(exception.getMessage().contains("Failed to determine")); } Mockito.verify(jdbcClient).closeClient(); @@ -562,11 +556,11 @@ public void testOceanBaseCompatibilityModeQueryFailurePreservesCause() throws Ex Mockito.eq(DataSourceType.OCEANBASE), Mockito.anyMap())) .thenReturn(jdbcClient); - JobException exception = Assert.assertThrows(JobException.class, + JobException exception = Assertions.assertThrows(JobException.class, () -> DataSourceConfigValidator.validateSourceBeforeTableCreation( DataSourceType.OCEANBASE, new HashMap<>())); - Assert.assertTrue(exception.getMessage().contains("query failed")); - Assert.assertNotNull(exception.getCause()); + Assertions.assertTrue(exception.getMessage().contains("query failed")); + Assertions.assertNotNull(exception.getCause()); } Mockito.verify(jdbcClient).closeClient(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/PostgresResourceValidatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/PostgresResourceValidatorTest.java index 27e3b04b2cd904..0dc550530f67f9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/PostgresResourceValidatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/PostgresResourceValidatorTest.java @@ -21,8 +21,8 @@ import org.apache.doris.job.exception.JobException; import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; @@ -35,11 +35,11 @@ public class PostgresResourceValidatorTest { @Test public void testRejectMultibyteOverLongDatabaseName() { String dbName = StringUtils.repeat("库", 22); - Assert.assertEquals(22, dbName.length()); + Assertions.assertEquals(22, dbName.length()); Map props = new HashMap<>(); props.put(DataSourceConfigKeys.DATABASE, dbName); - JobException e = Assert.assertThrows(JobException.class, + JobException e = Assertions.assertThrows(JobException.class, () -> PostgresResourceValidator.validate(props, "1", Collections.emptyList())); - Assert.assertTrue(e.getMessage(), e.getMessage().contains("bytes")); + Assertions.assertTrue(e.getMessage().contains("bytes"), e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobAdvanceSplitsTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobAdvanceSplitsTest.java index 507719685b01ad..24b94e11d4897a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobAdvanceSplitsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobAdvanceSplitsTest.java @@ -22,8 +22,8 @@ import org.apache.doris.job.offset.SourceOffsetProvider; import org.apache.doris.nereids.trees.plans.commands.insert.InsertIntoTableCommand; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -53,7 +53,7 @@ public void testLoopsUntilNoMoreSplits() throws Exception { // Many small tables: one split per round, splitting completes after 5 rounds. FakeOffsetProvider provider = new FakeOffsetProvider(1, 5); newJob(provider, 3600).advanceSplitsIfNeed(); - Assert.assertEquals("must keep admitting across rounds until noMoreSplits", 5, provider.rounds); + Assertions.assertEquals(5, provider.rounds, "must keep admitting across rounds until noMoreSplits"); } @Test @@ -61,8 +61,8 @@ public void testStopsAtPendingCap() throws Exception { // Fast producer that never finishes: must stop once the FE backlog cap is crossed. FakeOffsetProvider provider = new FakeOffsetProvider(100, -1); newJob(provider, 3600).advanceSplitsIfNeed(); - Assert.assertTrue("must stop once pending crosses the cap", provider.pendingSplitCount() >= CAP); - Assert.assertEquals("must not overshoot beyond one round past the cap", 6, provider.rounds); + Assertions.assertTrue(provider.pendingSplitCount() >= CAP, "must stop once pending crosses the cap"); + Assertions.assertEquals(6, provider.rounds, "must not overshoot beyond one round past the cap"); } @Test @@ -70,7 +70,7 @@ public void testBreaksWhenRoundProducesNothing() throws Exception { // A round that yields no new split (empty RPC / cursor moved) must break, not spin to deadline. FakeOffsetProvider provider = new FakeOffsetProvider(0, -1); newJob(provider, 3600).advanceSplitsIfNeed(); - Assert.assertEquals("must break after a no-progress round", 1, provider.rounds); + Assertions.assertEquals(1, provider.rounds, "must break after a no-progress round"); } @Test @@ -78,7 +78,7 @@ public void testSkipsWhenAlreadyDone() throws Exception { // Entry guard: noMoreSplits up front means the loop never runs. FakeOffsetProvider provider = new FakeOffsetProvider(1, 0); newJob(provider, 3600).advanceSplitsIfNeed(); - Assert.assertEquals("entry guard must skip the loop entirely", 0, provider.rounds); + Assertions.assertEquals(0, provider.rounds, "entry guard must skip the loop entirely"); } /** Minimal provider whose admission behaviour is fully controllable. */ diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobCheckDataQualityTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobCheckDataQualityTest.java index 06c5e1a5c75dbe..c15e22d9224ab5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobCheckDataQualityTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobCheckDataQualityTest.java @@ -24,8 +24,8 @@ import org.apache.doris.job.common.JobStatus; import org.apache.doris.job.exception.JobException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -74,9 +74,9 @@ private static void invokeCheckDataQuality(StreamingInsertJob job, long scannedR public void testNormalBatchWithinWindow() throws Exception { StreamingInsertJob job = newJob(0.10, 60_000L); invokeCheckDataQuality(job, 1000, 50); - Assert.assertEquals(1000L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); - Assert.assertEquals(50L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); - Assert.assertEquals(JobStatus.RUNNING, job.getJobStatus()); + Assertions.assertEquals(1000L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); + Assertions.assertEquals(50L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); + Assertions.assertEquals(JobStatus.RUNNING, job.getJobStatus()); } @Test @@ -92,8 +92,8 @@ public void testCombinedRatioViolationInsideWindow() throws Exception { } catch (JobException e) { thrown = e; } - Assert.assertNotNull("expected pause when combined ratio exceeds threshold", thrown); - Assert.assertEquals(JobStatus.PAUSED, job.getJobStatus()); + Assertions.assertNotNull(thrown, "expected pause when combined ratio exceeds threshold"); + Assertions.assertEquals(JobStatus.PAUSED, job.getJobStatus()); } // Bug reproducer: expired window with large clean data used to dilute a bad batch. @@ -111,9 +111,8 @@ public void testExpiredWindowDoesNotMaskBadBatch() throws Exception { } catch (JobException e) { thrown = e; } - Assert.assertNotNull("expected pause — bad batch (ratio=0.30) should not be diluted by expired window", - thrown); - Assert.assertEquals(JobStatus.PAUSED, job.getJobStatus()); + Assertions.assertNotNull(thrown, "expected pause — bad batch (ratio=0.30) should not be diluted by expired window"); + Assertions.assertEquals(JobStatus.PAUSED, job.getJobStatus()); } @Test @@ -126,9 +125,9 @@ public void testExpiredWindowRollsBeforeAccumulation() throws Exception { invokeCheckDataQuality(job, 100, 5); - Assert.assertEquals(100L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); - Assert.assertEquals(5L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); - Assert.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > oldStartTime); + Assertions.assertEquals(100L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); + Assertions.assertEquals(5L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); + Assertions.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > oldStartTime); } @Test @@ -141,9 +140,9 @@ public void testZeroScanBatchStillRollsExpiredWindow() throws Exception { invokeCheckDataQuality(job, 0, 0); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); - Assert.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > oldStartTime); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); + Assertions.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > oldStartTime); } private static StreamingInsertJob jobWithProperties(String maxIntervalSec) { @@ -167,8 +166,8 @@ public void testRecomputeDerivedFieldsRebuildsSampleWindowMs() throws Exception Deencapsulation.invoke(job, "recomputeDerivedFields"); - Assert.assertEquals(100_000L, (long) Deencapsulation.getField(job, "sampleWindowMs")); - Assert.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > 0L); + Assertions.assertEquals(100_000L, (long) Deencapsulation.getField(job, "sampleWindowMs")); + Assertions.assertTrue((long) Deencapsulation.getField(job, "sampleStartTime") > 0L); } @Test @@ -182,8 +181,8 @@ public void testModifyPropertiesInternalRefreshesDerivedFields() throws Exceptio alter.put(StreamingJobProperties.MAX_INTERVAL_SECOND_PROPERTY, "30"); Deencapsulation.invoke(job, "modifyPropertiesInternal", alter); - Assert.assertEquals(300_000L, (long) Deencapsulation.getField(job, "sampleWindowMs")); - Assert.assertEquals(30L, cfg.getTimerDefinition().getInterval().longValue()); + Assertions.assertEquals(300_000L, (long) Deencapsulation.getField(job, "sampleWindowMs")); + Assertions.assertEquals(30L, cfg.getTimerDefinition().getInterval().longValue()); } @Test @@ -194,8 +193,8 @@ public void testRecomputeDerivedFieldsResetsSampleCounters() throws Exception { Deencapsulation.invoke(job, "recomputeDerivedFields"); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); } @Test @@ -205,8 +204,8 @@ public void testMissingMaxFilterRatioIsNoop() throws Exception { invokeCheckDataQuality(job, 100, 50); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); - Assert.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); - Assert.assertEquals(JobStatus.RUNNING, job.getJobStatus()); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowScannedRows")); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(job, "sampleWindowFilteredRows")); + Assertions.assertEquals(JobStatus.RUNNING, job.getJobStatus()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLagTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLagTest.java index e1a64931c8be30..3ecee28f0b437f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLagTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLagTest.java @@ -24,8 +24,8 @@ import org.apache.doris.job.offset.jdbc.JdbcOffset; import org.apache.doris.job.offset.jdbc.JdbcSourceOffsetProvider; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; @@ -36,7 +36,7 @@ public class StreamingInsertJobLagTest { @Test public void testLastSourceEventTimestampUsesOffsetProvider() { StreamingInsertJob job = Deencapsulation.newInstance(StreamingInsertJob.class); - Assert.assertEquals(0L, job.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(0L, job.getLastSourceEventTimestampSeconds()); JdbcSourceOffsetProvider provider = new JdbcSourceOffsetProvider(); Map committedOffset = new HashMap<>(); @@ -46,9 +46,9 @@ public void testLastSourceEventTimestampUsesOffsetProvider() { provider.setCurrentOffset(new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset)))); Deencapsulation.setField(job, "offsetProvider", provider); - Assert.assertEquals(1787039821L, job.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(1787039821L, job.getLastSourceEventTimestampSeconds()); job.setLastTaskSuccessTime(1787039821123L); - Assert.assertEquals(1787039821L, job.getLastTaskSuccessTimeSeconds()); + Assertions.assertEquals(1787039821L, job.getLastTaskSuccessTimeSeconds()); } @Test @@ -71,6 +71,6 @@ public void testExplicitOffsetChangeInvalidatesLastObservedLag() throws Exceptio alterProperties.put(StreamingJobProperties.OFFSET_PROPERTY, "{\"lsn\":\"200\"}"); Deencapsulation.invoke(job, "modifyPropertiesInternal", alterProperties); - Assert.assertEquals(-1, provider.getLagBytes()); + Assertions.assertEquals(-1, provider.getLagBytes()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLateCallbackTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLateCallbackTest.java index 66c0679d1b1178..887dc426b8585f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLateCallbackTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobLateCallbackTest.java @@ -23,8 +23,8 @@ import org.apache.doris.job.common.TaskStatus; import org.apache.doris.job.offset.jdbc.JdbcSourceOffsetProvider; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -45,10 +45,8 @@ public void testCancelMarksIsCanceledOnFailedTask() { task.cancel(true); - Assert.assertTrue("isCanceled must flip even when task already FAILED", - task.getIsCanceled().get()); - Assert.assertEquals("status preserved when already terminal", - TaskStatus.FAILED, task.getStatus()); + Assertions.assertTrue(task.getIsCanceled().get(), "isCanceled must flip even when task already FAILED"); + Assertions.assertEquals(TaskStatus.FAILED, task.getStatus(), "status preserved when already terminal"); } @Test @@ -57,8 +55,8 @@ public void testCancelMarksIsCanceledOnSuccessTask() { task.cancel(true); - Assert.assertTrue(task.getIsCanceled().get()); - Assert.assertEquals(TaskStatus.SUCCESS, task.getStatus()); + Assertions.assertTrue(task.getIsCanceled().get()); + Assertions.assertEquals(TaskStatus.SUCCESS, task.getStatus()); } @Test @@ -67,8 +65,8 @@ public void testCancelTransitionsRunningToCanceled() { task.cancel(true); - Assert.assertTrue(task.getIsCanceled().get()); - Assert.assertEquals(TaskStatus.CANCELED, task.getStatus()); + Assertions.assertTrue(task.getIsCanceled().get()); + Assertions.assertEquals(TaskStatus.CANCELED, task.getStatus()); } @Test @@ -76,13 +74,12 @@ public void testCancelIdempotent() { StreamingMultiTblTask task = newTask(1004L, TaskStatus.RUNNING); task.cancel(true); - Assert.assertEquals(TaskStatus.CANCELED, task.getStatus()); - Assert.assertTrue(task.getIsCanceled().get()); + Assertions.assertEquals(TaskStatus.CANCELED, task.getStatus()); + Assertions.assertTrue(task.getIsCanceled().get()); Deencapsulation.setField(task, "errMsg", "first cancel"); task.cancel(true); - Assert.assertEquals("second cancel must early-return and leave state untouched", - "first cancel", Deencapsulation.getField(task, "errMsg")); + Assertions.assertEquals("first cancel", Deencapsulation.getField(task, "errMsg"), "second cancel must early-return and leave state untouched"); } @Test @@ -99,7 +96,7 @@ public void testCommitOffsetSkipsCanceledTask() throws Exception { StreamingMultiTblTask task = newTask(7777L, TaskStatus.FAILED); // simulate the bug timeline: task already FAILED via onFail, then cancel marks isCanceled. task.cancel(true); - Assert.assertTrue(task.getIsCanceled().get()); + Assertions.assertTrue(task.getIsCanceled().get()); Deencapsulation.setField(job, "runningStreamTask", task); @@ -114,7 +111,6 @@ public void testCommitOffsetSkipsCanceledTask() throws Exception { // no successCallback side-effects. job.commitOffset(req); - Assert.assertEquals("task status must stay terminal — late callback ignored", - TaskStatus.FAILED, task.getStatus()); + Assertions.assertEquals(TaskStatus.FAILED, task.getStatus(), "task status must stay terminal — late callback ignored"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobOffsetPersistenceTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobOffsetPersistenceTest.java index 0b13d0ec74586e..e3246f1b53074e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobOffsetPersistenceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingInsertJobOffsetPersistenceTest.java @@ -31,8 +31,8 @@ import org.apache.doris.transaction.GlobalTransactionMgrIface; import org.apache.doris.transaction.TxnStateCallbackFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -50,8 +50,8 @@ public void testFirstSnapshotCommitPersistsImmediately() throws Exception { job.commitOffset(snapshotRequest(1001L, "source_table:0", null)); - Assert.assertEquals(1, job.journalCount); - Assert.assertNotNull(job.getOffsetProviderPersist()); + Assertions.assertEquals(1, job.journalCount); + Assertions.assertNotNull(job.getOffsetProviderPersist()); } @Test @@ -64,8 +64,8 @@ public void testSnapshotCommitWithinIntervalDoesNotPersistAgain() throws Excepti provider.getRemainingSplits().add(snapshotSplit("source_table:1")); job.commitOffset(snapshotRequest(1003L, "source_table:1", null)); - Assert.assertEquals(1, job.journalCount); - Assert.assertNotNull(job.getOffsetProviderPersist()); + Assertions.assertEquals(1, job.journalCount); + Assertions.assertNotNull(job.getOffsetProviderPersist()); } @Test @@ -76,8 +76,8 @@ public void testBinlogCommitPersistsImmediately() throws Exception { job.commitOffset(binlogRequest(1002L, "100")); job.commitOffset(binlogRequest(1002L, "200")); - Assert.assertEquals(2, job.journalCount); - Assert.assertNotNull(job.getOffsetProviderPersist()); + Assertions.assertEquals(2, job.journalCount); + Assertions.assertNotNull(job.getOffsetProviderPersist()); } @Test @@ -86,14 +86,14 @@ public void testSnapshotToBinlogTransitionPersistsCompactedState() throws Except provider.getRemainingSplits().add(snapshotSplit("source_table:0")); TestStreamingInsertJob job = newJob(provider, 1008L); job.commitOffset(snapshotRequest(1008L, "source_table:0", null)); - Assert.assertEquals(1, job.journalCount); + Assertions.assertEquals(1, job.journalCount); job.commitOffset(binlogRequest(1008L, "200")); - Assert.assertEquals(2, job.journalCount); - Assert.assertFalse(job.getOffsetProviderPersist().contains("source_table:0")); - Assert.assertTrue(provider.getFinishedSplits().isEmpty()); - Assert.assertTrue(provider.getChunkHighWatermarkMap().isEmpty()); + Assertions.assertEquals(2, job.journalCount); + Assertions.assertFalse(job.getOffsetProviderPersist().contains("source_table:0")); + Assertions.assertTrue(provider.getFinishedSplits().isEmpty()); + Assertions.assertTrue(provider.getChunkHighWatermarkMap().isEmpty()); } @Test @@ -106,14 +106,14 @@ public void testSnapshotOffsetPersistsOnNextCommitAfterInterval() throws Excepti TestStreamingInsertJob job = newJob(provider, 1011L); job.commitOffset(snapshotRequest(1011L, "source_table:0", null)); - Assert.assertEquals(1, job.journalCount); + Assertions.assertEquals(1, job.journalCount); Deencapsulation.setField(job, "lastOffsetPersistTimeMs", System.currentTimeMillis() - 300_000L); provider.getRemainingSplits().add(snapshotSplit("source_table:1")); job.commitOffset(snapshotRequest(1011L, "source_table:1", null)); - Assert.assertEquals(2, job.journalCount); - Assert.assertTrue((long) Deencapsulation.getField(job, "lastOffsetPersistTimeMs") > 0L); + Assertions.assertEquals(2, job.journalCount); + Assertions.assertTrue((long) Deencapsulation.getField(job, "lastOffsetPersistTimeMs") > 0L); } finally { Config.streaming_job_snapshot_offset_persist_interval_sec = oldInterval; } @@ -130,9 +130,9 @@ public void testAlterOffsetReplacesSnapshotState() throws Exception { properties.put(StreamingJobProperties.OFFSET_PROPERTY, "{\"lsn\":\"300\"}"); Deencapsulation.invoke(job, "modifyPropertiesInternal", properties); - Assert.assertTrue(job.getOffsetProviderPersist().contains("300")); - Assert.assertTrue(provider.getFinishedSplits().isEmpty()); - Assert.assertTrue(provider.getChunkHighWatermarkMap().isEmpty()); + Assertions.assertTrue(job.getOffsetProviderPersist().contains("300")); + Assertions.assertTrue(provider.getFinishedSplits().isEmpty()); + Assertions.assertTrue(provider.getChunkHighWatermarkMap().isEmpty()); } @Test @@ -156,9 +156,9 @@ public void testNaturalFinishPersistsFinalState() throws Exception { long beforeFinish = System.currentTimeMillis(); job.onStreamTaskSuccess(task); - Assert.assertEquals(JobStatus.FINISHED, job.getJobStatus()); - Assert.assertTrue(job.getFinishTimeMs() >= beforeFinish); - Assert.assertEquals(1, job.journalCount); + Assertions.assertEquals(JobStatus.FINISHED, job.getJobStatus()); + Assertions.assertTrue(job.getFinishTimeMs() >= beforeFinish); + Assertions.assertEquals(1, job.journalCount); Mockito.verify(callbackFactory).removeCallback(9001L); } } @@ -178,8 +178,8 @@ public void testReplayUpdatedRestoresFinalStateAndRemovesCallback() { job.replayOnUpdated(replayJob); - Assert.assertEquals(JobStatus.FINISHED, job.getJobStatus()); - Assert.assertEquals(1234L, job.getFinishTimeMs()); + Assertions.assertEquals(JobStatus.FINISHED, job.getJobStatus()); + Assertions.assertEquals(1234L, job.getFinishTimeMs()); Mockito.verify(callbackFactory).removeCallback(9001L); } } @@ -192,7 +192,7 @@ public void testReplayUpdatedRestoresStartTime() { job.replayOnUpdated(replayJob); - Assert.assertEquals(1234L, job.getStartTimeMs()); + Assertions.assertEquals(1234L, job.getStartTimeMs()); } private static TestStreamingInsertJob newJob(JdbcSourceOffsetProvider provider, long taskId) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJdbcUrlNormalizerTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJdbcUrlNormalizerTest.java index 2dda159a11dcde..644e7dec742f3e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJdbcUrlNormalizerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJdbcUrlNormalizerTest.java @@ -19,8 +19,8 @@ import org.apache.doris.job.common.DataSourceType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class StreamingJdbcUrlNormalizerTest { @@ -29,10 +29,10 @@ public void testNormalizeMysqlJdbcUrl() { String jdbcUrl = StreamingJdbcUrlNormalizer.normalize( DataSourceType.MYSQL, "jdbc:mysql://127.0.0.1:3306/test"); - Assert.assertEquals("jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=false" + Assertions.assertEquals("jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=false" + "&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8", jdbcUrl); - Assert.assertFalse(jdbcUrl.contains("rewriteBatchedStatements")); + Assertions.assertFalse(jdbcUrl.contains("rewriteBatchedStatements")); } @Test @@ -40,11 +40,11 @@ public void testNormalizeMysqlJdbcUrlPreservesExplicitValues() { String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/test?tinyInt1isBit=true" + "&yearIsDateType=true&useUnicode=false&characterEncoding=GBK"; - Assert.assertEquals(jdbcUrl, + Assertions.assertEquals(jdbcUrl, StreamingJdbcUrlNormalizer.normalize(DataSourceType.MYSQL, jdbcUrl)); String partialJdbcUrl = "jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=true"; - Assert.assertEquals(partialJdbcUrl + "&tinyInt1isBit=false" + Assertions.assertEquals(partialJdbcUrl + "&tinyInt1isBit=false" + "&useUnicode=true&characterEncoding=utf-8", StreamingJdbcUrlNormalizer.normalize(DataSourceType.MYSQL, partialJdbcUrl)); } @@ -54,7 +54,7 @@ public void testNormalizeMysqlJdbcUrlMatchesExactParameterNames() { String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/test?YEARISDATETYPE=true" + "&custom=characterEncoding=utf-8"; - Assert.assertEquals(jdbcUrl + "&yearIsDateType=false&tinyInt1isBit=false" + Assertions.assertEquals(jdbcUrl + "&yearIsDateType=false&tinyInt1isBit=false" + "&useUnicode=true&characterEncoding=utf-8", StreamingJdbcUrlNormalizer.normalize(DataSourceType.MYSQL, jdbcUrl)); } @@ -64,7 +64,7 @@ public void testNormalizeMysqlJdbcUrlIsIdempotent() { String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=false" + "&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8"; - Assert.assertEquals(jdbcUrl, + Assertions.assertEquals(jdbcUrl, StreamingJdbcUrlNormalizer.normalize(DataSourceType.MYSQL, jdbcUrl)); } @@ -73,7 +73,7 @@ public void testNormalizeOceanBaseJdbcUrlUsesMysqlRules() { String jdbcUrl = StreamingJdbcUrlNormalizer.normalize( DataSourceType.OCEANBASE, "jdbc:mysql://127.0.0.1:2883/test"); - Assert.assertEquals("jdbc:mysql://127.0.0.1:2883/test?yearIsDateType=false" + Assertions.assertEquals("jdbc:mysql://127.0.0.1:2883/test?yearIsDateType=false" + "&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8", jdbcUrl); } @@ -82,7 +82,7 @@ public void testNormalizeOceanBaseJdbcUrlUsesMysqlRules() { public void testNormalizePostgresJdbcUrlDoesNotChange() { String jdbcUrl = "jdbc:postgresql://127.0.0.1:5432/test"; - Assert.assertEquals(jdbcUrl, + Assertions.assertEquals(jdbcUrl, StreamingJdbcUrlNormalizer.normalize(DataSourceType.POSTGRES, jdbcUrl)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJobPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJobPropertiesTest.java index 97a98031dde389..10ae94e1cc06c2 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJobPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingJobPropertiesTest.java @@ -23,8 +23,8 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.qe.SessionVariable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; @@ -39,11 +39,11 @@ public class StreamingJobPropertiesTest { public void testConstructorParsesPropertiesWithoutValidate() { // Case 1: empty properties -> should use defaults StreamingJobProperties emptyProps = new StreamingJobProperties(new HashMap<>()); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, emptyProps.getMaxIntervalSecond()); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_FILES, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_FILES, emptyProps.getS3BatchFiles()); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_BYTES, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_BYTES, emptyProps.getS3BatchBytes()); // Case 2: explicit max_interval=1 (the bug scenario) @@ -51,15 +51,15 @@ public void testConstructorParsesPropertiesWithoutValidate() { HashMap props = new HashMap<>(); props.put("max_interval", "1"); StreamingJobProperties customProps = new StreamingJobProperties(props); - Assert.assertEquals(1L, customProps.getMaxIntervalSecond()); + Assertions.assertEquals(1L, customProps.getMaxIntervalSecond()); // Case 3: explicit max_interval=5 HashMap props2 = new HashMap<>(); props2.put("max_interval", "5"); StreamingJobProperties customProps2 = new StreamingJobProperties(props2); - Assert.assertEquals(5L, customProps2.getMaxIntervalSecond()); + Assertions.assertEquals(5L, customProps2.getMaxIntervalSecond()); // s3 properties not set -> should use defaults - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_FILES, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_S3_BATCH_FILES, customProps2.getS3BatchFiles()); } @@ -73,21 +73,21 @@ public void testConstructorHandlesBadValues() { HashMap props = new HashMap<>(); props.put("max_interval", "abc"); StreamingJobProperties p = new StreamingJobProperties(props); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, p.getMaxIntervalSecond()); // zero value -> fallback to default (must be >= 1) HashMap props2 = new HashMap<>(); props2.put("max_interval", "0"); StreamingJobProperties p2 = new StreamingJobProperties(props2); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, p2.getMaxIntervalSecond()); // negative value -> fallback to default HashMap props3 = new HashMap<>(); props3.put("max_interval", "-1"); StreamingJobProperties p3 = new StreamingJobProperties(props3); - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, p3.getMaxIntervalSecond()); } @@ -101,10 +101,10 @@ public void testValidateStillRejectsBadValues() { props.put("max_interval", "0"); StreamingJobProperties p = new StreamingJobProperties(props); // constructor fallback is fine - Assert.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, + Assertions.assertEquals(StreamingJobProperties.DEFAULT_MAX_INTERVAL_SECOND, p.getMaxIntervalSecond()); // but validate() should throw - Assert.assertThrows(AnalysisException.class, p::validate); + Assertions.assertThrows(AnalysisException.class, p::validate); } @Test @@ -113,8 +113,8 @@ public void testSessionVariables() throws JobException { StreamingJobProperties jobProperties = new StreamingJobProperties(new HashMap<>()); ConnectContext ctx = InsertTask.makeConnectContext(null, null); SessionVariable defaultSessionVar = jobProperties.getSessionVariable(ctx.getSessionVariable()); - Assert.assertEquals(StreamingJobProperties.DEFAULT_JOB_INSERT_TIMEOUT, defaultSessionVar.getInsertTimeoutS()); - Assert.assertEquals(StreamingJobProperties.DEFAULT_JOB_QUERY_TIMEOUT, defaultSessionVar.getQueryTimeoutS()); + Assertions.assertEquals(StreamingJobProperties.DEFAULT_JOB_INSERT_TIMEOUT, defaultSessionVar.getInsertTimeoutS()); + Assertions.assertEquals(StreamingJobProperties.DEFAULT_JOB_QUERY_TIMEOUT, defaultSessionVar.getQueryTimeoutS()); // set session var ctx = InsertTask.makeConnectContext(null, null); @@ -124,8 +124,8 @@ public void testSessionVariables() throws JobException { ctx.setSessionVariable(userSessionVar); SessionVariable userSessionVarRes = jobProperties.getSessionVariable(ctx.getSessionVariable()); - Assert.assertEquals(1, userSessionVarRes.getInsertTimeoutS()); - Assert.assertEquals(2, userSessionVarRes.getQueryTimeoutS()); + Assertions.assertEquals(1, userSessionVarRes.getInsertTimeoutS()); + Assertions.assertEquals(2, userSessionVarRes.getQueryTimeoutS()); // set session map in job properties ctx = InsertTask.makeConnectContext(null, null); @@ -134,7 +134,7 @@ public void testSessionVariables() throws JobException { props.put("session.query_timeout", "20"); StreamingJobProperties jobPropertiesMap = new StreamingJobProperties(props); SessionVariable sessionVarMap = jobPropertiesMap.getSessionVariable(ctx.getSessionVariable()); - Assert.assertEquals(10, sessionVarMap.getInsertTimeoutS()); - Assert.assertEquals(20, sessionVarMap.getQueryTimeoutS()); + Assertions.assertEquals(10, sessionVarMap.getInsertTimeoutS()); + Assertions.assertEquals(20, sessionVarMap.getQueryTimeoutS()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingMultiTblTaskTimeoutTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingMultiTblTaskTimeoutTest.java index 453c4ef202e77a..3b646bf3f1a6ae 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingMultiTblTaskTimeoutTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/extensions/insert/streaming/StreamingMultiTblTaskTimeoutTest.java @@ -20,14 +20,14 @@ import org.apache.doris.common.Config; import org.apache.doris.job.cdc.StreamingTaskStatus; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class StreamingMultiTblTaskTimeoutTest { - @Before + @BeforeEach public void setup() { Config.streaming_task_timeout_multiplier = 10; Config.streaming_task_min_timeout_sec = 300; @@ -54,36 +54,36 @@ private StreamingTaskStatus status(long scanned) { @Test public void readAdvancingRenewsDeadline() { StreamingMultiTblTask t = newTask(10 * 3600_000L, 60L); - Assert.assertFalse(t.isTimeout(status(2000))); + Assertions.assertFalse(t.isTimeout(status(2000))); } @Test public void noProgressWithinBudgetNotTimeout() { StreamingMultiTblTask t = newTask(5 * 60_000L, 60L); - Assert.assertFalse(t.isTimeout(status(1000))); + Assertions.assertFalse(t.isTimeout(status(1000))); } @Test public void noProgressOverBudgetTimeout() { StreamingMultiTblTask t = newTask(11 * 60_000L, 60L); - Assert.assertTrue(t.isTimeout(status(1000))); + Assertions.assertTrue(t.isTimeout(status(1000))); } @Test public void smallIntervalFlooredByMinTimeout() { StreamingMultiTblTask t = newTask(4 * 60_000L, 1L); - Assert.assertFalse(t.isTimeout(status(1000))); + Assertions.assertFalse(t.isTimeout(status(1000))); } @Test public void nullProgressBehavesLikeOldTimeout() { StreamingMultiTblTask t = newTask(11 * 60_000L, 60L); - Assert.assertTrue(t.isTimeout(null)); + Assertions.assertTrue(t.isTimeout(null)); } @Test public void localTimeoutGatesProgressPull() { - Assert.assertFalse(newTask(5 * 60_000L, 60L).isLocalTimeout()); - Assert.assertTrue(newTask(11 * 60_000L, 60L).isLocalTimeout()); + Assertions.assertFalse(newTask(5 * 60_000L, 60L).isLocalTimeout()); + Assertions.assertTrue(newTask(11 * 60_000L, 60L).isLocalTimeout()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/manager/JobManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/manager/JobManagerTest.java index 0e2c07fd072316..11042e4008c4a8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/manager/JobManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/manager/JobManagerTest.java @@ -28,8 +28,8 @@ import org.apache.doris.utframe.TestWithFeService; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -52,8 +52,8 @@ public void testJobAuth() throws IOException, AnalysisException { manager.checkJobAuth("ctl1", "db1", tableNames); throw new RuntimeException("should exception"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Admin_priv,Load_priv")); - Assert.assertTrue(e.getMessage().contains("db1")); + Assertions.assertTrue(e.getMessage().contains("Admin_priv,Load_priv")); + Assertions.assertTrue(e.getMessage().contains("db1")); } tableNames.add("table1"); try { @@ -61,8 +61,8 @@ public void testJobAuth() throws IOException, AnalysisException { manager.checkJobAuth("ctl1", "db1", tableNames); throw new RuntimeException("should exception"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Admin_priv,Load_priv")); - Assert.assertTrue(e.getMessage().contains("table1")); + Assertions.assertTrue(e.getMessage().contains("Admin_priv,Load_priv")); + Assertions.assertTrue(e.getMessage().contains("table1")); } } } @@ -94,9 +94,9 @@ public void testCancelTaskByIdNotBlockedByOtherStreamingJob() throws JobExceptio // Cancelling the streaming job itself still rejected. try { manager.cancelTaskById("streaming_job", 100L); - Assert.fail("expected JobException for streaming job"); + Assertions.fail("expected JobException for streaming job"); } catch (JobException e) { - Assert.assertTrue(e.getMessage().contains("streaming job not support")); + Assertions.assertTrue(e.getMessage().contains("streaming job not support")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderAsyncSplitTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderAsyncSplitTest.java index a4a1230aada6ff..033f5c8f50d57a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderAsyncSplitTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderAsyncSplitTest.java @@ -22,9 +22,10 @@ import org.apache.doris.job.exception.JobException; import org.apache.doris.job.util.StreamingJobUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +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.mockito.ArgumentMatchers; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -93,7 +94,7 @@ public Long getJobId() { private TestableProvider provider; private MockedStatic utilsMock; - @Before + @BeforeEach public void setup() { provider = new TestableProvider(); utilsMock = Mockito.mockStatic(StreamingJobUtils.class); @@ -104,7 +105,7 @@ public void setup() { .then(invocation -> null); } - @org.junit.After + @AfterEach public void tearDown() { if (utilsMock != null) { utilsMock.close(); @@ -127,16 +128,16 @@ private static SnapshotSplit split(String tableId, int chunkId, Long start, Long @Test public void testInitWithEmptySyncTablesIsAllDone() throws JobException { provider.initOnCreate(Collections.emptyList()); - Assert.assertTrue(provider.noMoreSplits()); + Assertions.assertTrue(provider.noMoreSplits()); } @Test public void testInitWithSyncTablesNotDone() throws JobException { provider.initOnCreate(Arrays.asList("db.tbl_a")); - Assert.assertNotNull(provider.committedSplitProgress); - Assert.assertNotNull(provider.cdcSplitProgress); - Assert.assertNull(provider.cdcSplitProgress.getCurrentSplittingTable()); - Assert.assertFalse(provider.noMoreSplits()); + Assertions.assertNotNull(provider.committedSplitProgress); + Assertions.assertNotNull(provider.cdcSplitProgress); + Assertions.assertNull(provider.cdcSplitProgress.getCurrentSplittingTable()); + Assertions.assertFalse(provider.noMoreSplits()); } @Test @@ -147,7 +148,7 @@ public void testNoMoreSplitsTrueAfterBinlogTransition() throws JobException { // scheduler re-cut snapshot chunks after snapshot phase is over. provider.initOnCreate(Arrays.asList("db.tbl_a", "db.tbl_b")); provider.setCurrentOffset(new JdbcOffset(Collections.singletonList(new BinlogSplit()))); - Assert.assertTrue(provider.noMoreSplits()); + Assertions.assertTrue(provider.noMoreSplits()); } @Test @@ -157,7 +158,7 @@ public void testNoMoreSplitsStillFalseDuringSnapshot() throws JobException { provider.initOnCreate(Arrays.asList("db.tbl_a")); provider.setCurrentOffset(new JdbcOffset( Collections.singletonList(split("db.tbl_a", 0, null, 100L)))); - Assert.assertFalse(provider.noMoreSplits()); + Assertions.assertFalse(provider.noMoreSplits()); } // ===== advanceSplits ===== @@ -171,16 +172,16 @@ public void testAdvanceFirstCallPicksFirstTableWithNullStart() throws JobExcepti provider.advanceSplits(); - Assert.assertEquals(2, provider.remainingSplits.size()); - Assert.assertEquals("tbl_a", provider.cdcSplitProgress.getCurrentSplittingTable()); - Assert.assertArrayEquals(new Object[]{200L}, provider.cdcSplitProgress.getNextSplitStart()); - Assert.assertEquals(Integer.valueOf(2), provider.cdcSplitProgress.getNextSplitId()); + Assertions.assertEquals(2, provider.remainingSplits.size()); + Assertions.assertEquals("tbl_a", provider.cdcSplitProgress.getCurrentSplittingTable()); + Assertions.assertArrayEquals(new Object[]{200L}, provider.cdcSplitProgress.getNextSplitStart()); + Assertions.assertEquals(Integer.valueOf(2), provider.cdcSplitProgress.getNextSplitId()); - Assert.assertEquals(1, provider.rpcCalls.size()); + Assertions.assertEquals(1, provider.rpcCalls.size()); RpcCall first = provider.rpcCalls.get(0); - Assert.assertEquals("tbl_a", first.table); - Assert.assertNull("first call should pass null nextSplitStart (= START_BOUND)", first.startVal); - Assert.assertNull(first.splitId); + Assertions.assertEquals("tbl_a", first.table); + Assertions.assertNull(first.startVal, "first call should pass null nextSplitStart (= START_BOUND)"); + Assertions.assertNull(first.splitId); } @Test @@ -192,12 +193,12 @@ public void testAdvanceContinuesOnSameTableAfterFirstBatch() throws JobException provider.advanceSplits(); provider.advanceSplits(); - Assert.assertEquals(2, provider.rpcCalls.size()); + Assertions.assertEquals(2, provider.rpcCalls.size()); RpcCall second = provider.rpcCalls.get(1); - Assert.assertEquals("tbl_a", second.table); - Assert.assertArrayEquals(new Object[]{100L}, second.startVal); - Assert.assertEquals(Integer.valueOf(1), second.splitId); - Assert.assertEquals(2, provider.remainingSplits.size()); + Assertions.assertEquals("tbl_a", second.table); + Assertions.assertArrayEquals(new Object[]{100L}, second.startVal); + Assertions.assertEquals(Integer.valueOf(1), second.splitId); + Assertions.assertEquals(2, provider.remainingSplits.size()); } @Test @@ -209,16 +210,15 @@ public void testAdvanceTableDoneSwitchesToNextTable() throws JobException { provider.mockBatches.add(Arrays.asList(split("db.tbl_b", 0, null, 50L))); provider.advanceSplits(); - Assert.assertNull("after tbl_a done, currentSplittingTable should clear", - provider.cdcSplitProgress.getCurrentSplittingTable()); - Assert.assertFalse("tbl_b still pending", provider.noMoreSplits()); + Assertions.assertNull(provider.cdcSplitProgress.getCurrentSplittingTable(), "after tbl_a done, currentSplittingTable should clear"); + Assertions.assertFalse(provider.noMoreSplits(), "tbl_b still pending"); provider.advanceSplits(); - Assert.assertEquals(2, provider.rpcCalls.size()); - Assert.assertEquals("tbl_b", provider.rpcCalls.get(1).table); - Assert.assertEquals("tbl_b", provider.cdcSplitProgress.getCurrentSplittingTable()); - Assert.assertArrayEquals(new Object[]{50L}, provider.cdcSplitProgress.getNextSplitStart()); + Assertions.assertEquals(2, provider.rpcCalls.size()); + Assertions.assertEquals("tbl_b", provider.rpcCalls.get(1).table); + Assertions.assertEquals("tbl_b", provider.cdcSplitProgress.getCurrentSplittingTable()); + Assertions.assertArrayEquals(new Object[]{50L}, provider.cdcSplitProgress.getNextSplitStart()); } @Test @@ -228,8 +228,8 @@ public void testAllSyncTablesDoneMakesNoMoreSplitsTrue() throws JobException { provider.advanceSplits(); - Assert.assertTrue(provider.noMoreSplits()); - Assert.assertEquals(1, provider.remainingSplits.size()); + Assertions.assertTrue(provider.noMoreSplits()); + Assertions.assertEquals(1, provider.remainingSplits.size()); } @Test @@ -242,8 +242,7 @@ public void testAdvanceSplitsDedupsBySplitId() throws JobException { provider.advanceSplits(); - Assert.assertEquals("duplicate splitId should be filtered out", - 1, provider.remainingSplits.size()); + Assertions.assertEquals(1, provider.remainingSplits.size(), "duplicate splitId should be filtered out"); } @Test @@ -252,11 +251,11 @@ public void testAdvanceWithEmptyBatchIsNoop() throws JobException { // mockBatches empty → rpcFetchSplitsBatch returns empty list provider.advanceSplits(); - Assert.assertEquals(0, provider.remainingSplits.size()); + Assertions.assertEquals(0, provider.remainingSplits.size()); // currentSplittingTable was set then RPC returned empty; we leave it set // (next advance retries on same table from null start). Just assert no progress. - Assert.assertNull(provider.cdcSplitProgress.getNextSplitStart()); - Assert.assertNull(provider.cdcSplitProgress.getNextSplitId()); + Assertions.assertNull(provider.cdcSplitProgress.getNextSplitStart()); + Assertions.assertNull(provider.cdcSplitProgress.getNextSplitId()); } // ===== updateOffset advances committedSplitProgress ===== @@ -281,13 +280,13 @@ public void testUpdateOffsetAdvancesCommittedProgressOnMidChunk() throws JobExce JdbcOffset endOffset = new JdbcOffset(Collections.singletonList(commitSplit("db.tbl_a:0"))); provider.updateOffset(endOffset); - Assert.assertEquals(1, provider.finishedSplits.size()); - Assert.assertEquals(1, provider.remainingSplits.size()); + Assertions.assertEquals(1, provider.finishedSplits.size()); + Assertions.assertEquals(1, provider.remainingSplits.size()); JdbcSourceOffsetProvider.SplitProgress committed = provider.committedSplitProgress; - Assert.assertEquals("tbl_a", committed.getCurrentSplittingTable()); - Assert.assertArrayEquals(new Object[]{100L}, committed.getNextSplitStart()); - Assert.assertEquals(Integer.valueOf(1), committed.getNextSplitId()); + Assertions.assertEquals("tbl_a", committed.getCurrentSplittingTable()); + Assertions.assertArrayEquals(new Object[]{100L}, committed.getNextSplitStart()); + Assertions.assertEquals(Integer.valueOf(1), committed.getNextSplitId()); } @Test @@ -300,11 +299,11 @@ public void testUpdateOffsetLastChunkClearsCommittedProgress() throws JobExcepti provider.updateOffset(endOffset); JdbcSourceOffsetProvider.SplitProgress committed = provider.committedSplitProgress; - Assert.assertNull(committed.getCurrentSplittingTable()); - Assert.assertNull(committed.getNextSplitStart()); - Assert.assertNull(committed.getNextSplitId()); - Assert.assertEquals(1, provider.finishedSplits.size()); - Assert.assertEquals(0, provider.remainingSplits.size()); + Assertions.assertNull(committed.getCurrentSplittingTable()); + Assertions.assertNull(committed.getNextSplitStart()); + Assertions.assertNull(committed.getNextSplitId()); + Assertions.assertEquals(1, provider.finishedSplits.size()); + Assertions.assertEquals(0, provider.remainingSplits.size()); } @Test @@ -316,8 +315,8 @@ public void testUpdateOffsetReplayPathSkipsWhenSplitMissing() throws JobExceptio provider.updateOffset(endOffset); // committed progress untouched; finishedSplits not added (we have nothing to fill in). - Assert.assertNull(provider.committedSplitProgress.getCurrentSplittingTable()); - Assert.assertEquals(0, provider.finishedSplits.size()); + Assertions.assertNull(provider.committedSplitProgress.getCurrentSplittingTable()); + Assertions.assertEquals(0, provider.finishedSplits.size()); } // ===== computeCdcRemainingTables (covered indirectly via noMoreSplits) ===== @@ -330,20 +329,20 @@ public void testTouchedTablesRemovedFromRemaining() throws JobException { // tbl_a is now done (in remainingSplits + currentSplittingTable cleared). // 2 more tables remain; noMoreSplits should still be false. - Assert.assertFalse(provider.noMoreSplits()); - Assert.assertNull(provider.cdcSplitProgress.getCurrentSplittingTable()); + Assertions.assertFalse(provider.noMoreSplits()); + Assertions.assertNull(provider.cdcSplitProgress.getCurrentSplittingTable()); // 2nd advance picks tbl_b provider.mockBatches.add(Arrays.asList(split("db.tbl_b", 0, null, null))); provider.advanceSplits(); - Assert.assertEquals("tbl_b", provider.rpcCalls.get(1).table); + Assertions.assertEquals("tbl_b", provider.rpcCalls.get(1).table); // 3rd advance picks tbl_c provider.mockBatches.add(Arrays.asList(split("db.tbl_c", 0, null, null))); provider.advanceSplits(); - Assert.assertEquals("tbl_c", provider.rpcCalls.get(2).table); + Assertions.assertEquals("tbl_c", provider.rpcCalls.get(2).table); - Assert.assertTrue(provider.noMoreSplits()); + Assertions.assertTrue(provider.noMoreSplits()); } // ===== findResumeMidSplit (replay helper) ===== @@ -356,7 +355,7 @@ public void testFindResumeMidSplitSingleTableFullyCutReturnsNull() { Collections.singletonList("db.tbl_a"), Arrays.asList(s0, s1), Collections.emptyList()); - Assert.assertNull(mid); + Assertions.assertNull(mid); } @Test @@ -367,9 +366,9 @@ public void testFindResumeMidSplitSingleTableCutToMid() { Collections.singletonList("db.tbl_a"), Arrays.asList(s0, s1), Collections.emptyList()); - Assert.assertNotNull(mid); - Assert.assertEquals("db.tbl_a:1", mid.getSplitId()); - Assert.assertArrayEquals(new Object[]{200L}, mid.getSplitEnd()); + Assertions.assertNotNull(mid); + Assertions.assertEquals("db.tbl_a:1", mid.getSplitId()); + Assertions.assertArrayEquals(new Object[]{200L}, mid.getSplitEnd()); } @Test @@ -381,8 +380,8 @@ public void testFindResumeMidSplitMultiTableOnlyOneMid() { Arrays.asList("db.tbl_a", "db.tbl_b", "db.tbl_c"), Collections.singletonList(a0), Collections.singletonList(b0)); - Assert.assertNotNull(mid); - Assert.assertEquals("db.tbl_b:0", mid.getSplitId()); + Assertions.assertNotNull(mid); + Assertions.assertEquals("db.tbl_b:0", mid.getSplitId()); } @Test @@ -395,16 +394,16 @@ public void testFindResumeMidSplitMaxIdSpreadAcrossLists() { Collections.singletonList("db.tbl_a"), Arrays.asList(f0, f1), Collections.singletonList(r2)); - Assert.assertNotNull(mid); - Assert.assertEquals("db.tbl_a:2", mid.getSplitId()); - Assert.assertArrayEquals(new Object[]{300L}, mid.getSplitEnd()); + Assertions.assertNotNull(mid); + Assertions.assertEquals("db.tbl_a:2", mid.getSplitId()); + Assertions.assertArrayEquals(new Object[]{300L}, mid.getSplitEnd()); } @Test public void testFindResumeMidSplitEmptyInputs() { - Assert.assertNull(JdbcSourceOffsetProvider.findResumeMidSplit( + Assertions.assertNull(JdbcSourceOffsetProvider.findResumeMidSplit( Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - Assert.assertNull(JdbcSourceOffsetProvider.findResumeMidSplit( + Assertions.assertNull(JdbcSourceOffsetProvider.findResumeMidSplit( Collections.singletonList("db.tbl_a"), Collections.emptyList(), Collections.emptyList())); } @@ -420,8 +419,8 @@ public void testFindResumeMidSplitBareSyncTableQualifiedSplitTableId() { Collections.singletonList("tbl_a"), Arrays.asList(s0, s1), Collections.emptyList()); - Assert.assertNotNull(mid); - Assert.assertEquals("schema.tbl_a:1", mid.getSplitId()); + Assertions.assertNotNull(mid); + Assertions.assertEquals("schema.tbl_a:1", mid.getSplitId()); } @Test @@ -433,37 +432,45 @@ public void testFindResumeMidSplitSyncTablesContainsUntouchedTable() { Arrays.asList("db.tbl_a", "db.tbl_b"), Collections.singletonList(a0), Collections.emptyList()); - Assert.assertNull(mid); + Assertions.assertNull(mid); } // ===== splitIdOf validation ===== @Test public void testSplitIdOfHappyPath() { - Assert.assertEquals(0, JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:0")); - Assert.assertEquals(42, JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:42")); + Assertions.assertEquals(0, JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:0")); + Assertions.assertEquals(42, JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:42")); // table with colon in its qualifier: lastIndexOf(':') takes the trailing one. - Assert.assertEquals(7, JdbcSourceOffsetProvider.splitIdOf("schema:tbl:7")); + Assertions.assertEquals(7, JdbcSourceOffsetProvider.splitIdOf("schema:tbl:7")); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSplitIdOfNoColonThrows() { - JdbcSourceOffsetProvider.splitIdOf("db.tbl_a_0"); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + JdbcSourceOffsetProvider.splitIdOf("db.tbl_a_0"); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSplitIdOfTrailingColonThrows() { - JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:"); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:"); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSplitIdOfNonNumericSuffixThrows() { - JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:abc"); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + JdbcSourceOffsetProvider.splitIdOf("db.tbl_a:abc"); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSplitIdOfNullThrows() { - JdbcSourceOffsetProvider.splitIdOf(null); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + JdbcSourceOffsetProvider.splitIdOf(null); + }); } // ===== mode gate ===== @@ -476,7 +483,7 @@ public void testNoMoreSplitsLatestModeAlwaysTrue() { // Even if cachedSyncTables is populated (e.g. by replayIfNeed), latest mode // must report noMoreSplits=true so scheduler skips advanceSplits entirely. provider.cachedSyncTables = Arrays.asList("db.tbl_a", "db.tbl_b"); - Assert.assertTrue(provider.noMoreSplits()); + Assertions.assertTrue(provider.noMoreSplits()); } @Test @@ -485,7 +492,6 @@ public void testNoMoreSplitsSnapshotModeStillRespectsState() throws JobException org.apache.doris.job.cdc.DataSourceConfigKeys.OFFSET, org.apache.doris.job.cdc.DataSourceConfigKeys.OFFSET_SNAPSHOT); provider.initOnCreate(Arrays.asList("db.tbl_a")); - Assert.assertFalse("snapshot mode with un-split tables must return false", - provider.noMoreSplits()); + Assertions.assertFalse(provider.noMoreSplits(), "snapshot mode with un-split tables must return false"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderErrorHandlingTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderErrorHandlingTest.java index 1da12b3c97a6e2..fe7b2304105e18 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderErrorHandlingTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderErrorHandlingTest.java @@ -21,8 +21,8 @@ import org.apache.doris.job.exception.JobException; import com.fasterxml.jackson.core.type.TypeReference; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; @@ -42,9 +42,9 @@ public void testParseSuccessEnvelopeReturnsTypedPayload() throws JobException { + "\"data\":[{\"splitId\":\"db.t:0\",\"tableId\":\"db.t\"}]}"; List splits = provider.parseCdcResponseData(response, new TypeReference>() {}); - Assert.assertEquals(1, splits.size()); - Assert.assertEquals("db.t:0", splits.get(0).getSplitId()); - Assert.assertEquals("db.t", splits.get(0).getTableId()); + Assertions.assertEquals(1, splits.size()); + Assertions.assertEquals("db.t:0", splits.get(0).getSplitId()); + Assertions.assertEquals("db.t", splits.get(0).getTableId()); } @Test @@ -54,10 +54,9 @@ public void testParseFailureEnvelopeSurfacesOriginalError() { String response = "{\"code\":1,\"msg\":\"Internal Error\",\"data\":\"" + realError + "\"}"; try { provider.parseCdcResponseData(response, new TypeReference>() {}); - Assert.fail("a failed envelope must throw"); + Assertions.fail("a failed envelope must throw"); } catch (JobException e) { - Assert.assertTrue("the real remote error must be surfaced, got: " + e.getMessage(), - e.getMessage().contains(realError)); + Assertions.assertTrue(e.getMessage().contains(realError), "the real remote error must be surfaced, got: " + e.getMessage()); } } @@ -68,10 +67,9 @@ public void testParseSuccessEnvelopeWithIncompatibleDataSurfacesRawResponse() { String response = "{\"code\":0,\"msg\":\"Success\",\"data\":\"not-a-map\"}"; try { provider.parseCdcResponseData(response, new TypeReference>() {}); - Assert.fail("an incompatible success payload must throw"); + Assertions.fail("an incompatible success payload must throw"); } catch (JobException e) { - Assert.assertTrue("the raw response must be surfaced, got: " + e.getMessage(), - e.getMessage().contains("not-a-map")); + Assertions.assertTrue(e.getMessage().contains("not-a-map"), "the raw response must be surfaced, got: " + e.getMessage()); } } @@ -81,10 +79,9 @@ public void testParseUnparseableResponseThrows() { String response = "502 Bad Gateway"; try { provider.parseCdcResponseData(response, new TypeReference() {}); - Assert.fail("an unparseable response must throw"); + Assertions.fail("an unparseable response must throw"); } catch (JobException e) { - Assert.assertTrue("the raw response must be surfaced, got: " + e.getMessage(), - e.getMessage().contains("502")); + Assertions.assertTrue(e.getMessage().contains("502"), "the raw response must be surfaced, got: " + e.getMessage()); } } @@ -98,9 +95,9 @@ protected void initSourceReader() throws JobException { }; try { provider.initOnCreate(Collections.singletonList("db.t")); - Assert.fail("CREATE JOB must fail when the remote reader cannot be opened"); + Assertions.fail("CREATE JOB must fail when the remote reader cannot be opened"); } catch (JobException e) { - Assert.assertTrue(e.getMessage().contains("simulated reader init failure")); + Assertions.assertTrue(e.getMessage().contains("simulated reader init failure")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderLagTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderLagTest.java index fbcf94af12a492..5d99b8196aa254 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderLagTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderLagTest.java @@ -25,8 +25,8 @@ import org.apache.doris.job.common.DataSourceType; import org.apache.doris.job.exception.JobException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -41,7 +41,7 @@ public void testPostgresSnapshotDoesNotSendFeReferenceOffset() { provider.finishedSplits.add(snapshotSplit("split-1", offset("lsn", "300"))); provider.finishedSplits.add(snapshotSplit("split-2", offset("lsn", "100"))); - Assert.assertNull(provider.getLagReferenceOffset()); + Assertions.assertNull(provider.getLagReferenceOffset()); } @Test @@ -51,7 +51,7 @@ public void testPostgresIncrementalPhaseUsesCommittedOffset() { provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset))); - Assert.assertEquals(committedOffset, provider.getLagReferenceOffset()); + Assertions.assertEquals(committedOffset, provider.getLagReferenceOffset()); } @Test @@ -61,7 +61,7 @@ public void testInitialSnapshotUsesFirstCommittedMysqlHighWatermark() { provider.finishedSplits.add(snapshotSplit("split-2", mysqlOffset("mysql-bin.000009", 900))); provider.finishedSplits.add(snapshotSplit("split-3", mysqlOffset("mysql-bin.000010", 50))); - Assert.assertEquals(mysqlOffset("mysql-bin.000010", 100), provider.getLagReferenceOffset()); + Assertions.assertEquals(mysqlOffset("mysql-bin.000010", 100), provider.getLagReferenceOffset()); } @Test @@ -72,7 +72,7 @@ public void testIncrementalPhaseUsesCommittedBinlogOffset() { provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset))); - Assert.assertEquals(committedOffset, provider.getLagReferenceOffset()); + Assertions.assertEquals(committedOffset, provider.getLagReferenceOffset()); } @Test @@ -83,7 +83,7 @@ public void testRestoredSnapshotToBinlogTransitionUsesSnapshotHighWatermark() { provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit())); - Assert.assertEquals(mysqlOffset("mysql-bin.000003", 300), provider.getLagReferenceOffset()); + Assertions.assertEquals(mysqlOffset("mysql-bin.000003", 300), provider.getLagReferenceOffset()); } @Test @@ -91,18 +91,18 @@ public void testSnapshotOnlyDoesNotExposeSourceLogLag() { JdbcSourceOffsetProvider provider = provider(DataSourceType.POSTGRES, DataSourceConfigKeys.OFFSET_SNAPSHOT); provider.finishedSplits.add(snapshotSplit("split-1", offset("lsn", "100"))); - Assert.assertNull(provider.getLagReferenceOffset()); - Assert.assertEquals("-1", provider.getLag()); + Assertions.assertNull(provider.getLagReferenceOffset()); + Assertions.assertEquals("-1", provider.getLag()); } @Test public void testLagIsAlwaysNumeric() { JdbcSourceOffsetProvider provider = new JdbcSourceOffsetProvider(); - Assert.assertEquals("-1", provider.getLag()); + Assertions.assertEquals("-1", provider.getLag()); provider.setLagBytes(4096); - Assert.assertEquals("4096", provider.getLag()); - Assert.assertEquals(4096, provider.getLagBytes()); + Assertions.assertEquals("4096", provider.getLag()); + Assertions.assertEquals(4096, provider.getLagBytes()); } @Test @@ -113,7 +113,7 @@ public void testMysqlLastSourceEventTimestampUsesCommittedOffsetSeconds() { provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset))); - Assert.assertEquals(1787039821L, provider.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(1787039821L, provider.getLastSourceEventTimestampSeconds()); } @Test @@ -125,7 +125,7 @@ public void testPostgresLastSourceEventTimestampConvertsCommittedOffsetMicrosToS provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset))); - Assert.assertEquals(1787039821L, provider.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(1787039821L, provider.getLastSourceEventTimestampSeconds()); } @Test @@ -137,7 +137,7 @@ public void testPostgresInitialOffsetTimestampIsUnavailable() { provider.currentOffset = new JdbcOffset(Collections.singletonList(new BinlogSplit(committedOffset))); - Assert.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); } @Test @@ -146,11 +146,11 @@ public void testLastSourceEventTimestampUnavailableBeforeCommittedBinlogTimestam provider.currentOffset = new JdbcOffset(Collections.singletonList( snapshotSplit("split-1", mysqlOffset("mysql-bin.000001", 100)))); - Assert.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); provider.currentOffset = new JdbcOffset(Collections.singletonList( new BinlogSplit(mysqlOffset("mysql-bin.000002", 250)))); - Assert.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); + Assertions.assertEquals(0L, provider.getLastSourceEventTimestampSeconds()); } @Test @@ -160,7 +160,7 @@ public void testUnavailableLagDoesNotOverwriteLastSuccessfulValue() { provider.updateLagBytes(-1); - Assert.assertEquals(4096, provider.getLagBytes()); + Assertions.assertEquals(4096, provider.getLagBytes()); } @Test @@ -170,7 +170,7 @@ public void testSuccessfulLagReplacesLastSuccessfulValue() { provider.updateLagBytes(2048); - Assert.assertEquals(2048, provider.getLagBytes()); + Assertions.assertEquals(2048, provider.getLagBytes()); } @Test @@ -181,8 +181,8 @@ public void testParseFetchEndOffsetResponse() throws JobException { FetchEndOffsetResult result = provider.parseFetchEndOffsetResponse(response); - Assert.assertEquals(offset("lsn", "200"), result.getEndOffset()); - Assert.assertEquals(4096, result.getLagBytes()); + Assertions.assertEquals(offset("lsn", "200"), result.getEndOffset()); + Assertions.assertEquals(4096, result.getLagBytes()); } @Test @@ -192,8 +192,8 @@ public void testParseLegacyFetchEndOffsetResponse() throws JobException { FetchEndOffsetResult result = provider.parseFetchEndOffsetResponse(response); - Assert.assertEquals(offset("lsn", "200"), result.getEndOffset()); - Assert.assertEquals(-1, result.getLagBytes()); + Assertions.assertEquals(offset("lsn", "200"), result.getEndOffset()); + Assertions.assertEquals(-1, result.getLagBytes()); } @Test @@ -204,8 +204,8 @@ public void testParseFetchEndOffsetResponseWithoutLag() throws JobException { FetchEndOffsetResult result = provider.parseFetchEndOffsetResponse(response); - Assert.assertEquals(offset("lsn", "200"), result.getEndOffset()); - Assert.assertEquals(-1, result.getLagBytes()); + Assertions.assertEquals(offset("lsn", "200"), result.getEndOffset()); + Assertions.assertEquals(-1, result.getLagBytes()); } @Test @@ -213,8 +213,8 @@ public void testFetchEndOffsetRequestUsesEmptyReferenceOffsetAsCapabilitySignal( FetchEndOffsetRequest request = new FetchEndOffsetRequest("123", "POSTGRES", Collections.emptyMap(), null, null); - Assert.assertNotNull(request.getReferenceOffset()); - Assert.assertTrue(request.getReferenceOffset().isEmpty()); + Assertions.assertNotNull(request.getReferenceOffset()); + Assertions.assertTrue(request.getReferenceOffset().isEmpty()); } private static JdbcSourceOffsetProvider provider(DataSourceType type, String startupMode) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderOffsetTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderOffsetTest.java index d71416fd3c5faf..9a6a601d8b7bd5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderOffsetTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProviderOffsetTest.java @@ -23,8 +23,8 @@ import org.apache.doris.job.cdc.split.SnapshotSplit; import org.apache.doris.job.extensions.insert.streaming.StreamingInsertJob; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; @@ -41,9 +41,9 @@ public void testSnapshotOffsetUsesConfiguredPersistInterval() { provider.currentOffset = new JdbcOffset( Collections.singletonList(snapshotSplit("source_table:0"))); - Assert.assertTrue(provider.shouldPersistOffset(0L, 1_000L)); - Assert.assertFalse(provider.shouldPersistOffset(1_000L, 123_999L)); - Assert.assertTrue(provider.shouldPersistOffset(1_000L, 124_000L)); + Assertions.assertTrue(provider.shouldPersistOffset(0L, 1_000L)); + Assertions.assertFalse(provider.shouldPersistOffset(1_000L, 123_999L)); + Assertions.assertTrue(provider.shouldPersistOffset(1_000L, 124_000L)); } finally { Config.streaming_job_snapshot_offset_persist_interval_sec = oldInterval; } @@ -55,7 +55,7 @@ public void testBinlogOffsetPersistsImmediately() { provider.currentOffset = new JdbcOffset(Collections.singletonList( new BinlogSplit(Collections.singletonMap("lsn", "100")))); - Assert.assertTrue(provider.shouldPersistOffset(1_000L, 1_001L)); + Assertions.assertTrue(provider.shouldPersistOffset(1_000L, 1_001L)); } @Test @@ -78,8 +78,8 @@ public void testEndOffsetRemainsWhenItIsAheadOfCurrentOffset() { provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(currentOffset)))); - Assert.assertTrue(provider.hasMoreDataToConsume()); - Assert.assertEquals(endOffset, provider.getEndBinlogOffset()); + Assertions.assertTrue(provider.hasMoreDataToConsume()); + Assertions.assertEquals(endOffset, provider.getEndBinlogOffset()); } @Test @@ -89,9 +89,9 @@ public void testStaleCompareDoesNotOverwriteRefreshedEndOffset() { provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(Collections.singletonMap("lsn", "200"))))); - Assert.assertTrue(provider.hasMoreDataToConsume()); - Assert.assertTrue(provider.hasMoreData); - Assert.assertEquals(Collections.singletonMap("lsn", "300"), provider.getEndBinlogOffset()); + Assertions.assertTrue(provider.hasMoreDataToConsume()); + Assertions.assertTrue(provider.hasMoreData); + Assertions.assertEquals(Collections.singletonMap("lsn", "300"), provider.getEndBinlogOffset()); } @Test @@ -101,9 +101,9 @@ public void testStaleCompareDoesNotOverwriteAlteredCurrentOffsetState() { provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(Collections.singletonMap("lsn", "200"))))); - Assert.assertTrue(provider.hasMoreDataToConsume()); - Assert.assertTrue(provider.hasMoreData); - Assert.assertEquals(Collections.singletonMap("lsn", "100"), + Assertions.assertTrue(provider.hasMoreDataToConsume()); + Assertions.assertTrue(provider.hasMoreData); + Assertions.assertEquals(Collections.singletonMap("lsn", "100"), ((BinlogSplit) provider.currentOffset.getSplits().get(0)).getStartingOffset()); } @@ -147,11 +147,11 @@ public void testBinlogOffsetRestoredFromPersistInfo() throws Exception { restored.replayIfNeed(job); - Assert.assertNotNull(restored.currentOffset); - Assert.assertFalse(restored.currentOffset.snapshotSplit()); - Assert.assertEquals("200", ((BinlogSplit) restored.currentOffset.getSplits().get(0)) + Assertions.assertNotNull(restored.currentOffset); + Assertions.assertFalse(restored.currentOffset.snapshotSplit()); + Assertions.assertEquals("200", ((BinlogSplit) restored.currentOffset.getSplits().get(0)) .getStartingOffset().get("lsn")); - Assert.assertTrue(restored.chunkHighWatermarkMap.isEmpty()); + Assertions.assertTrue(restored.chunkHighWatermarkMap.isEmpty()); } @Test @@ -165,11 +165,11 @@ public void testTvfBinlogOffsetRestoredFromPersistInfo() throws Exception { restored.restoreFromPersistInfo(source.getPersistInfo()); restored.replayIfNeed(job); - Assert.assertNotNull(restored.currentOffset); - Assert.assertFalse(restored.currentOffset.snapshotSplit()); - Assert.assertEquals("200", ((BinlogSplit) restored.currentOffset.getSplits().get(0)) + Assertions.assertNotNull(restored.currentOffset); + Assertions.assertFalse(restored.currentOffset.snapshotSplit()); + Assertions.assertEquals("200", ((BinlogSplit) restored.currentOffset.getSplits().get(0)) .getStartingOffset().get("lsn")); - Assert.assertTrue(restored.chunkHighWatermarkMap.isEmpty()); + Assertions.assertTrue(restored.chunkHighWatermarkMap.isEmpty()); } private static void assertEndOffsetAdvancesWhenCurrentOffsetIsAhead(JdbcSourceOffsetProvider provider) { @@ -181,10 +181,10 @@ private static void assertEndOffsetAdvancesWhenCurrentOffsetIsAhead(JdbcSourceOf provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(committedOffset)))); - Assert.assertEquals(staleEndOffset, provider.getEndBinlogOffset()); - Assert.assertFalse(provider.hasMoreDataToConsume()); - Assert.assertEquals(committedOffset, provider.getEndBinlogOffset()); - Assert.assertEquals("{\"lsn\":\"200\"}", provider.getShowMaxOffset()); + Assertions.assertEquals(staleEndOffset, provider.getEndBinlogOffset()); + Assertions.assertFalse(provider.hasMoreDataToConsume()); + Assertions.assertEquals(committedOffset, provider.getEndBinlogOffset()); + Assertions.assertEquals("{\"lsn\":\"200\"}", provider.getShowMaxOffset()); } private static void assertValidBinlogOffsetClearsSnapshotState(JdbcSourceOffsetProvider provider) { @@ -194,19 +194,19 @@ private static void assertValidBinlogOffsetClearsSnapshotState(JdbcSourceOffsetP provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(binlogOffset)))); - Assert.assertTrue(provider.chunkHighWatermarkMap.isEmpty()); - Assert.assertTrue(provider.remainingSplits.isEmpty()); - Assert.assertTrue(provider.finishedSplits.isEmpty()); + Assertions.assertTrue(provider.chunkHighWatermarkMap.isEmpty()); + Assertions.assertTrue(provider.remainingSplits.isEmpty()); + Assertions.assertTrue(provider.finishedSplits.isEmpty()); assertProgressCleared(provider.committedSplitProgress); assertProgressCleared(provider.cdcSplitProgress); - Assert.assertEquals("table-schemas", provider.tableSchemas); + Assertions.assertEquals("table-schemas", provider.tableSchemas); Map expectedPersist = new HashMap<>(binlogOffset); expectedPersist.put(JdbcSourceOffsetProvider.SPLIT_ID, BinlogSplit.BINLOG_SPLIT_ID); - Assert.assertEquals(expectedPersist, provider.binlogOffsetPersist); + Assertions.assertEquals(expectedPersist, provider.binlogOffsetPersist); String persistInfo = provider.getPersistInfo(); - Assert.assertFalse(persistInfo.contains("source_table:0")); - Assert.assertFalse(persistInfo.contains("source_table:1")); - Assert.assertTrue(persistInfo.contains("table-schemas")); + Assertions.assertFalse(persistInfo.contains("source_table:0")); + Assertions.assertFalse(persistInfo.contains("source_table:1")); + Assertions.assertTrue(persistInfo.contains("table-schemas")); } private static void assertEmptyBinlogOffsetKeepsPreviousState(JdbcSourceOffsetProvider provider) { @@ -219,14 +219,14 @@ private static void assertEmptyBinlogOffsetKeepsPreviousState(JdbcSourceOffsetPr provider.updateOffset(new JdbcOffset( Collections.singletonList(new BinlogSplit(Collections.emptyMap())))); - Assert.assertSame(previousOffset, provider.currentOffset); - Assert.assertFalse(provider.hasMoreData); - Assert.assertFalse(provider.chunkHighWatermarkMap.isEmpty()); - Assert.assertFalse(provider.remainingSplits.isEmpty()); - Assert.assertFalse(provider.finishedSplits.isEmpty()); - Assert.assertEquals("source_table", provider.committedSplitProgress.getCurrentSplittingTable()); - Assert.assertEquals("source_table", provider.cdcSplitProgress.getCurrentSplittingTable()); - Assert.assertNull(provider.binlogOffsetPersist); + Assertions.assertSame(previousOffset, provider.currentOffset); + Assertions.assertFalse(provider.hasMoreData); + Assertions.assertFalse(provider.chunkHighWatermarkMap.isEmpty()); + Assertions.assertFalse(provider.remainingSplits.isEmpty()); + Assertions.assertFalse(provider.finishedSplits.isEmpty()); + Assertions.assertEquals("source_table", provider.committedSplitProgress.getCurrentSplittingTable()); + Assertions.assertEquals("source_table", provider.cdcSplitProgress.getCurrentSplittingTable()); + Assertions.assertNull(provider.binlogOffsetPersist); } private static void assertRepeatedValidBinlogOffsetCleanupIsIdempotent( @@ -241,11 +241,11 @@ private static void assertRepeatedValidBinlogOffsetCleanupIsIdempotent( provider.chunkHighWatermarkMap; provider.updateOffset(binlogOffset); - Assert.assertEquals(firstPersistInfo, provider.getPersistInfo()); - Assert.assertSame(clearedHighWatermarkMap, provider.chunkHighWatermarkMap); - Assert.assertTrue(provider.chunkHighWatermarkMap.isEmpty()); - Assert.assertTrue(provider.remainingSplits.isEmpty()); - Assert.assertTrue(provider.finishedSplits.isEmpty()); + Assertions.assertEquals(firstPersistInfo, provider.getPersistInfo()); + Assertions.assertSame(clearedHighWatermarkMap, provider.chunkHighWatermarkMap); + Assertions.assertTrue(provider.chunkHighWatermarkMap.isEmpty()); + Assertions.assertTrue(provider.remainingSplits.isEmpty()); + Assertions.assertTrue(provider.finishedSplits.isEmpty()); assertProgressCleared(provider.committedSplitProgress); assertProgressCleared(provider.cdcSplitProgress); } @@ -290,10 +290,10 @@ private static JdbcSourceOffsetProvider.SplitProgress splitProgress() { } private static void assertProgressCleared(JdbcSourceOffsetProvider.SplitProgress progress) { - Assert.assertNotNull(progress); - Assert.assertNull(progress.getCurrentSplittingTable()); - Assert.assertNull(progress.getNextSplitStart()); - Assert.assertNull(progress.getNextSplitId()); + Assertions.assertNotNull(progress); + Assertions.assertNull(progress.getCurrentSplittingTable()); + Assertions.assertNull(progress.getNextSplitStart()); + Assertions.assertNull(progress.getNextSplitId()); } private static class TestJdbcSourceOffsetProvider extends JdbcSourceOffsetProvider { diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcTvfSourceOffsetProviderTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcTvfSourceOffsetProviderTest.java index 09f336fc4424a4..e780bd77baafd4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcTvfSourceOffsetProviderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/JdbcTvfSourceOffsetProviderTest.java @@ -19,8 +19,8 @@ import org.apache.doris.job.cdc.DataSourceConfigKeys; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -37,10 +37,10 @@ public void testEnsureInitializedNormalizesMysqlJdbcUrl() throws Exception { provider.ensureInitialized(1L, properties); - Assert.assertEquals("jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=false" + Assertions.assertEquals("jdbc:mysql://127.0.0.1:3306/test?yearIsDateType=false" + "&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8", provider.getSourceProperties().get(DataSourceConfigKeys.JDBC_URL)); - Assert.assertEquals("jdbc:mysql://127.0.0.1:3306/test", + Assertions.assertEquals("jdbc:mysql://127.0.0.1:3306/test", properties.get(DataSourceConfigKeys.JDBC_URL)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/SplitProgressTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/SplitProgressTest.java index 9fccdc0b01280b..a1fd9ff05544dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/SplitProgressTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/offset/jdbc/SplitProgressTest.java @@ -19,17 +19,17 @@ import org.apache.doris.job.offset.jdbc.JdbcSourceOffsetProvider.SplitProgress; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SplitProgressTest { @Test public void testDefaultStateIsAllNull() { SplitProgress p = new SplitProgress(); - Assert.assertNull(p.getCurrentSplittingTable()); - Assert.assertNull(p.getNextSplitStart()); - Assert.assertNull(p.getNextSplitId()); + Assertions.assertNull(p.getCurrentSplittingTable()); + Assertions.assertNull(p.getNextSplitStart()); + Assertions.assertNull(p.getNextSplitId()); } @Test @@ -40,21 +40,21 @@ public void testCopyDeepClonesNextSplitStart() { original.setNextSplitId(5); SplitProgress copy = original.copy(); - Assert.assertEquals("db.tbl_a", copy.getCurrentSplittingTable()); - Assert.assertArrayEquals(new Object[]{100L}, copy.getNextSplitStart()); - Assert.assertEquals(Integer.valueOf(5), copy.getNextSplitId()); + Assertions.assertEquals("db.tbl_a", copy.getCurrentSplittingTable()); + Assertions.assertArrayEquals(new Object[]{100L}, copy.getNextSplitStart()); + Assertions.assertEquals(Integer.valueOf(5), copy.getNextSplitId()); // Mutating copy.nextSplitStart must not affect the original (deep copy). copy.getNextSplitStart()[0] = 999L; - Assert.assertEquals(100L, original.getNextSplitStart()[0]); + Assertions.assertEquals(100L, original.getNextSplitStart()[0]); } @Test public void testCopyHandlesNullFields() { SplitProgress original = new SplitProgress(); SplitProgress copy = original.copy(); - Assert.assertNull(copy.getCurrentSplittingTable()); - Assert.assertNull(copy.getNextSplitStart()); - Assert.assertNull(copy.getNextSplitId()); + Assertions.assertNull(copy.getCurrentSplittingTable()); + Assertions.assertNull(copy.getNextSplitStart()); + Assertions.assertNull(copy.getNextSplitId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/job/util/StreamingJobUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/job/util/StreamingJobUtilsTest.java index e8279cf3d1dc21..dcc96e6686e916 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/job/util/StreamingJobUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/job/util/StreamingJobUtilsTest.java @@ -31,9 +31,9 @@ import org.apache.doris.job.exception.JobException; import org.apache.doris.qe.GlobalVariable; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -51,7 +51,7 @@ public class StreamingJobUtilsTest { @Mock private JdbcClient jdbcClient; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); } @@ -75,21 +75,21 @@ public void testGetColumnsWithPrimaryKeySorting() throws Exception { List result = StreamingJobUtils.getColumns(jdbcClient, database, table, primaryKeys); // Verify primary keys are at the front in correct order - Assert.assertEquals(5, result.size()); - Assert.assertEquals("id", result.get(0).getName()); - Assert.assertEquals("name", result.get(1).getName()); + Assertions.assertEquals(5, result.size()); + Assertions.assertEquals("id", result.get(0).getName()); + Assertions.assertEquals("name", result.get(1).getName()); // Verify varchar primary key columns have their length multiplied by 3 Column nameColumn = result.get(1); - Assert.assertEquals(150, nameColumn.getType().getLength()); // 50 * 3 + Assertions.assertEquals(150, nameColumn.getType().getLength()); // 50 * 3 // Verify non-primary key columns follow - Assert.assertEquals("age", result.get(2).getName()); - Assert.assertEquals("email", result.get(3).getName()); - Assert.assertEquals("address", result.get(4).getName()); + Assertions.assertEquals("age", result.get(2).getName()); + Assertions.assertEquals("email", result.get(3).getName()); + Assertions.assertEquals("address", result.get(4).getName()); // Verify non-primary key varchar columns also have their length multiplied by 3 Column emailColumn = result.get(3); - Assert.assertEquals(300, emailColumn.getType().getLength()); // 100 * 3 + Assertions.assertEquals(300, emailColumn.getType().getLength()); // 100 * 3 Column addressColumn = result.get(4); - Assert.assertEquals(600, addressColumn.getType().getLength()); // 200 * 3 + Assertions.assertEquals(600, addressColumn.getType().getLength()); // 200 * 3 } @Test @@ -111,16 +111,16 @@ public void testGetColumnsWithVarcharTypeConversion() throws Exception { .filter(col -> col.getName().equals("short_name")) .findFirst() .orElse(null); - Assert.assertNotNull(shortName); - Assert.assertEquals(150, shortName.getType().getLength()); // 50 * 3 + Assertions.assertNotNull(shortName); + Assertions.assertEquals(150, shortName.getType().getLength()); // 50 * 3 // Verify long varchar becomes STRING type Column longName = result.stream() .filter(col -> col.getName().equals("long_name")) .findFirst() .orElse(null); - Assert.assertNotNull(longName); - Assert.assertTrue(longName.getType().isStringType()); + Assertions.assertNotNull(longName); + Assertions.assertTrue(longName.getType().isStringType()); } @Test @@ -141,9 +141,9 @@ public void testGetColumnsWithStringTypeAsPrimaryKey() throws Exception { .filter(col -> col.getName().equals("id")) .findFirst() .orElse(null); - Assert.assertNotNull(idColumn); - Assert.assertTrue(idColumn.getType().isVarchar()); - Assert.assertEquals(ScalarType.MAX_VARCHAR_LENGTH, idColumn.getType().getLength()); + Assertions.assertNotNull(idColumn); + Assertions.assertTrue(idColumn.getType().isVarchar()); + Assertions.assertEquals(ScalarType.MAX_VARCHAR_LENGTH, idColumn.getType().getLength()); } @Test @@ -161,10 +161,10 @@ public void testGetColumnsWithEmptyPrimaryKeys() throws Exception { List result = StreamingJobUtils.getColumns(jdbcClient, database, table, primaryKeys); // Verify columns maintain original order when no primary keys - Assert.assertEquals(3, result.size()); - Assert.assertEquals("col1", result.get(0).getName()); - Assert.assertEquals("col2", result.get(1).getName()); - Assert.assertEquals("col3", result.get(2).getName()); + Assertions.assertEquals(3, result.size()); + Assertions.assertEquals("col1", result.get(0).getName()); + Assertions.assertEquals("col2", result.get(1).getName()); + Assertions.assertEquals("col3", result.get(2).getName()); } @Test @@ -185,14 +185,14 @@ public void testGetColumnsWithMultiplePrimaryKeys() throws Exception { List result = StreamingJobUtils.getColumns(jdbcClient, database, table, primaryKeys); // Verify primary keys are sorted in the order defined in primaryKeys list - Assert.assertEquals(6, result.size()); - Assert.assertEquals("pk3", result.get(0).getName()); - Assert.assertEquals("pk1", result.get(1).getName()); - Assert.assertEquals("pk2", result.get(2).getName()); + Assertions.assertEquals(6, result.size()); + Assertions.assertEquals("pk3", result.get(0).getName()); + Assertions.assertEquals("pk1", result.get(1).getName()); + Assertions.assertEquals("pk2", result.get(2).getName()); // Verify non-primary keys follow - Assert.assertEquals("data1", result.get(3).getName()); - Assert.assertEquals("data2", result.get(4).getName()); - Assert.assertEquals("data3", result.get(5).getName()); + Assertions.assertEquals("data1", result.get(3).getName()); + Assertions.assertEquals("data2", result.get(4).getName()); + Assertions.assertEquals("data3", result.get(5).getName()); } @Test @@ -209,13 +209,13 @@ public void testGetColumnsWithUnsupportedColumnType() throws Exception { // This should throw IllegalArgumentException due to unsupported column type try { StreamingJobUtils.getColumns(jdbcClient, database, table, primaryKeys); - Assert.fail("Expected IllegalArgumentException to be thrown"); + Assertions.fail("Expected IllegalArgumentException to be thrown"); } catch (IllegalArgumentException e) { // Verify the exception message contains expected information String message = e.getMessage(); - Assert.assertTrue(message.contains("Unsupported column type")); - Assert.assertTrue(message.contains("test_table")); - Assert.assertTrue(message.contains("unsupported_col")); + Assertions.assertTrue(message.contains("Unsupported column type")); + Assertions.assertTrue(message.contains("test_table")); + Assertions.assertTrue(message.contains("unsupported_col")); } } @@ -238,16 +238,16 @@ public void testGetColumnsWithVarcharPrimaryKeyLengthMultiplication() throws Exc .filter(col -> col.getName().equals("pk_varchar")) .findFirst() .orElse(null); - Assert.assertNotNull(pkVarcharColumn); - Assert.assertEquals(300, pkVarcharColumn.getType().getLength()); // 100 * 3 + Assertions.assertNotNull(pkVarcharColumn); + Assertions.assertEquals(300, pkVarcharColumn.getType().getLength()); // 100 * 3 // Verify normal varchar column also has length multiplied by 3 Column normalVarcharColumn = result.stream() .filter(col -> col.getName().equals("normal_varchar")) .findFirst() .orElse(null); - Assert.assertNotNull(normalVarcharColumn); - Assert.assertEquals(150, normalVarcharColumn.getType().getLength()); // 50 * 3 + Assertions.assertNotNull(normalVarcharColumn); + Assertions.assertEquals(150, normalVarcharColumn.getType().getLength()); // 50 * 3 } @Test @@ -255,7 +255,7 @@ public void testGetOceanBaseRemoteDbName() { Map properties = new HashMap<>(); properties.put(DataSourceConfigKeys.DATABASE, "test_db"); - Assert.assertEquals("test_db", + Assertions.assertEquals("test_db", StreamingJobUtils.getRemoteDbName(DataSourceType.OCEANBASE, properties)); } @@ -270,7 +270,7 @@ public void testGenerateCreateTableCmdsClosesJdbcClientOnFailure() { .thenReturn("test_db"); Mockito.when(jdbcClient.getTablesNameList("test_db")).thenReturn(new ArrayList<>()); - Assert.assertThrows(JobException.class, () -> StreamingJobUtils.generateCreateTableCmds( + Assertions.assertThrows(JobException.class, () -> StreamingJobUtils.generateCreateTableCmds( "target_db", DataSourceType.OCEANBASE, properties, new HashMap<>())); Mockito.verify(jdbcClient).closeClient(); @@ -309,7 +309,7 @@ public void testGenerateCreateTableCmdsFindsMixedCasePrecreatedTargetWhenStoredL utils.when(() -> StreamingJobUtils.getJdbcClient(DataSourceType.POSTGRES, properties)) .thenReturn(jdbcClient); - Assert.assertFalse(StreamingJobUtils.generateCreateTableCmds( + Assertions.assertFalse(StreamingJobUtils.generateCreateTableCmds( "target_db", DataSourceType.POSTGRES, properties, new HashMap<>()) .get("source_table").isPresent()); } finally { diff --git a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolOptionsTest.java b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolOptionsTest.java index 426f5e3e72b4a4..b7ac96e89340e9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolOptionsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolOptionsTest.java @@ -19,23 +19,23 @@ import org.apache.doris.common.FeConstants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class BDBToolOptionsTest { @Test public void test() { BDBToolOptions options = new BDBToolOptions(true, "", false, "", "", 0); - Assert.assertFalse(options.hasFromKey()); - Assert.assertFalse(options.hasEndKey()); - Assert.assertEquals(FeConstants.meta_version, options.getMetaVersion()); + Assertions.assertFalse(options.hasFromKey()); + Assertions.assertFalse(options.hasEndKey()); + Assertions.assertEquals(FeConstants.meta_version, options.getMetaVersion()); options = new BDBToolOptions(false, "12345", false, "12345", "12456", 35); - Assert.assertTrue(options.hasFromKey()); - Assert.assertTrue(options.hasEndKey()); - Assert.assertNotSame(FeConstants.meta_version, options.getMetaVersion()); - Assert.assertTrue(options.toString().contains("12345")); + Assertions.assertTrue(options.hasFromKey()); + Assertions.assertTrue(options.hasEndKey()); + Assertions.assertNotSame(FeConstants.meta_version, options.getMetaVersion()); + Assertions.assertTrue(options.toString().contains("12345")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolTest.java b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolTest.java index 5940935a3166f8..3b77cfb7ea6ac1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBToolTest.java @@ -30,10 +30,10 @@ import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import com.sleepycat.je.OperationStatus; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -45,7 +45,7 @@ public class BDBToolTest { private static Database db; private static String dbName = "12345"; - @BeforeClass + @BeforeAll public static void setEnv() { try { File file = new File("./bdb"); @@ -111,7 +111,7 @@ public static void setEnv() { } } - @AfterClass + @AfterAll public static void deleteEnv() { File file = new File(path); if (file.isDirectory()) { @@ -129,7 +129,7 @@ public static void deleteEnv() { public void testList() { BDBToolOptions options = new BDBToolOptions(true, "", false, "", "", 0); BDBTool tool = new BDBTool(path, options); - Assert.assertTrue(tool.run()); + Assertions.assertTrue(tool.run()); } @Test @@ -137,27 +137,27 @@ public void testDbStat() { // wrong db name BDBToolOptions options = new BDBToolOptions(false, "12346", true, "", "", 0); BDBTool tool = new BDBTool(path, options); - Assert.assertFalse(tool.run()); + Assertions.assertFalse(tool.run()); // right db name options = new BDBToolOptions(false, "12345", true, "", "", 0); tool = new BDBTool(path, options); - Assert.assertTrue(tool.run()); + Assertions.assertTrue(tool.run()); } @Test public void testGetKey() { BDBToolOptions options = new BDBToolOptions(false, "12345", false, "", "", 0); BDBTool tool = new BDBTool(path, options); - Assert.assertTrue(tool.run()); + Assertions.assertTrue(tool.run()); options = new BDBToolOptions(false, "12345", false, "23456", "12345", 0); tool = new BDBTool(path, options); - Assert.assertFalse(tool.run()); + Assertions.assertFalse(tool.run()); options = new BDBToolOptions(false, "12345", false, "23456", "", 0); tool = new BDBTool(path, options); - Assert.assertTrue(tool.run()); + Assertions.assertTrue(tool.run()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/DeleteJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/DeleteJobTest.java index b937a755640206..1abf76ece827ae 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/DeleteJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/DeleteJobTest.java @@ -32,10 +32,10 @@ import org.apache.doris.thrift.TStorageMedium; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -86,7 +86,7 @@ protected void innerClear() { } }; - @Before + @BeforeEach public void setUp() throws Exception { invertedIndex.addTablet(TABLET_ID, new TabletMeta(DB_ID, TABLE_ID, PARTITION_ID, 5L, 6, TStorageMedium.HDD, false /* isRowBinlog */)); @@ -99,7 +99,7 @@ public void setUp() throws Exception { mockedEnvStatic.when(Env::getCurrentInvertedIndex).thenReturn(invertedIndex); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -120,7 +120,7 @@ public void testAwaitIgnoresFailureStatusAfterQuorumReached() throws Exception { deleteJob.await(); - Assert.assertEquals(DeleteJob.DeleteState.QUORUM_FINISHED, deleteJob.getState()); + Assertions.assertEquals(DeleteJob.DeleteState.QUORUM_FINISHED, deleteJob.getState()); } @Test @@ -133,12 +133,12 @@ public void testAwaitReturnsFailureStatusWhenQuorumNotReached() { try { deleteJob.await(); - Assert.fail("delete job should fail when quorum is not reached"); + Assertions.fail("delete job should fail when quorum is not reached"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("too many versions")); - Assert.assertEquals(DeleteJob.DeleteState.UN_QUORUM, deleteJob.getState()); + Assertions.assertTrue(e.getMessage().contains("too many versions")); + Assertions.assertEquals(DeleteJob.DeleteState.UN_QUORUM, deleteJob.getState()); } catch (Exception e) { - Assert.fail("unexpected exception: " + e.getMessage()); + Assertions.fail("unexpected exception: " + e.getMessage()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/EtlJobStatusTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/EtlJobStatusTest.java index 0958312199bfc9..440713380d8459 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/EtlJobStatusTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/EtlJobStatusTest.java @@ -19,8 +19,8 @@ import org.apache.doris.thrift.TEtlState; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -70,18 +70,18 @@ public void testSerialization() throws Exception { stats = etlJobStatus1.getStats(); counters = etlJobStatus1.getCounters(); - Assert.assertEquals(etlJobStatus1.getState().name(), "FINISHED"); + Assertions.assertEquals(etlJobStatus1.getState().name(), "FINISHED"); for (int count = 0; count < 5; ++count) { String statsKey = "statsKey" + count; String statsValue = "statsValue" + count; String countersKey = "countersKey" + count; String countersValue = "countersValue" + count; - Assert.assertEquals(stats.get(statsKey), statsValue); - Assert.assertEquals(counters.get(countersKey), countersValue); + Assertions.assertEquals(stats.get(statsKey), statsValue); + Assertions.assertEquals(counters.get(countersKey), countersValue); } - Assert.assertEquals(etlJobStatus, etlJobStatus1); - Assert.assertEquals(trackingUrl, etlJobStatus1.getTrackingUrl()); + Assertions.assertEquals(etlJobStatus, etlJobStatus1); + Assertions.assertEquals(trackingUrl, etlJobStatus1.getTrackingUrl()); dis.close(); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/ExportJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/ExportJobTest.java index e197eb202c1a90..d95324d6a7d5dd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/ExportJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/ExportJobTest.java @@ -21,8 +21,8 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.datasource.property.fileformat.ParquetFileFormatProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; @@ -37,12 +37,12 @@ public void testEnableInt96TimestampsOutfileProperty() { Map outfileProperties = Deencapsulation.invoke(exportJob, "convertOutfileProperties"); - Assert.assertFalse(outfileProperties.containsKey( + Assertions.assertFalse(outfileProperties.containsKey( ParquetFileFormatProperties.ENABLE_INT96_TIMESTAMPS)); exportJob.setEnableInt96Timestamps("false"); outfileProperties = Deencapsulation.invoke(exportJob, "convertOutfileProperties"); - Assert.assertEquals("false", outfileProperties.get( + Assertions.assertEquals("false", outfileProperties.get( ParquetFileFormatProperties.ENABLE_INT96_TIMESTAMPS)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/ExportOutfileInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/ExportOutfileInfoTest.java index 6aa6764cd8d415..846ba03f9f7bc3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/ExportOutfileInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/ExportOutfileInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.persist.gson.GsonUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; @@ -69,7 +69,7 @@ public void testOutfileInfo() throws Exception { String showInfo = GsonUtils.GSON.toJson(allOutfileInfo); System.out.println(showInfo); - Assert.assertEquals( + Assertions.assertEquals( "[[{\"fileNumber\":\"2\",\"totalRows\":\"1234\",\"fileSize\":\"10240\"," + "\"url\":\"file:///172.20.32.136/path/to/result2_c6df5f01bd664dde-a2168b019b6c2b3f_*\"}," + "{\"fileNumber\":\"2\",\"totalRows\":\"1235\",\"fileSize\":\"10250\"," diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/FailMsgTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/FailMsgTest.java index cef5389ce6b959..ed91fbcf5f03fe 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/FailMsgTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/FailMsgTest.java @@ -17,8 +17,8 @@ package org.apache.doris.load; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -43,10 +43,10 @@ public void testSerialization() throws Exception { FailMsg failMsg1 = new FailMsg(); failMsg1.readFields(dis); - Assert.assertEquals(failMsg1.getMsg(), "Job failed"); - Assert.assertEquals(failMsg1.getCancelType(), FailMsg.CancelType.ETL_QUALITY_UNSATISFIED); + Assertions.assertEquals(failMsg1.getMsg(), "Job failed"); + Assertions.assertEquals(failMsg1.getCancelType(), FailMsg.CancelType.ETL_QUALITY_UNSATISFIED); - Assert.assertEquals(failMsg1, failMsg); + Assertions.assertEquals(failMsg1, failMsg); dis.close(); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerBackendSelectionTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerBackendSelectionTest.java index db26b5ddbfdf54..8979a3b76605a3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerBackendSelectionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerBackendSelectionTest.java @@ -32,9 +32,9 @@ import com.google.common.cache.Cache; import com.google.common.collect.ImmutableMap; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -43,7 +43,7 @@ public class GroupCommitManagerBackendSelectionTest { - @After + @AfterEach public void resetBackendSelectionProvider() { BackendSelectionManager.resetProviderForTest(); } @@ -51,7 +51,7 @@ public void resetBackendSelectionProvider() { private final String originalCloudUniqueId = Config.cloud_unique_id; private final String originalDeployMode = Config.deploy_mode; - @After + @AfterEach public void tearDown() { Config.cloud_unique_id = originalCloudUniqueId; Config.deploy_mode = originalDeployMode; @@ -64,8 +64,8 @@ public void testDisabledLoadSelectionDoesNotResolveDecision() { BackendSelectionManager.setProviderForTest(policy); - Assert.assertNull(GroupCommitManager.getGroupCommitLoadSelectionHint(context)); - Assert.assertEquals(0, policy.getLoadSelectionHintCalls); + Assertions.assertNull(GroupCommitManager.getGroupCommitLoadSelectionHint(context)); + Assertions.assertEquals(0, policy.getLoadSelectionHintCalls); } @Test @@ -89,11 +89,11 @@ public void testEffectiveLoadSelectionCacheUsesSelectionKey() throws Exception { long cachedOtherBackendId = manager.selectBackendForGroupCommitInternal( tableId, "", policy.otherDecision); - Assert.assertEquals(1L, firstBackendId); - Assert.assertEquals(1L, secondBackendId); - Assert.assertEquals(1L, otherBackendId); - Assert.assertEquals(1L, cachedOtherBackendId); - Assert.assertEquals(2, policy.orderLoadCandidatesCalls); + Assertions.assertEquals(1L, firstBackendId); + Assertions.assertEquals(1L, secondBackendId); + Assertions.assertEquals(1L, otherBackendId); + Assertions.assertEquals(1L, cachedOtherBackendId); + Assertions.assertEquals(2, policy.orderLoadCandidatesCalls); } } @@ -112,9 +112,9 @@ public void testRequiredLoadSelectionDoesNotReuseCachedBackend() throws Exceptio mockedEnv.when(Env::getCurrentEnv).thenReturn(env); mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); - Assert.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", policy.decision)); - Assert.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", policy.decision)); - Assert.assertEquals(2, policy.partitionCalls); + Assertions.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", policy.decision)); + Assertions.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", policy.decision)); + Assertions.assertEquals(2, policy.partitionCalls); } } @@ -133,7 +133,7 @@ public void testNullSelectionHintDoesNotReachPolicyPreferencePredicate() throws mockedEnv.when(Env::getCurrentEnv).thenReturn(env); mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); - Assert.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", null)); + Assertions.assertEquals(1L, manager.selectBackendForGroupCommitInternal(tableId, "", null)); } } @@ -150,7 +150,7 @@ public void testPreferenceKeyedBackendCacheStaysBounded() throws Exception { } cache.cleanUp(); - Assert.assertTrue("cache must stay bounded, size=" + cache.size(), cache.size() <= 10000); + Assertions.assertTrue(cache.size() <= 10000, "cache must stay bounded, size=" + cache.size()); } @Test @@ -178,9 +178,9 @@ public void testCloudGroupCommitIgnoresLoadSelectionDecision() throws Exception long firstBackendId = manager.selectBackendForGroupCommitInternal(tableId, cluster, policy.decision); long secondBackendId = manager.selectBackendForGroupCommitInternal(tableId, cluster, policy.decision); - Assert.assertEquals(1L, firstBackendId); - Assert.assertEquals(1L, secondBackendId); - Assert.assertEquals(0, policy.orderLoadCandidatesCalls); + Assertions.assertEquals(1L, firstBackendId); + Assertions.assertEquals(1L, secondBackendId); + Assertions.assertEquals(0, policy.orderLoadCandidatesCalls); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerTest.java index 7012e16d8deed9..5635d98ea1944a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/GroupCommitManagerTest.java @@ -25,10 +25,10 @@ import org.apache.doris.system.Backend; import com.google.common.collect.ImmutableMap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -49,7 +49,7 @@ public class GroupCommitManagerTest { private OlapTable table; private CloudSystemInfoService systemInfoService; - @Before + @BeforeEach public void setUp() { originalCloudUniqueId = Config.cloud_unique_id; originalDeployMode = Config.deploy_mode; @@ -66,7 +66,7 @@ public void setUp() { Mockito.when(table.getGroupCommitIntervalMs()).thenReturn(1000); } - @After + @AfterEach public void tearDown() { Config.cloud_unique_id = originalCloudUniqueId; Config.deploy_mode = originalDeployMode; @@ -90,13 +90,13 @@ public void testVirtualComputeGroupUsesActiveBackendsForCacheAndFailover() throw mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); GroupCommitManager manager = new GroupCommitManager(); - Assert.assertEquals(BACKEND_A_ID, + Assertions.assertEquals(BACKEND_A_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, VIRTUAL_CLUSTER)); Mockito.verify(systemInfoService, Mockito.never()).getPhysicalCluster(Mockito.anyString()); Mockito.verify(systemInfoService, Mockito.never()).getBackend(Mockito.anyLong()); Mockito.clearInvocations(systemInfoService); - Assert.assertEquals(BACKEND_A_ID, + Assertions.assertEquals(BACKEND_A_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, VIRTUAL_CLUSTER)); Mockito.verify(systemInfoService).getBackendInCurrentCluster(VIRTUAL_CLUSTER, BACKEND_A_ID); Mockito.verify(systemInfoService, Mockito.never()).getCloudIdToBackend(Mockito.anyString()); @@ -106,7 +106,7 @@ public void testVirtualComputeGroupUsesActiveBackendsForCacheAndFailover() throw Mockito.clearInvocations(systemInfoService); activeBackends.set(ImmutableMap.of(BACKEND_B_ID, backendB)); - Assert.assertEquals(BACKEND_B_ID, + Assertions.assertEquals(BACKEND_B_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, VIRTUAL_CLUSTER)); Mockito.verify(systemInfoService).getBackendInCurrentCluster(VIRTUAL_CLUSTER, BACKEND_A_ID); Mockito.verify(systemInfoService).getCloudIdToBackend(VIRTUAL_CLUSTER); @@ -134,14 +134,14 @@ public void testLoadDisabledCachedBackendIsReplacedFromActiveBackends() throws E mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); GroupCommitManager manager = new GroupCommitManager(); - Assert.assertEquals(BACKEND_A_ID, + Assertions.assertEquals(BACKEND_A_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, VIRTUAL_CLUSTER)); Mockito.clearInvocations(systemInfoService); activeBackends.set(ImmutableMap.of(BACKEND_A_ID, backendA1, BACKEND_B_ID, backendA2)); backendA1.setLoadDisabled(true); - Assert.assertEquals(BACKEND_B_ID, + Assertions.assertEquals(BACKEND_B_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, VIRTUAL_CLUSTER)); Mockito.verify(systemInfoService).getBackendInCurrentCluster(VIRTUAL_CLUSTER, BACKEND_A_ID); Mockito.verify(systemInfoService).getCloudIdToBackend(VIRTUAL_CLUSTER); @@ -166,9 +166,9 @@ public void testLocalGroupCommitStillUsesGlobalBackendLookup() throws Exception mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); GroupCommitManager manager = new GroupCommitManager(); - Assert.assertEquals(BACKEND_A_ID, + Assertions.assertEquals(BACKEND_A_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, null)); - Assert.assertEquals(BACKEND_A_ID, + Assertions.assertEquals(BACKEND_A_ID, manager.selectBackendForGroupCommitInternal(TABLE_ID, null)); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/LoadJobRowResultTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/LoadJobRowResultTest.java index cf1268ec4de0e6..da8ae68c3d8c33 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/LoadJobRowResultTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/LoadJobRowResultTest.java @@ -17,24 +17,24 @@ package org.apache.doris.load; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class LoadJobRowResultTest { @Test public void testResult() { LoadJobRowResult result = new LoadJobRowResult(); - Assert.assertEquals("Records: 0 Deleted: 0 Skipped: 0 Warnings: 0", result.toString()); + Assertions.assertEquals("Records: 0 Deleted: 0 Skipped: 0 Warnings: 0", result.toString()); result.setRecords(199); - Assert.assertEquals("Records: 199 Deleted: 0 Skipped: 0 Warnings: 0", result.toString()); + Assertions.assertEquals("Records: 199 Deleted: 0 Skipped: 0 Warnings: 0", result.toString()); result.incRecords(1); result.setSkipped(20); - Assert.assertEquals("Records: 200 Deleted: 0 Skipped: 20 Warnings: 0", result.toString()); + Assertions.assertEquals("Records: 200 Deleted: 0 Skipped: 20 Warnings: 0", result.toString()); result.incSkipped(20); - Assert.assertEquals("Records: 200 Deleted: 0 Skipped: 40 Warnings: 0", result.toString()); - Assert.assertEquals(200, result.getRecords()); - Assert.assertEquals(40, result.getSkipped()); - Assert.assertEquals(0, result.getWarnings()); + Assertions.assertEquals("Records: 200 Deleted: 0 Skipped: 40 Warnings: 0", result.toString()); + Assertions.assertEquals(200, result.getRecords()); + Assertions.assertEquals(40, result.getSkipped()); + Assertions.assertEquals(0, result.getWarnings()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/PartitionLoadInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/PartitionLoadInfoTest.java index c6bd5086c36298..8e9a8f1ab1d054 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/PartitionLoadInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/PartitionLoadInfoTest.java @@ -17,8 +17,8 @@ package org.apache.doris.load; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -73,16 +73,16 @@ public void testSerialization() throws Exception { List sources1 = partitionLoadInfo1.getSources(); - Assert.assertEquals(partitionLoadInfo1.getVersion(), 100000); - Assert.assertEquals(sources1.size(), 2); - Assert.assertEquals(sources1.get(0).getFileUrls().size(), 10); - Assert.assertEquals(sources1.get(0).getColumnNames().size(), 10); - Assert.assertEquals(sources1.get(1).getFileUrls().size(), 30); - Assert.assertEquals(sources1.get(1).getColumnNames().size(), 30); + Assertions.assertEquals(partitionLoadInfo1.getVersion(), 100000); + Assertions.assertEquals(sources1.size(), 2); + Assertions.assertEquals(sources1.get(0).getFileUrls().size(), 10); + Assertions.assertEquals(sources1.get(0).getColumnNames().size(), 10); + Assertions.assertEquals(sources1.get(1).getFileUrls().size(), 30); + Assertions.assertEquals(sources1.get(1).getColumnNames().size(), 30); - Assert.assertEquals(partitionLoadInfo1, partitionLoadInfo); - Assert.assertEquals(rPartitionLoadInfo0, partitionLoadInfo0); - Assert.assertNotEquals(partitionLoadInfo0, partitionLoadInfo1); + Assertions.assertEquals(partitionLoadInfo1, partitionLoadInfo); + Assertions.assertEquals(rPartitionLoadInfo0, partitionLoadInfo0); + Assertions.assertNotEquals(partitionLoadInfo0, partitionLoadInfo1); dis.close(); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/SourceTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/SourceTest.java index ae4bd0f5fec954..969f5663575f0b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/SourceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/SourceTest.java @@ -17,8 +17,8 @@ package org.apache.doris.load; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -68,20 +68,20 @@ public void testSerialization() throws Exception { Source rSource2 = new Source(); rSource2.readFields(dis); - Assert.assertEquals(rSource0, source0); - Assert.assertEquals(source0, source0); - Assert.assertNotEquals(rSource0, this); - Assert.assertEquals(rSource1, source1); - Assert.assertNotEquals(rSource2, source2); - Assert.assertNotEquals(rSource0, source1); + Assertions.assertEquals(rSource0, source0); + Assertions.assertEquals(source0, source0); + Assertions.assertNotEquals(rSource0, this); + Assertions.assertEquals(rSource1, source1); + Assertions.assertNotEquals(rSource2, source2); + Assertions.assertNotEquals(rSource0, source1); rSource2.setFileUrls(null); - Assert.assertNotEquals(rSource2, source2); + Assertions.assertNotEquals(rSource2, source2); rSource2.setColumnNames(null); rSource2.setFileUrls(new ArrayList()); rSource2.setColumnNames(null); rSource2.setFileUrls(null); - Assert.assertEquals(rSource2, source2); + Assertions.assertEquals(rSource2, source2); dis.close(); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java index 8f266e81ab82e7..1b925f06e0944b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/StreamLoadHandlerTest.java @@ -32,8 +32,8 @@ import org.apache.doris.thrift.TStreamLoadPutRequest; import org.apache.doris.thrift.TStreamLoadPutResult; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -53,7 +53,7 @@ public void testSelectBackendSkipsDecommissioningBackend() throws Exception { try { Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", systemInfoService); - Assert.assertEquals(selectedBackend.getId(), StreamLoadHandler.selectBackend("cluster0").getId()); + Assertions.assertEquals(selectedBackend.getId(), StreamLoadHandler.selectBackend("cluster0").getId()); } finally { Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", originalSystemInfoService); } @@ -81,9 +81,9 @@ public void testSetCloudClusterUsesBackendComputeGroup() throws Exception { request, null, new TStreamLoadPutResult(), "127.0.0.1"); handler.setCloudCluster(); - Assert.assertEquals("backend_compute_group", + Assertions.assertEquals("backend_compute_group", ConnectContext.get().getSessionVariable().getCloudCluster()); - Assert.assertEquals("backend_compute_group", request.getCloudCluster()); + Assertions.assertEquals("backend_compute_group", request.getCloudCluster()); } finally { ConnectContext.remove(); Config.cloud_unique_id = originalCloudUniqueId; @@ -132,9 +132,9 @@ public void testGroupCommitValidatesBackendComputeGroupPrivilege() throws Except request, null, new TStreamLoadPutResult(), "127.0.0.1"); try { handler.setCloudCluster(); - Assert.fail("group commit should validate compute group privilege"); + Assertions.fail("group commit should validate compute group privilege"); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("USAGE denied")); + Assertions.assertTrue(e.getMessage().contains("USAGE denied")); } Mockito.verify(cloudEnv).changeCloudCluster( diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/TabletLoadInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/TabletLoadInfoTest.java index 02a268f9b2b454..1504a4045654ff 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/TabletLoadInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/TabletLoadInfoTest.java @@ -20,9 +20,9 @@ import org.apache.doris.catalog.FakeEnv; import org.apache.doris.common.FeConstants; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -33,7 +33,7 @@ public class TabletLoadInfoTest { private FakeEnv fakeEnv; - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -66,12 +66,12 @@ public void testSerialization() throws Exception { TabletLoadInfo tabletLoadInfo1 = new TabletLoadInfo(); tabletLoadInfo1.readFields(dis); - Assert.assertEquals("hdfs://host:port/dir", tabletLoadInfo1.getFilePath()); - Assert.assertEquals(1L, tabletLoadInfo1.getFileSize()); + Assertions.assertEquals("hdfs://host:port/dir", tabletLoadInfo1.getFilePath()); + Assertions.assertEquals(1L, tabletLoadInfo1.getFileSize()); - Assert.assertEquals(tabletLoadInfo1, tabletLoadInfo); - Assert.assertEquals(rTabletLoadInfo0, tabletLoadInfo0); - Assert.assertNotEquals(rTabletLoadInfo0, tabletLoadInfo1); + Assertions.assertEquals(tabletLoadInfo1, tabletLoadInfo); + Assertions.assertEquals(rTabletLoadInfo0, tabletLoadInfo0); + Assertions.assertNotEquals(rTabletLoadInfo0, tabletLoadInfo1); dis.close(); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerFileGroupAggInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerFileGroupAggInfoTest.java index 12d03346cec860..e4c7cb88e7d665 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerFileGroupAggInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerFileGroupAggInfoTest.java @@ -24,8 +24,8 @@ import org.apache.doris.load.BrokerFileGroupAggInfo.FileGroupAggKey; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -75,44 +75,46 @@ public void test1() throws DdlException { brokerFileGroupAggInfo.addFileGroup(group5); Map> map = brokerFileGroupAggInfo.getAggKeyToFileGroups(); - Assert.assertEquals(4, map.keySet().size()); + Assertions.assertEquals(4, map.keySet().size()); FileGroupAggKey aggKey = new FileGroupAggKey(1L, Lists.newArrayList(10L)); - Assert.assertEquals(2, map.get(aggKey).size()); + Assertions.assertEquals(2, map.get(aggKey).size()); aggKey = new FileGroupAggKey(2L, Lists.newArrayList()); - Assert.assertEquals(1, map.get(aggKey).size()); + Assertions.assertEquals(1, map.get(aggKey).size()); aggKey = new FileGroupAggKey(3L, Lists.newArrayList(11L, 12L)); - Assert.assertEquals(1, map.get(aggKey).size()); + Assertions.assertEquals(1, map.get(aggKey).size()); aggKey = new FileGroupAggKey(4L, Lists.newArrayList()); - Assert.assertEquals(1, map.get(aggKey).size()); + Assertions.assertEquals(1, map.get(aggKey).size()); } - @Test(expected = DdlException.class) + @Test public void test2() throws DdlException { - /* - * data description: - * table 1 -> partition[10, 11] file1 - * table 1 -> partition[11, 12] file2 - * table 2 -> partition[] file3 - * - * output: - * throw exception - */ - BrokerFileGroupAggInfo brokerFileGroupAggInfo = new BrokerFileGroupAggInfo(); - - BrokerFileGroup group1 = Deencapsulation.newInstance(BrokerFileGroup.class); - Deencapsulation.setField(group1, "tableId", 1L); - Deencapsulation.setField(group1, "partitionIds", Lists.newArrayList(10L, 11L)); - - BrokerFileGroup group2 = Deencapsulation.newInstance(BrokerFileGroup.class); - Deencapsulation.setField(group2, "tableId", 1L); - Deencapsulation.setField(group2, "partitionIds", Lists.newArrayList(11L, 12L)); - - BrokerFileGroup group3 = Deencapsulation.newInstance(BrokerFileGroup.class); - Deencapsulation.setField(group3, "tableId", 2L); - Deencapsulation.setField(group3, "partitionIds", Lists.newArrayList()); - - brokerFileGroupAggInfo.addFileGroup(group1); - brokerFileGroupAggInfo.addFileGroup(group2); + Assertions.assertThrows(DdlException.class, () -> { + /* + * data description: + * table 1 -> partition[10, 11] file1 + * table 1 -> partition[11, 12] file2 + * table 2 -> partition[] file3 + * + * output: + * throw exception + */ + BrokerFileGroupAggInfo brokerFileGroupAggInfo = new BrokerFileGroupAggInfo(); + + BrokerFileGroup group1 = Deencapsulation.newInstance(BrokerFileGroup.class); + Deencapsulation.setField(group1, "tableId", 1L); + Deencapsulation.setField(group1, "partitionIds", Lists.newArrayList(10L, 11L)); + + BrokerFileGroup group2 = Deencapsulation.newInstance(BrokerFileGroup.class); + Deencapsulation.setField(group2, "tableId", 1L); + Deencapsulation.setField(group2, "partitionIds", Lists.newArrayList(11L, 12L)); + + BrokerFileGroup group3 = Deencapsulation.newInstance(BrokerFileGroup.class); + Deencapsulation.setField(group3, "tableId", 2L); + Deencapsulation.setField(group3, "partitionIds", Lists.newArrayList()); + + brokerFileGroupAggInfo.addFileGroup(group1); + brokerFileGroupAggInfo.addFileGroup(group2); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadJobTest.java index 21dcba9e98895f..9c488169ab4c70 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadJobTest.java @@ -55,9 +55,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -70,7 +70,7 @@ public class BrokerLoadJobTest { - @BeforeClass + @BeforeAll public static void start() { MetricRepo.init(); } @@ -101,8 +101,8 @@ public void testGetTableNames() throws MetaNotFoundException { Mockito.doReturn(Optional.of(table)).when(database).getTable(1L); Mockito.when(table.getName()).thenReturn(tableName); - Assert.assertEquals(1, brokerLoadJob.getTableNamesForShow().size()); - Assert.assertTrue(brokerLoadJob.getTableNamesForShow().contains(tableName)); + Assertions.assertEquals(1, brokerLoadJob.getTableNamesForShow().size()); + Assertions.assertTrue(brokerLoadJob.getTableNamesForShow().contains(tableName)); } } @@ -119,7 +119,7 @@ public void testExecuteJob() { brokerLoadJob.unprotectedExecuteJob(); Map idToTasks = Deencapsulation.getField(brokerLoadJob, "idToTasks"); - Assert.assertEquals(1, idToTasks.size()); + Assertions.assertEquals(1, idToTasks.size()); } } @@ -133,9 +133,9 @@ public void testLoadBackendSelectionModesSurviveSerialization() { String serialized = GsonUtils.GSON.toJson(job); BrokerLoadJob restored = GsonUtils.GSON.fromJson(serialized, BrokerLoadJob.class); - Assert.assertEquals("key_a", restored.getLoadBackendSelectionHint().getPreferredKey()); - Assert.assertEquals(mode, restored.getLoadBackendSelectionHint().getMode()); - Assert.assertEquals("persisted", restored.getLoadBackendSelectionHint().getReason()); + Assertions.assertEquals("key_a", restored.getLoadBackendSelectionHint().getPreferredKey()); + Assertions.assertEquals(mode, restored.getLoadBackendSelectionHint().getMode()); + Assertions.assertEquals("persisted", restored.getLoadBackendSelectionHint().getReason()); } BrokerLoadJob job = new BrokerLoadJob(); @@ -144,7 +144,7 @@ public void testLoadBackendSelectionModesSurviveSerialization() { String serialized = GsonUtils.GSON.toJson(job); BrokerLoadJob unknownMode = GsonUtils.GSON.fromJson( serialized.replace("\"m\":\"PREFER\"", "\"m\":\"FUTURE\""), BrokerLoadJob.class); - Assert.assertEquals(BackendSelection.Mode.DEFAULT, unknownMode.getLoadBackendSelectionHint().getMode()); + Assertions.assertEquals(BackendSelection.Mode.DEFAULT, unknownMode.getLoadBackendSelectionHint().getMode()); } @Test @@ -173,7 +173,7 @@ public void testRestoreLoadBackendSelectionForAsyncPlanning() { job.setComputeGroup(); - Assert.assertSame(hint, context.getLoadBackendSelectionDecision()); + Assertions.assertSame(hint, context.getLoadBackendSelectionDecision()); } finally { ConnectContext.remove(); } @@ -187,7 +187,7 @@ public void testPendingTaskOnFinishedWithJobCancelled() { brokerLoadJob.onTaskFinished(attachment); Set finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds"); - Assert.assertEquals(0, finishedTaskIds.size()); + Assertions.assertEquals(0, finishedTaskIds.size()); } @Test @@ -203,7 +203,7 @@ public void testPendingTaskOnFinishedWithDuplicated() { brokerLoadJob.onTaskFinished(attachment); Map idToTasks = Deencapsulation.getField(brokerLoadJob, "idToTasks"); - Assert.assertEquals(0, idToTasks.size()); + Assertions.assertEquals(0, idToTasks.size()); } @Test @@ -302,10 +302,10 @@ public void testPendingTaskOnFinished() throws Exception { brokerLoadJob.onTaskFinished(attachment); Set finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds"); - Assert.assertEquals(1, finishedTaskIds.size()); - Assert.assertEquals(true, finishedTaskIds.contains(taskId)); + Assertions.assertEquals(1, finishedTaskIds.size()); + Assertions.assertEquals(true, finishedTaskIds.contains(taskId)); Map idToTasks = Deencapsulation.getField(brokerLoadJob, "idToTasks"); - Assert.assertEquals(3, idToTasks.size()); + Assertions.assertEquals(3, idToTasks.size()); } } @@ -328,12 +328,12 @@ public void testLoadingTaskOnFinishedWithUnfinishedTask() { brokerLoadJob.onTaskFinished(attachment); Set finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds"); - Assert.assertEquals(1, finishedTaskIds.size()); + Assertions.assertEquals(1, finishedTaskIds.size()); EtlStatus loadingStatus = Deencapsulation.getField(brokerLoadJob, "loadingStatus"); - Assert.assertEquals("10", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); - Assert.assertEquals("1", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); + Assertions.assertEquals("10", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); + Assertions.assertEquals("1", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); int progress = Deencapsulation.getField(brokerLoadJob, "progress"); - Assert.assertEquals(50, progress); + Assertions.assertEquals(50, progress); } @Test @@ -371,13 +371,13 @@ public void testLoadingTaskOnFinishedWithErrorNum() { brokerLoadJob.onTaskFinished(attachment1); brokerLoadJob.onTaskFinished(attachment2); Set finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds"); - Assert.assertEquals(2, finishedTaskIds.size()); + Assertions.assertEquals(2, finishedTaskIds.size()); EtlStatus loadingStatus = Deencapsulation.getField(brokerLoadJob, "loadingStatus"); - Assert.assertEquals("30", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); - Assert.assertEquals("3", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); + Assertions.assertEquals("30", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); + Assertions.assertEquals("3", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); int progress = Deencapsulation.getField(brokerLoadJob, "progress"); - Assert.assertEquals(99, progress); - Assert.assertEquals(JobState.CANCELLED, Deencapsulation.getField(brokerLoadJob, "state")); + Assertions.assertEquals(99, progress); + Assertions.assertEquals(JobState.CANCELLED, Deencapsulation.getField(brokerLoadJob, "state")); } } @@ -415,12 +415,12 @@ public void testLoadingTaskOnFinished() throws Exception { brokerLoadJob.onTaskFinished(attachment1); Set finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds"); - Assert.assertEquals(1, finishedTaskIds.size()); + Assertions.assertEquals(1, finishedTaskIds.size()); EtlStatus loadingStatus = Deencapsulation.getField(brokerLoadJob, "loadingStatus"); - Assert.assertEquals("10", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); - Assert.assertEquals("0", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); + Assertions.assertEquals("10", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL)); + Assertions.assertEquals("0", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL)); int progress = Deencapsulation.getField(brokerLoadJob, "progress"); - Assert.assertEquals(99, progress); + Assertions.assertEquals(99, progress); } } @@ -439,9 +439,9 @@ public void testExecuteReplayOnAborted() { Mockito.when(attachment.getJobState()).thenReturn(JobState.CANCELLED); brokerLoadJob.replayTxnAttachment(txnState); - Assert.assertEquals(99, (int) Deencapsulation.getField(brokerLoadJob, "progress")); - Assert.assertEquals(1, brokerLoadJob.getFinishTimestamp()); - Assert.assertEquals(JobState.CANCELLED, brokerLoadJob.getState()); + Assertions.assertEquals(99, (int) Deencapsulation.getField(brokerLoadJob, "progress")); + Assertions.assertEquals(1, brokerLoadJob.getFinishTimestamp()); + Assertions.assertEquals(JobState.CANCELLED, brokerLoadJob.getState()); } @@ -460,9 +460,9 @@ public void testExecuteReplayOnVisible() { Mockito.when(attachment.getJobState()).thenReturn(JobState.LOADING); brokerLoadJob.replayTxnAttachment(txnState); - Assert.assertEquals(99, (int) Deencapsulation.getField(brokerLoadJob, "progress")); - Assert.assertEquals(1, brokerLoadJob.getFinishTimestamp()); - Assert.assertEquals(JobState.LOADING, brokerLoadJob.getState()); + Assertions.assertEquals(99, (int) Deencapsulation.getField(brokerLoadJob, "progress")); + Assertions.assertEquals(1, brokerLoadJob.getFinishTimestamp()); + Assertions.assertEquals(JobState.LOADING, brokerLoadJob.getState()); } @Test @@ -478,7 +478,7 @@ public void testBeginTxnReusesAlreadyBegunTxn() throws Exception { brokerLoadJob.beginTxn(); } - Assert.assertEquals(12345L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); + Assertions.assertEquals(12345L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); Mockito.verifyNoInteractions(transactionMgr); } @@ -510,7 +510,7 @@ public void testBeginTxnAdoptsOwnPreparedTxn() throws Exception { brokerLoadJob.beginTxn(); } - Assert.assertEquals(777L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); + Assertions.assertEquals(777L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); } @Test @@ -547,8 +547,8 @@ public void testBeginTxnFinishesOwnVisibleTxn() throws Exception { brokerLoadJob.beginTxn(); } - Assert.assertEquals(888L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); - Assert.assertEquals(JobState.FINISHED, brokerLoadJob.getState()); + Assertions.assertEquals(888L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); + Assertions.assertEquals(JobState.FINISHED, brokerLoadJob.getState()); Mockito.verify(callbackFactory).removeCallback(1001L); Mockito.verify(editLog).logEndLoadJob(Mockito.any(LoadJobFinalOperation.class)); } @@ -576,13 +576,13 @@ public void testBeginTxnRethrowsForeignLabelConflict() throws Exception { try { brokerLoadJob.beginTxn(); - Assert.fail("expected LabelAlreadyUsedException"); + Assertions.fail("expected LabelAlreadyUsedException"); } catch (LabelAlreadyUsedException expected) { // expected } } - Assert.assertEquals(0L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); + Assertions.assertEquals(0L, (long) Deencapsulation.getField(brokerLoadJob, "transactionId")); } @Test @@ -651,11 +651,11 @@ public void testPendingTaskOnFinishedWithNereidsPlanningError() throws Exception brokerLoadJob.onTaskFinished(attachment); - Assert.assertEquals(JobState.CANCELLED, brokerLoadJob.getState()); + Assertions.assertEquals(JobState.CANCELLED, brokerLoadJob.getState()); FailMsg failMsg = Deencapsulation.getField(brokerLoadJob, "failMsg"); - Assert.assertTrue(failMsg.getMsg().contains("exceed limit usage")); + Assertions.assertTrue(failMsg.getMsg().contains("exceed limit usage")); Map idToTasks = Deencapsulation.getField(brokerLoadJob, "idToTasks"); - Assert.assertEquals(0, idToTasks.size()); + Assertions.assertEquals(0, idToTasks.size()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadPendingTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadPendingTaskTest.java index ef821c00e745b9..65bcd182d3d9af 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadPendingTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/BrokerLoadPendingTaskTest.java @@ -30,8 +30,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -137,8 +137,8 @@ public void testExecuteTask() throws UserException { brokerLoadPendingTask.executeTask(); BrokerPendingTaskAttachment brokerPendingTaskAttachment = Deencapsulation.getField(brokerLoadPendingTask, "attachment"); - Assert.assertEquals(1, brokerPendingTaskAttachment.getFileNumByTable(aggKey)); - Assert.assertEquals(1L, + Assertions.assertEquals(1, brokerPendingTaskAttachment.getFileNumByTable(aggKey)); + Assertions.assertEquals(1L, brokerPendingTaskAttachment.getFileStatusByTable(aggKey).get(0).get(0).size); } finally { mockedFsFactory.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/ExportMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/ExportMgrTest.java index 116c20ebe7a310..c953119d99e1dd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/ExportMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/ExportMgrTest.java @@ -31,9 +31,9 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.qe.SessionVariable; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -46,7 +46,7 @@ public class ExportMgrTest { private AccessControllerManager accessManager = Mockito.mock(AccessControllerManager.class); - @Before + @BeforeEach public void setUp() { MockedAuth.mockedAccess(accessManager); } @@ -72,22 +72,22 @@ public void testShowExport() throws Exception { exportMgr.unprotectAddJob(job3); List> r1 = exportMgr.getExportJobInfosByIdOrState(-1, 3, "", true, null, null, -1); - Assert.assertEquals(r1.size(), 1); + Assertions.assertEquals(r1.size(), 1); List> r2 = exportMgr.getExportJobInfosByIdOrState(-1, 0, "", false, null, null, -1); - Assert.assertEquals(r2.size(), 3); + Assertions.assertEquals(r2.size(), 3); List> r3 = exportMgr.getExportJobInfosByIdOrState(-1, 0, "aabbcc", false, null, null, -1); - Assert.assertEquals(r3.size(), 1); + Assertions.assertEquals(r3.size(), 1); List> r4 = exportMgr.getExportJobInfosByIdOrState(-1, 0, "%bb%", true, null, null, -1); - Assert.assertEquals(r4.size(), 3); + Assertions.assertEquals(r4.size(), 3); List> r5 = exportMgr.getExportJobInfosByIdOrState(-1, 0, "aabb%", true, null, null, -1); - Assert.assertEquals(r5.size(), 2); + Assertions.assertEquals(r5.size(), 2); List> r6 = exportMgr.getExportJobInfosByIdOrState(-1, 0, "%dd", true, null, null, -1); - Assert.assertEquals(r6.size(), 1); + Assertions.assertEquals(r6.size(), 1); } } @@ -108,8 +108,8 @@ public void testRemoveOldExportJobs() { // Assertions: Check the number of jobs remaining List remainingJobs = exportMgr.getJobs(); - Assert.assertTrue(remainingJobs.size() <= Config.history_job_keep_max_second); - Assert.assertEquals(7, remainingJobs.size()); // Expecting 8 jobs to remain + Assertions.assertTrue(remainingJobs.size() <= Config.history_job_keep_max_second); + Assertions.assertEquals(7, remainingJobs.size()); // Expecting 8 jobs to remain for (int i = 11; i <= 1010; i++) { @@ -124,13 +124,13 @@ public void testRemoveOldExportJobs() { exportMgr.removeOldExportJobs(); // Assertions: Check the number of jobs remaining remainingJobs = exportMgr.getJobs(); - Assert.assertTrue(remainingJobs.size() <= Config.history_job_keep_max_second); - Assert.assertEquals(1000, remainingJobs.size()); // Expecting 1000 jobs to remain + Assertions.assertTrue(remainingJobs.size() <= Config.history_job_keep_max_second); + Assertions.assertEquals(1000, remainingJobs.size()); // Expecting 1000 jobs to remain // check the created time remainingJobs.sort(Comparator.comparingLong(entry -> entry.getCreateTimeMs())); for (int i = 0; i < remainingJobs.size(); ++i) { - Assert.assertEquals(1010 - i, remainingJobs.get(i).getId()); + Assertions.assertEquals(1010 - i, remainingJobs.get(i).getId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/InsertLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/InsertLoadJobTest.java index 80add9934eaf92..1dd529037eda1a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/InsertLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/InsertLoadJobTest.java @@ -25,8 +25,8 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.datasource.InternalCatalog; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -58,10 +58,10 @@ public void testGetTableNames() throws MetaNotFoundException { Mockito.when(table.getName()).thenReturn(tableName); Set tableNames = insertLoadJob.getTableNamesForShow(); - Assert.assertEquals(1, tableNames.size()); - Assert.assertTrue(tableNames.contains(tableName)); - Assert.assertEquals(JobState.FINISHED, insertLoadJob.getState()); - Assert.assertEquals(Integer.valueOf(100), Deencapsulation.getField(insertLoadJob, "progress")); + Assertions.assertEquals(1, tableNames.size()); + Assertions.assertTrue(tableNames.contains(tableName)); + Assertions.assertEquals(JobState.FINISHED, insertLoadJob.getState()); + Assertions.assertEquals(Integer.valueOf(100), Deencapsulation.getField(insertLoadJob, "progress")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadJobTest.java index 886e166fffe0b6..7d5f08f81f2c31 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadJobTest.java @@ -29,9 +29,9 @@ import org.apache.doris.transaction.TxnStateCallbackFactory; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -39,7 +39,7 @@ public class LoadJobTest { - @BeforeClass + @BeforeAll public static void start() { MetricRepo.init(); } @@ -51,7 +51,7 @@ public void testSetJobPropertiesWithErrorTimeout() { LoadJob loadJob = new BrokerLoadJob(); try { loadJob.setJobProperties(jobProperties); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { // CHECKSTYLE IGNORE THIS LINE } @@ -68,12 +68,12 @@ public void testSetJobProperties() { LoadJob loadJob = new BrokerLoadJob(); try { loadJob.setJobProperties(jobProperties); - Assert.assertEquals(1000, loadJob.getTimeout()); - Assert.assertEquals(0.1, loadJob.getMaxFilterRatio(), 0); - Assert.assertEquals(1024, loadJob.getExecMemLimit()); - Assert.assertTrue(loadJob.isStrictMode()); + Assertions.assertEquals(1000, loadJob.getTimeout()); + Assertions.assertEquals(0.1, loadJob.getMaxFilterRatio(), 0); + Assertions.assertEquals(1024, loadJob.getExecMemLimit()); + Assertions.assertTrue(loadJob.isStrictMode()); } catch (DdlException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -92,9 +92,9 @@ public void testExecute() { try { loadJob.execute(); } catch (LoadException e) { - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } - Assert.assertEquals(JobState.PENDING, loadJob.getState()); + Assertions.assertEquals(JobState.PENDING, loadJob.getState()); } } @@ -104,7 +104,7 @@ public void testProcessTimeoutWithCompleted() { Deencapsulation.setField(loadJob, "state", JobState.FINISHED); loadJob.processTimeout(); - Assert.assertEquals(JobState.FINISHED, loadJob.getState()); + Assertions.assertEquals(JobState.FINISHED, loadJob.getState()); } @Test @@ -114,7 +114,7 @@ public void testProcessTimeoutWithIsCommitting() { Deencapsulation.setField(loadJob, "state", JobState.LOADING); loadJob.processTimeout(); - Assert.assertEquals(JobState.LOADING, loadJob.getState()); + Assertions.assertEquals(JobState.LOADING, loadJob.getState()); } @Test @@ -122,7 +122,7 @@ public void testProcessTimeoutWithLongTimeoutSecond() { LoadJob loadJob = new BrokerLoadJob(); loadJob.setTimeout(1000L); loadJob.processTimeout(); - Assert.assertEquals(JobState.PENDING, loadJob.getState()); + Assertions.assertEquals(JobState.PENDING, loadJob.getState()); } @Test @@ -143,7 +143,7 @@ public void testProcessTimeout() { Deencapsulation.setField(loadJob, "createTimestamp", 0L); loadJob.processTimeout(); - Assert.assertEquals(JobState.CANCELLED, loadJob.getState()); + Assertions.assertEquals(JobState.CANCELLED, loadJob.getState()); } } @@ -151,8 +151,8 @@ public void testProcessTimeout() { public void testUpdateStateToLoading() { LoadJob loadJob = new BrokerLoadJob(); loadJob.updateState(JobState.LOADING); - Assert.assertEquals(JobState.LOADING, loadJob.getState()); - Assert.assertNotEquals(-1, (long) Deencapsulation.getField(loadJob, "loadStartTimestamp")); + Assertions.assertEquals(JobState.LOADING, loadJob.getState()); + Assertions.assertNotEquals(-1, (long) Deencapsulation.getField(loadJob, "loadStartTimestamp")); } @Test @@ -170,12 +170,12 @@ public void testUpdateStateToFinished() { LoadJob loadJob = new BrokerLoadJob(); loadJob.idToTasks.put(1L, loadTask1); - Assert.assertEquals(1, loadJob.idToTasks.size()); + Assertions.assertEquals(1, loadJob.idToTasks.size()); loadJob.updateState(JobState.FINISHED); - Assert.assertEquals(JobState.FINISHED, loadJob.getState()); - Assert.assertNotEquals(-1, (long) Deencapsulation.getField(loadJob, "finishTimestamp")); - Assert.assertEquals(100, (int) Deencapsulation.getField(loadJob, "progress")); - Assert.assertEquals(0, loadJob.idToTasks.size()); + Assertions.assertEquals(JobState.FINISHED, loadJob.getState()); + Assertions.assertNotEquals(-1, (long) Deencapsulation.getField(loadJob, "finishTimestamp")); + Assertions.assertEquals(100, (int) Deencapsulation.getField(loadJob, "progress")); + Assertions.assertEquals(0, loadJob.idToTasks.size()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadLoadingTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadLoadingTaskTest.java index d82cb64c0268b3..d48864a3728f95 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadLoadingTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadLoadingTaskTest.java @@ -19,8 +19,8 @@ import org.apache.doris.thrift.TQueryOptions; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class LoadLoadingTaskTest { @@ -40,8 +40,8 @@ public void testBatchSizeSettingLogic() { if (enableMemTableOnSinkNode1) { queryOptionsWithMemTable.setBatchSize(brokerLoadBatchSize); } - Assert.assertTrue(queryOptionsWithMemTable.isEnableMemtableOnSinkNode()); - Assert.assertEquals(brokerLoadBatchSize, queryOptionsWithMemTable.getBatchSize()); + Assertions.assertTrue(queryOptionsWithMemTable.isEnableMemtableOnSinkNode()); + Assertions.assertEquals(brokerLoadBatchSize, queryOptionsWithMemTable.getBatchSize()); // Case 2: enableMemTableOnSinkNode = false, setBatchSize should NOT be called TQueryOptions queryOptionsWithoutMemTable = new TQueryOptions(); @@ -50,8 +50,8 @@ public void testBatchSizeSettingLogic() { if (enableMemTableOnSinkNode2) { queryOptionsWithoutMemTable.setBatchSize(brokerLoadBatchSize); } - Assert.assertFalse(queryOptionsWithoutMemTable.isEnableMemtableOnSinkNode()); + Assertions.assertFalse(queryOptionsWithoutMemTable.isEnableMemtableOnSinkNode()); // batch_size should remain 0 (unset), BE will use DEFAULT_BATCH_SIZE (4062) - Assert.assertEquals(0, queryOptionsWithoutMemTable.getBatchSize()); + Assertions.assertEquals(0, queryOptionsWithoutMemTable.getBatchSize()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadManagerTest.java index cbe30ec56a4569..33f1949dac02d6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/LoadManagerTest.java @@ -26,10 +26,10 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.datasource.InternalCatalog; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -48,13 +48,13 @@ public class LoadManagerTest { private int oldStreamingLabelKeepMaxSecond; private int oldLabelNumThreshold; - @Before + @BeforeEach public void setUp() throws Exception { oldStreamingLabelKeepMaxSecond = Config.streaming_label_keep_max_second; oldLabelNumThreshold = Config.label_num_threshold; } - @After + @AfterEach public void tearDown() throws Exception { Config.streaming_label_keep_max_second = oldStreamingLabelKeepMaxSecond; Config.label_num_threshold = oldLabelNumThreshold; @@ -93,7 +93,7 @@ public void testSerializationNormal() throws Exception { Map loadJobs = Deencapsulation.getField(loadManager, fieldName); Map newLoadJobs = Deencapsulation.getField(newLoadManager, fieldName); - Assert.assertEquals(loadJobs, newLoadJobs); + Assertions.assertEquals(loadJobs, newLoadJobs); } } @@ -129,7 +129,7 @@ public void testSerializationWithJobRemoved() throws Exception { LoadManager newLoadManager = deserializeFromFile(file); Map newLoadJobs = Deencapsulation.getField(newLoadManager, fieldName); - Assert.assertEquals(0, newLoadJobs.size()); + Assertions.assertEquals(0, newLoadJobs.size()); } } @@ -164,11 +164,11 @@ public void testCleanOverLimitJobs() throws Exception { Map idToJobs = Deencapsulation.getField(loadManager, fieldName); Map>> dbIdToLabelToLoadJobs = Deencapsulation.getField(loadManager, "dbIdToLabelToLoadJobs"); - Assert.assertEquals(1, idToJobs.size()); - Assert.assertEquals(1, dbIdToLabelToLoadJobs.size()); + Assertions.assertEquals(1, idToJobs.size()); + Assertions.assertEquals(1, dbIdToLabelToLoadJobs.size()); LoadJob loadJob = idToJobs.get(job2.getId()); - Assert.assertEquals("job2", loadJob.getLabel()); - Assert.assertNotNull(dbIdToLabelToLoadJobs.get(1L).get("job2")); + Assertions.assertEquals("job2", loadJob.getLabel()); + Assertions.assertNotNull(dbIdToLabelToLoadJobs.get(1L).get("job2")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/TokenManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/TokenManagerTest.java index 2f8f143734426f..8926370feb6a5e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/TokenManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/loadv2/TokenManagerTest.java @@ -21,13 +21,13 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.common.UserException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TokenManagerTest { - @Before + @BeforeEach public void runBefore() { FeConstants.runningUnitTest = true; } @@ -37,7 +37,7 @@ public void testTokenCheck() throws UserException { TokenManager tokenManager = new TokenManager(); tokenManager.start(); String token = tokenManager.acquireToken(); - Assert.assertTrue(tokenManager.checkAuthToken(token)); + Assertions.assertTrue(tokenManager.checkAuthToken(token)); } @Test @@ -46,7 +46,7 @@ public void testSameToken() throws UserException { tokenManager.start(); String token1 = tokenManager.acquireToken(); String token2 = tokenManager.acquireToken(); - Assert.assertNotNull(token1); - Assert.assertEquals(token1, token2); + Assertions.assertNotNull(token1); + Assertions.assertEquals(token1, token2); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaAwsMskIamAuthTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaAwsMskIamAuthTest.java index ed77128d02ffb4..18764b97328574 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaAwsMskIamAuthTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaAwsMskIamAuthTest.java @@ -20,9 +20,9 @@ import org.apache.doris.common.UserException; import org.apache.doris.load.routineload.kafka.KafkaDataSourceProperties; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -34,7 +34,7 @@ public class KafkaAwsMskIamAuthTest { private Map dataSourceProperties; - @Before + @BeforeEach public void setUp() { dataSourceProperties = new HashMap<>(); dataSourceProperties.put("kafka_broker_list", "b-1.msk-cluster.xxx.kafka.us-east-1.amazonaws.com:9098"); @@ -53,10 +53,10 @@ public void testValidAwsMskIamConfig() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); - Assert.assertEquals("OAUTHBEARER", props.getCustomKafkaProperties().get("sasl.mechanism")); - Assert.assertEquals("us-east-1", props.getCustomKafkaProperties().get("aws.region")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); + Assertions.assertEquals("OAUTHBEARER", props.getCustomKafkaProperties().get("sasl.mechanism")); + Assertions.assertEquals("us-east-1", props.getCustomKafkaProperties().get("aws.region")); } @Test @@ -69,9 +69,9 @@ public void testValidOAuthBearerConfig() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); - Assert.assertEquals("OAUTHBEARER", props.getCustomKafkaProperties().get("sasl.mechanism")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); + Assertions.assertEquals("OAUTHBEARER", props.getCustomKafkaProperties().get("sasl.mechanism")); } @Test @@ -85,10 +85,10 @@ public void testMissingSecurityProtocol() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for missing security.protocol"); + Assertions.fail("Should throw AnalysisException for missing security.protocol"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("security.protocol")); - Assert.assertTrue(e.getMessage().contains("SASL_SSL")); + Assertions.assertTrue(e.getMessage().contains("security.protocol")); + Assertions.assertTrue(e.getMessage().contains("SASL_SSL")); } } @@ -104,9 +104,9 @@ public void testInvalidSecurityProtocol() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for invalid security.protocol"); + Assertions.fail("Should throw AnalysisException for invalid security.protocol"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("SASL_SSL")); + Assertions.assertTrue(e.getMessage().contains("SASL_SSL")); } } @@ -121,10 +121,10 @@ public void testMissingSaslMechanism() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for missing sasl.mechanism"); + Assertions.fail("Should throw AnalysisException for missing sasl.mechanism"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("sasl.mechanism")); - Assert.assertTrue(e.getMessage().contains("OAUTHBEARER")); + Assertions.assertTrue(e.getMessage().contains("sasl.mechanism")); + Assertions.assertTrue(e.getMessage().contains("OAUTHBEARER")); } } @@ -140,9 +140,9 @@ public void testInvalidSaslMechanism() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for invalid sasl.mechanism with AWS config"); + Assertions.fail("Should throw AnalysisException for invalid sasl.mechanism with AWS config"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("OAUTHBEARER")); + Assertions.assertTrue(e.getMessage().contains("OAUTHBEARER")); } } @@ -158,10 +158,10 @@ public void testMissingRegionWithRoleArn() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for missing region with AWS properties"); + Assertions.fail("Should throw AnalysisException for missing region with AWS properties"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.region")); - Assert.assertTrue(e.getMessage().contains("required")); + Assertions.assertTrue(e.getMessage().contains("aws.region")); + Assertions.assertTrue(e.getMessage().contains("required")); } } @@ -179,11 +179,11 @@ public void testCompleteAwsIamConfigWithRoleArn() throws UserException { props.analyze(); Map customProps = props.getCustomKafkaProperties(); - Assert.assertEquals("SASL_SSL", customProps.get("security.protocol")); - Assert.assertEquals("OAUTHBEARER", customProps.get("sasl.mechanism")); - Assert.assertEquals("us-east-1", customProps.get("aws.region")); - Assert.assertEquals("arn:aws:iam::123456789012:role/MyMskRole", customProps.get("aws.role_arn")); - Assert.assertEquals("default", customProps.get("aws.profile_name")); + Assertions.assertEquals("SASL_SSL", customProps.get("security.protocol")); + Assertions.assertEquals("OAUTHBEARER", customProps.get("sasl.mechanism")); + Assertions.assertEquals("us-east-1", customProps.get("aws.region")); + Assertions.assertEquals("arn:aws:iam::123456789012:role/MyMskRole", customProps.get("aws.role_arn")); + Assertions.assertEquals("default", customProps.get("aws.profile_name")); } @Test @@ -199,7 +199,7 @@ public void testExternalIdWithRoleArn() throws UserException { props.analyze(); Map customProps = props.getCustomKafkaProperties(); - Assert.assertEquals("external-id-123", customProps.get("aws.external_id")); + Assertions.assertEquals("external-id-123", customProps.get("aws.external_id")); } @Test @@ -214,10 +214,10 @@ public void testExternalIdWithoutRoleArn() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for external_id without role_arn"); + Assertions.fail("Should throw AnalysisException for external_id without role_arn"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.external_id")); - Assert.assertTrue(e.getMessage().contains("aws.role_arn")); + Assertions.assertTrue(e.getMessage().contains("aws.external_id")); + Assertions.assertTrue(e.getMessage().contains("aws.role_arn")); } } @@ -233,9 +233,9 @@ public void testScramSha256Config() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); - Assert.assertEquals("SCRAM-SHA-256", props.getCustomKafkaProperties().get("sasl.mechanism")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("SASL_SSL", props.getCustomKafkaProperties().get("security.protocol")); + Assertions.assertEquals("SCRAM-SHA-256", props.getCustomKafkaProperties().get("sasl.mechanism")); } @Test @@ -247,8 +247,8 @@ public void testPlaintextConfigWithoutSasl() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("PLAINTEXT", props.getCustomKafkaProperties().get("security.protocol")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("PLAINTEXT", props.getCustomKafkaProperties().get("security.protocol")); } @Test @@ -263,8 +263,8 @@ public void testSslConfigWithoutSasl() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("SSL", props.getCustomKafkaProperties().get("security.protocol")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("SSL", props.getCustomKafkaProperties().get("security.protocol")); } @Test @@ -281,9 +281,9 @@ public void testPublicAccessWithExplicitCredentials() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("us-east-1", props.getCustomKafkaProperties().get("aws.region")); - Assert.assertEquals("AKIAIOSFODNN7EXAMPLE", props.getCustomKafkaProperties().get("aws.access_key")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("us-east-1", props.getCustomKafkaProperties().get("aws.region")); + Assertions.assertEquals("AKIAIOSFODNN7EXAMPLE", props.getCustomKafkaProperties().get("aws.access_key")); } @Test @@ -299,10 +299,10 @@ public void testPublicAccessWithoutCredentials() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for public access without credentials"); + Assertions.fail("Should throw AnalysisException for public access without credentials"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("public")); - Assert.assertTrue(e.getMessage().contains("credentials")); + Assertions.assertTrue(e.getMessage().contains("public")); + Assertions.assertTrue(e.getMessage().contains("credentials")); } } @@ -318,8 +318,8 @@ public void testInternalAccessWithInstanceProfile() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("INSTANCE_PROFILE", props.getCustomKafkaProperties().get("aws.credentials_provider")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("INSTANCE_PROFILE", props.getCustomKafkaProperties().get("aws.credentials_provider")); } @Test @@ -334,10 +334,10 @@ public void testRoleArnWithCredentialsProvider() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("arn:aws:iam::123456789012:role/MyMskRole", + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("arn:aws:iam::123456789012:role/MyMskRole", props.getCustomKafkaProperties().get("aws.role_arn")); - Assert.assertEquals("ENV", props.getCustomKafkaProperties().get("aws.credentials_provider")); + Assertions.assertEquals("ENV", props.getCustomKafkaProperties().get("aws.credentials_provider")); } @Test @@ -352,8 +352,8 @@ public void testInternalAccessWithProfile() throws UserException { props.setTimezone("UTC"); props.analyze(); - Assert.assertNotNull(props.getCustomKafkaProperties()); - Assert.assertEquals("default", props.getCustomKafkaProperties().get("aws.profile_name")); + Assertions.assertNotNull(props.getCustomKafkaProperties()); + Assertions.assertEquals("default", props.getCustomKafkaProperties().get("aws.profile_name")); } @Test @@ -371,8 +371,8 @@ public void testCrossAccountAccessWithRoleArnAndCredentials() throws UserExcepti props.analyze(); Map customProps = props.getCustomKafkaProperties(); - Assert.assertEquals("AKIAIOSFODNN7EXAMPLE", customProps.get("aws.access_key")); - Assert.assertEquals("arn:aws:iam::111111111111:role/AccountAMskRole", customProps.get("aws.role_arn")); + Assertions.assertEquals("AKIAIOSFODNN7EXAMPLE", customProps.get("aws.access_key")); + Assertions.assertEquals("arn:aws:iam::111111111111:role/AccountAMskRole", customProps.get("aws.role_arn")); } @Test @@ -389,11 +389,11 @@ public void testMissingAccessKeyWithSecretKeyPublicAccess() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for missing access key"); + Assertions.fail("Should throw AnalysisException for missing access key"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.access_key")); - Assert.assertTrue(e.getMessage().contains("aws.secret_key")); - Assert.assertTrue(e.getMessage().contains("together")); + Assertions.assertTrue(e.getMessage().contains("aws.access_key")); + Assertions.assertTrue(e.getMessage().contains("aws.secret_key")); + Assertions.assertTrue(e.getMessage().contains("together")); } } @@ -411,11 +411,11 @@ public void testMissingSecretKeyWithAccessKeyPublicAccess() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for missing secret key"); + Assertions.fail("Should throw AnalysisException for missing secret key"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.access_key")); - Assert.assertTrue(e.getMessage().contains("aws.secret_key")); - Assert.assertTrue(e.getMessage().contains("together")); + Assertions.assertTrue(e.getMessage().contains("aws.access_key")); + Assertions.assertTrue(e.getMessage().contains("aws.secret_key")); + Assertions.assertTrue(e.getMessage().contains("together")); } } @@ -434,11 +434,11 @@ public void testPublicAccessWithProfileOnly() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for public access without explicit credentials"); + Assertions.fail("Should throw AnalysisException for public access without explicit credentials"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.access_key")); - Assert.assertTrue(e.getMessage().contains("aws.secret_key")); - Assert.assertTrue(e.getMessage().contains("together")); + Assertions.assertTrue(e.getMessage().contains("aws.access_key")); + Assertions.assertTrue(e.getMessage().contains("aws.secret_key")); + Assertions.assertTrue(e.getMessage().contains("together")); } } @@ -457,11 +457,11 @@ public void testPublicAccessWithCredentialsProviderOnly() { try { props.analyze(); - Assert.fail("Should throw AnalysisException for public access without explicit credentials"); + Assertions.fail("Should throw AnalysisException for public access without explicit credentials"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("aws.access_key")); - Assert.assertTrue(e.getMessage().contains("aws.secret_key")); - Assert.assertTrue(e.getMessage().contains("together")); + Assertions.assertTrue(e.getMessage().contains("aws.access_key")); + Assertions.assertTrue(e.getMessage().contains("aws.secret_key")); + Assertions.assertTrue(e.getMessage().contains("together")); } } @@ -483,9 +483,9 @@ public void testMultipleCredentialsSources() throws UserException { // All properties should be preserved (BE will use them in priority order) Map customProps = props.getCustomKafkaProperties(); - Assert.assertEquals("AKIAIOSFODNN7EXAMPLE", customProps.get("aws.access_key")); - Assert.assertEquals("arn:aws:iam::123456789012:role/MyRole", customProps.get("aws.role_arn")); - Assert.assertEquals("external-id-123", customProps.get("aws.external_id")); - Assert.assertEquals("default", customProps.get("aws.profile_name")); + Assertions.assertEquals("AKIAIOSFODNN7EXAMPLE", customProps.get("aws.access_key")); + Assertions.assertEquals("arn:aws:iam::123456789012:role/MyRole", customProps.get("aws.role_arn")); + Assertions.assertEquals("external-id-123", customProps.get("aws.external_id")); + Assertions.assertEquals("default", customProps.get("aws.profile_name")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java index 7f0c8588372403..696b42b6d34518 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KafkaRoutineLoadJobTest.java @@ -54,10 +54,10 @@ import org.apache.kafka.common.PartitionInfo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -90,7 +90,7 @@ public class KafkaRoutineLoadJobTest { private MockedStatic connectContextStatic; - @Before + @BeforeEach public void init() { connectContextStatic = MockedAuth.mockedConnectContext(connectContext, "root", "192.168.1.1"); @@ -99,7 +99,7 @@ public void init() { partitionNames = new PartitionNamesInfo(false, partitionNameList); } - @After + @AfterEach public void tearDown() { if (connectContextStatic != null) { connectContextStatic.close(); @@ -120,25 +120,25 @@ public void testRoutineLoadTaskConcurrentNum() throws MetaNotFoundException { new KafkaRoutineLoadJob(1L, "kafka_routine_load_job", 1L, 1L, "127.0.0.1:9020", "topic1", UserIdentity.ADMIN); Deencapsulation.setField(routineLoadJob, "currentKafkaPartitions", partitionList1); - Assert.assertEquals(2, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(2, routineLoadJob.calculateCurrentConcurrentTaskNum()); // 3 partitions, 4 be routineLoadJob = new KafkaRoutineLoadJob(1L, "kafka_routine_load_job", 1L, 1L, "127.0.0.1:9020", "topic1", UserIdentity.ADMIN); Deencapsulation.setField(routineLoadJob, "currentKafkaPartitions", partitionList2); - Assert.assertEquals(3, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(3, routineLoadJob.calculateCurrentConcurrentTaskNum()); // 4 partitions, 4 be routineLoadJob = new KafkaRoutineLoadJob(1L, "kafka_routine_load_job", 1L, 1L, "127.0.0.1:9020", "topic1", UserIdentity.ADMIN); Deencapsulation.setField(routineLoadJob, "currentKafkaPartitions", partitionList3); - Assert.assertEquals(4, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(4, routineLoadJob.calculateCurrentConcurrentTaskNum()); // 7 partitions, 4 be routineLoadJob = new KafkaRoutineLoadJob(1L, "kafka_routine_load_job", 1L, 1L, "127.0.0.1:9020", "topic1", UserIdentity.ADMIN); Deencapsulation.setField(routineLoadJob, "currentKafkaPartitions", partitionList4); - Assert.assertEquals(6, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(6, routineLoadJob.calculateCurrentConcurrentTaskNum()); } @Test @@ -162,17 +162,17 @@ public void testDivideRoutineLoadJob() throws UserException { // todo(ml): assert List routineLoadTaskInfoList = Deencapsulation.getField(routineLoadJob, "routineLoadTaskInfoList"); - Assert.assertEquals(2, routineLoadTaskInfoList.size()); + Assertions.assertEquals(2, routineLoadTaskInfoList.size()); for (RoutineLoadTaskInfo routineLoadTaskInfo : routineLoadTaskInfoList) { KafkaTaskInfo kafkaTaskInfo = (KafkaTaskInfo) routineLoadTaskInfo; - Assert.assertEquals(false, kafkaTaskInfo.isRunning()); + Assertions.assertEquals(false, kafkaTaskInfo.isRunning()); if (kafkaTaskInfo.getPartitions().size() == 2) { - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(1)); - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(6)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(1)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(6)); } else if (kafkaTaskInfo.getPartitions().size() == 1) { - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(4)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(4)); } else { - Assert.fail(); + Assertions.fail(); } } } @@ -199,7 +199,7 @@ public void testUpdateLagRefreshesLatestOffsetCache() throws UserException { routineLoadJob.updateLag(); - Assert.assertEquals(15L, routineLoadJob.totalLag().longValue()); + Assertions.assertEquals(15L, routineLoadJob.totalLag().longValue()); } } finally { Config.cloud_unique_id = originalCloudUniqueId; @@ -237,7 +237,7 @@ public void testUpdateLagRebuildsConvertedPropertiesAfterReplay() throws UserExc routineLoadJob.updateLag(); - Assert.assertEquals(5L, routineLoadJob.totalLag().longValue()); + Assertions.assertEquals(5L, routineLoadJob.totalLag().longValue()); kafkaUtilStatic.verify(() -> KafkaUtil.getLatestOffsets(Mockito.eq(1L), Mockito.any(UUID.class), Mockito.eq("127.0.0.1:9020"), Mockito.eq("topic1"), Mockito.>argThat(properties -> @@ -269,7 +269,7 @@ public void testUpdateProgressWarnsWhenReadCommittedTaskHasZeroRowsAndLag() thro Deencapsulation.invoke(routineLoadJob, "updateProgress", attachment); String otherMsg = Deencapsulation.getField(routineLoadJob, "otherMsg"); - Assert.assertTrue(otherMsg.contains("some records may be in uncommitted transactions")); + Assertions.assertTrue(otherMsg.contains("some records may be in uncommitted transactions")); } @Test @@ -299,58 +299,58 @@ public void testDisplayCustomPropertiesMasksKafkaSecrets() { String customPropertiesJson = routineLoadJob.customPropertiesJsonToString(); Map showCreateCustomProperties = routineLoadJob.getCustomProperties(); - Assert.assertFalse(customPropertiesJson.contains("plain_secret")); - Assert.assertFalse(customPropertiesJson.contains("jaas_secret")); - Assert.assertFalse(customPropertiesJson.contains("oauth_client_secret")); - Assert.assertFalse(customPropertiesJson.contains("oauth_alias_secret")); - Assert.assertFalse(customPropertiesJson.contains("oauth_private_key_pem")); - Assert.assertFalse(customPropertiesJson.contains("oauth_private_key_passphrase")); - Assert.assertFalse(customPropertiesJson.contains("keystore_secret")); - Assert.assertFalse(customPropertiesJson.contains("keystore_key_secret")); - Assert.assertFalse(customPropertiesJson.contains("key_pem_secret")); - Assert.assertFalse(customPropertiesJson.contains("aws_access_key")); - Assert.assertFalse(customPropertiesJson.contains("aws_secret")); - Assert.assertFalse(customPropertiesJson.contains("aws_session_secret")); - Assert.assertFalse(customPropertiesJson.contains("bare_password_secret")); - Assert.assertFalse(customPropertiesJson.contains("bare_secret_key")); - Assert.assertFalse(customPropertiesJson.contains("bare_session_token")); - Assert.assertTrue(customPropertiesJson.contains("\"sasl.password\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"sasl.jaas.config\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"sasl.oauthbearer.client.secret\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains( + Assertions.assertFalse(customPropertiesJson.contains("plain_secret")); + Assertions.assertFalse(customPropertiesJson.contains("jaas_secret")); + Assertions.assertFalse(customPropertiesJson.contains("oauth_client_secret")); + Assertions.assertFalse(customPropertiesJson.contains("oauth_alias_secret")); + Assertions.assertFalse(customPropertiesJson.contains("oauth_private_key_pem")); + Assertions.assertFalse(customPropertiesJson.contains("oauth_private_key_passphrase")); + Assertions.assertFalse(customPropertiesJson.contains("keystore_secret")); + Assertions.assertFalse(customPropertiesJson.contains("keystore_key_secret")); + Assertions.assertFalse(customPropertiesJson.contains("key_pem_secret")); + Assertions.assertFalse(customPropertiesJson.contains("aws_access_key")); + Assertions.assertFalse(customPropertiesJson.contains("aws_secret")); + Assertions.assertFalse(customPropertiesJson.contains("aws_session_secret")); + Assertions.assertFalse(customPropertiesJson.contains("bare_password_secret")); + Assertions.assertFalse(customPropertiesJson.contains("bare_secret_key")); + Assertions.assertFalse(customPropertiesJson.contains("bare_session_token")); + Assertions.assertTrue(customPropertiesJson.contains("\"sasl.password\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"sasl.jaas.config\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"sasl.oauthbearer.client.secret\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains( "\"sasl.oauthbearer.client.credentials.client.secret\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"sasl.oauthbearer.assertion.private.key.pem\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains( + Assertions.assertTrue(customPropertiesJson.contains("\"sasl.oauthbearer.assertion.private.key.pem\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains( "\"sasl.oauthbearer.assertion.private.key.passphrase\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"ssl.keystore.password\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"ssl.keystore.key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"ssl.key.pem\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.access_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.secret_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.session_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"password\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"secret_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"session_token\":\"******\"")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.sasl.password")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.sasl.jaas.config")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.sasl.oauthbearer.client.secret")); - Assert.assertEquals("******", + Assertions.assertTrue(customPropertiesJson.contains("\"ssl.keystore.password\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"ssl.keystore.key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"ssl.key.pem\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.access_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.secret_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.session_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"password\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"secret_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"session_token\":\"******\"")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.password")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.jaas.config")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.oauthbearer.client.secret")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.oauthbearer.client.credentials.client.secret")); - Assert.assertEquals("******", + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.oauthbearer.assertion.private.key.pem")); - Assert.assertEquals("******", + Assertions.assertEquals("******", showCreateCustomProperties.get("property.sasl.oauthbearer.assertion.private.key.passphrase")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.ssl.keystore.password")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.ssl.keystore.key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.ssl.key.pem")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.access_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.secret_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.session_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.password")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.secret_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.session_token")); - Assert.assertEquals("doris", showCreateCustomProperties.get("property.sasl.username")); - Assert.assertEquals("plain_secret", customProperties.get("sasl.password")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.ssl.keystore.password")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.ssl.keystore.key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.ssl.key.pem")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.access_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.secret_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.session_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.password")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.secret_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.session_token")); + Assertions.assertEquals("doris", showCreateCustomProperties.get("property.sasl.username")); + Assertions.assertEquals("plain_secret", customProperties.get("sasl.password")); } @Test @@ -392,12 +392,12 @@ public void testReadCommittedZeroRowsWithLagDelaysNextTask() throws UserExceptio kafkaTaskInfo.handleTaskByTxnCommitAttachment(attachment); - Assert.assertFalse(kafkaTaskInfo.getIsEof()); - Assert.assertTrue(kafkaTaskInfo.needDedalySchedule()); + Assertions.assertFalse(kafkaTaskInfo.getIsEof()); + Assertions.assertTrue(kafkaTaskInfo.needDedalySchedule()); RoutineLoadTaskInfo newTask = Deencapsulation.invoke(routineLoadJob, "unprotectRenewTask", kafkaTaskInfo, false); - Assert.assertTrue(newTask.needDedalySchedule()); + Assertions.assertTrue(newTask.needDedalySchedule()); } } @@ -429,7 +429,7 @@ public void testAdaptiveBatchUsesTaskLagThreshold() { TRoutineLoadTask unknownLagThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke( taskWithUnknownLag, "adaptiveBatchParam", unknownLagThriftTask, routineLoadJob); - Assert.assertEquals(20L, unknownLagThriftTask.getMaxIntervalS()); + Assertions.assertEquals(20L, unknownLagThriftTask.getMaxIntervalS()); Map latestOffsets = Maps.newHashMap(); latestOffsets.put(1, 10_000_010L); @@ -444,10 +444,10 @@ public void testAdaptiveBatchUsesTaskLagThreshold() { TRoutineLoadTask thresholdThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke( taskAtLagThreshold, "adaptiveBatchParam", thresholdThriftTask, routineLoadJob); - Assert.assertEquals(20L, thresholdThriftTask.getMaxIntervalS()); - Assert.assertEquals(200000L, thresholdThriftTask.getMaxBatchRows()); - Assert.assertEquals(100L * 1024 * 1024, thresholdThriftTask.getMaxBatchSize()); - Assert.assertEquals(routineLoadJob.getTimeout() * 1000L, taskAtLagThreshold.getTimeoutMs()); + Assertions.assertEquals(20L, thresholdThriftTask.getMaxIntervalS()); + Assertions.assertEquals(200000L, thresholdThriftTask.getMaxBatchRows()); + Assertions.assertEquals(100L * 1024 * 1024, thresholdThriftTask.getMaxBatchSize()); + Assertions.assertEquals(routineLoadJob.getTimeout() * 1000L, taskAtLagThreshold.getTimeoutMs()); KafkaTaskInfo taskAboveLagThreshold = new KafkaTaskInfo(new UUID(1, 3), 1L, 20000, taskProgress, false, 1000, true); @@ -455,12 +455,12 @@ public void testAdaptiveBatchUsesTaskLagThreshold() { TRoutineLoadTask adaptiveThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke( taskAboveLagThreshold, "adaptiveBatchParam", adaptiveThriftTask, routineLoadJob); - Assert.assertEquals(360L, adaptiveThriftTask.getMaxIntervalS()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, + Assertions.assertEquals(360L, adaptiveThriftTask.getMaxIntervalS()); + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, adaptiveThriftTask.getMaxBatchRows()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, adaptiveThriftTask.getMaxBatchSize()); - Assert.assertEquals(360L * Config.routine_load_task_timeout_multiplier * 1000, + Assertions.assertEquals(360L * Config.routine_load_task_timeout_multiplier * 1000, taskAboveLagThreshold.getTimeoutMs()); Deencapsulation.setField(routineLoadJob, "maxBatchRows", 50_000_000L); @@ -473,9 +473,9 @@ public void testAdaptiveBatchUsesTaskLagThreshold() { TRoutineLoadTask configuredThresholdThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke(taskAtConfiguredLagThreshold, "adaptiveBatchParam", configuredThresholdThriftTask, routineLoadJob); - Assert.assertEquals(20L, configuredThresholdThriftTask.getMaxIntervalS()); - Assert.assertEquals(50_000_000L, configuredThresholdThriftTask.getMaxBatchRows()); - Assert.assertEquals(routineLoadJob.getTimeout() * 1000L, + Assertions.assertEquals(20L, configuredThresholdThriftTask.getMaxIntervalS()); + Assertions.assertEquals(50_000_000L, configuredThresholdThriftTask.getMaxBatchRows()); + Assertions.assertEquals(routineLoadJob.getTimeout() * 1000L, taskAtConfiguredLagThreshold.getTimeoutMs()); KafkaTaskInfo taskAboveConfiguredLagThreshold = new KafkaTaskInfo(new UUID(1, 5), 1L, 20000, @@ -484,8 +484,8 @@ public void testAdaptiveBatchUsesTaskLagThreshold() { TRoutineLoadTask configuredAdaptiveThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke(taskAboveConfiguredLagThreshold, "adaptiveBatchParam", configuredAdaptiveThriftTask, routineLoadJob); - Assert.assertEquals(360L, configuredAdaptiveThriftTask.getMaxIntervalS()); - Assert.assertEquals(50_000_000L, configuredAdaptiveThriftTask.getMaxBatchRows()); + Assertions.assertEquals(360L, configuredAdaptiveThriftTask.getMaxIntervalS()); + Assertions.assertEquals(50_000_000L, configuredAdaptiveThriftTask.getMaxBatchRows()); } finally { Config.routine_load_adaptive_min_batch_interval_sec = previousAdaptiveIntervalSec; } @@ -519,23 +519,23 @@ public void testAdaptiveBatchUsesCapturedIntervalAcrossConfigChange() { taskProgress, false, 1000, false); scheduledTask.updateAdaptiveTimeout(routineLoadJob); long adaptiveTimeoutMs = 360L * Config.routine_load_task_timeout_multiplier * 1000L; - Assert.assertEquals(adaptiveTimeoutMs, scheduledTask.getTimeoutMs()); + Assertions.assertEquals(adaptiveTimeoutMs, scheduledTask.getTimeoutMs()); Config.routine_load_adaptive_min_batch_interval_sec = 720; TRoutineLoadTask scheduledThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke(scheduledTask, "adaptiveBatchParam", scheduledThriftTask, routineLoadJob); - Assert.assertEquals(360L, scheduledThriftTask.getMaxIntervalS()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, scheduledThriftTask.getMaxBatchRows()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, scheduledThriftTask.getMaxBatchSize()); - Assert.assertEquals(adaptiveTimeoutMs, scheduledTask.getTimeoutMs()); + Assertions.assertEquals(360L, scheduledThriftTask.getMaxIntervalS()); + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, scheduledThriftTask.getMaxBatchRows()); + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, scheduledThriftTask.getMaxBatchSize()); + Assertions.assertEquals(adaptiveTimeoutMs, scheduledTask.getTimeoutMs()); KafkaTaskInfo nextSchedulingAttempt = new KafkaTaskInfo(new UUID(1, 7), 1L, 20000, taskProgress, false, 1000, false); nextSchedulingAttempt.updateAdaptiveTimeout(routineLoadJob); TRoutineLoadTask nextThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke(nextSchedulingAttempt, "adaptiveBatchParam", nextThriftTask, routineLoadJob); - Assert.assertEquals(720L, nextThriftTask.getMaxIntervalS()); - Assert.assertEquals(720L * Config.routine_load_task_timeout_multiplier * 1000L, + Assertions.assertEquals(720L, nextThriftTask.getMaxIntervalS()); + Assertions.assertEquals(720L * Config.routine_load_task_timeout_multiplier * 1000L, nextSchedulingAttempt.getTimeoutMs()); for (int nonPositiveInterval : new int[] {0, -1}) { @@ -546,14 +546,14 @@ public void testAdaptiveBatchUsesCapturedIntervalAcrossConfigChange() { TRoutineLoadTask nonPositiveConfigThriftTask = new TRoutineLoadTask(); Deencapsulation.invoke(nonPositiveConfigTask, "adaptiveBatchParam", nonPositiveConfigThriftTask, routineLoadJob); - Assert.assertEquals(30L, nonPositiveConfigThriftTask.getMaxIntervalS()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, + Assertions.assertEquals(30L, nonPositiveConfigThriftTask.getMaxIntervalS()); + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_ROWS, nonPositiveConfigThriftTask.getMaxBatchRows()); - Assert.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, + Assertions.assertEquals(RoutineLoadJob.DEFAULT_MAX_BATCH_SIZE, nonPositiveConfigThriftTask.getMaxBatchSize()); long normalTimeoutMs = Math.max(30L * Config.routine_load_task_timeout_multiplier, Config.routine_load_task_min_timeout_sec) * 1000L; - Assert.assertEquals(normalTimeoutMs, nonPositiveConfigTask.getTimeoutMs()); + Assertions.assertEquals(normalTimeoutMs, nonPositiveConfigTask.getTimeoutMs()); } } finally { Config.routine_load_adaptive_min_batch_interval_sec = previousAdaptiveIntervalSec; @@ -591,8 +591,8 @@ public void testProcessTimeOutTasks() throws Exception { List idToRoutineLoadTask = Deencapsulation.getField(routineLoadJob, "routineLoadTaskInfoList"); - Assert.assertNotEquals("1", idToRoutineLoadTask.get(0).getId()); - Assert.assertEquals(1, idToRoutineLoadTask.size()); + Assertions.assertNotEquals("1", idToRoutineLoadTask.get(0).getId()); + Assertions.assertEquals(1, idToRoutineLoadTask.size()); } } @@ -656,14 +656,14 @@ public void testFromCreateStmt() throws UserException { Deencapsulation.setField(createRoutineLoadInfo, "dataSourceProperties", dsProperties); KafkaRoutineLoadJob kafkaRoutineLoadJob = KafkaRoutineLoadJob.fromCreateInfo(createRoutineLoadInfo, connectContext); - Assert.assertEquals(jobName, kafkaRoutineLoadJob.getName()); - Assert.assertEquals(dbId, kafkaRoutineLoadJob.getDbId()); - Assert.assertEquals(tableId, kafkaRoutineLoadJob.getTableId()); - Assert.assertEquals(serverAddress, Deencapsulation.getField(kafkaRoutineLoadJob, "brokerList")); - Assert.assertEquals(topicName, Deencapsulation.getField(kafkaRoutineLoadJob, "topic")); + Assertions.assertEquals(jobName, kafkaRoutineLoadJob.getName()); + Assertions.assertEquals(dbId, kafkaRoutineLoadJob.getDbId()); + Assertions.assertEquals(tableId, kafkaRoutineLoadJob.getTableId()); + Assertions.assertEquals(serverAddress, Deencapsulation.getField(kafkaRoutineLoadJob, "brokerList")); + Assertions.assertEquals(topicName, Deencapsulation.getField(kafkaRoutineLoadJob, "topic")); List kafkaPartitionResult = Deencapsulation.getField(kafkaRoutineLoadJob, "customKafkaPartitions"); - Assert.assertEquals(kafkaPartitionString, Joiner.on(",").join(kafkaPartitionResult)); - Assert.assertEquals(sequenceColumnName, kafkaRoutineLoadJob.getSequenceCol()); + Assertions.assertEquals(kafkaPartitionString, Joiner.on(",").join(kafkaPartitionResult)); + Assertions.assertEquals(sequenceColumnName, kafkaRoutineLoadJob.getSequenceCol()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KinesisRoutineLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KinesisRoutineLoadJobTest.java index 65aebd0084e729..5b71adc6cc35d8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KinesisRoutineLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/KinesisRoutineLoadJobTest.java @@ -29,8 +29,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; @@ -54,13 +54,13 @@ public void testRoutineLoadTaskConcurrentNum() { Deencapsulation.setField(routineLoadJob, "closedKinesisShards", Lists.newArrayList("shard-2")); - Assert.assertEquals(3, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(3, routineLoadJob.calculateCurrentConcurrentTaskNum()); Deencapsulation.setField(routineLoadJob, "desireTaskConcurrentNum", 2); - Assert.assertEquals(2, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(2, routineLoadJob.calculateCurrentConcurrentTaskNum()); Config.max_routine_load_task_concurrent_num = 1; - Assert.assertEquals(1, routineLoadJob.calculateCurrentConcurrentTaskNum()); + Assertions.assertEquals(1, routineLoadJob.calculateCurrentConcurrentTaskNum()); } finally { Config.max_routine_load_task_concurrent_num = oldMaxConcurrent; } @@ -93,12 +93,12 @@ public void testGetStatisticContainsKinesisFields() { Gson gson = new Gson(); Map statistic = gson.fromJson(routineLoadJob.getStatistic(), Map.class); - Assert.assertEquals(2L, ((Number) statistic.get("openShardNum")).longValue()); - Assert.assertEquals(1L, ((Number) statistic.get("closedShardNum")).longValue()); - Assert.assertEquals(4L, ((Number) statistic.get("trackedShardNum")).longValue()); - Assert.assertEquals(3L, ((Number) statistic.get("cachedMillisBehindLatestShardNum")).longValue()); - Assert.assertEquals(100L, ((Number) statistic.get("totalMillisBehindLatest")).longValue()); - Assert.assertEquals(100L, ((Number) statistic.get("maxMillisBehindLatest")).longValue()); + Assertions.assertEquals(2L, ((Number) statistic.get("openShardNum")).longValue()); + Assertions.assertEquals(1L, ((Number) statistic.get("closedShardNum")).longValue()); + Assertions.assertEquals(4L, ((Number) statistic.get("trackedShardNum")).longValue()); + Assertions.assertEquals(3L, ((Number) statistic.get("cachedMillisBehindLatestShardNum")).longValue()); + Assertions.assertEquals(100L, ((Number) statistic.get("totalMillisBehindLatest")).longValue()); + Assertions.assertEquals(100L, ((Number) statistic.get("maxMillisBehindLatest")).longValue()); } @Test @@ -114,7 +114,7 @@ public void testHasMoreDataToConsumeShouldKeepPollingWhenLagCacheIsZero() throws Map shardToSeqNum = new HashMap<>(); shardToSeqNum.put("shard-0", "100"); - Assert.assertTrue(routineLoadJob.hasMoreDataToConsume(UUID.randomUUID(), shardToSeqNum)); + Assertions.assertTrue(routineLoadJob.hasMoreDataToConsume(UUID.randomUUID(), shardToSeqNum)); } @Test @@ -140,15 +140,15 @@ public void testLagCacheShouldUseLatestReportInsteadOfHistoricalMax() throws Exc Deencapsulation.invoke(routineLoadJob, "updateProgressAndOffsetsCache", attachment); Map updatedLagCache = Deencapsulation.getField(routineLoadJob, "cachedShardWithMillsBehindLatest"); - Assert.assertEquals(100L, updatedLagCache.get("shard-0").longValue()); + Assertions.assertEquals(100L, updatedLagCache.get("shard-0").longValue()); Gson gson = new Gson(); Map statistic = gson.fromJson(routineLoadJob.getStatistic(), Map.class); - Assert.assertEquals(100L, ((Number) statistic.get("totalMillisBehindLatest")).longValue()); - Assert.assertEquals(100L, ((Number) statistic.get("maxMillisBehindLatest")).longValue()); + Assertions.assertEquals(100L, ((Number) statistic.get("totalMillisBehindLatest")).longValue()); + Assertions.assertEquals(100L, ((Number) statistic.get("maxMillisBehindLatest")).longValue()); Map lag = gson.fromJson(routineLoadJob.getLag(), Map.class); - Assert.assertEquals(100L, ((Number) lag.get("shard-0")).longValue()); + Assertions.assertEquals(100L, ((Number) lag.get("shard-0")).longValue()); } @Test @@ -181,19 +181,19 @@ public void testModifyPropertiesShouldClearStaleCustomShardsWhenStreamChanges() Deencapsulation.invoke(routineLoadJob, "modifyPropertiesInternal", new HashMap(), dataSourceProperties); - Assert.assertEquals("stream-2", Deencapsulation.getField(routineLoadJob, "stream")); + Assertions.assertEquals("stream-2", Deencapsulation.getField(routineLoadJob, "stream")); List customKinesisShards = Deencapsulation.getField(routineLoadJob, "customKinesisShards"); - Assert.assertTrue(customKinesisShards.isEmpty()); + Assertions.assertTrue(customKinesisShards.isEmpty()); List openKinesisShards = Deencapsulation.getField(routineLoadJob, "openKinesisShards"); - Assert.assertTrue(openKinesisShards.isEmpty()); + Assertions.assertTrue(openKinesisShards.isEmpty()); List closedKinesisShards = Deencapsulation.getField(routineLoadJob, "closedKinesisShards"); - Assert.assertTrue(closedKinesisShards.isEmpty()); + Assertions.assertTrue(closedKinesisShards.isEmpty()); KinesisProgress progress = Deencapsulation.getField(routineLoadJob, "progress"); - Assert.assertFalse(progress.hasShards()); + Assertions.assertFalse(progress.hasShards()); Map cachedLag = Deencapsulation.getField(routineLoadJob, "cachedShardWithMillsBehindLatest"); - Assert.assertTrue(cachedLag.isEmpty()); + Assertions.assertTrue(cachedLag.isEmpty()); } @Test @@ -222,11 +222,11 @@ public void testModifyPropertiesShouldReplaceCustomShardsWhenExplicitShardsProvi new HashMap(), dataSourceProperties); List customKinesisShards = Deencapsulation.getField(routineLoadJob, "customKinesisShards"); - Assert.assertEquals(Lists.newArrayList("shard-1", "shard-2"), customKinesisShards); + Assertions.assertEquals(Lists.newArrayList("shard-1", "shard-2"), customKinesisShards); KinesisProgress progress = Deencapsulation.getField(routineLoadJob, "progress"); - Assert.assertEquals("101", progress.getSequenceNumberByShard("shard-1")); - Assert.assertEquals("202", progress.getSequenceNumberByShard("shard-2")); + Assertions.assertEquals("101", progress.getSequenceNumberByShard("shard-1")); + Assertions.assertEquals("202", progress.getSequenceNumberByShard("shard-2")); } @Test @@ -243,23 +243,23 @@ public void testShardRefreshShouldMoveRetiredParentToClosedUntilConsumed() throw Deencapsulation.setField(routineLoadJob, "newCurrentKinesisShards", Lists.newArrayList("shard-child-0", "shard-child-1")); - Assert.assertTrue((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); + Assertions.assertTrue((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); List openKinesisShards = Deencapsulation.getField(routineLoadJob, "openKinesisShards"); List closedKinesisShards = Deencapsulation.getField(routineLoadJob, "closedKinesisShards"); - Assert.assertEquals(new HashSet<>(Lists.newArrayList("shard-child-0", "shard-child-1")), + Assertions.assertEquals(new HashSet<>(Lists.newArrayList("shard-child-0", "shard-child-1")), new HashSet<>(openKinesisShards)); - Assert.assertEquals(new HashSet<>(Lists.newArrayList("shard-parent")), + Assertions.assertEquals(new HashSet<>(Lists.newArrayList("shard-parent")), new HashSet<>(closedKinesisShards)); Deencapsulation.invoke(routineLoadJob, "updateNewShardProgress"); KinesisProgress progress = Deencapsulation.getField(routineLoadJob, "progress"); - Assert.assertTrue(progress.containsShard("shard-parent")); - Assert.assertTrue(progress.containsShard("shard-child-0")); - Assert.assertTrue(progress.containsShard("shard-child-1")); + Assertions.assertTrue(progress.containsShard("shard-parent")); + Assertions.assertTrue(progress.containsShard("shard-child-0")); + Assertions.assertTrue(progress.containsShard("shard-child-1")); Deencapsulation.setField(routineLoadJob, "state", RoutineLoadJob.JobState.NEED_SCHEDULE); routineLoadJob.divideRoutineLoadJob(2); - Assert.assertEquals(new HashSet<>(Lists.newArrayList("shard-parent", "shard-child-0", "shard-child-1")), + Assertions.assertEquals(new HashSet<>(Lists.newArrayList("shard-parent", "shard-child-0", "shard-child-1")), collectAssignedShards(routineLoadJob)); } @@ -277,7 +277,7 @@ public void testFullyConsumedClosedParentShouldNotReappearOnRefresh() throws Exc Deencapsulation.setField(routineLoadJob, "newCurrentKinesisShards", Lists.newArrayList("shard-child-0", "shard-child-1")); - Assert.assertTrue((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); + Assertions.assertTrue((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); Deencapsulation.invoke(routineLoadJob, "updateNewShardProgress"); Map childProgress = new HashMap<>(); @@ -294,21 +294,21 @@ public void testFullyConsumedClosedParentShouldNotReappearOnRefresh() throws Exc Deencapsulation.invoke(routineLoadJob, "updateProgressAndOffsetsCache", attachment); KinesisProgress progress = Deencapsulation.getField(routineLoadJob, "progress"); - Assert.assertFalse(progress.containsShard("shard-parent")); - Assert.assertTrue(progress.containsShard("shard-child-0")); - Assert.assertTrue(progress.containsShard("shard-child-1")); + Assertions.assertFalse(progress.containsShard("shard-parent")); + Assertions.assertTrue(progress.containsShard("shard-child-0")); + Assertions.assertTrue(progress.containsShard("shard-child-1")); List openKinesisShards = Deencapsulation.getField(routineLoadJob, "openKinesisShards"); - Assert.assertEquals(new HashSet<>(Lists.newArrayList("shard-child-0", "shard-child-1")), + Assertions.assertEquals(new HashSet<>(Lists.newArrayList("shard-child-0", "shard-child-1")), new HashSet<>(openKinesisShards)); - Assert.assertTrue(((List) Deencapsulation.getField(routineLoadJob, "closedKinesisShards")).isEmpty()); + Assertions.assertTrue(((List) Deencapsulation.getField(routineLoadJob, "closedKinesisShards")).isEmpty()); Map cachedLag = Deencapsulation.getField(routineLoadJob, "cachedShardWithMillsBehindLatest"); - Assert.assertFalse(cachedLag.containsKey("shard-parent")); - Assert.assertEquals(0L, cachedLag.get("shard-child-0").longValue()); - Assert.assertEquals(100L, cachedLag.get("shard-child-1").longValue()); + Assertions.assertFalse(cachedLag.containsKey("shard-parent")); + Assertions.assertEquals(0L, cachedLag.get("shard-child-0").longValue()); + Assertions.assertEquals(100L, cachedLag.get("shard-child-1").longValue()); Deencapsulation.setField(routineLoadJob, "newCurrentKinesisShards", Lists.newArrayList("shard-child-0", "shard-child-1")); - Assert.assertFalse((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); + Assertions.assertFalse((Boolean) Deencapsulation.invoke(routineLoadJob, "isKinesisShardsChanged")); } @Test @@ -326,17 +326,17 @@ public void testDisplayCustomPropertiesMasksKinesisSecrets() { String customPropertiesJson = routineLoadJob.customPropertiesJsonToString(); Map showCreateCustomProperties = routineLoadJob.getCustomProperties(); - Assert.assertFalse(customPropertiesJson.contains("aws_access_key")); - Assert.assertFalse(customPropertiesJson.contains("aws_secret")); - Assert.assertFalse(customPropertiesJson.contains("aws_session_secret")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.access_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.secret_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.session_key\":\"******\"")); - Assert.assertTrue(customPropertiesJson.contains("\"aws.role_arn\":\"role_arn_value\"")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.access_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.secret_key")); - Assert.assertEquals("******", showCreateCustomProperties.get("property.aws.session_key")); - Assert.assertEquals("role_arn_value", showCreateCustomProperties.get("property.aws.role_arn")); + Assertions.assertFalse(customPropertiesJson.contains("aws_access_key")); + Assertions.assertFalse(customPropertiesJson.contains("aws_secret")); + Assertions.assertFalse(customPropertiesJson.contains("aws_session_secret")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.access_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.secret_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.session_key\":\"******\"")); + Assertions.assertTrue(customPropertiesJson.contains("\"aws.role_arn\":\"role_arn_value\"")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.access_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.secret_key")); + Assertions.assertEquals("******", showCreateCustomProperties.get("property.aws.session_key")); + Assertions.assertEquals("role_arn_value", showCreateCustomProperties.get("property.aws.role_arn")); } private Set collectAssignedShards(KinesisRoutineLoadJob routineLoadJob) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadBackendSelectionTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadBackendSelectionTest.java index 10d39a7cfeda66..6b73d1dcadd10e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadBackendSelectionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadBackendSelectionTest.java @@ -27,8 +27,8 @@ import org.apache.doris.system.Backend; import org.apache.doris.system.SystemInfoService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Arrays; @@ -56,7 +56,7 @@ public void testAvailableBeForTaskDoesNotReuseDecommissioningPreviousBeWhenEligi RoutineLoadManager routineLoadManager = new TestRoutineLoadManager( Collections.singletonList(eligibleBackend.getId())); - Assert.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, previousBackend.getId())); + Assertions.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, previousBackend.getId())); } finally { Config.max_routine_load_task_num_per_be = originalMaxRoutineLoadTaskNumPerBe; Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", originalSystemInfoService); @@ -78,7 +78,7 @@ public void testCloudAvailableBackendIdsSkipsLoadDisabledBackend() throws Except Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", systemInfoService); TestCloudRoutineLoadManager routineLoadManager = new TestCloudRoutineLoadManager(routineLoadJob); - Assert.assertEquals(Collections.singletonList(selectedBackend.getId()), + Assertions.assertEquals(Collections.singletonList(selectedBackend.getId()), routineLoadManager.getAvailableBackendIdsForTest(1L)); } finally { Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", originalSystemInfoService); @@ -110,8 +110,8 @@ public void testAvailableBeForTaskDoesNotReuseSaturatedPreviousBe() throws Excep Deencapsulation.setField(routineLoadManager, "idToRoutineLoadJob", idToRoutineLoadJob); routineLoadManager.updateBeIdToMaxConcurrentTasks(); - Assert.assertEquals(0, routineLoadManager.getClusterIdleSlotNum()); - Assert.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, previousBackend.getId())); + Assertions.assertEquals(0, routineLoadManager.getClusterIdleSlotNum()); + Assertions.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, previousBackend.getId())); } finally { Config.max_routine_load_task_num_per_be = originalMaxRoutineLoadTaskNumPerBe; Deencapsulation.setField(Env.getCurrentEnv(), "systemInfo", originalSystemInfoService); diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadJobTest.java index d2724063abfab2..1ce644f8ab4dbf 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadJobTest.java @@ -48,8 +48,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.kafka.common.PartitionInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -70,13 +70,13 @@ public void testFirstErrorMsgInTxnCommitAttachment() { thriftAttachment.setFirstErrorMsg(overlongFirstErrorMsg); RLTaskTxnCommitAttachment attachment = new RLTaskTxnCommitAttachment(thriftAttachment); - Assert.assertEquals(Config.first_error_msg_max_length, attachment.getFirstErrorMsg().length()); - Assert.assertTrue(attachment.getFirstErrorMsg().endsWith("...")); + Assertions.assertEquals(Config.first_error_msg_max_length, attachment.getFirstErrorMsg().length()); + Assertions.assertTrue(attachment.getFirstErrorMsg().endsWith("...")); RLTaskTxnCommitAttachment cloudAttachment = TxnUtil.rtTaskTxnCommitAttachmentFromPb( TxnUtil.rlTaskTxnCommitAttachmentToPb(attachment)); - Assert.assertEquals("http://127.0.0.1/error_log", cloudAttachment.getErrorLogUrl()); - Assert.assertEquals(attachment.getFirstErrorMsg(), cloudAttachment.getFirstErrorMsg()); + Assertions.assertEquals("http://127.0.0.1/error_log", cloudAttachment.getErrorLogUrl()); + Assertions.assertEquals(attachment.getFirstErrorMsg(), cloudAttachment.getFirstErrorMsg()); } @Test @@ -103,7 +103,7 @@ public void testAfterAbortedReasonOffsetOutOfRange() throws UserException { routineLoadJob.writeLock(); routineLoadJob.afterAborted(transactionState, true, txnStatusChangeReasonString); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); } } @@ -140,10 +140,10 @@ public void testAfterAborted() throws UserException { routineLoadJob.afterAborted(transactionState, true, txnStatusChangeReasonString); RoutineLoadStatistic jobStatistic = Deencapsulation.getField(routineLoadJob, "jobStatistic"); - Assert.assertEquals(RoutineLoadJob.JobState.RUNNING, routineLoadJob.getState()); - Assert.assertEquals(new Long(1), Deencapsulation.getField(jobStatistic, "abortedTaskNum")); - Assert.assertEquals("http://127.0.0.1/error_log", routineLoadJob.getErrorLogUrls().peek()); - Assert.assertEquals("invalid source row", routineLoadJob.getFirstErrorMsg()); + Assertions.assertEquals(RoutineLoadJob.JobState.RUNNING, routineLoadJob.getState()); + Assertions.assertEquals(new Long(1), Deencapsulation.getField(jobStatistic, "abortedTaskNum")); + Assertions.assertEquals("http://127.0.0.1/error_log", routineLoadJob.getErrorLogUrls().peek()); + Assertions.assertEquals("invalid source row", routineLoadJob.getFirstErrorMsg()); } @Test @@ -165,7 +165,7 @@ public void testAfterCommittedWhileTaskAborted() throws UserException { routineLoadJob.writeLock(); routineLoadJob.afterCommitted(transactionState, true); } catch (TransactionException e) { - Assert.fail(); + Assertions.fail(); } } @@ -186,10 +186,10 @@ public void testGetShowInfo() { Deencapsulation.setField(routineLoadJob, "firstErrorMsg", "invalid source row"); List showInfo = routineLoadJob.getShowInfo(); - Assert.assertEquals(true, showInfo.stream().filter(entity -> !Strings.isNullOrEmpty(entity)) + Assertions.assertEquals(true, showInfo.stream().filter(entity -> !Strings.isNullOrEmpty(entity)) .anyMatch(entity -> entity.equals(errorReason.toString()))); - Assert.assertEquals(24, showInfo.size()); - Assert.assertEquals("invalid source row", showInfo.get(23)); + Assertions.assertEquals(24, showInfo.size()); + Assertions.assertEquals("invalid source row", showInfo.get(23)); } @Test @@ -212,7 +212,7 @@ public void testUpdateWhileDbDeleted() throws UserException { RoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob(); routineLoadJob.update(); - Assert.assertEquals(RoutineLoadJob.JobState.CANCELLED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.CANCELLED, routineLoadJob.getState()); } } @@ -238,7 +238,7 @@ public void testUpdateWhileTableDeleted() throws UserException { RoutineLoadJob routineLoadJob = new KafkaRoutineLoadJob(); routineLoadJob.update(); - Assert.assertEquals(RoutineLoadJob.JobState.CANCELLED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.CANCELLED, routineLoadJob.getState()); } } @@ -279,7 +279,7 @@ public void testUpdateWhilePartitionChanged() throws UserException { Deencapsulation.setField(routineLoadJob, "progress", kafkaProgress); routineLoadJob.update(); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob.getState()); } } @@ -297,7 +297,7 @@ public void testUpdateNumOfDataErrorRowMoreThanMax() { Deencapsulation.setField(routineLoadJob, "maxBatchRows", 0); Deencapsulation.invoke(routineLoadJob, "updateNumOfData", 1L, 1L, 0L, 1L, 1L, false); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, Deencapsulation.getField(routineLoadJob, "state")); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, Deencapsulation.getField(routineLoadJob, "state")); } } @@ -315,12 +315,12 @@ public void testUpdateTotalMoreThanBatch() { Deencapsulation.setField(routineLoadJob, "firstErrorMsg", "invalid source row"); Deencapsulation.invoke(routineLoadJob, "updateNumOfData", 2L, 0L, 0L, 1L, 1L, false); - Assert.assertEquals(RoutineLoadJob.JobState.RUNNING, Deencapsulation.getField(routineLoadJob, "state")); - Assert.assertEquals(new Long(0), Deencapsulation.getField(jobStatistic, "currentErrorRows")); - Assert.assertEquals(new Long(0), Deencapsulation.getField(jobStatistic, "currentTotalRows")); - Assert.assertEquals("", Deencapsulation.getField(routineLoadJob, "otherMsg")); - Assert.assertTrue(routineLoadJob.getErrorLogUrls().isEmpty()); - Assert.assertEquals("", routineLoadJob.getFirstErrorMsg()); + Assertions.assertEquals(RoutineLoadJob.JobState.RUNNING, Deencapsulation.getField(routineLoadJob, "state")); + Assertions.assertEquals(new Long(0), Deencapsulation.getField(jobStatistic, "currentErrorRows")); + Assertions.assertEquals(new Long(0), Deencapsulation.getField(jobStatistic, "currentTotalRows")); + Assertions.assertEquals("", Deencapsulation.getField(routineLoadJob, "otherMsg")); + Assertions.assertTrue(routineLoadJob.getErrorLogUrls().isEmpty()); + Assertions.assertEquals("", routineLoadJob.getFirstErrorMsg()); } @@ -339,7 +339,7 @@ public void testGetBeIdToConcurrentTaskNum() { Mockito.when(routineLoadTaskInfo1.getBeId()).thenReturn(1L); Map beIdConcurrentTasksNum = routineLoadJob.getBeCurrentTasksNumMap(); - Assert.assertEquals(2, (int) beIdConcurrentTasksNum.get(1L)); + Assertions.assertEquals(2, (int) beIdConcurrentTasksNum.get(1L)); } @Test @@ -373,49 +373,49 @@ public void testGetShowCreateInfo() throws UserException { + "\"kafka_topic\" = \"test_topic\"\n" + ");"; System.out.println(showCreateInfo); - Assert.assertEquals(expect, showCreateInfo); + Assertions.assertEquals(expect, showCreateInfo); } @Test public void testParseUniqueKeyUpdateMode() { // Test valid mode strings - Assert.assertEquals(TUniqueKeyUpdateMode.UPSERT, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPSERT, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("UPSERT")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPSERT, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPSERT, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("upsert")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("UPDATE_FIXED_COLUMNS")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("update_fixed_columns")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("UPDATE_FLEXIBLE_COLUMNS")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("Update_Flexible_Columns")); // Test invalid mode strings - Assert.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode(null)); - Assert.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("INVALID")); - Assert.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("")); - Assert.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("PARTIAL_UPDATE")); + Assertions.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode(null)); + Assertions.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("INVALID")); + Assertions.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("")); + Assertions.assertNull(CreateRoutineLoadInfo.parseUniqueKeyUpdateMode("PARTIAL_UPDATE")); } @Test public void testParseAndValidateUniqueKeyUpdateMode() throws Exception { // Test valid mode strings - Assert.assertEquals(TUniqueKeyUpdateMode.UPSERT, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPSERT, CreateRoutineLoadInfo.parseAndValidateUniqueKeyUpdateMode("UPSERT")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, CreateRoutineLoadInfo.parseAndValidateUniqueKeyUpdateMode("UPDATE_FIXED_COLUMNS")); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, CreateRoutineLoadInfo.parseAndValidateUniqueKeyUpdateMode("UPDATE_FLEXIBLE_COLUMNS")); // Test invalid mode string throws exception try { CreateRoutineLoadInfo.parseAndValidateUniqueKeyUpdateMode("INVALID_MODE"); - Assert.fail("Expected AnalysisException"); + Assertions.fail("Expected AnalysisException"); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("unique_key_update_mode")); - Assert.assertTrue(e.getMessage().contains("INVALID_MODE")); + Assertions.assertTrue(e.getMessage().contains("unique_key_update_mode")); + Assertions.assertTrue(e.getMessage().contains("INVALID_MODE")); } } @@ -428,7 +428,7 @@ public void testUniqueKeyUpdateModeInJobProperties() { Deencapsulation.setField(job, "jobProperties", jobProperties); Deencapsulation.setField(job, "uniqueKeyUpdateMode", TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS); - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, job.getUniqueKeyUpdateMode()); + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, job.getUniqueKeyUpdateMode()); } @Test @@ -456,8 +456,8 @@ public void testBackwardCompatibilityPartialColumnsToUniqueKeyUpdateMode() throw } // Verify the backward compatibility logic - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, uniqueKeyUpdateMode); - Assert.assertTrue(isPartialUpdate); + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FIXED_COLUMNS, uniqueKeyUpdateMode); + Assertions.assertTrue(isPartialUpdate); } @Test @@ -494,9 +494,9 @@ public void testUniqueKeyUpdateModeTakesPrecedenceOverPartialColumns() throws Ex } // unique_key_update_mode should take precedence - Assert.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, uniqueKeyUpdateMode); + Assertions.assertEquals(TUniqueKeyUpdateMode.UPDATE_FLEXIBLE_COLUMNS, uniqueKeyUpdateMode); // isPartialUpdate should be false for UPDATE_FLEXIBLE_COLUMNS - Assert.assertFalse(isPartialUpdate); + Assertions.assertFalse(isPartialUpdate); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadManagerTest.java index ff68df157872a4..45c9a750a26f79 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadManagerTest.java @@ -57,8 +57,8 @@ import com.google.common.collect.Maps; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -123,9 +123,9 @@ public void testCreateJobAuthDeny() { try { createRoutineLoadInfo.checkJobProperties(); routineLoadManager.createRoutineLoadJob(createRoutineLoadInfo, connectContext); - Assert.fail(); + Assertions.fail(); } catch (LoadException | DdlException e) { - Assert.fail(); + Assertions.fail(); } catch (AnalysisException e) { LOG.info("Access deny"); } catch (UserException e) { @@ -162,7 +162,7 @@ public void testCreateWithSameName() { Deencapsulation.setField(routineLoadManager, "dbToNameToRoutineLoadJob", dbToNameToRoutineLoadJob); try { routineLoadManager.addRoutineLoadJob(kafkaRoutineLoadJob, "db", "table"); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { LOG.info(e.getMessage()); } @@ -214,12 +214,12 @@ public void testCreateWithSameNameOfStoppedJob() throws UserException { Map>> result = Deencapsulation.getField(routineLoadManager, "dbToNameToRoutineLoadJob"); Map result1 = Deencapsulation.getField(routineLoadManager, "idToRoutineLoadJob"); - Assert.assertEquals(1, result.size()); - Assert.assertEquals(Long.valueOf(1L), result.keySet().iterator().next()); + Assertions.assertEquals(1, result.size()); + Assertions.assertEquals(Long.valueOf(1L), result.keySet().iterator().next()); Map> resultNameToRoutineLoadJob = result.get(1L); - Assert.assertEquals(jobName, resultNameToRoutineLoadJob.keySet().iterator().next()); - Assert.assertEquals(2, resultNameToRoutineLoadJob.values().iterator().next().size()); - Assert.assertEquals(2, result1.values().size()); + Assertions.assertEquals(jobName, resultNameToRoutineLoadJob.keySet().iterator().next()); + Assertions.assertEquals(2, resultNameToRoutineLoadJob.values().iterator().next().size()); + Assertions.assertEquals(2, result1.values().size()); } } @@ -249,7 +249,7 @@ public void testGetMinTaskBeId() throws LoadException { Deencapsulation.setField(routineLoadManager, "idToRoutineLoadJob", idToRoutineLoadJob); - Assert.assertEquals(2L, routineLoadManager.getMinTaskBeId("default")); + Assertions.assertEquals(2L, routineLoadManager.getMinTaskBeId("default")); } } @@ -263,7 +263,7 @@ public void testGetMinTaskBeIdWhileClusterDeleted() { RoutineLoadManager routineLoadManager = new RoutineLoadManager(); try { routineLoadManager.getMinTaskBeId("default"); - Assert.fail(); + Assertions.fail(); } catch (LoadException e) { // do nothing } @@ -294,10 +294,10 @@ public void testGetMinTaskBeIdWhileNoSlot() { Deencapsulation.setField(routineLoadManager, "idToRoutineLoadJob", routineLoadJobMap); try { - Assert.assertEquals(-1, routineLoadManager.getMinTaskBeId("default")); + Assertions.assertEquals(-1, routineLoadManager.getMinTaskBeId("default")); } catch (LoadException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } } @@ -328,7 +328,7 @@ public void testGetTotalIdleTaskNum() { Deencapsulation.setField(routineLoadManager, "idToRoutineLoadJob", idToRoutineLoadJob); routineLoadManager.updateBeIdToMaxConcurrentTasks(); - Assert.assertEquals(Config.max_routine_load_task_num_per_be * 2 - 1, + Assertions.assertEquals(Config.max_routine_load_task_num_per_be * 2 - 1, routineLoadManager.getClusterIdleSlotNum()); } } @@ -382,10 +382,10 @@ public void testGetJobByName() { Deencapsulation.setField(routineLoadManager, "dbToNameToRoutineLoadJob", dbToNameRoutineLoadList); List result = routineLoadManager.getJobByName(jobName); - Assert.assertEquals(3, result.size()); - Assert.assertEquals(routineLoadJob2, result.get(0)); - Assert.assertEquals(routineLoadJob1, result.get(1)); - Assert.assertEquals(routineLoadJob3, result.get(2)); + Assertions.assertEquals(3, result.size()); + Assertions.assertEquals(routineLoadJob2, result.get(0)); + Assertions.assertEquals(routineLoadJob1, result.get(1)); + Assertions.assertEquals(routineLoadJob3, result.get(2)); } @@ -411,16 +411,16 @@ public void testGetJob() throws MetaNotFoundException, Deencapsulation.setField(routineLoadManager, "idToRoutineLoadJob", idToRoutineLoadJob); List result = routineLoadManager.getJob(null, null, true, null); - Assert.assertEquals(3, result.size()); - Assert.assertEquals(routineLoadJob2, result.get(0)); - Assert.assertEquals(routineLoadJob1, result.get(1)); - Assert.assertEquals(routineLoadJob3, result.get(2)); + Assertions.assertEquals(3, result.size()); + Assertions.assertEquals(routineLoadJob2, result.get(0)); + Assertions.assertEquals(routineLoadJob1, result.get(1)); + Assertions.assertEquals(routineLoadJob3, result.get(2)); PatternMatcher matcher = PatternMatcher.createMysqlPattern("%test%", true); result = routineLoadManager.getJob(null, null, true, matcher); - Assert.assertEquals(2, result.size()); - Assert.assertEquals(routineLoadJob1, result.get(0)); - Assert.assertEquals(routineLoadJob3, result.get(1)); + Assertions.assertEquals(2, result.size()); + Assertions.assertEquals(routineLoadJob1, result.get(0)); + Assertions.assertEquals(routineLoadJob3, result.get(1)); } @Test @@ -456,10 +456,10 @@ public void testGetJobIncludeHistory() throws MetaNotFoundException { Deencapsulation.setField(routineLoadManager, "dbToNameToRoutineLoadJob", dbToNameToRoutineLoadJob); List result = routineLoadManager.getJob("", "", true, null); - Assert.assertEquals(3, result.size()); - Assert.assertEquals(routineLoadJob2, result.get(0)); - Assert.assertEquals(routineLoadJob1, result.get(1)); - Assert.assertEquals(routineLoadJob3, result.get(2)); + Assertions.assertEquals(3, result.size()); + Assertions.assertEquals(routineLoadJob2, result.get(0)); + Assertions.assertEquals(routineLoadJob1, result.get(1)); + Assertions.assertEquals(routineLoadJob3, result.get(2)); } } @@ -515,7 +515,7 @@ public void testPauseRoutineLoadJob() throws UserException { routineLoadManager.pauseRoutineLoadJob(pauseRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); for (int i = 0; i < 3; i++) { Deencapsulation.setField(routineLoadJob, "pauseReason", @@ -526,10 +526,10 @@ public void testPauseRoutineLoadJob() throws UserException { throw new UserException("thread sleep failed"); } routineLoadManager.updateRoutineLoadJob(); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); } routineLoadManager.updateRoutineLoadJob(); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); } } @@ -579,7 +579,7 @@ public void testResumeRoutineLoadJob() throws UserException { routineLoadManager.resumeRoutineLoadJob(resumeRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob.getState()); } } @@ -633,7 +633,7 @@ public void testStopRoutineLoadJob() throws UserException { routineLoadManager.stopRoutineLoadJob(stopRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.STOPPED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.STOPPED, routineLoadJob.getState()); } } @@ -659,7 +659,7 @@ public void testCheckBeToTask() throws UserException { KafkaRoutineLoadJob job = new KafkaRoutineLoadJob(1L, "testjob", 10000, 10001, "192.168.1.1:9090", "testtopic", UserIdentity.ADMIN); routineLoadManager.addRoutineLoadJob(job, "testdb", "testtable"); - Assert.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, 1L)); + Assertions.assertEquals(-1L, routineLoadManager.getAvailableBeForTask(1L, 1L)); } } @@ -691,8 +691,8 @@ public void testCleanOldRoutineLoadJobs() { routineLoadManager.cleanOldRoutineLoadJobs(); - Assert.assertEquals(0, dbToNameToRoutineLoadJob.size()); - Assert.assertEquals(0, idToRoutineLoadJob.size()); + Assertions.assertEquals(0, dbToNameToRoutineLoadJob.size()); + Assertions.assertEquals(0, idToRoutineLoadJob.size()); } } @@ -726,8 +726,8 @@ public void testCleanOverLimitRoutineLoadJobs() { Config.label_num_threshold = 0; routineLoadManager.cleanOverLimitRoutineLoadJobs(); - Assert.assertEquals(0, dbToNameToRoutineLoadJob.size()); - Assert.assertEquals(0, idToRoutineLoadJob.size()); + Assertions.assertEquals(0, dbToNameToRoutineLoadJob.size()); + Assertions.assertEquals(0, idToRoutineLoadJob.size()); } } @@ -746,7 +746,7 @@ public void testGetBeIdConcurrentTaskMaps() { Mockito.when(routineLoadJob.getBeCurrentTasksNumMap()).thenReturn(beIdToConcurrenTaskNum); Map result = Deencapsulation.invoke(routineLoadManager, "getBeCurrentTasksNumMap"); - Assert.assertEquals(1, (int) result.get(1L)); + Assertions.assertEquals(1, (int) result.get(1L)); } @@ -772,7 +772,7 @@ public void testReplayRemoveOldRoutineLoad() { Mockito.when(operation.getId()).thenReturn(1L); routineLoadManager.replayRemoveOldRoutineLoad(operation); - Assert.assertEquals(0, idToRoutineLoadJob.size()); + Assertions.assertEquals(0, idToRoutineLoadJob.size()); } @Test @@ -798,7 +798,7 @@ public void testReplayChangeRoutineLoadJob() { Mockito.when(operation.getJobState()).thenReturn(RoutineLoadJob.JobState.PAUSED); routineLoadManager.replayChangeRoutineLoadJob(operation); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); } @Test @@ -851,7 +851,7 @@ public void testAlterRoutineLoadJob() throws UserException { routineLoadManager.stopRoutineLoadJob(stopRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.STOPPED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.STOPPED, routineLoadJob.getState()); } } @@ -894,8 +894,8 @@ public void testPauseAndResumeAllRoutineLoadJob() throws UserException { dbToNameToRoutineLoadJob.put(1L, nameToRoutineLoadJob); Deencapsulation.setField(routineLoadManager, "dbToNameToRoutineLoadJob", dbToNameToRoutineLoadJob); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); Mockito.when(pauseRoutineLoadCommand.isAll()).thenReturn(true); Mockito.when(pauseRoutineLoadCommand.getDbFullName()).thenReturn(""); @@ -914,12 +914,12 @@ public void testPauseAndResumeAllRoutineLoadJob() throws UserException { Mockito.when(resumeRoutineLoadCommand.getDbFullName()).thenReturn(""); routineLoadManager.pauseRoutineLoadJob(pauseRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob1.getState()); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob2.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob1.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob2.getState()); routineLoadManager.resumeRoutineLoadJob(resumeRoutineLoadCommand); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); - Assert.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob2.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob1.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.NEED_SCHEDULE, routineLoadJob2.getState()); } } @@ -937,18 +937,18 @@ public void testCalAutoResumeInterval() throws Exception { jobRoutine.autoResumeCount = 0; long interval = ScheduleRule.calAutoResumeInterval(jobRoutine); - Assert.assertEquals(Math.min((long) Math.pow(2, 0) * backOffTimeSec, maxBackOffTimeSec), interval); + Assertions.assertEquals(Math.min((long) Math.pow(2, 0) * backOffTimeSec, maxBackOffTimeSec), interval); jobRoutine.autoResumeCount = 1; interval = ScheduleRule.calAutoResumeInterval(jobRoutine); - Assert.assertEquals(Math.min((long) Math.pow(2, 1) * backOffTimeSec, maxBackOffTimeSec), interval); + Assertions.assertEquals(Math.min((long) Math.pow(2, 1) * backOffTimeSec, maxBackOffTimeSec), interval); jobRoutine.autoResumeCount = 5; interval = ScheduleRule.calAutoResumeInterval(jobRoutine); - Assert.assertEquals(maxBackOffTimeSec, interval); + Assertions.assertEquals(maxBackOffTimeSec, interval); jobRoutine.autoResumeCount = 1000; interval = ScheduleRule.calAutoResumeInterval(jobRoutine); - Assert.assertEquals(maxBackOffTimeSec, interval); + Assertions.assertEquals(maxBackOffTimeSec, interval); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java index 1bfd862c939607..bf828829b730b9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadSchedulerTest.java @@ -36,8 +36,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -104,10 +104,10 @@ public void testNormalRunOneCycle() throws LoadException, MetaNotFoundException for (RoutineLoadTaskInfo routineLoadTaskInfo : routineLoadTaskInfoList) { KafkaTaskInfo kafkaTaskInfo = (KafkaTaskInfo) routineLoadTaskInfo; if (kafkaTaskInfo.getPartitions().size() == 2) { - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(100)); - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(300)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(100)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(300)); } else { - Assert.assertTrue(kafkaTaskInfo.getPartitions().contains(200)); + Assertions.assertTrue(kafkaTaskInfo.getPartitions().contains(200)); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java index c99877c2cc47e4..533ca2ba989b87 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/RoutineLoadTaskSchedulerTest.java @@ -35,10 +35,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -55,13 +55,13 @@ public class RoutineLoadTaskSchedulerTest { private AgentTaskExecutor agentTaskExecutor = Mockito.mock(AgentTaskExecutor.class); private MockedStatic envStatic; - @Before + @BeforeEach public void setUp() { envStatic = Mockito.mockStatic(Env.class); envStatic.when(Env::getCurrentEnv).thenReturn(env); } - @After + @AfterEach public void tearDown() { envStatic.close(); } @@ -131,15 +131,15 @@ public void testSubmitTaskFailureRenewsTaskWithJobWriteLock() { Deencapsulation.invoke(routineLoadTaskScheduler, "handleSubmitTaskFailure", routineLoadTaskInfo, "network error"); - Assert.assertTrue(routineLoadJob.isRenewCalledWithWriteLock()); + Assertions.assertTrue(routineLoadJob.isRenewCalledWithWriteLock()); List routineLoadTaskInfoList = Deencapsulation.getField(routineLoadJob, "routineLoadTaskInfoList"); - Assert.assertEquals(1, routineLoadTaskInfoList.size()); - Assert.assertNotSame(routineLoadTaskInfo, routineLoadTaskInfoList.get(0)); + Assertions.assertEquals(1, routineLoadTaskInfoList.size()); + Assertions.assertNotSame(routineLoadTaskInfo, routineLoadTaskInfoList.get(0)); LinkedBlockingDeque needScheduleTasksQueue = Deencapsulation.getField(routineLoadTaskScheduler, "needScheduleTasksQueue"); - Assert.assertSame(routineLoadTaskInfoList.get(0), needScheduleTasksQueue.peek()); + Assertions.assertSame(routineLoadTaskInfoList.get(0), needScheduleTasksQueue.peek()); } @Test @@ -160,10 +160,10 @@ public void testSubmitTaskFailureSkipsRenewWhenTaskRemoved() { Deencapsulation.invoke(routineLoadTaskScheduler, "handleSubmitTaskFailure", routineLoadTaskInfo, "network error"); - Assert.assertFalse(routineLoadJob.isRenewCalled()); + Assertions.assertFalse(routineLoadJob.isRenewCalled()); LinkedBlockingDeque needScheduleTasksQueue = Deencapsulation.getField(routineLoadTaskScheduler, "needScheduleTasksQueue"); - Assert.assertTrue(needScheduleTasksQueue.isEmpty()); + Assertions.assertTrue(needScheduleTasksQueue.isEmpty()); } @Test @@ -185,10 +185,10 @@ public void testSubmitTaskFailureSkipsRenewWhenJobPaused() { Deencapsulation.invoke(routineLoadTaskScheduler, "handleSubmitTaskFailure", routineLoadTaskInfo, "network error"); - Assert.assertFalse(routineLoadJob.isRenewCalled()); + Assertions.assertFalse(routineLoadJob.isRenewCalled()); LinkedBlockingDeque needScheduleTasksQueue = Deencapsulation.getField(routineLoadTaskScheduler, "needScheduleTasksQueue"); - Assert.assertTrue(needScheduleTasksQueue.isEmpty()); + Assertions.assertTrue(needScheduleTasksQueue.isEmpty()); } private static class LockCheckingKafkaRoutineLoadJob extends KafkaRoutineLoadJob { diff --git a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/kinesis/KinesisDataSourcePropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/kinesis/KinesisDataSourcePropertiesTest.java index 6d81c5f987d7bb..06416355f2dc76 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/load/routineload/kinesis/KinesisDataSourcePropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/load/routineload/kinesis/KinesisDataSourcePropertiesTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.AnalysisException; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; @@ -37,7 +37,7 @@ public void testConvertAndCheckDataSourcePropertiesWithAwsEndpoint() throws Exce KinesisDataSourceProperties properties = new KinesisDataSourceProperties(dataSourceProperties); properties.convertAndCheckDataSourceProperties(); - Assert.assertEquals("http://localhost:4566", properties.getEndpoint()); + Assertions.assertEquals("http://localhost:4566", properties.getEndpoint()); } @Test @@ -50,7 +50,7 @@ public void testConvertAndCheckDataSourcePropertiesWithLegacyEndpoint() throws E KinesisDataSourceProperties properties = new KinesisDataSourceProperties(dataSourceProperties); properties.convertAndCheckDataSourceProperties(); - Assert.assertEquals("http://localhost:4566", properties.getEndpoint()); + Assertions.assertEquals("http://localhost:4566", properties.getEndpoint()); } @Test @@ -62,9 +62,9 @@ public void testPositionsShouldRejectDatetimeString() { dataSourceProperties.put(KinesisConfiguration.KINESIS_POSITIONS.getName(), "2026-04-08 00:00:00"); KinesisDataSourceProperties properties = new KinesisDataSourceProperties(dataSourceProperties); - AnalysisException e = Assert.assertThrows(AnalysisException.class, + AnalysisException e = Assertions.assertThrows(AnalysisException.class, properties::convertAndCheckDataSourceProperties); - Assert.assertTrue(e.getMessage().contains("must be TRIM_HORIZON, LATEST, or a valid sequence number")); + Assertions.assertTrue(e.getMessage().contains("must be TRIM_HORIZON, LATEST, or a valid sequence number")); } @Test @@ -76,8 +76,8 @@ public void testDefaultPositionShouldRejectDatetimeString() { "2026-04-08 00:00:00"); KinesisDataSourceProperties properties = new KinesisDataSourceProperties(dataSourceProperties); - AnalysisException e = Assert.assertThrows(AnalysisException.class, + AnalysisException e = Assertions.assertThrows(AnalysisException.class, properties::convertAndCheckDataSourceProperties); - Assert.assertTrue(e.getMessage().contains("TRIM_HORIZON, LATEST, or a valid sequence number")); + Assertions.assertTrue(e.getMessage().contains("TRIM_HORIZON, LATEST, or a valid sequence number")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/master/MasterImplDeleteTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/master/MasterImplDeleteTaskTest.java index 8f89fb0f40ff05..82401e1f2f0e93 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/master/MasterImplDeleteTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/master/MasterImplDeleteTaskTest.java @@ -32,10 +32,10 @@ import org.apache.doris.thrift.TTaskType; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -58,7 +58,7 @@ public class MasterImplDeleteTaskTest { private MockedStatic mockedEnvStatic; private MockedConstruction mockedReportHandlerConstruction; - @Before + @BeforeEach public void setUp() { AgentTaskQueue.clearAllTasks(); @@ -78,7 +78,7 @@ public void setUp() { masterImpl = new MasterImpl(); } - @After + @AfterEach public void tearDown() { AgentTaskQueue.clearAllTasks(); if (mockedEnvStatic != null) { @@ -100,10 +100,10 @@ public void testDeletePushGenericFailureCountsDownSingleMark() { masterImpl.finishTask(newFinishTaskRequest(TStatusCode.INTERNAL_ERROR)); - Assert.assertEquals(1, latch.getCount()); - Assert.assertEquals(TStatusCode.INTERNAL_ERROR, latch.getStatus().getErrorCode()); - Assert.assertEquals(1, pushTask.getFailedTimes()); - Assert.assertNull(AgentTaskQueue.getTask(BACKEND_ID, TTaskType.REALTIME_PUSH, SIGNATURE)); + Assertions.assertEquals(1, latch.getCount()); + Assertions.assertEquals(TStatusCode.INTERNAL_ERROR, latch.getStatus().getErrorCode()); + Assertions.assertEquals(1, pushTask.getFailedTimes()); + Assertions.assertNull(AgentTaskQueue.getTask(BACKEND_ID, TTaskType.REALTIME_PUSH, SIGNATURE)); } @Test @@ -117,10 +117,10 @@ public void testDeletePushInvalidArgumentCountsDownToZero() { masterImpl.finishTask(newFinishTaskRequest(TStatusCode.INVALID_ARGUMENT)); - Assert.assertEquals(0, latch.getCount()); - Assert.assertEquals(TStatusCode.INVALID_ARGUMENT, latch.getStatus().getErrorCode()); - Assert.assertEquals(1, pushTask.getFailedTimes()); - Assert.assertNull(AgentTaskQueue.getTask(BACKEND_ID, TTaskType.REALTIME_PUSH, SIGNATURE)); + Assertions.assertEquals(0, latch.getCount()); + Assertions.assertEquals(TStatusCode.INVALID_ARGUMENT, latch.getStatus().getErrorCode()); + Assertions.assertEquals(1, pushTask.getFailedTimes()); + Assertions.assertNull(AgentTaskQueue.getTask(BACKEND_ID, TTaskType.REALTIME_PUSH, SIGNATURE)); } @Test @@ -131,9 +131,9 @@ public void testDeletePushFailedWithMsgKeepsFailureStatus() { PushTask pushTask = newDeletePushTask(latch); pushTask.failedWithMsg("submit failed"); - Assert.assertEquals(0, latch.getCount()); - Assert.assertEquals(TStatusCode.CANCELLED, latch.getStatus().getErrorCode()); - Assert.assertEquals("submit failed", latch.getStatus().getErrorMsg()); + Assertions.assertEquals(0, latch.getCount()); + Assertions.assertEquals(TStatusCode.CANCELLED, latch.getStatus().getErrorCode()); + Assertions.assertEquals("submit failed", latch.getStatus().getErrorMsg()); } private PushTask newDeletePushTask(MarkedCountDownLatch latch) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java b/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java index 1c8c8a2a7ddf70..b0716ec2b8ec7a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/master/MetaHelperTest.java @@ -24,10 +24,10 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; 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 java.io.File; import java.io.IOException; @@ -40,7 +40,7 @@ public void test() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String bodyStr = mapper.writeValueAsString(bodyBefore); ResponseBody bodyAfter = MetaHelper.parseResponse(bodyStr, StorageInfo.class); - Assert.assertEquals(bodyAfter, bodyBefore); + Assertions.assertEquals(bodyAfter, bodyBefore); } private ResponseBody buildResponseBody() { @@ -80,12 +80,12 @@ public void testFile() throws IOException { if (errorFileWithSuffix.exists()) { errorFileWithSuffix.delete(); } - Assert.assertThrows(Exception.class, () -> MetaHelper.complete(errorFilename, tempDir)); - Assert.assertThrows(Exception.class, () -> MetaHelper.getFile(errorFilename, tempDir)); + Assertions.assertThrows(Exception.class, () -> MetaHelper.complete(errorFilename, tempDir)); + Assertions.assertThrows(Exception.class, () -> MetaHelper.getFile(errorFilename, tempDir)); if (rightFileWithSuffix.exists()) { rightFileWithSuffix.delete(); } - Assert.assertEquals(rightFileWithSuffix.getName() + ".part", MetaHelper.getFile(rightFilename, tempDir).getName()); + Assertions.assertEquals(rightFileWithSuffix.getName() + ".part", MetaHelper.getFile(rightFilename, tempDir).getName()); } @@ -96,7 +96,7 @@ public void testFileNameCheck() { MetaHelper.checkIsValidFileName("image.1"); MetaHelper.checkIsValidFileName("image.1.part"); MetaHelper.checkIsValidFileName("image.1.part.1"); - Assert.assertThrows(IllegalArgumentException.class, () -> MetaHelper.checkIsValidFileName("../testfile.")); + Assertions.assertThrows(IllegalArgumentException.class, () -> MetaHelper.checkIsValidFileName("../testfile.")); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/master/RowBinlogReportHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/master/RowBinlogReportHandlerTest.java index 7aaceb12cc6d40..63a5308b82327d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/master/RowBinlogReportHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/master/RowBinlogReportHandlerTest.java @@ -24,10 +24,10 @@ import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -45,7 +45,7 @@ public class RowBinlogReportHandlerTest { private MockedStatic mockedEnvStatic; private TabletInvertedIndex invertedIndex; - @Before + @BeforeEach public void setUp() { invertedIndex = Mockito.mock(TabletInvertedIndex.class); @@ -53,7 +53,7 @@ public void setUp() { mockedEnvStatic.when(Env::getCurrentInvertedIndex).thenReturn(invertedIndex); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -85,12 +85,12 @@ public void storageMediumMigrationKeepsPairedBaseRollupAndOrdinaryTablets() { ReportHandler.filterRowBinlogTabletMigration(migrationMap, 10001L); - Assert.assertEquals(3, migrationMap.size()); - Assert.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, baseTabletId)); - Assert.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, rollupTabletId)); - Assert.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, ordinaryTabletId)); - Assert.assertFalse(migrationMap.containsEntry(TStorageMedium.SSD, rowBinlogTabletId)); - Assert.assertFalse(migrationMap.containsEntry(TStorageMedium.SSD, missingTabletId)); + Assertions.assertEquals(3, migrationMap.size()); + Assertions.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, baseTabletId)); + Assertions.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, rollupTabletId)); + Assertions.assertTrue(migrationMap.containsEntry(TStorageMedium.SSD, ordinaryTabletId)); + Assertions.assertFalse(migrationMap.containsEntry(TStorageMedium.SSD, rowBinlogTabletId)); + Assertions.assertFalse(migrationMap.containsEntry(TStorageMedium.SSD, missingTabletId)); } private TabletMeta tabletMeta(long tableId, long partitionId, long indexId) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/metric/MetricsTest.java b/fe/fe-core/src/test/java/org/apache/doris/metric/MetricsTest.java index 36d272f698401a..ddb71021794ca0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/metric/MetricsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/metric/MetricsTest.java @@ -41,9 +41,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; @@ -57,7 +57,7 @@ @Slf4j public class MetricsTest { - @BeforeClass + @BeforeAll public static void setUp() { FeConstants.runningUnitTest = true; MetricRepo.init(); @@ -66,20 +66,20 @@ public static void setUp() { @Test public void testTcpMetrics() { List metrics = MetricRepo.getMetricsByName("snmp"); - Assert.assertEquals(4, metrics.size()); + Assertions.assertEquals(4, metrics.size()); for (Metric metric : metrics) { GaugeMetric gm = (GaugeMetric) metric; String metricName = gm.getLabels().get(0).getValue(); if (metricName.equals("tcp_retrans_segs")) { - Assert.assertEquals(Long.valueOf(826271L), (Long) gm.getValue()); + Assertions.assertEquals(Long.valueOf(826271L), (Long) gm.getValue()); } else if (metricName.equals("tcp_in_errs")) { - Assert.assertEquals(Long.valueOf(12712L), (Long) gm.getValue()); + Assertions.assertEquals(Long.valueOf(12712L), (Long) gm.getValue()); } else if (metricName.equals("tcp_in_segs")) { - Assert.assertEquals(Long.valueOf(1034019111L), (Long) gm.getValue()); + Assertions.assertEquals(Long.valueOf(1034019111L), (Long) gm.getValue()); } else if (metricName.equals("tcp_out_segs")) { - Assert.assertEquals(Long.valueOf(1166716939L), (Long) gm.getValue()); + Assertions.assertEquals(Long.valueOf(1166716939L), (Long) gm.getValue()); } else { - Assert.fail(); + Assertions.fail(); } } } @@ -96,14 +96,14 @@ public void testConnectionMaxMetrics() throws Exception { MetricVisitor visitor = new PrometheusMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_connection_max gauge")); - Assert.assertTrue(metricResult.contains("doris_fe_connection_max 13086")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_arrow_flight_connection_total gauge")); - Assert.assertTrue(metricResult.contains("doris_fe_arrow_flight_connection_total 0")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_arrow_flight_connection_max gauge")); - Assert.assertTrue(metricResult.contains("doris_fe_arrow_flight_connection_max 8765")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_user_connection_max gauge")); - Assert.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"metric_user\"} 321")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_connection_max gauge")); + Assertions.assertTrue(metricResult.contains("doris_fe_connection_max 13086")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_arrow_flight_connection_total gauge")); + Assertions.assertTrue(metricResult.contains("doris_fe_arrow_flight_connection_total 0")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_arrow_flight_connection_max gauge")); + Assertions.assertTrue(metricResult.contains("doris_fe_arrow_flight_connection_max 8765")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_user_connection_max gauge")); + Assertions.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"metric_user\"} 321")); Env.getServingEnv().getAuth().updateUserPropertyInternal(Auth.ROOT_USER, Lists.newArrayList( Pair.of(UserProperty.PROP_MAX_USER_CONNECTIONS, "456")), true); @@ -111,7 +111,7 @@ public void testConnectionMaxMetrics() throws Exception { visitor = new PrometheusMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 456")); + Assertions.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 456")); Auth auth = new Auth(); auth.updateUserPropertyInternal(Auth.ROOT_USER, Lists.newArrayList( @@ -120,8 +120,8 @@ public void testConnectionMaxMetrics() throws Exception { visitor = new PrometheusMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 456")); - Assert.assertFalse(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 789")); + Assertions.assertTrue(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 456")); + Assertions.assertFalse(metricResult.contains("doris_fe_user_connection_max{user=\"root\"} 789")); } finally { Config.qe_max_connection = originQeMaxConnection; Config.arrow_flight_max_connections = originArrowFlightMaxConnections; @@ -158,15 +158,15 @@ public void testStreamingJobTimeAndLagMetrics() { MetricRepo.updateStreamingJobPerJobMetrics(); String metricResult = getPrometheusMetrics(); - Assert.assertTrue(metricResult.contains("doris_fe_streaming_job_per_job_lag_bytes" + Assertions.assertTrue(metricResult.contains("doris_fe_streaming_job_per_job_lag_bytes" + "{job_id=\"1787039821000\", job_name=\"streaming_metric_job\"} 4096")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_streaming_job_per_job_last_source_event_timestamp_seconds" + "{job_id=\"1787039821000\", job_name=\"streaming_metric_job\"} 1787039800")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_streaming_job_per_job_last_task_success_time_seconds" + "{job_id=\"1787039821000\", job_name=\"streaming_metric_job\"} 1787039821")); - Assert.assertFalse(metricResult.contains("doris_fe_streaming_job_per_job_lag{")); + Assertions.assertFalse(metricResult.contains("doris_fe_streaming_job_per_job_lag{")); } finally { jobMap.remove(job.getJobId()); MetricRepo.updateStreamingJobPerJobMetrics(); @@ -184,16 +184,16 @@ public void testUserQueryMetrics() { MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); MetricRepo.visitHistograms(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_query_total counter")); - Assert.assertTrue(metricResult.contains("doris_fe_query_total{user=\"test_user\"} 1")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_query_err counter")); - Assert.assertTrue(metricResult.contains("doris_fe_query_err{user=\"test_user\"} 1")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_query_latency_ms summary")); - Assert.assertTrue(metricResult.contains("doris_fe_query_latency_ms{quantile=\"0.999\"} 0.0")); - Assert.assertTrue(metricResult.contains("doris_fe_query_latency_ms{quantile=\"0.999\",user=\"test_user\"} 10.0")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_query_total counter")); + Assertions.assertTrue(metricResult.contains("doris_fe_query_total{user=\"test_user\"} 1")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_query_err counter")); + Assertions.assertTrue(metricResult.contains("doris_fe_query_err{user=\"test_user\"} 1")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_query_latency_ms summary")); + Assertions.assertTrue(metricResult.contains("doris_fe_query_latency_ms{quantile=\"0.999\"} 0.0")); + Assertions.assertTrue(metricResult.contains("doris_fe_query_latency_ms{quantile=\"0.999\",user=\"test_user\"} 10.0")); + Assertions.assertTrue(metricResult.contains( "doris_fe_query_latency_ms{quantile=\"0.999\",user=\"xxx.yyy@example.com\"} 20.0")); - Assert.assertFalse(metricResult.contains("doris_fe_query_latency_ms_yyy@example_com")); + Assertions.assertFalse(metricResult.contains("doris_fe_query_latency_ms_yyy@example_com")); } @@ -206,10 +206,10 @@ public void testPrometheusVisitorKeepsLabeledHistogramValuesOutOfMetricName() { prometheusVisitor.visitHistogram(MetricVisitor.FE_PREFIX, histogramMetric.getName(), histogramMetric.getHistogram(), histogramMetric.getLabels()); String prometheusResult = prometheusVisitor.finish(); - Assert.assertTrue(prometheusResult.contains( + Assertions.assertTrue(prometheusResult.contains( "doris_fe_query_latency_ms{quantile=\"0.999\",user=\"xxx.yyy@example.com\"} 30.0")); - Assert.assertFalse(prometheusResult.contains("doris_fe_query_latency_ms_yyy@example_com")); - Assert.assertFalse(prometheusResult.contains("user=\"xxx\"")); + Assertions.assertFalse(prometheusResult.contains("doris_fe_query_latency_ms_yyy@example_com")); + Assertions.assertFalse(prometheusResult.contains("user=\"xxx\"")); } @Test @@ -221,9 +221,9 @@ public void testJsonVisitorKeepsLabeledHistogramValuesOutOfMetricName() { jsonVisitor.visitHistogram(MetricVisitor.FE_PREFIX, histogramMetric.getName(), histogramMetric.getHistogram(), histogramMetric.getLabels()); String jsonResult = jsonVisitor.finish(); - Assert.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_query_latency_ms\"")); - Assert.assertTrue(jsonResult.contains("\"user\":\"xxx.yyy@example.com\"")); - Assert.assertFalse(jsonResult.contains("\"metric\":\"doris_fe_query_latency_ms_yyy@example_com\"")); + Assertions.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_query_latency_ms\"")); + Assertions.assertTrue(jsonResult.contains("\"user\":\"xxx.yyy@example.com\"")); + Assertions.assertFalse(jsonResult.contains("\"metric\":\"doris_fe_query_latency_ms_yyy@example_com\"")); } @Test @@ -258,15 +258,15 @@ public void testHistogramMetricRegistryWithSpecialCharacters() { MetricVisitor prometheusVisitor = new PrometheusMetricVisitor(); registry.acceptHistograms(prometheusVisitor); String prometheusResult = prometheusVisitor.finish(); - Assert.assertTrue(prometheusResult.contains( + Assertions.assertTrue(prometheusResult.contains( "doris_fe_query_latency_ms{quantile=\"0.999\",cluster_id=\"cluster.id-1\"," + "cluster_name=\"cluster.name@prod\"} 40.0")); - Assert.assertTrue(prometheusResult.contains( + Assertions.assertTrue(prometheusResult.contains( "doris_fe_meta_service_rpc_latency_ms{quantile=\"0.999\",method=\"get.Instance\"} 50.0")); - Assert.assertFalse(prometheusResult.contains("doris_fe_query_latency_ms_id-1_cluster")); - Assert.assertFalse(prometheusResult.contains("doris_fe_meta_service_rpc_latency_ms_Instance")); - Assert.assertFalse(prometheusResult.contains("doris_fe_stale_latency_ms")); - Assert.assertFalse(prometheusResult.contains("doris_fe_disabled_latency_ms")); + Assertions.assertFalse(prometheusResult.contains("doris_fe_query_latency_ms_id-1_cluster")); + Assertions.assertFalse(prometheusResult.contains("doris_fe_meta_service_rpc_latency_ms_Instance")); + Assertions.assertFalse(prometheusResult.contains("doris_fe_stale_latency_ms")); + Assertions.assertFalse(prometheusResult.contains("doris_fe_disabled_latency_ms")); } @Test @@ -287,13 +287,13 @@ public void testVirtualComputeGroupSwitchMetricRename() { MetricVisitor visitor = new PrometheusMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_virtual_compute_group_switch_total counter")); - Assert.assertTrue(metricResult.contains("src_compute_group_name=\"src_new_name\"")); - Assert.assertTrue(metricResult.contains("doris_fe_virtual_compute_group_switch_total" + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_virtual_compute_group_switch_total counter")); + Assertions.assertTrue(metricResult.contains("src_compute_group_name=\"src_new_name\"")); + Assertions.assertTrue(metricResult.contains("doris_fe_virtual_compute_group_switch_total" + "{virtual_compute_group_id=\"virtual_id\", virtual_compute_group_name=\"virtual_name\", " + "src_compute_group_id=\"src_id\", src_compute_group_name=\"src_new_name\", " + "dst_compute_group_id=\"dst_id\", dst_compute_group_name=\"dst_name\"} 2")); - Assert.assertFalse(metricResult.contains("src_compute_group_name=\"src_old_name\"")); + Assertions.assertFalse(metricResult.contains("src_compute_group_name=\"src_old_name\"")); } finally { MetricRepo.DORIS_METRIC_REGISTER.removeMetrics("virtual_compute_group_switch_total"); if (CloudMetrics.VIRTUAL_COMPUTE_GROUP_SWITCH_COUNTER != null) { @@ -314,32 +314,32 @@ public void testCloudTabletRebalancerMetrics() { MetricRepo.updateCloudTabletRebalancerMetrics(125L, 4096L, 200L); String metricResult = getPrometheusMetrics(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_cloud_tablet_rebalancer_round_total counter")); - Assert.assertTrue(metricResult.contains("doris_fe_cloud_tablet_rebalancer_round_total 1")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_cloud_tablet_rebalancer_round_total counter")); + Assertions.assertTrue(metricResult.contains("doris_fe_cloud_tablet_rebalancer_round_total 1")); + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_allocated_bytes_total 4096")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_last_round_allocated_bytes 4096")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_duration_ms_total 125")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_last_round_duration_ms 125")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_tablet_scan_total 200")); MetricRepo.updateCloudTabletRebalancerMetrics(25L, -1L, 50L); metricResult = getPrometheusMetrics(); - Assert.assertTrue(metricResult.contains("doris_fe_cloud_tablet_rebalancer_round_total 2")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains("doris_fe_cloud_tablet_rebalancer_round_total 2")); + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_allocated_bytes_total 4096")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_last_round_allocated_bytes -1")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_duration_ms_total 150")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_last_round_duration_ms 25")); - Assert.assertTrue(metricResult.contains( + Assertions.assertTrue(metricResult.contains( "doris_fe_cloud_tablet_rebalancer_tablet_scan_total 250")); } finally { Config.cloud_unique_id = originCloudUniqueId; @@ -379,23 +379,23 @@ public void testCloudWarmUpSyncJobMetricsReadStatsDirectlyFromJob() { MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.singletonList(job)); String metricResult = getPrometheusMetrics(); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_info" + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_info" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", sync_mode=\"EVENT_DRIVEN\", " + "sync_event=\"LOAD\", job_state=\"RUNNING\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\"} 1")); - Assert.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_create_time_ms")); - Assert.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_last_trigger_time_ms")); - Assert.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_stats")); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_create_time_ms")); + Assertions.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_last_trigger_time_ms")); + Assertions.assertFalse(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_stats")); + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"src\", window=\"5m\"} 113246208")); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"dst\", window=\"5m\"} 100663296")); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"src\", window=\"30m\"} 226492416")); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"dst\", window=\"1h\"} 301989888")); @@ -405,10 +405,10 @@ public void testCloudWarmUpSyncJobMetricsReadStatsDirectlyFromJob() { updatedStats.computeGap(); job.setSyncStats(updatedStats); String updatedMetricResult = getPrometheusMetrics(); - Assert.assertTrue(updatedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(updatedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"src\", window=\"5m\"} 12")); - Assert.assertTrue(updatedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(updatedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"dst\", window=\"5m\"} 10")); @@ -428,16 +428,16 @@ public void testCloudWarmUpSyncJobMetricsReadStatsDirectlyFromJob() { replayedJob.setSyncStats(replayedStats); MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.singletonList(replayedJob)); String replayedMetricResult = getPrometheusMetrics(); - Assert.assertTrue(replayedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + Assertions.assertTrue(replayedMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes" + "{job_id=\"1778211593204\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\", side=\"src\", window=\"5m\"} 10")); replayedJob.setJobState(CloudWarmUpJob.JobState.CANCELLED); MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.singletonList(replayedJob)); String cancelledMetricResult = getPrometheusMetrics(); - Assert.assertTrue(cancelledMetricResult.contains("job_state=\"CANCELLED\"")); - Assert.assertFalse(cancelledMetricResult.contains("job_state=\"RUNNING\"")); - Assert.assertFalse(cancelledMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes")); + Assertions.assertTrue(cancelledMetricResult.contains("job_state=\"CANCELLED\"")); + Assertions.assertFalse(cancelledMetricResult.contains("job_state=\"RUNNING\"")); + Assertions.assertFalse(cancelledMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_size_bytes")); } finally { MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.emptyList()); Config.cloud_unique_id = oldCloudUniqueId; @@ -471,7 +471,7 @@ public void testEventDrivenCloudWarmUpSyncJobTriggerGapMetric() { MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.singletonList(job)); String metricResult = getPrometheusMetrics(); - Assert.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_trigger_gap_ms" + Assertions.assertTrue(metricResult.contains("doris_fe_file_cache_warm_up_sync_job_trigger_gap_ms" + "{job_id=\"1778211593205\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\"} 800")); @@ -488,7 +488,7 @@ public void testEventDrivenCloudWarmUpSyncJobTriggerGapMetric() { MetricRepo.syncCloudWarmUpSyncJobMetricDefinitions(Collections.singletonList(clusterLevelJob)); String clusterMetricResult = getPrometheusMetrics(); - Assert.assertTrue(clusterMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_trigger_gap_ms" + Assertions.assertTrue(clusterMetricResult.contains("doris_fe_file_cache_warm_up_sync_job_trigger_gap_ms" + "{job_id=\"1778211593206\", job_type=\"CLUSTER\", src_cluster_name=\"warmup_source\", " + "dst_cluster_name=\"warmup_target\"} 800")); } finally { @@ -514,8 +514,8 @@ public void testGc() { String finalMetricPrometheus = metric; gcMxBeans.forEach(gcMxBean -> { String name = gcMxBean.getName(); - Assert.assertTrue(finalMetricPrometheus.contains("jvm_gc{name=\"" + name + " Count\", type=\"count\"} ")); - Assert.assertTrue(finalMetricPrometheus.contains("jvm_gc{name=\"" + name + " Time\", type=\"time\"} ")); + Assertions.assertTrue(finalMetricPrometheus.contains("jvm_gc{name=\"" + name + " Count\", type=\"count\"} ")); + Assertions.assertTrue(finalMetricPrometheus.contains("jvm_gc{name=\"" + name + " Time\", type=\"time\"} ")); }); JsonMetricVisitor jsonMetricVisitor = new JsonMetricVisitor(); @@ -529,55 +529,55 @@ public void testGc() { if (jsonObject.findValue("tags").findValue("metric").asText().equals("jvm_gc") && jsonObject.findValue("tags").findValue("name").asText().contains(name + " Count")) { size.getAndDecrement(); - Assert.assertTrue(jsonObject.findValue("tags").findValue("name").asText().contains(name + " Count") + Assertions.assertTrue(jsonObject.findValue("tags").findValue("name").asText().contains(name + " Count") || jsonObject.findValue("tags").findValue("name").asText().contains(name + " Time")); } })); - Assert.assertTrue(size.get() < JsonUtil.parseArray(finalMetricJson).size()); + Assertions.assertTrue(size.get() < JsonUtil.parseArray(finalMetricJson).size()); } @Test public void testCatalogAndDatabaseMetrics() { List catalogMetrics = MetricRepo.getMetricsByName("catalog_num"); - Assert.assertEquals(1, catalogMetrics.size()); + Assertions.assertEquals(1, catalogMetrics.size()); GaugeMetric catalogMetric = (GaugeMetric) catalogMetrics.get(0); - Assert.assertEquals("catalog_num", catalogMetric.getName()); - Assert.assertEquals(MetricUnit.NOUNIT, catalogMetric.getUnit()); - Assert.assertEquals("total catalog num", catalogMetric.getDescription()); + Assertions.assertEquals("catalog_num", catalogMetric.getName()); + Assertions.assertEquals(MetricUnit.NOUNIT, catalogMetric.getUnit()); + Assertions.assertEquals("total catalog num", catalogMetric.getDescription()); List dbMetrics = MetricRepo.getMetricsByName("internal_database_num"); - Assert.assertEquals(1, dbMetrics.size()); + Assertions.assertEquals(1, dbMetrics.size()); GaugeMetric dbMetric = (GaugeMetric) dbMetrics.get(0); - Assert.assertEquals("internal_database_num", dbMetric.getName()); - Assert.assertEquals(MetricUnit.NOUNIT, dbMetric.getUnit()); - Assert.assertEquals("total internal database num", dbMetric.getDescription()); + Assertions.assertEquals("internal_database_num", dbMetric.getName()); + Assertions.assertEquals(MetricUnit.NOUNIT, dbMetric.getUnit()); + Assertions.assertEquals("total internal database num", dbMetric.getDescription()); List tableMetrics = MetricRepo.getMetricsByName("internal_table_num"); - Assert.assertEquals(1, tableMetrics.size()); + Assertions.assertEquals(1, tableMetrics.size()); GaugeMetric tableMetric = (GaugeMetric) tableMetrics.get(0); - Assert.assertEquals("internal_table_num", tableMetric.getName()); - Assert.assertEquals(MetricUnit.NOUNIT, tableMetric.getUnit()); - Assert.assertEquals("total internal table num", tableMetric.getDescription()); + Assertions.assertEquals("internal_table_num", tableMetric.getName()); + Assertions.assertEquals(MetricUnit.NOUNIT, tableMetric.getUnit()); + Assertions.assertEquals("total internal table num", tableMetric.getDescription()); // Test metrics in Prometheus format MetricVisitor visitor = new PrometheusMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_catalog_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_internal_database_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_internal_table_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_catalog_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_internal_database_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_internal_table_num gauge")); // Test metrics in JSON format JsonMetricVisitor jsonVisitor = new JsonMetricVisitor(); MetricRepo.DORIS_METRIC_REGISTER.accept(jsonVisitor); String jsonResult = jsonVisitor.finish(); - Assert.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_catalog_num\"")); - Assert.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_internal_database_num\"")); - Assert.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_internal_table_num\"")); + Assertions.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_catalog_num\"")); + Assertions.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_internal_database_num\"")); + Assertions.assertTrue(jsonResult.contains("\"metric\":\"doris_fe_internal_table_num\"")); } @Test @@ -590,13 +590,13 @@ public void testMTMVMetrics() { MetricRepo.visitHistograms(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_failed_num counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_success_num counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_pending_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_skip_num counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_running_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_num gauge")); - Assert.assertTrue( + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_failed_num counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_success_num counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_pending_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_skip_num counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_task_running_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_async_materialized_view_num gauge")); + Assertions.assertTrue( metricResult.contains("# TYPE doris_fe_async_materialized_view_task_duration_ms summary")); } @@ -610,21 +610,21 @@ public void testStatisticsMetrics() { MetricRepo.visitHistograms(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_succeed_analyze_job counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_failed_analyze_job counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_succeed_analyze_task counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_failed_analyze_task counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_invalid_stats counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_table_rate gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_column_rate gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_table_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_column_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_not_analyzed_table_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_empty_table_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_high_priority_queue_length gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_mid_priority_queue_length gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_low_priority_queue_length gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_very_low_priority_queue_length gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_succeed_analyze_job counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_failed_analyze_job counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_succeed_analyze_task counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_failed_analyze_task counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_invalid_stats counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_table_rate gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_column_rate gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_table_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_unhealthy_column_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_not_analyzed_table_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_empty_table_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_high_priority_queue_length gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_mid_priority_queue_length gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_low_priority_queue_length gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_statistics_very_low_priority_queue_length gauge")); } @Test @@ -637,10 +637,10 @@ public void testSqlCacheMetrics() { MetricRepo.visitHistograms(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_added counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_hit counter")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_total_search_times counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_added counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_hit counter")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_sql_cache_total_search_times counter")); } @Test @@ -653,23 +653,23 @@ public void testPlanMetrics() { MetricRepo.visitHistograms(visitor); String metricResult = visitor.finish(); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_num gauge")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_parse_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_analyze_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_rewrite_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_fold_const_by_be_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_optimize_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_translate_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_init_scan_node_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_finalize_scan_node_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_create_scan_range_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_distribute_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_external_catalog_meta_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_external_tvf_init_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_lock_tables_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_partition_prune_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_cloud_meta_duration_ms summary")); - Assert.assertTrue(metricResult.contains("# TYPE doris_fe_plan_materialized_view_rewrite_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_num gauge")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_parse_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_analyze_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_rewrite_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_fold_const_by_be_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_optimize_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_translate_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_init_scan_node_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_finalize_scan_node_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_create_scan_range_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_distribute_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_external_catalog_meta_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_external_tvf_init_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_lock_tables_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_partition_prune_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_cloud_meta_duration_ms summary")); + Assertions.assertTrue(metricResult.contains("# TYPE doris_fe_plan_materialized_view_rewrite_duration_ms summary")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVExpandPartitionTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVExpandPartitionTest.java index 145de3f4e57d9e..d849c7edba47cb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVExpandPartitionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVExpandPartitionTest.java @@ -31,9 +31,9 @@ import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; @@ -66,7 +66,7 @@ public class MTMVExpandPartitionTest { private Map dailyBasePartitions; private Map monthlyMvPartitions; - @Before + @BeforeEach public void setUp() throws Exception { dailyBasePartitions = Maps.newHashMap(); dailyBasePartitions.put("p20210101", buildRange("2021-01-01", "2021-01-02")); @@ -92,8 +92,8 @@ public void testExpandSinglePartitionToMonth() throws Exception { queryUsed, monthlyMvPartitions, Sets.newHashSet(rangeTable)); Set expanded = result.get(RANGE_TABLE_QUALIFIERS); - Assert.assertNotNull(expanded); - Assert.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), expanded); + Assertions.assertNotNull(expanded); + Assertions.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), expanded); } @Test @@ -105,8 +105,8 @@ public void testExpandMultipleMonths() throws Exception { queryUsed, monthlyMvPartitions, Sets.newHashSet(rangeTable)); Set expanded = result.get(RANGE_TABLE_QUALIFIERS); - Assert.assertNotNull(expanded); - Assert.assertEquals( + Assertions.assertNotNull(expanded); + Assertions.assertEquals( Sets.newHashSet("p20210101", "p20210102", "p20210103", "p20210201", "p20210202"), expanded); } @@ -119,7 +119,7 @@ public void testMultiplePartitionsSelectSameMvRange() throws Exception { Map, Set> result = MTMVPartitionExpander.expandToMvPartitionGranularity( queryUsed, monthlyMvPartitions, Sets.newHashSet(rangeTable)); - Assert.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), + Assertions.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), result.get(RANGE_TABLE_QUALIFIERS)); } @@ -134,7 +134,7 @@ public void testRangeGapDoesNotMatch() throws Exception { Map, Set> result = MTMVPartitionExpander.expandToMvPartitionGranularity( queryUsed, mvPartitionsWithGap, Sets.newHashSet(rangeTable)); - Assert.assertTrue(result.get(RANGE_TABLE_QUALIFIERS).isEmpty()); + Assertions.assertTrue(result.get(RANGE_TABLE_QUALIFIERS).isEmpty()); } @Test @@ -158,16 +158,16 @@ public void testManyPartitionsSparseAndBroadFilters() throws Exception { Map, Set> sparseResult = MTMVPartitionExpander.expandToMvPartitionGranularity( sparseFilter, mvPartitions, Sets.newHashSet(manyPartitionTable)); - Assert.assertEquals(30, sparseResult.get(RANGE_TABLE_QUALIFIERS).size()); - Assert.assertTrue(sparseResult.get(RANGE_TABLE_QUALIFIERS).contains("p30")); - Assert.assertTrue(sparseResult.get(RANGE_TABLE_QUALIFIERS).contains("p59")); + Assertions.assertEquals(30, sparseResult.get(RANGE_TABLE_QUALIFIERS).size()); + Assertions.assertTrue(sparseResult.get(RANGE_TABLE_QUALIFIERS).contains("p30")); + Assertions.assertTrue(sparseResult.get(RANGE_TABLE_QUALIFIERS).contains("p59")); Map, Set> broadFilter = Maps.newHashMap(); broadFilter.put(RANGE_TABLE_QUALIFIERS, basePartitions.keySet()); Map, Set> broadResult = MTMVPartitionExpander.expandToMvPartitionGranularity( broadFilter, mvPartitions, Sets.newHashSet(manyPartitionTable)); - Assert.assertEquals(basePartitions.keySet(), broadResult.get(RANGE_TABLE_QUALIFIERS)); + Assertions.assertEquals(basePartitions.keySet(), broadResult.get(RANGE_TABLE_QUALIFIERS)); } @Test @@ -179,8 +179,8 @@ public void testListPartitionPassthrough() throws Exception { queryUsed, monthlyMvPartitions, Sets.newHashSet(listTable)); Set expanded = result.get(LIST_TABLE_QUALIFIERS); - Assert.assertNotNull(expanded); - Assert.assertEquals(Sets.newHashSet("p1"), expanded); + Assertions.assertNotNull(expanded); + Assertions.assertEquals(Sets.newHashSet("p1"), expanded); } @Test @@ -192,8 +192,8 @@ public void testNonExistentPartition() throws Exception { queryUsed, monthlyMvPartitions, Sets.newHashSet(rangeTable)); Set expanded = result.get(RANGE_TABLE_QUALIFIERS); - Assert.assertNotNull(expanded); - Assert.assertTrue(expanded.isEmpty()); + Assertions.assertNotNull(expanded); + Assertions.assertTrue(expanded.isEmpty()); } @Test @@ -208,8 +208,8 @@ public void testBasePartitionOutsideMvRange() throws Exception { queryUsed, janOnlyMv, Sets.newHashSet(rangeTable)); Set expanded = result.get(RANGE_TABLE_QUALIFIERS); - Assert.assertNotNull(expanded); - Assert.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), expanded); + Assertions.assertNotNull(expanded); + Assertions.assertEquals(Sets.newHashSet("p20210101", "p20210102", "p20210103"), expanded); } @Test @@ -221,7 +221,7 @@ public void testPctTableNotInFilter() throws Exception { Map, Set> result = MTMVPartitionExpander.expandToMvPartitionGranularity( queryUsed, monthlyMvPartitions, Sets.newHashSet(rangeTable)); - Assert.assertNull(result.get(RANGE_TABLE_QUALIFIERS)); + Assertions.assertNull(result.get(RANGE_TABLE_QUALIFIERS)); } @Test @@ -229,7 +229,7 @@ public void testEmptyFilter() throws Exception { Map, Set> result = MTMVPartitionExpander.expandToMvPartitionGranularity( Maps.newHashMap(), monthlyMvPartitions, Sets.newHashSet(rangeTable)); - Assert.assertTrue(result.isEmpty()); + Assertions.assertTrue(result.isEmpty()); } // --- helpers --- diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobInfoTest.java index 82257881fbf31d..cf362b624296e3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.Config; import org.apache.doris.job.extensions.mtmv.MTMVTask; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MTMVJobInfoTest { @@ -31,15 +31,15 @@ public void testAddHistoryTask() { Config.max_persistence_task_count = 0; MTMVJobInfo jobInfo = new MTMVJobInfo("dummyJob"); jobInfo.addHistoryTask(new MTMVTask()); - Assert.assertEquals(0, jobInfo.getHistoryTasks().size()); + Assertions.assertEquals(0, jobInfo.getHistoryTasks().size()); Config.max_persistence_task_count = 2; for (int i = 0; i < 3; i++) { jobInfo.addHistoryTask(new MTMVTask()); } - Assert.assertEquals(2, jobInfo.getHistoryTasks().size()); + Assertions.assertEquals(2, jobInfo.getHistoryTasks().size()); Config.max_persistence_task_count = 1; jobInfo.addHistoryTask(new MTMVTask()); - Assert.assertEquals(1, jobInfo.getHistoryTasks().size()); + Assertions.assertEquals(1, jobInfo.getHistoryTasks().size()); Config.max_persistence_task_count = originalCount; } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobManagerTest.java index b97dc6b4d9986a..ae5a8f9917ba66 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVJobManagerTest.java @@ -32,8 +32,8 @@ import org.apache.doris.qe.ConnectContext; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -73,10 +73,10 @@ public void testRefreshMTMVPassesCurrentComputeGroupToTaskContext() throws Excep ArgumentCaptor captor = ArgumentCaptor.forClass(MTMVTaskContext.class); Mockito.verify(jobManager).triggerJob(Mockito.eq(100L), captor.capture()); MTMVTaskContext taskContext = captor.getValue(); - Assert.assertEquals(MTMVTaskTriggerMode.MANUAL, taskContext.getTriggerMode()); - Assert.assertEquals(Lists.newArrayList("p1"), taskContext.getPartitions()); - Assert.assertFalse(taskContext.isComplete()); - Assert.assertEquals("cg1", taskContext.getComputeGroup()); + Assertions.assertEquals(MTMVTaskTriggerMode.MANUAL, taskContext.getTriggerMode()); + Assertions.assertEquals(Lists.newArrayList("p1"), taskContext.getPartitions()); + Assertions.assertFalse(taskContext.isComplete()); + Assertions.assertEquals("cg1", taskContext.getComputeGroup()); } finally { Config.cloud_unique_id = originCloudUniqueId; ConnectContext.remove(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionCheckUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionCheckUtilTest.java index 647e5490935f4b..e8e504c69ce906 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionCheckUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionCheckUtilTest.java @@ -33,10 +33,10 @@ import org.apache.doris.datasource.mvcc.PluginDrivenMvccExternalTable; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -60,7 +60,7 @@ public class MTMVPartitionCheckUtilTest { private MockedStatic dynamicPartitionUtilStatic; private MockedStatic partitionExprUtilStatic; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException, DdlException, MetaNotFoundException { @@ -85,7 +85,7 @@ public void setUp() Mockito.when(relatedPartitionInfo.getPartitionExprs()).thenReturn(relatedExprs); } - @After + @AfterEach public void tearDown() { partitionExprUtilStatic.close(); dynamicPartitionUtilStatic.close(); @@ -95,7 +95,7 @@ public void tearDown() { public void testCheckIfAllowMultiTablePartitionRefreshNotOlapTable() { Pair res = MTMVPartitionCheckUtil.checkIfAllowMultiTablePartitionRefresh( nonOlapTable); - Assert.assertFalse(res.first); + Assertions.assertFalse(res.first); } @Test @@ -103,7 +103,7 @@ public void testCheckIfAllowMultiTablePartitionRefreshNotRangePartition() { Mockito.when(originalTable.getPartitionType()).thenReturn(PartitionType.LIST); Pair res = MTMVPartitionCheckUtil.checkIfAllowMultiTablePartitionRefresh( originalTable); - Assert.assertFalse(res.first); + Assertions.assertFalse(res.first); } @Test @@ -113,7 +113,7 @@ public void testCheckIfAllowMultiTablePartitionRefreshNotDynamicAndAuto() { .thenReturn(false); Pair res = MTMVPartitionCheckUtil.checkIfAllowMultiTablePartitionRefresh( originalTable); - Assert.assertFalse(res.first); + Assertions.assertFalse(res.first); } @Test @@ -123,7 +123,7 @@ public void testCheckIfAllowMultiTablePartitionRefreshDynamic() { .thenReturn(false); Pair res = MTMVPartitionCheckUtil.checkIfAllowMultiTablePartitionRefresh( originalTable); - Assert.assertTrue(res.first); + Assertions.assertTrue(res.first); } @Test @@ -133,13 +133,13 @@ public void testCheckIfAllowMultiTablePartitionRefreshAuto() { .thenReturn(true); Pair res = MTMVPartitionCheckUtil.checkIfAllowMultiTablePartitionRefresh( originalTable); - Assert.assertTrue(res.first); + Assertions.assertTrue(res.first); } @Test public void testCompareDynamicPartition() throws AnalysisException { Pair res = MTMVPartitionCheckUtil.compareDynamicPartition(originalTable, relatedTable); - Assert.assertTrue(res.first); + Assertions.assertTrue(res.first); } @Test @@ -147,7 +147,7 @@ public void testCompareDynamicPartitionNotEqual() throws AnalysisException { Mockito.when(relatedDynamicPartitionProperty.getStartOfWeek()).thenReturn(new StartOfDate(1, 1, 1)); Mockito.when(originalDynamicPartitionProperty.getStartOfWeek()).thenReturn(new StartOfDate(1, 1, 2)); Pair res = MTMVPartitionCheckUtil.compareDynamicPartition(originalTable, relatedTable); - Assert.assertFalse(res.first); + Assertions.assertFalse(res.first); } @Test @@ -160,7 +160,7 @@ public void testCompareAutoPartition() throws AnalysisException { Mockito.eq(relatedExprs), Mockito.any(PartitionType.class))) .thenReturn(partitionExprUtilInstance.new FunctionIntervalInfo("datetrunc", "week", 1)); Pair res = MTMVPartitionCheckUtil.compareAutoPartition(originalTable, relatedTable); - Assert.assertTrue(res.first); + Assertions.assertTrue(res.first); } @Test @@ -172,6 +172,6 @@ public void testCompareAutoPartitionNotEqual() throws AnalysisException { Mockito.eq(relatedExprs), Mockito.any(PartitionType.class))) .thenReturn(partitionExprUtilInstance.new FunctionIntervalInfo("datetrunc", "week", 2)); Pair res = MTMVPartitionCheckUtil.compareAutoPartition(originalTable, relatedTable); - Assert.assertFalse(res.first); + Assertions.assertFalse(res.first); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionUtilTest.java index 80f91de79125cc..bb484c7ce7b694 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPartitionUtilTest.java @@ -32,10 +32,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -62,7 +62,7 @@ public class MTMVPartitionUtilTest { private Set baseTables = Sets.newHashSet(); - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { baseTables.add(baseTableInfo); @@ -127,7 +127,7 @@ public void setUp() throws NoSuchMethodException, SecurityException, AnalysisExc Mockito.when(catalogIf.getName()).thenReturn("ctl1"); } - @After + @AfterEach public void tearDown() { mtmvUtilStatic.close(); refreshContextStatic.close(); @@ -136,7 +136,7 @@ public void tearDown() { @Test public void testIsMTMVSyncNormal() { boolean mtmvSync = MTMVPartitionUtil.isMTMVSync(mtmv); - Assert.assertTrue(mtmvSync); + Assertions.assertTrue(mtmvSync); } @Test @@ -144,14 +144,14 @@ public void testIsMTMVSyncNotSync() { Mockito.when(refreshSnapshot.equalsWithBaseTable(Mockito.anyString(), Mockito.any(BaseTableInfo.class), Mockito.any(MTMVSnapshotIf.class))) .thenReturn(false); boolean mtmvSync = MTMVPartitionUtil.isMTMVSync(mtmv); - Assert.assertFalse(mtmvSync); + Assertions.assertFalse(mtmvSync); } @Test public void testIsSyncWithPartition() throws AnalysisException { boolean isSyncWithPartition = MTMVPartitionUtil .isSyncWithPartitions(context, "name1", Sets.newHashSet("name2"), baseOlapTable); - Assert.assertTrue(isSyncWithPartition); + Assertions.assertTrue(isSyncWithPartition); } @Test @@ -160,7 +160,7 @@ public void testIsSyncWithPartitionNotEqual() throws AnalysisException { .thenReturn(Sets.newHashSet("name2", "name3")); boolean isSyncWithPartition = MTMVPartitionUtil .isSyncWithPartitions(context, "name1", Sets.newHashSet("name2"), baseOlapTable); - Assert.assertFalse(isSyncWithPartition); + Assertions.assertFalse(isSyncWithPartition); } @Test @@ -170,7 +170,7 @@ public void testIsSyncWithPartitionNotSync() throws AnalysisException { .thenReturn(false); boolean isSyncWithPartition = MTMVPartitionUtil .isSyncWithPartitions(context, "name1", Sets.newHashSet("name2"), baseOlapTable); - Assert.assertFalse(isSyncWithPartition); + Assertions.assertFalse(isSyncWithPartition); } @Test @@ -185,8 +185,8 @@ public void testIsMTMVPartitionSyncWithImmutableExcludedTriggerTables() throws A boolean isMTMVPartitionSync = MTMVPartitionUtil.isMTMVPartitionSync(context, "name1", baseTables, excludedTriggerTables); - Assert.assertTrue(isMTMVPartitionSync); - Assert.assertTrue(excludedTriggerTables.isEmpty()); + Assertions.assertTrue(isMTMVPartitionSync); + Assertions.assertTrue(excludedTriggerTables.isEmpty()); } @Test @@ -196,61 +196,61 @@ public void testGeneratePartitionName() { inValues.add(Lists.newArrayList(new PartitionValue("value21"), new PartitionValue("value22"))); PartitionKeyDesc inDesc = PartitionKeyDesc.createIn(inValues); String inName = MTMVPartitionUtil.generatePartitionName(inDesc); - Assert.assertEquals("p_20201010010101_value12_value21_value22", inName); + Assertions.assertEquals("p_20201010010101_value12_value21_value22", inName); PartitionKeyDesc rangeDesc = PartitionKeyDesc.createFixed( Lists.newArrayList(new PartitionValue(1L)), Lists.newArrayList(new PartitionValue(2L)) ); String rangeName = MTMVPartitionUtil.generatePartitionName(rangeDesc); - Assert.assertEquals("p_1_2", rangeName); + Assertions.assertEquals("p_1_2", rangeName); } @Test public void testIsTableExcluded() { Set excludedTriggerTables = Sets.newHashSet(new TableNameInfo("table1")); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table1"))); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db2", "table1"))); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl2", "db1", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table2"))); excludedTriggerTables = Sets.newHashSet(new TableNameInfo("db1.table1")); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db2", "table1"))); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl2", "db1", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table2"))); excludedTriggerTables = Sets.newHashSet(new TableNameInfo("ctl1.db1.table1")); - Assert.assertTrue( + Assertions.assertTrue( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db2", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl2", "db1", "table1"))); - Assert.assertFalse( + Assertions.assertFalse( MTMVPartitionUtil.isTableExcluded(excludedTriggerTables, new TableNameInfo("ctl1", "db1", "table2"))); } @Test public void testIsTableNamelike() { TableNameInfo tableNameToCheck = new TableNameInfo("ctl1", "db1", "table1"); - Assert.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("table1"), tableNameToCheck)); - Assert.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("db1.table1"), tableNameToCheck)); - Assert.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db1.table1"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.table1"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db2.table1"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db1.table2"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl2.db1.table1"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("db1"), tableNameToCheck)); - Assert.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1"), tableNameToCheck)); + Assertions.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("table1"), tableNameToCheck)); + Assertions.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("db1.table1"), tableNameToCheck)); + Assertions.assertTrue(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db1.table1"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.table1"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db2.table1"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1.db1.table2"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl2.db1.table1"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("db1"), tableNameToCheck)); + Assertions.assertFalse(MTMVPartitionUtil.isTableNamelike(new TableNameInfo("ctl1"), tableNameToCheck)); } @Test @@ -285,10 +285,10 @@ public void testGetBaseVersionsUsesAllFullyMappedPartitions() throws AnalysisExc public void testGetTableSnapshotFromContext() throws AnalysisException { Map cache = Maps.newHashMap(); Mockito.when(context.getBaseTableSnapshotCache()).thenReturn(cache); - Assert.assertTrue(cache.isEmpty()); + Assertions.assertTrue(cache.isEmpty()); MTMVPartitionUtil.getTableSnapshotFromContext(baseOlapTable, context); - Assert.assertEquals(1, cache.size()); - Assert.assertEquals(baseSnapshotIf, cache.values().iterator().next()); + Assertions.assertEquals(1, cache.size()); + Assertions.assertEquals(baseSnapshotIf, cache.values().iterator().next()); } private Map> pctMapping(String... partitionNames) { @@ -329,12 +329,12 @@ private void assertFetchedPartitionNames( return visibleVersions; }); - Assert.assertEquals(expectedPartitionNames, + Assertions.assertEquals(expectedPartitionNames, MTMVPartitionUtil.getBaseVersions(mtmv, partitionMappings) .getPartitionVersions(baseOlapTable).keySet()); } - Assert.assertEquals(1, versionRequests.size()); - Assert.assertEquals(expectedPartitionNames, versionRequests.get(0)); + Assertions.assertEquals(1, versionRequests.size()); + Assertions.assertEquals(expectedPartitionNames, versionRequests.get(0)); Mockito.verify(baseOlapTable, Mockito.never()).getPartitions(); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPlanUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPlanUtilTest.java index 310c603b00baef..1cbe28ea4e861f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPlanUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVPlanUtilTest.java @@ -49,7 +49,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -136,10 +135,10 @@ public void testGenerateColumnsBySql() throws Exception { } private void checkRes(List expect, List actual) { - Assert.assertEquals(expect.size(), actual.size()); + Assertions.assertEquals(expect.size(), actual.size()); for (int i = 0; i < expect.size(); i++) { - Assert.assertEquals(expect.get(i).getName(), actual.get(i).getName()); - Assert.assertEquals(expect.get(i).getType(), actual.get(i).getType()); + Assertions.assertEquals(expect.get(i).getName(), actual.get(i).getName()); + Assertions.assertEquals(expect.get(i).getType(), actual.get(i).getType()); } } @@ -153,25 +152,25 @@ public void testGetDataType() { Mockito.when(slot.getName()).thenReturn("slot_name"); // test i=0 DataType dataType = MTMVPlanUtil.getDataType(slot, 0, connectContext, "pcol", Sets.newHashSet("dcol")); - Assert.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); + Assertions.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); // test isColumnFromTable and is not managed table dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("dcol")); - Assert.assertEquals(StringType.INSTANCE, dataType); + Assertions.assertEquals(StringType.INSTANCE, dataType); // test is partitionCol dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "slot_name", Sets.newHashSet("dcol")); - Assert.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); + Assertions.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); // test is partitdistribution Col dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); + Assertions.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); // test managed table Mockito.when(slot.getOriginalTable()).thenReturn(Optional.of(slotTable)); Mockito.when(slotTable.isManagedTable()).thenReturn(true); dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(StringType.INSTANCE, dataType); + Assertions.assertEquals(StringType.INSTANCE, dataType); // test is not column table boolean originalUseMaxLengthOfVarcharInCtas = connectContext.getSessionVariable().useMaxLengthOfVarcharInCtas; @@ -179,25 +178,25 @@ public void testGetDataType() { Mockito.when(slot.isColumnFromTable()).thenReturn(false); connectContext.getSessionVariable().useMaxLengthOfVarcharInCtas = true; dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); + Assertions.assertEquals(VarcharType.MAX_VARCHAR_TYPE, dataType); connectContext.getSessionVariable().useMaxLengthOfVarcharInCtas = false; dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(new VarcharType(10), dataType); + Assertions.assertEquals(new VarcharType(10), dataType); connectContext.getSessionVariable().useMaxLengthOfVarcharInCtas = originalUseMaxLengthOfVarcharInCtas; // test null type Mockito.when(slot.getDataType()).thenReturn(NullType.INSTANCE); dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(TinyIntType.INSTANCE, dataType); + Assertions.assertEquals(TinyIntType.INSTANCE, dataType); // test decimal type Mockito.when(slot.getDataType()).thenReturn(DecimalV2Type.createDecimalV2Type(1, 1)); boolean originalEnableDecimalConversion = Config.enable_decimal_conversion; Config.enable_decimal_conversion = false; dataType = MTMVPlanUtil.getDataType(slot, 1, connectContext, "pcol", Sets.newHashSet("slot_name")); - Assert.assertEquals(DecimalV2Type.SYSTEM_DEFAULT, dataType); + Assertions.assertEquals(DecimalV2Type.SYSTEM_DEFAULT, dataType); Config.enable_decimal_conversion = originalEnableDecimalConversion; diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRefreshSnapshotTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRefreshSnapshotTest.java index 413aee45d1b65c..385a95c00d87b5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRefreshSnapshotTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRefreshSnapshotTest.java @@ -21,9 +21,9 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Map; @@ -39,7 +39,7 @@ public class MTMVRefreshSnapshotTest { private BaseTableInfo existTable = Mockito.mock(BaseTableInfo.class); private BaseTableInfo nonExistTable = Mockito.mock(BaseTableInfo.class); - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { Mockito.when(existTable.getCtlName()).thenReturn("ctl1"); Mockito.when(existTable.getDbName()).thenReturn("db1"); @@ -64,24 +64,24 @@ public void testPartitionSync() { // normal boolean sync = refreshSnapshot.equalsWithPct(mvExistPartitionName, relatedExistPartitionName, new MTMVVersionSnapshot(correctVersion, 0), existTable); - Assert.assertTrue(sync); + Assertions.assertTrue(sync); // non exist mv partition sync = refreshSnapshot.equalsWithPct("mvp2", relatedExistPartitionName, new MTMVVersionSnapshot(correctVersion, 0), existTable); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // non exist related partition sync = refreshSnapshot .equalsWithPct(mvExistPartitionName, "p2", new MTMVVersionSnapshot(correctVersion, 0), existTable); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // snapshot value not equal sync = refreshSnapshot.equalsWithPct(mvExistPartitionName, relatedExistPartitionName, new MTMVVersionSnapshot(2L, 0), existTable); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // snapshot type not equal sync = refreshSnapshot.equalsWithPct(mvExistPartitionName, relatedExistPartitionName, new MTMVTimestampSnapshot(correctVersion), existTable); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); } @Test @@ -89,22 +89,22 @@ public void testTableSync() { // normal boolean sync = refreshSnapshot.equalsWithBaseTable(mvExistPartitionName, existTable, new MTMVVersionSnapshot(correctVersion, 0)); - Assert.assertTrue(sync); + Assertions.assertTrue(sync); // non exist mv partition sync = refreshSnapshot .equalsWithBaseTable("mvp2", existTable, new MTMVVersionSnapshot(correctVersion, 0)); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // non exist related partition sync = refreshSnapshot .equalsWithBaseTable(mvExistPartitionName, nonExistTable, new MTMVVersionSnapshot(correctVersion, 0)); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // snapshot value not equal sync = refreshSnapshot .equalsWithBaseTable(mvExistPartitionName, existTable, new MTMVVersionSnapshot(2L, 0)); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); // snapshot type not equal sync = refreshSnapshot.equalsWithBaseTable(mvExistPartitionName, existTable, new MTMVTimestampSnapshot(correctVersion)); - Assert.assertFalse(sync); + Assertions.assertFalse(sync); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescRollUpGeneratorTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescRollUpGeneratorTest.java index 7fdcde6a3cc5b1..b499083eb6d392 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescRollUpGeneratorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescRollUpGeneratorTest.java @@ -33,8 +33,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -79,9 +79,9 @@ public void testRollUpRange() throws AnalysisException { PartitionKeyDesc expectDesc202002 = PartitionKeyDesc.createFixed( Lists.newArrayList(new PartitionValue("2020-02-01")), Lists.newArrayList(new PartitionValue("2020-03-01"))); - Assert.assertEquals(2, res.size()); - Assert.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc202001)); - Assert.assertEquals(Sets.newHashSet("name3"), res.get(expectDesc202002)); + Assertions.assertEquals(2, res.size()); + Assertions.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc202001)); + Assertions.assertEquals(Sets.newHashSet("name3"), res.get(expectDesc202002)); } } @@ -106,9 +106,9 @@ public void testRollUpList() throws AnalysisException { PartitionKeyDesc expectDesc202001 = generateInDesc("2020-01-01", "2020-01-02"); PartitionKeyDesc expectDesc202002 = generateInDesc("2020-02-01"); - Assert.assertEquals(2, res.size()); - Assert.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc202001)); - Assert.assertEquals(Sets.newHashSet("name3"), res.get(expectDesc202002)); + Assertions.assertEquals(2, res.size()); + Assertions.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc202001)); + Assertions.assertEquals(Sets.newHashSet("name3"), res.get(expectDesc202002)); } } @@ -162,8 +162,8 @@ public void testRollUpRangeTimestampTz() throws AnalysisException { PartitionKeyDesc expectDesc = PartitionKeyDesc.createFixed( Lists.newArrayList(new PartitionValue("2024-01-15 00:00:00+00:00")), Lists.newArrayList(new PartitionValue("2024-01-16 00:00:00+00:00"))); - Assert.assertEquals(1, res.size()); - Assert.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc)); + Assertions.assertEquals(1, res.size()); + Assertions.assertEquals(Sets.newHashSet("name1", "name2"), res.get(expectDesc)); // Verify that the rolled-up PartitionKeyDesc produces correct UTC partition keys // regardless of session timezone (America/New_York = UTC-5). @@ -180,10 +180,8 @@ public void testRollUpRangeTimestampTz() throws AnalysisException { // Both should be stored as midnight UTC, not shifted to session-local time. String lowKeyStr = lowKey.getKeys().get(0).getStringValue(); String upperKeyStr = upperKey.getKeys().get(0).getStringValue(); - Assert.assertTrue("Lower bound should be 2024-01-15 midnight UTC, but was: " + lowKeyStr, - lowKeyStr.startsWith("2024-01-15 00:00:00")); - Assert.assertTrue("Upper bound should be 2024-01-16 midnight UTC, but was: " + upperKeyStr, - upperKeyStr.startsWith("2024-01-16 00:00:00")); + Assertions.assertTrue(lowKeyStr.startsWith("2024-01-15 00:00:00"), "Lower bound should be 2024-01-15 midnight UTC, but was: " + lowKeyStr); + Assertions.assertTrue(upperKeyStr.startsWith("2024-01-16 00:00:00"), "Upper bound should be 2024-01-16 midnight UTC, but was: " + upperKeyStr); } finally { ConnectContext.remove(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescSyncLimitGeneratorTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescSyncLimitGeneratorTest.java index 5d142344d0c4cf..cf340093b52e33 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescSyncLimitGeneratorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelatedPartitionDescSyncLimitGeneratorTest.java @@ -23,8 +23,8 @@ import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -39,27 +39,27 @@ public void testGenerateMTMVPartitionSyncConfigByProperties() throws AnalysisExc Map mvProperties = Maps.newHashMap(); MTMVPartitionSyncConfig config = generator .generateMTMVPartitionSyncConfigByProperties(mvProperties); - Assert.assertEquals(-1, config.getSyncLimit()); - Assert.assertFalse(config.getDateFormat().isPresent()); - Assert.assertEquals(MTMVPartitionSyncTimeUnit.DAY, config.getTimeUnit()); + Assertions.assertEquals(-1, config.getSyncLimit()); + Assertions.assertFalse(config.getDateFormat().isPresent()); + Assertions.assertEquals(MTMVPartitionSyncTimeUnit.DAY, config.getTimeUnit()); mvProperties.put(PropertyAnalyzer.PROPERTIES_PARTITION_SYNC_LIMIT, "1"); config = generator.generateMTMVPartitionSyncConfigByProperties(mvProperties); - Assert.assertEquals(1, config.getSyncLimit()); - Assert.assertFalse(config.getDateFormat().isPresent()); - Assert.assertEquals(MTMVPartitionSyncTimeUnit.DAY, config.getTimeUnit()); + Assertions.assertEquals(1, config.getSyncLimit()); + Assertions.assertFalse(config.getDateFormat().isPresent()); + Assertions.assertEquals(MTMVPartitionSyncTimeUnit.DAY, config.getTimeUnit()); mvProperties.put(PropertyAnalyzer.PROPERTIES_PARTITION_TIME_UNIT, "month"); config = generator.generateMTMVPartitionSyncConfigByProperties(mvProperties); - Assert.assertEquals(1, config.getSyncLimit()); - Assert.assertFalse(config.getDateFormat().isPresent()); - Assert.assertEquals(MTMVPartitionSyncTimeUnit.MONTH, config.getTimeUnit()); + Assertions.assertEquals(1, config.getSyncLimit()); + Assertions.assertFalse(config.getDateFormat().isPresent()); + Assertions.assertEquals(MTMVPartitionSyncTimeUnit.MONTH, config.getTimeUnit()); mvProperties.put(PropertyAnalyzer.PROPERTIES_PARTITION_DATE_FORMAT, "%Y%m%d"); config = generator.generateMTMVPartitionSyncConfigByProperties(mvProperties); - Assert.assertEquals(1, config.getSyncLimit()); - Assert.assertEquals("%Y%m%d", config.getDateFormat().get()); - Assert.assertEquals(MTMVPartitionSyncTimeUnit.MONTH, config.getTimeUnit()); + Assertions.assertEquals(1, config.getSyncLimit()); + Assertions.assertEquals("%Y%m%d", config.getDateFormat().get()); + Assertions.assertEquals(MTMVPartitionSyncTimeUnit.MONTH, config.getTimeUnit()); } @Test @@ -70,19 +70,19 @@ public void testGetNowTruncSubSec() throws AnalysisException { ms.when(DateTimeAcquire::now).thenReturn(dateTimeLiteral); long nowTruncSubSec = generator.getNowTruncSubSec(MTMVPartitionSyncTimeUnit.DAY, 1); // 2020-02-03 - Assert.assertEquals(1580659200L, nowTruncSubSec); + Assertions.assertEquals(1580659200L, nowTruncSubSec); nowTruncSubSec = generator.getNowTruncSubSec(MTMVPartitionSyncTimeUnit.MONTH, 1); // 2020-02-01 - Assert.assertEquals(1580486400L, nowTruncSubSec); + Assertions.assertEquals(1580486400L, nowTruncSubSec); nowTruncSubSec = generator.getNowTruncSubSec(MTMVPartitionSyncTimeUnit.YEAR, 1); // 2020-01-01 - Assert.assertEquals(1577808000L, nowTruncSubSec); + Assertions.assertEquals(1577808000L, nowTruncSubSec); nowTruncSubSec = generator.getNowTruncSubSec(MTMVPartitionSyncTimeUnit.MONTH, 3); // 2019-12-01 - Assert.assertEquals(1575129600L, nowTruncSubSec); + Assertions.assertEquals(1575129600L, nowTruncSubSec); nowTruncSubSec = generator.getNowTruncSubSec(MTMVPartitionSyncTimeUnit.DAY, 4); // 2020-01-31 - Assert.assertEquals(1580400000L, nowTruncSubSec); + Assertions.assertEquals(1580400000L, nowTruncSubSec); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelationManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelationManagerTest.java index bfd4f6d439ccbe..3709e3adf0d923 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelationManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRelationManagerTest.java @@ -21,9 +21,9 @@ import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Set; @@ -34,7 +34,7 @@ public class MTMVRelationManagerTest { private BaseTableInfo t3 = Mockito.mock(BaseTableInfo.class); private BaseTableInfo t4 = Mockito.mock(BaseTableInfo.class); - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { Mockito.when(mv1.getCtlName()).thenReturn("ctl1"); Mockito.when(mv1.getDbName()).thenReturn("db1"); @@ -66,13 +66,13 @@ public void testGetMtmvsByBaseTableOneLevelAndFromView() { manager.refreshMTMVCache(mv1Relation, mv1); // should return mv2 Set mv1OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(mv1); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), mv1OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), mv1OneLevel)); // should return mv2 Set t3OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(t3); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3OneLevel)); // should return mv1 Set t4OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(t4); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4OneLevel)); // update mv2 only use t3,remove mv1 mv2Relation = new MTMVRelation(Sets.newHashSet(t3), Sets.newHashSet(t3), Sets.newHashSet(t3), @@ -80,13 +80,13 @@ public void testGetMtmvsByBaseTableOneLevelAndFromView() { manager.refreshMTMVCache(mv2Relation, mv2); // should return empty mv1OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(mv1); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(), mv1OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(), mv1OneLevel)); // should return mv2 t3OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(t3); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3OneLevel)); // should return mv1 t4OneLevel = manager.getMtmvsByBaseTableOneLevelAndFromView(t4); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4OneLevel)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4OneLevel)); } @Test @@ -102,13 +102,13 @@ public void testGetMtmvsByBaseTable() { manager.refreshMTMVCache(mv1Relation, mv1); // should return mv2 Set mv1All = manager.getMtmvsByBaseTable(mv1); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), mv1All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), mv1All)); // should return mv2 Set t3All = manager.getMtmvsByBaseTable(t3); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3All)); // should return mv1 Set t4All = manager.getMtmvsByBaseTable(t4); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1, mv2), t4All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1, mv2), t4All)); // update mv2 only use t3,remove mv1 mv2Relation = new MTMVRelation(Sets.newHashSet(t3), Sets.newHashSet(t3), Sets.newHashSet(t3), @@ -116,12 +116,12 @@ public void testGetMtmvsByBaseTable() { manager.refreshMTMVCache(mv2Relation, mv2); // should return empty mv1All = manager.getMtmvsByBaseTableOneLevelAndFromView(mv1); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(), mv1All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(), mv1All)); // should return mv2 t3All = manager.getMtmvsByBaseTableOneLevelAndFromView(t3); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv2), t3All)); // should return mv1 t4All = manager.getMtmvsByBaseTableOneLevelAndFromView(t4); - Assert.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4All)); + Assertions.assertTrue(CollectionUtils.isEqualCollection(Sets.newHashSet(mv1), t4All)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRewriteUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRewriteUtilTest.java index 230090736466a5..73b565b5ca99db 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRewriteUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVRewriteUtilTest.java @@ -42,10 +42,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -70,7 +70,7 @@ public class MTMVRewriteUtilTest { private MockedStatic mtmvUtilStatic; private long currentTimeMills = 3L; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { mtmvPartitionUtilStatic = Mockito.mockStatic(MTMVPartitionUtil.class); mtmvUtilStatic = Mockito.mockStatic(MTMVUtil.class); @@ -116,7 +116,7 @@ public void setUp() throws NoSuchMethodException, SecurityException, AnalysisExc Mockito.when(mtmv.canBeCandidate()).thenReturn(true); } - @After + @AfterEach public void tearDown() { mtmvPartitionUtilStatic.close(); mtmvUtilStatic.close(); @@ -135,7 +135,7 @@ public void testGetMTMVCanRewritePartitionsForceConsistent() throws AnalysisExce // if forceConsistent this should get 0 partitions which mtmv can use. Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, true, null); - Assert.assertEquals(0, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(0, mtmvCanRewritePartitions.size()); } @Test @@ -143,7 +143,7 @@ public void testGetMTMVCanRewritePartitionsNormal() { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -158,7 +158,7 @@ public void testGetMTMVCanRewritePartitionsInGracePeriod() throws AnalysisExcept Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -173,7 +173,7 @@ public void testGetMTMVCanRewritePartitionsNotInGracePeriod() throws AnalysisExc Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(0, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(0, mtmvCanRewritePartitions.size()); } @Test @@ -184,7 +184,7 @@ public void testGetMTMVCanRewritePartitionsDisableMaterializedViewRewrite() { null); // getMTMVCanRewritePartitions only check the partition is valid or not, it doesn't care the // isEnableMaterializedViewRewriteWhenBaseTableUnawareness - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -196,7 +196,7 @@ public void testGetMTMVCanRewritePartitionsNotSync() throws AnalysisException { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(0, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(0, mtmvCanRewritePartitions.size()); } @Test @@ -208,7 +208,7 @@ public void testGetMTMVCanRewritePartitionsEnableContainExternalTable() { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -222,7 +222,7 @@ public void testGetMTMVCanRewritePartitionsDisableContainExternalTable() { null); // getMTMVCanRewritePartitions only check the partition is valid or not, it doesn't care the // isEnableMaterializedViewRewriteWhenBaseTableUnawareness - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -231,7 +231,7 @@ public void testGetMTMVCanRewritePartitionsStateAbnormal() { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(0, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(0, mtmvCanRewritePartitions.size()); } @Test @@ -240,7 +240,7 @@ public void testGetMTMVCanRewritePartitionsRefreshStateAbnormal() { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(1, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(1, mtmvCanRewritePartitions.size()); } @Test @@ -249,7 +249,7 @@ public void testGetMTMVCanRewritePartitionsRefreshStateInit() { Collection mtmvCanRewritePartitions = MTMVRewriteUtil .getMTMVCanRewritePartitions(mtmv, ctx, currentTimeMills, false, null); - Assert.assertEquals(0, mtmvCanRewritePartitions.size()); + Assertions.assertEquals(0, mtmvCanRewritePartitions.size()); } @Test @@ -261,10 +261,10 @@ public void testPctToMv() { ImmutableMap.of(t1, Sets.newHashSet("t1_p1", "t1_p2"), t2, Sets.newHashSet("t2_p1"))); partitionMappings.put("mv_p2", ImmutableMap.of(t2, Sets.newHashSet("t2_p2"))); Map, String> pctToMv = MTMVRewriteUtil.getPctToMv(partitionMappings); - Assert.assertEquals("mv_p1", pctToMv.get(Pair.of(t1, "t1_p1"))); - Assert.assertEquals("mv_p1", pctToMv.get(Pair.of(t1, "t1_p2"))); - Assert.assertEquals("mv_p1", pctToMv.get(Pair.of(t2, "t2_p1"))); - Assert.assertEquals("mv_p2", pctToMv.get(Pair.of(t2, "t2_p2"))); + Assertions.assertEquals("mv_p1", pctToMv.get(Pair.of(t1, "t1_p1"))); + Assertions.assertEquals("mv_p1", pctToMv.get(Pair.of(t1, "t1_p2"))); + Assertions.assertEquals("mv_p1", pctToMv.get(Pair.of(t2, "t2_p1"))); + Assertions.assertEquals("mv_p2", pctToMv.get(Pair.of(t2, "t2_p2"))); } private static class TestMTMVRelatedTable implements MTMVRelatedTableIf { diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTaskTest.java index f0bf165b2dbbcd..f3c2d9378c0006 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTaskTest.java @@ -37,10 +37,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -61,7 +61,7 @@ public class MTMVTaskTest { private MockedStatic mtmvPartitionUtilStatic; private static final String COMPUTE_GROUP = "ComputeGroup"; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException, DdlException, MetaNotFoundException { @@ -89,7 +89,7 @@ public void setUp() Mockito.when(mtmv.hasCompleteRefreshSnapshot()).thenReturn(true); } - @After + @AfterEach public void tearDown() { mtmvUtilStatic.close(); mtmvPartitionUtilStatic.close(); @@ -100,7 +100,7 @@ public void testCalculateNeedRefreshPartitionsManualComplete() throws AnalysisEx MTMVTaskContext context = new MTMVTaskContext(MTMVTaskTriggerMode.MANUAL, null, true, null); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(allPartitionNames, result); + Assertions.assertEquals(allPartitionNames, result); } @Test @@ -109,7 +109,7 @@ public void testCalculateNeedRefreshPartitionsManualPartitions() throws Analysis false, null); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(Lists.newArrayList(poneName), result); + Assertions.assertEquals(Lists.newArrayList(poneName), result); } @Test @@ -118,7 +118,7 @@ public void testCalculateNeedRefreshPartitionsSystem() throws AnalysisException MTMVTaskContext context = new MTMVTaskContext(MTMVTaskTriggerMode.SYSTEM); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertTrue(CollectionUtils.isEmpty(result)); + Assertions.assertTrue(CollectionUtils.isEmpty(result)); } @Test @@ -126,7 +126,7 @@ public void testCalculateNeedRefreshPartitionsSystemComplete() throws AnalysisEx MTMVTaskContext context = new MTMVTaskContext(MTMVTaskTriggerMode.SYSTEM); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(allPartitionNames, result); + Assertions.assertEquals(allPartitionNames, result); } @Test @@ -138,7 +138,7 @@ public void testCalculateNeedRefreshPartitionsSystemIncompleteRefreshSnapshot() MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(allPartitionNames, result); + Assertions.assertEquals(allPartitionNames, result); mtmvPartitionUtilStatic.verify(() -> MTMVPartitionUtil.isMTMVSync( Mockito.nullable(MTMVRefreshContext.class), Mockito.nullable(Set.class), Mockito.nullable(Set.class)), Mockito.never()); @@ -154,7 +154,7 @@ public void testCalculateNeedRefreshPartitionsManualPartitionsIncompleteRefreshS MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(Lists.newArrayList(poneName), result); + Assertions.assertEquals(Lists.newArrayList(poneName), result); } @Test @@ -163,7 +163,7 @@ public void testCalculateNeedRefreshPartitionsSystemNotSyncComplete() throws Ana MTMVTaskContext context = new MTMVTaskContext(MTMVTaskTriggerMode.SYSTEM); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(allPartitionNames, result); + Assertions.assertEquals(allPartitionNames, result); } @Test @@ -176,14 +176,14 @@ public void testCalculateNeedRefreshPartitionsSystemNotSyncAuto() throws Analysi MTMVTaskContext context = new MTMVTaskContext(MTMVTaskTriggerMode.SYSTEM); MTMVTask task = new MTMVTask(mtmv, relation, context); List result = task.calculateNeedRefreshPartitions(null); - Assert.assertEquals(Lists.newArrayList(ptwoName), result); + Assertions.assertEquals(Lists.newArrayList(ptwoName), result); } @Test public void testTaskSchemaContainsComputeGroup() { Column lastColumn = MTMVTask.SCHEMA.get(MTMVTask.SCHEMA.size() - 1); - Assert.assertEquals(COMPUTE_GROUP, lastColumn.getName()); - Assert.assertEquals(MTMVTask.SCHEMA.size() - 1, + Assertions.assertEquals(COMPUTE_GROUP, lastColumn.getName()); + Assertions.assertEquals(MTMVTask.SCHEMA.size() - 1, MTMVTask.COLUMN_TO_INDEX.get(COMPUTE_GROUP.toLowerCase()).intValue()); } @@ -194,7 +194,7 @@ public void testGetTvfInfoReturnsComputeGroup() { TRow row = task.getTvfInfo("job1"); - Assert.assertEquals("cg1", row.getColumnValue() + Assertions.assertEquals("cg1", row.getColumnValue() .get(MTMVTask.COLUMN_TO_INDEX.get(COMPUTE_GROUP.toLowerCase())).getStringVal()); } @@ -210,7 +210,7 @@ public void testRecordComputeGroupFromContext() { Deencapsulation.invoke(task, "recordComputeGroup", ctx); TRow row = task.getTvfInfo("job1"); - Assert.assertEquals("cg1", row.getColumnValue() + Assertions.assertEquals("cg1", row.getColumnValue() .get(MTMVTask.COLUMN_TO_INDEX.get(COMPUTE_GROUP.toLowerCase())).getStringVal()); } finally { Config.cloud_unique_id = originCloudUniqueId; @@ -228,7 +228,7 @@ public void testSetComputeGroupFromTaskContext() { Deencapsulation.invoke(task, "setComputeGroup", ctx); - Assert.assertEquals("cg1", ctx.getSessionVariable().getCloudCluster()); + Assertions.assertEquals("cg1", ctx.getSessionVariable().getCloudCluster()); } finally { Config.cloud_unique_id = originCloudUniqueId; } @@ -240,7 +240,7 @@ public void testGetTvfInfoReturnsNullStringForMissingComputeGroup() { TRow row = task.getTvfInfo("job1"); - Assert.assertEquals(FeConstants.null_string, row.getColumnValue() + Assertions.assertEquals(FeConstants.null_string, row.getColumnValue() .get(MTMVTask.COLUMN_TO_INDEX.get(COMPUTE_GROUP.toLowerCase())).getStringVal()); } @@ -250,7 +250,7 @@ public void testDeserializeOldTaskWithoutComputeGroup() { TRow row = task.getTvfInfo("job1"); - Assert.assertEquals(FeConstants.null_string, row.getColumnValue() + Assertions.assertEquals(FeConstants.null_string, row.getColumnValue() .get(MTMVTask.COLUMN_TO_INDEX.get(COMPUTE_GROUP.toLowerCase())).getStringVal()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java index 25c62451e43aea..28995195eb044f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVTest.java @@ -41,8 +41,8 @@ import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -79,7 +79,7 @@ public void testToInfoString() { Sets.newHashSet())); mtmv.setMvPartitionInfo(new MTMVPartitionInfo()); mtmv.setRefreshSnapshot(new MTMVRefreshSnapshot()); - Assert.assertEquals(expect, mtmv.toInfoString()); + Assertions.assertEquals(expect, mtmv.toInfoString()); } private MTMVRefreshInfo buildMTMVRefreshInfo(MTMV mtmv) { @@ -117,9 +117,9 @@ public void testCalculateDoublyPartitionMappings() throws AnalysisException { baseToMv.put(basePartitionName, mvPartitionName); } } - Assert.assertEquals(mvToBase.get("mvp1"), Sets.newHashSet("baseP1_1", "baseP1_2")); - Assert.assertEquals(baseToMv.get("baseP1_1"), "mvp1"); - Assert.assertEquals(baseToMv.get("baseP1_2"), "mvp1"); + Assertions.assertEquals(mvToBase.get("mvp1"), Sets.newHashSet("baseP1_1", "baseP1_2")); + Assertions.assertEquals(baseToMv.get("baseP1_1"), "mvp1"); + Assertions.assertEquals(baseToMv.get("baseP1_2"), "mvp1"); } private Map> mockRelatedPartitionDescs() throws AnalysisException { @@ -156,25 +156,25 @@ public void testGetExcludedTriggerTables() { mvProperties.put(PropertyAnalyzer.PROPERTIES_EXCLUDED_TRIGGER_TABLES, "t1"); Set excludedTriggerTables = mtmv.getExcludedTriggerTables(); - Assert.assertEquals(1, excludedTriggerTables.size()); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, null, "t1"))); + Assertions.assertEquals(1, excludedTriggerTables.size()); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, null, "t1"))); mvProperties.put(PropertyAnalyzer.PROPERTIES_EXCLUDED_TRIGGER_TABLES, "db1.t1"); excludedTriggerTables = mtmv.getExcludedTriggerTables(); - Assert.assertEquals(1, excludedTriggerTables.size()); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, "db1", "t1"))); + Assertions.assertEquals(1, excludedTriggerTables.size()); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, "db1", "t1"))); mvProperties.put(PropertyAnalyzer.PROPERTIES_EXCLUDED_TRIGGER_TABLES, "ctl1.db1.t1"); excludedTriggerTables = mtmv.getExcludedTriggerTables(); - Assert.assertEquals(1, excludedTriggerTables.size()); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo("ctl1", "db1", "t1"))); + Assertions.assertEquals(1, excludedTriggerTables.size()); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo("ctl1", "db1", "t1"))); mvProperties.put(PropertyAnalyzer.PROPERTIES_EXCLUDED_TRIGGER_TABLES, "ctl1.db1.t1,db2.t2,t3"); excludedTriggerTables = mtmv.getExcludedTriggerTables(); - Assert.assertEquals(3, excludedTriggerTables.size()); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo("ctl1", "db1", "t1"))); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, "db2", "t2"))); - Assert.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, null, "t3"))); + Assertions.assertEquals(3, excludedTriggerTables.size()); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo("ctl1", "db1", "t1"))); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, "db2", "t2"))); + Assertions.assertTrue(excludedTriggerTables.contains(new TableNameInfo(null, null, "t3"))); } @Test @@ -195,9 +195,9 @@ public void testAlterMvPropertiesWithExcludedTriggerTablesChange() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); - Assert.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); - Assert.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); + Assertions.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); + Assertions.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); mtmv.getRefreshSnapshot().getPartitionSnapshots().put("p1", new MTMVRefreshPartitionSnapshot()); oldSchemaChangeVersion = mtmv.getSchemaChangeVersion(); @@ -205,9 +205,9 @@ public void testAlterMvPropertiesWithExcludedTriggerTablesChange() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); - Assert.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); - Assert.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); + Assertions.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); + Assertions.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); } @Test @@ -226,8 +226,8 @@ public void testAlterMvPropertiesWithSameExcludedTriggerTables() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(oldSchemaChangeVersion, mtmv.getSchemaChangeVersion()); - Assert.assertFalse(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(oldSchemaChangeVersion, mtmv.getSchemaChangeVersion()); + Assertions.assertFalse(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); } @Test @@ -247,9 +247,9 @@ public void testAlterMvPropertiesWithReducedExcludedTriggerTables() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); - Assert.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); - Assert.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); + Assertions.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); + Assertions.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); mtmv.getRefreshSnapshot().getPartitionSnapshots().put("p1", new MTMVRefreshPartitionSnapshot()); oldSchemaChangeVersion = mtmv.getSchemaChangeVersion(); @@ -257,9 +257,9 @@ public void testAlterMvPropertiesWithReducedExcludedTriggerTables() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); - Assert.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); - Assert.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(MTMVState.NORMAL, mtmv.getStatus().getState()); + Assertions.assertEquals(oldSchemaChangeVersion + 1, mtmv.getSchemaChangeVersion()); + Assertions.assertTrue(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); } @Test @@ -278,8 +278,8 @@ public void testAlterMvPropertiesWithOtherProperty() { mtmv.alterMvProperties(newProperties); - Assert.assertEquals(oldSchemaChangeVersion, mtmv.getSchemaChangeVersion()); - Assert.assertFalse(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); + Assertions.assertEquals(oldSchemaChangeVersion, mtmv.getSchemaChangeVersion()); + Assertions.assertFalse(mtmv.getRefreshSnapshot().getPartitionSnapshots().isEmpty()); } @Test @@ -288,19 +288,19 @@ public void testAlterStatus() { MTMVStatus status = new MTMVStatus(); mtmv.setStatus(status); // test init - Assert.assertEquals(MTMVState.INIT, status.getState()); - Assert.assertEquals(MTMVRefreshState.INIT, status.getRefreshState()); + Assertions.assertEquals(MTMVState.INIT, status.getState()); + Assertions.assertEquals(MTMVRefreshState.INIT, status.getRefreshState()); // test schema change status.setRefreshState(MTMVRefreshState.SUCCESS); mtmv.alterStatus(new MTMVStatus(MTMVState.SCHEMA_CHANGE, "base table")); - Assert.assertEquals(MTMVState.SCHEMA_CHANGE, status.getState()); - Assert.assertEquals(MTMVRefreshState.SUCCESS, status.getRefreshState()); + Assertions.assertEquals(MTMVState.SCHEMA_CHANGE, status.getState()); + Assertions.assertEquals(MTMVRefreshState.SUCCESS, status.getRefreshState()); MTMVStatus alterStatus = new MTMVStatus(); alterStatus.setState(MTMVState.SCHEMA_CHANGE); alterStatus.setSchemaChangeDetail("base table"); mtmv.alterStatus(new MTMVStatus(MTMVState.SCHEMA_CHANGE, "base table")); - Assert.assertEquals(MTMVState.SCHEMA_CHANGE, status.getState()); - Assert.assertEquals(MTMVRefreshState.SUCCESS, status.getRefreshState()); + Assertions.assertEquals(MTMVState.SCHEMA_CHANGE, status.getState()); + Assertions.assertEquals(MTMVRefreshState.SUCCESS, status.getRefreshState()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVUtilTest.java b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVUtilTest.java index 5e99b5e6e2c2e9..555ae5458b91a4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVUtilTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mtmv/MTMVUtilTest.java @@ -24,8 +24,8 @@ import org.apache.doris.catalog.Type; import org.apache.doris.common.AnalysisException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Optional; @@ -34,18 +34,18 @@ public class MTMVUtilTest { public void testGetExprTimeSec() throws AnalysisException { LiteralExpr expr = new DateLiteral(2020, 1, 1); long exprTimeSec = MTMVUtil.getExprTimeSec(expr, Optional.empty()); - Assert.assertEquals(1577808000L, exprTimeSec); + Assertions.assertEquals(1577808000L, exprTimeSec); expr = new StringLiteral("2020-01-01"); exprTimeSec = MTMVUtil.getExprTimeSec(expr, Optional.of("%Y-%m-%d")); - Assert.assertEquals(1577808000L, exprTimeSec); + Assertions.assertEquals(1577808000L, exprTimeSec); expr = new IntLiteral(20200101); exprTimeSec = MTMVUtil.getExprTimeSec(expr, Optional.of("%Y%m%d")); - Assert.assertEquals(1577808000L, exprTimeSec); + Assertions.assertEquals(1577808000L, exprTimeSec); expr = new DateLiteral(Type.DATE, true); exprTimeSec = MTMVUtil.getExprTimeSec(expr, Optional.empty()); - Assert.assertEquals(253402185600L, exprTimeSec); + Assertions.assertEquals(253402185600L, exprTimeSec); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java index 403c2e8a0b4c25..5a7000e432e3e1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/ConnectionExceedTest.java @@ -31,8 +31,8 @@ import org.apache.doris.service.arrowflight.tokens.FlightTokenDetails; import org.apache.doris.service.arrowflight.tokens.FlightTokenManager; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -69,21 +69,21 @@ public void testHandleConnectionExceed() throws Exception { ConnectContext context1 = new ConnectContext(); context1.setEnv(mockEnv); context1.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%")); - Assert.assertTrue(scheduler.submit(context1)); - Assert.assertEquals(-1, scheduler.getConnectPoolMgr().registerConnection(context1)); + Assertions.assertTrue(scheduler.submit(context1)); + Assertions.assertEquals(-1, scheduler.getConnectPoolMgr().registerConnection(context1)); // Create second context and register ConnectContext context2 = new ConnectContext(); context2.setEnv(mockEnv); context2.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%")); - Assert.assertTrue(scheduler.submit(context2)); - Assert.assertEquals(-1, scheduler.getConnectPoolMgr().registerConnection(context2)); + Assertions.assertTrue(scheduler.submit(context2)); + Assertions.assertEquals(-1, scheduler.getConnectPoolMgr().registerConnection(context2)); // Create third context and try to register - should fail ConnectContext context3 = new ConnectContext(); context3.setEnv(mockEnv); context3.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%")); - Assert.assertTrue(scheduler.submit(context3)); + Assertions.assertTrue(scheduler.submit(context3)); // Create AcceptListener and handle the connection AcceptListener listener = new AcceptListener(scheduler); @@ -93,8 +93,8 @@ public void testHandleConnectionExceed() throws Exception { scheduler.getConnectPoolMgr().getMaxConnections(), 2, // Mocked user connection limit scheduler.getConnectionNum()); - Assert.assertEquals(expectedMsg, context3.getState().getErrorMessage()); - Assert.assertEquals(ErrorCode.ERR_TOO_MANY_USER_CONNECTIONS, context3.getState().getErrorCode()); + Assertions.assertEquals(expectedMsg, context3.getState().getErrorMessage()); + Assertions.assertEquals(ErrorCode.ERR_TOO_MANY_USER_CONNECTIONS, context3.getState().getErrorCode()); } } @@ -152,21 +152,21 @@ public void testFlightSessionConnectionExceed() throws Exception { ConnectContext context1 = new ConnectContext(); context1.setEnv(mockEnv); context1.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%")); - Assert.assertTrue(scheduler.submit(context1)); - Assert.assertEquals(-1, scheduler.getFlightSqlConnectPoolMgr().registerConnection(context1)); + Assertions.assertTrue(scheduler.submit(context1)); + Assertions.assertEquals(-1, scheduler.getFlightSqlConnectPoolMgr().registerConnection(context1)); // Create second context and register ConnectContext context2 = new ConnectContext(); context2.setEnv(mockEnv); context2.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%")); - Assert.assertTrue(scheduler.submit(context2)); - Assert.assertEquals(-1, scheduler.getFlightSqlConnectPoolMgr().registerConnection(context2)); + Assertions.assertTrue(scheduler.submit(context2)); + Assertions.assertEquals(-1, scheduler.getFlightSqlConnectPoolMgr().registerConnection(context2)); // Create FlightSessionsWithTokenManager and try to create a new connection FlightSessionsWithTokenManager manager = new FlightSessionsWithTokenManager(mockTokenManager); try { manager.createConnectContext("test_token"); - Assert.fail("Should throw IllegalArgumentException"); + Assertions.fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { // Verify error message is set correctly String expectedMsg = String.format( @@ -175,7 +175,7 @@ public void testFlightSessionConnectionExceed() throws Exception { + "max connections: %d, used: %d.", scheduler.getFlightSqlConnectPoolMgr().getMaxConnections(), scheduler.getConnectionNum()); - Assert.assertEquals(expectedMsg, e.getMessage()); + Assertions.assertEquals(expectedMsg, e.getMessage()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlAuthPacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlAuthPacketTest.java index dac01dbab03449..8290347b368189 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlAuthPacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlAuthPacketTest.java @@ -17,9 +17,9 @@ package org.apache.doris.mysql; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -29,7 +29,7 @@ public class MysqlAuthPacketTest { private ByteBuffer byteBuffer; - @Before + @BeforeEach public void setUp() { MysqlSerializer serializer = MysqlSerializer.newInstance(); @@ -65,12 +65,12 @@ public void setUp() { @Test public void testRead() { MysqlAuthPacket packet = new MysqlAuthPacket(); - Assert.assertTrue(packet.readFrom(byteBuffer)); - Assert.assertEquals("palo-user", packet.getUser()); - Assert.assertEquals("testDb", packet.getDb()); - Assert.assertEquals("oidc-token", new String(packet.getAuthResponse(), StandardCharsets.UTF_8)); - Assert.assertEquals(OIDC_PLUGIN_NAME, packet.getPluginName()); - Assert.assertEquals("mysql", packet.getConnectAttributes().get("_client_name")); - Assert.assertEquals("9.2.0", packet.getConnectAttributes().get("_client_version")); + Assertions.assertTrue(packet.readFrom(byteBuffer)); + Assertions.assertEquals("palo-user", packet.getUser()); + Assertions.assertEquals("testDb", packet.getDb()); + Assertions.assertEquals("oidc-token", new String(packet.getAuthResponse(), StandardCharsets.UTF_8)); + Assertions.assertEquals(OIDC_PLUGIN_NAME, packet.getPluginName()); + Assertions.assertEquals("mysql", packet.getConnectAttributes().get("_client_name")); + Assertions.assertEquals("9.2.0", packet.getConnectAttributes().get("_client_version")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCapabilityTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCapabilityTest.java index d0755742fd65f6..7b7ee02cda8af8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCapabilityTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCapabilityTest.java @@ -17,20 +17,20 @@ package org.apache.doris.mysql; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MysqlCapabilityTest { @Test public void testToString() { MysqlCapability capability = new MysqlCapability(1); - Assert.assertEquals("CLIENT_LONG_PASSWORD", capability.toString()); + Assertions.assertEquals("CLIENT_LONG_PASSWORD", capability.toString()); capability = new MysqlCapability(0x3); - Assert.assertEquals("CLIENT_LONG_PASSWORD | CLIENT_FOUND_ROWS", capability.toString()); + Assertions.assertEquals("CLIENT_LONG_PASSWORD | CLIENT_FOUND_ROWS", capability.toString()); capability = new MysqlCapability(0xfffffff); - Assert.assertEquals("CLIENT_LONG_PASSWORD | CLIENT_FOUND_ROWS | CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB" + Assertions.assertEquals("CLIENT_LONG_PASSWORD | CLIENT_FOUND_ROWS | CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB" + " | CLIENT_NO_SCHEMA | CLIENT_COMPRESS | CLIENT_ODBC | CLIENT_LOCAL_FILES" + " | CLIENT_IGNORE_SPACE | CLIENT_PROTOCOL_41 | CLIENT_INTERACTIVE | CLIENT_SSL" + " | CLIENT_IGNORE_SIGPIPE | CLIENT_TRANSACTIONS | CLIENT_RESERVED | CLIENT_SECURE_CONNECTION" @@ -43,13 +43,13 @@ public void testToString() { @Test public void testDefaultFlags() { MysqlCapability capability = MysqlCapability.DEFAULT_CAPABILITY; - Assert.assertEquals("CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB | CLIENT_LOCAL_FILES | CLIENT_PROTOCOL_41" + Assertions.assertEquals("CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB | CLIENT_LOCAL_FILES | CLIENT_PROTOCOL_41" + " | CLIENT_SECURE_CONNECTION | CLIENT_PLUGIN_AUTH | CLIENT_CONNECT_ATTRS" + " | CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | CLIENT_DEPRECATE_EOF", capability.toString()); - Assert.assertTrue(capability.supportClientLocalFile()); - Assert.assertTrue(capability.isConnectAttrs()); - Assert.assertTrue(capability.isPluginAuthDataLengthEncoded()); - Assert.assertTrue(capability.isDeprecatedEOF()); + Assertions.assertTrue(capability.supportClientLocalFile()); + Assertions.assertTrue(capability.isConnectAttrs()); + Assertions.assertTrue(capability.isPluginAuthDataLengthEncoded()); + Assertions.assertTrue(capability.isDeprecatedEOF()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java index 20023b02d7af0d..fe796991efef28 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlChannelTest.java @@ -21,8 +21,8 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.qe.ConnectContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.xnio.StreamConnection; @@ -69,7 +69,7 @@ public void testSendAfterException() throws IOException { buf.flip(); try { mysqlChannel.sendOnePacket(buf); - Assert.fail(); + Assertions.fail(); } catch (IOException ignore) { // do nothing } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColDefTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColDefTest.java index 21cedea8172825..128bff339f75f8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColDefTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColDefTest.java @@ -17,7 +17,7 @@ package org.apache.doris.mysql; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MysqlColDefTest { diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColTypeTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColTypeTest.java index 3a0b70305d807c..1229f4bbd8b870 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColTypeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlColTypeTest.java @@ -19,8 +19,8 @@ import org.apache.doris.catalog.MysqlColType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MysqlColTypeTest { @@ -29,38 +29,38 @@ public void testGetCode() { MysqlColType type; // decimal type = MysqlColType.MYSQL_TYPE_DECIMAL; - Assert.assertEquals(0, type.getCode()); - Assert.assertEquals("DECIMAL", type.toString()); + Assertions.assertEquals(0, type.getCode()); + Assertions.assertEquals("DECIMAL", type.toString()); // tiny type = MysqlColType.MYSQL_TYPE_TINY; - Assert.assertEquals(1, type.getCode()); - Assert.assertEquals("TINY INT", type.toString()); + Assertions.assertEquals(1, type.getCode()); + Assertions.assertEquals("TINY INT", type.toString()); // SHORT type = MysqlColType.MYSQL_TYPE_SHORT; - Assert.assertEquals(2, type.getCode()); - Assert.assertEquals("SMALL INT", type.toString()); + Assertions.assertEquals(2, type.getCode()); + Assertions.assertEquals("SMALL INT", type.toString()); // LONG type = MysqlColType.MYSQL_TYPE_LONG; - Assert.assertEquals(3, type.getCode()); - Assert.assertEquals("INT", type.toString()); + Assertions.assertEquals(3, type.getCode()); + Assertions.assertEquals("INT", type.toString()); // FLOAT type = MysqlColType.MYSQL_TYPE_FLOAT; - Assert.assertEquals(4, type.getCode()); - Assert.assertEquals("FLOAT", type.toString()); + Assertions.assertEquals(4, type.getCode()); + Assertions.assertEquals("FLOAT", type.toString()); // DOUBLE type = MysqlColType.MYSQL_TYPE_DOUBLE; - Assert.assertEquals(5, type.getCode()); - Assert.assertEquals("DOUBLE", type.toString()); + Assertions.assertEquals(5, type.getCode()); + Assertions.assertEquals("DOUBLE", type.toString()); // NULL type = MysqlColType.MYSQL_TYPE_NULL; - Assert.assertEquals(6, type.getCode()); - Assert.assertEquals("NULL", type.toString()); + Assertions.assertEquals(6, type.getCode()); + Assertions.assertEquals("NULL", type.toString()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCommandTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCommandTest.java index e4640bcdd4b28a..055d6dddfa7596 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCommandTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlCommandTest.java @@ -17,8 +17,8 @@ package org.apache.doris.mysql; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MysqlCommandTest { @@ -27,16 +27,16 @@ public void testFromCode() { MysqlCommand command; command = MysqlCommand.fromCode(3); - Assert.assertEquals(command, MysqlCommand.COM_QUERY); + Assertions.assertEquals(command, MysqlCommand.COM_QUERY); command = MysqlCommand.fromCode(32); - Assert.assertNull(command); + Assertions.assertNull(command); } @Test public void testToString() { MysqlCommand command = MysqlCommand.fromCode(1); - Assert.assertEquals("Quit", command.toString()); + Assertions.assertEquals("Quit", command.toString()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlEofPacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlEofPacketTest.java index 68a42985bdbe62..a198227bc850f4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlEofPacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlEofPacketTest.java @@ -19,16 +19,16 @@ import org.apache.doris.qe.QueryState; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; public class MysqlEofPacketTest { MysqlCapability capability; - @Before + @BeforeEach public void setUp() { capability = new MysqlCapability(MysqlCapability.Flag.CLIENT_PROTOCOL_41.getFlagBit()); } @@ -43,14 +43,14 @@ public void testWrite() { ByteBuffer buffer = serializer.toByteBuffer(); // assert indicator(int1): 0 - Assert.assertEquals(0xfe, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0xfe, MysqlProto.readInt1(buffer)); // assert warnings(int2): 0 - Assert.assertEquals(0x00, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readInt2(buffer)); // assert status flags(int2): 0 - Assert.assertEquals(0x00, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readInt2(buffer)); - Assert.assertEquals(0, buffer.remaining()); + Assertions.assertEquals(0, buffer.remaining()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlErrPacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlErrPacketTest.java index a57e6d669aed7b..c72b312c9bd888 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlErrPacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlErrPacketTest.java @@ -19,16 +19,16 @@ import org.apache.doris.qe.QueryState; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; public class MysqlErrPacketTest { private MysqlCapability capability; - @Before + @BeforeEach public void setUp() { capability = new MysqlCapability(MysqlCapability.Flag.CLIENT_PROTOCOL_41.getFlagBit()); } @@ -44,17 +44,17 @@ public void testWrite() { ByteBuffer buffer = serializer.toByteBuffer(); // assert indicator - Assert.assertEquals(0xff, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0xff, MysqlProto.readInt1(buffer)); // error code - Assert.assertEquals(1105, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(1105, MysqlProto.readInt2(buffer)); // sql state marker - Assert.assertEquals('#', MysqlProto.readInt1(buffer)); + Assertions.assertEquals('#', MysqlProto.readInt1(buffer)); // sql state - Assert.assertEquals("HY000", new String(MysqlProto.readFixedString(buffer, 5))); + Assertions.assertEquals("HY000", new String(MysqlProto.readFixedString(buffer, 5))); // sql state - Assert.assertEquals("error", new String(MysqlProto.readEofString(buffer))); + Assertions.assertEquals("error", new String(MysqlProto.readEofString(buffer))); - Assert.assertEquals(0, buffer.remaining()); + Assertions.assertEquals(0, buffer.remaining()); } @Test @@ -67,18 +67,18 @@ public void testWriteNullMsg() { ByteBuffer buffer = serializer.toByteBuffer(); // assert indicator - Assert.assertEquals(0xff, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0xff, MysqlProto.readInt1(buffer)); // error code - Assert.assertEquals(1064, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(1064, MysqlProto.readInt2(buffer)); // sql state marker - Assert.assertEquals('#', MysqlProto.readInt1(buffer)); + Assertions.assertEquals('#', MysqlProto.readInt1(buffer)); // sql state - Assert.assertEquals("HY000", new String(MysqlProto.readFixedString(buffer, 5))); + Assertions.assertEquals("HY000", new String(MysqlProto.readFixedString(buffer, 5))); // sql state // NOTE: we put one space if MysqlErrPacket's errorMessage is null or empty - Assert.assertEquals("Unknown error", new String(MysqlProto.readEofString(buffer))); + Assertions.assertEquals("Unknown error", new String(MysqlProto.readEofString(buffer))); - Assert.assertEquals(0, buffer.remaining()); + Assertions.assertEquals(0, buffer.remaining()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlHandshakePacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlHandshakePacketTest.java index 8fba2b852a27f3..3b262281f24348 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlHandshakePacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlHandshakePacketTest.java @@ -18,10 +18,10 @@ package org.apache.doris.mysql; import com.google.common.primitives.Bytes; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -32,7 +32,7 @@ public class MysqlHandshakePacketTest { private MysqlCapability capability; private MockedStatic mockedMysqlPassword; - @Before + @BeforeEach public void setUp() { buf = new byte[20]; for (int i = 0; i < 20; ++i) { @@ -45,7 +45,7 @@ public void setUp() { capability = new MysqlCapability(0); } - @After + @AfterEach public void tearDown() { if (mockedMysqlPassword != null) { mockedMysqlPassword.close(); @@ -61,44 +61,44 @@ public void testWrite() { ByteBuffer buffer = serializer.toByteBuffer(); // assert protocol version - Assert.assertEquals(10, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(10, MysqlProto.readInt1(buffer)); // server version - Assert.assertEquals("5.7.99", new String(MysqlProto.readNulTerminateString(buffer))); + Assertions.assertEquals("5.7.99", new String(MysqlProto.readNulTerminateString(buffer))); // connection id - Assert.assertEquals(1090, MysqlProto.readInt4(buffer)); + Assertions.assertEquals(1090, MysqlProto.readInt4(buffer)); // plugin data 1 byte[] pluginData1 = MysqlProto.readFixedString(buffer, 8); - Assert.assertEquals(0, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0, MysqlProto.readInt1(buffer)); int flags = 0; flags = MysqlProto.readInt2(buffer); // char set - Assert.assertEquals(33, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(33, MysqlProto.readInt1(buffer)); // status flags - Assert.assertEquals(0, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0, MysqlProto.readInt2(buffer)); // capability flags flags |= MysqlProto.readInt2(buffer) << 16; - Assert.assertEquals(MysqlProto.SERVER_USE_SSL + Assertions.assertEquals(MysqlProto.SERVER_USE_SSL ? MysqlCapability.SSL_CAPABILITY.getFlags() : MysqlCapability.DEFAULT_CAPABILITY.getFlags(), flags); MysqlCapability advertisedCapability = new MysqlCapability(flags); - Assert.assertTrue(advertisedCapability.isConnectAttrs()); - Assert.assertTrue(advertisedCapability.isPluginAuthDataLengthEncoded()); + Assertions.assertTrue(advertisedCapability.isConnectAttrs()); + Assertions.assertTrue(advertisedCapability.isPluginAuthDataLengthEncoded()); // length of plugin data - Assert.assertEquals(21, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(21, MysqlProto.readInt1(buffer)); // length of plugin data byte[] toCheck = new byte[10]; byte[] reserved = MysqlProto.readFixedString(buffer, 10); for (int i = 0; i < 10; ++i) { - Assert.assertEquals(toCheck[i], reserved[i]); + Assertions.assertEquals(toCheck[i], reserved[i]); } byte[] pluginData2 = MysqlProto.readFixedString(buffer, 12); byte[] pluginData = Bytes.concat(pluginData1, pluginData2); for (int i = 0; i < 20; ++i) { - Assert.assertEquals(buf[i], pluginData[i]); + Assertions.assertEquals(buf[i], pluginData[i]); } // one byte - Assert.assertEquals(0, MysqlProto.readInt1(buffer)); - Assert.assertEquals(22, buffer.remaining()); + Assertions.assertEquals(0, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(22, buffer.remaining()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlOkPacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlOkPacketTest.java index 9fe47adbf5ebd1..028409ef6af5a9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlOkPacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlOkPacketTest.java @@ -19,16 +19,16 @@ import org.apache.doris.qe.QueryState; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; public class MysqlOkPacketTest { private MysqlCapability capability; - @Before + @BeforeEach public void setUp() { capability = new MysqlCapability(MysqlCapability.Flag.CLIENT_PROTOCOL_41.getFlagBit()); } @@ -42,26 +42,26 @@ public void testWrite() { ByteBuffer buffer = serializer.toByteBuffer(); // assert OK packet indicator 0x00 - Assert.assertEquals(0x00, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readInt1(buffer)); // assert affect rows vint: 0 - Assert.assertEquals(0x00, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readVInt(buffer)); // assert last insert id, vint: 0 - Assert.assertEquals(0x00, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readVInt(buffer)); // assert status flags, int2: 0 - Assert.assertEquals(0x00, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readInt2(buffer)); // assert warnings, int2: 0 - Assert.assertEquals(0x00, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0x00, MysqlProto.readInt2(buffer)); // When infoMessage is empty, an empty len-encoded string (0x00) should still be written. // This is required because OkPacket.parse() in MySQL Connector/J unconditionally reads // STRING_LENENC for info. Without this byte, the driver throws // ArrayIndexOutOfBoundsException when CLIENT_DEPRECATE_EOF is negotiated. - Assert.assertEquals(0x00, MysqlProto.readVInt(buffer)); - Assert.assertEquals(0, buffer.remaining()); + Assertions.assertEquals(0x00, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0, buffer.remaining()); } @Test @@ -76,7 +76,7 @@ public void testWritePayloadSizeGreaterThan5() { ByteBuffer buffer = serializer.toByteBuffer(); int payloadLength = buffer.remaining(); - Assert.assertTrue("OK packet payload should be > 5 for CLIENT_DEPRECATE_EOF compatibility, got: " - + payloadLength, payloadLength > 5); + Assertions.assertTrue(payloadLength > 5, "OK packet payload should be > 5 for CLIENT_DEPRECATE_EOF compatibility, got: " + + payloadLength); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlPasswordTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlPasswordTest.java index f14bbf017633d4..5be787b460efdd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlPasswordTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlPasswordTest.java @@ -21,34 +21,35 @@ import org.apache.doris.common.Config; import org.apache.doris.qe.GlobalVariable; -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 java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.nio.file.Files; +import java.nio.file.Path; public class MysqlPasswordTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + public Path tempFolder; private String originalDictionaryFile; private String originalSecurityPluginsDir; - @Before + @BeforeEach public void setUp() { // Save original values originalDictionaryFile = GlobalVariable.validatePasswordDictionaryFile; originalSecurityPluginsDir = Config.security_plugins_dir; } - @After + @AfterEach public void tearDown() { // Restore original values GlobalVariable.validatePasswordDictionaryFile = originalDictionaryFile; @@ -57,18 +58,18 @@ public void tearDown() { @Test public void testMakePassword() { - Assert.assertEquals("*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4", + Assertions.assertEquals("*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4", new String(MysqlPassword.makeScrambledPassword("mypass"))); - Assert.assertEquals("", new String(MysqlPassword.makeScrambledPassword(""))); + Assertions.assertEquals("", new String(MysqlPassword.makeScrambledPassword(""))); // null - Assert.assertEquals("", new String(MysqlPassword.makeScrambledPassword(null))); + Assertions.assertEquals("", new String(MysqlPassword.makeScrambledPassword(null))); - Assert.assertEquals("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32", + Assertions.assertEquals("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32", new String(MysqlPassword.makeScrambledPassword("aBc@321"))); - Assert.assertEquals(new String(new byte[0]), + Assertions.assertEquals(new String(new byte[0]), new String(MysqlPassword.getSaltFromPassword(new byte[0]))); } @@ -79,34 +80,38 @@ public void testCheckPass() throws UnsupportedEncodingException { byte[] publicSeed = MysqlPassword.createRandomString(20); byte[] codePass = MysqlPassword.scramble(publicSeed, "mypass"); - Assert.assertTrue(MysqlPassword.checkScramble(codePass, + Assertions.assertTrue(MysqlPassword.checkScramble(codePass, publicSeed, MysqlPassword.getSaltFromPassword("*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4".getBytes("UTF-8")))); - Assert.assertFalse(MysqlPassword.checkScramble(codePass, + Assertions.assertFalse(MysqlPassword.checkScramble(codePass, publicSeed, MysqlPassword.getSaltFromPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32".getBytes("UTF-8")))); } @Test public void testCheckPassword() throws AnalysisException { - Assert.assertEquals("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32", + Assertions.assertEquals("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32", new String(MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32"))); - Assert.assertEquals("", new String(MysqlPassword.checkPassword(null))); + Assertions.assertEquals("", new String(MysqlPassword.checkPassword(null))); } - @Test(expected = AnalysisException.class) + @Test public void testCheckPasswdFail() throws AnalysisException { - MysqlPassword.checkPassword("*9A6EC1164108A8D3DA3BE3F35A56F6499B6FC32"); - Assert.fail("No exception throws"); + Assertions.assertThrows(AnalysisException.class, () -> { + MysqlPassword.checkPassword("*9A6EC1164108A8D3DA3BE3F35A56F6499B6FC32"); + Assertions.fail("No exception throws"); + }); } - @Test(expected = AnalysisException.class) + @Test public void testCheckPasswdFail2() throws AnalysisException { - Assert.assertNotNull(MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32")); - MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC3H"); - Assert.fail("No exception throws"); + Assertions.assertThrows(AnalysisException.class, () -> { + Assertions.assertNotNull(MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC32")); + MysqlPassword.checkPassword("*9A6EC51164108A8D3DA3BE3F35A56F6499B6FC3H"); + Assertions.fail("No exception throws"); + }); } // ==================== validatePlainPassword Tests ==================== @@ -135,9 +140,9 @@ public void testValidatePasswordTooShort() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Aa1!abc"); - Assert.fail("Expected AnalysisException for password too short"); + Assertions.fail("Expected AnalysisException for password too short"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("at least 8 characters")); + Assertions.assertTrue(e.getMessage().contains("at least 8 characters")); } } @@ -146,16 +151,16 @@ public void testValidatePasswordNullOrEmpty() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, null); - Assert.fail("Expected AnalysisException for null password"); + Assertions.fail("Expected AnalysisException for null password"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("at least 8 characters")); + Assertions.assertTrue(e.getMessage().contains("at least 8 characters")); } try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, ""); - Assert.fail("Expected AnalysisException for empty password"); + Assertions.fail("Expected AnalysisException for empty password"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("at least 8 characters")); + Assertions.assertTrue(e.getMessage().contains("at least 8 characters")); } } @@ -164,9 +169,9 @@ public void testValidatePasswordMissingDigit() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Abcdefgh!"); - Assert.fail("Expected AnalysisException for missing digit"); + Assertions.fail("Expected AnalysisException for missing digit"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Missing: numeric")); + Assertions.assertTrue(e.getMessage().contains("Missing: numeric")); } } @@ -175,9 +180,9 @@ public void testValidatePasswordMissingLowercase() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "ABCDEFG1!"); - Assert.fail("Expected AnalysisException for missing lowercase"); + Assertions.fail("Expected AnalysisException for missing lowercase"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Missing: lowercase")); + Assertions.assertTrue(e.getMessage().contains("Missing: lowercase")); } } @@ -186,9 +191,9 @@ public void testValidatePasswordMissingUppercase() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "abcdefg1!"); - Assert.fail("Expected AnalysisException for missing uppercase"); + Assertions.fail("Expected AnalysisException for missing uppercase"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Missing: uppercase")); + Assertions.assertTrue(e.getMessage().contains("Missing: uppercase")); } } @@ -197,9 +202,9 @@ public void testValidatePasswordMissingSpecialChar() { GlobalVariable.validatePasswordDictionaryFile = ""; try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Abcdefg12"); - Assert.fail("Expected AnalysisException for missing special character"); + Assertions.fail("Expected AnalysisException for missing special character"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Missing: special character")); + Assertions.assertTrue(e.getMessage().contains("Missing: special character")); } } @@ -209,11 +214,11 @@ public void testValidatePasswordMissingMultipleTypes() { try { // Missing digit, uppercase, special char MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "abcdefghij"); - Assert.fail("Expected AnalysisException for missing multiple types"); + Assertions.fail("Expected AnalysisException for missing multiple types"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("numeric")); - Assert.assertTrue(e.getMessage().contains("uppercase")); - Assert.assertTrue(e.getMessage().contains("special character")); + Assertions.assertTrue(e.getMessage().contains("numeric")); + Assertions.assertTrue(e.getMessage().contains("uppercase")); + Assertions.assertTrue(e.getMessage().contains("special character")); } } @@ -236,10 +241,9 @@ public void testValidatePasswordBuiltinDictionaryWord() { for (String password : dictionaryPasswords) { try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, password); - Assert.fail("Expected AnalysisException for dictionary word in: " + password); + Assertions.fail("Expected AnalysisException for dictionary word in: " + password); } catch (AnalysisException e) { - Assert.assertTrue("Expected dictionary word error for: " + password, - e.getMessage().contains("dictionary word")); + Assertions.assertTrue(e.getMessage().contains("dictionary word"), "Expected dictionary word error for: " + password); } } } @@ -259,9 +263,9 @@ public void testValidatePasswordDictionaryWordCaseInsensitive() { for (String password : caseVariants) { try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, password); - Assert.fail("Expected AnalysisException for case-insensitive dictionary word in: " + password); + Assertions.fail("Expected AnalysisException for case-insensitive dictionary word in: " + password); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("dictionary word")); + Assertions.assertTrue(e.getMessage().contains("dictionary word")); } } } @@ -269,10 +273,10 @@ public void testValidatePasswordDictionaryWordCaseInsensitive() { @Test public void testValidatePasswordWithExternalDictionary() throws IOException, AnalysisException { // Set security_plugins_dir to temp folder - Config.security_plugins_dir = tempFolder.getRoot().getAbsolutePath(); + Config.security_plugins_dir = tempFolder.toFile().getAbsolutePath(); // Create a temporary dictionary file in the security_plugins_dir - File dictFile = tempFolder.newFile("test_dictionary.txt"); + File dictFile = Files.createFile(tempFolder.resolve("test_dictionary.txt")).toFile(); try (FileWriter writer = new FileWriter(dictFile)) { writer.write("# This is a comment\n"); writer.write("customword\n"); @@ -287,23 +291,23 @@ public void testValidatePasswordWithExternalDictionary() throws IOException, Ana // Password containing custom dictionary word should fail try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Customword1!"); - Assert.fail("Expected AnalysisException for custom dictionary word"); + Assertions.fail("Expected AnalysisException for custom dictionary word"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("customword")); + Assertions.assertTrue(e.getMessage().contains("customword")); } try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Secretkey1!"); - Assert.fail("Expected AnalysisException for custom dictionary word"); + Assertions.fail("Expected AnalysisException for custom dictionary word"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("secretkey")); + Assertions.assertTrue(e.getMessage().contains("secretkey")); } try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Forbidden1!"); - Assert.fail("Expected AnalysisException for custom dictionary word"); + Assertions.fail("Expected AnalysisException for custom dictionary word"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("forbidden")); + Assertions.assertTrue(e.getMessage().contains("forbidden")); } // Password not containing custom dictionary words should pass @@ -314,7 +318,7 @@ public void testValidatePasswordWithExternalDictionary() throws IOException, Ana @Test public void testValidatePasswordDictionaryFileNotFound() throws AnalysisException { // Set security_plugins_dir to a valid path - Config.security_plugins_dir = tempFolder.getRoot().getAbsolutePath(); + Config.security_plugins_dir = tempFolder.toFile().getAbsolutePath(); // When dictionary file doesn't exist, should fall back to built-in dictionary GlobalVariable.validatePasswordDictionaryFile = "non_existent_dictionary.txt"; @@ -322,9 +326,9 @@ public void testValidatePasswordDictionaryFileNotFound() throws AnalysisExceptio // Built-in dictionary word should still fail try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Test@123Xy"); - Assert.fail("Expected AnalysisException for built-in dictionary word"); + Assertions.fail("Expected AnalysisException for built-in dictionary word"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("dictionary word")); + Assertions.assertTrue(e.getMessage().contains("dictionary word")); } // Valid password should pass @@ -334,10 +338,10 @@ public void testValidatePasswordDictionaryFileNotFound() throws AnalysisExceptio @Test public void testValidatePasswordDictionaryFileReload() throws IOException, AnalysisException { // Set security_plugins_dir to temp folder - Config.security_plugins_dir = tempFolder.getRoot().getAbsolutePath(); + Config.security_plugins_dir = tempFolder.toFile().getAbsolutePath(); // Create first dictionary file - File dictFile1 = tempFolder.newFile("dict1.txt"); + File dictFile1 = Files.createFile(tempFolder.resolve("dict1.txt")).toFile(); try (FileWriter writer = new FileWriter(dictFile1)) { writer.write("wordone\n"); } @@ -348,13 +352,13 @@ public void testValidatePasswordDictionaryFileReload() throws IOException, Analy // Should fail for wordone try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Wordone12!"); - Assert.fail("Expected AnalysisException for wordone"); + Assertions.fail("Expected AnalysisException for wordone"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("wordone")); + Assertions.assertTrue(e.getMessage().contains("wordone")); } // Create second dictionary file with different content - File dictFile2 = tempFolder.newFile("dict2.txt"); + File dictFile2 = Files.createFile(tempFolder.resolve("dict2.txt")).toFile(); try (FileWriter writer = new FileWriter(dictFile2)) { writer.write("wordtwo\n"); } @@ -368,16 +372,16 @@ public void testValidatePasswordDictionaryFileReload() throws IOException, Analy // Should fail for wordtwo try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Wordtwo12!"); - Assert.fail("Expected AnalysisException for wordtwo"); + Assertions.fail("Expected AnalysisException for wordtwo"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("wordtwo")); + Assertions.assertTrue(e.getMessage().contains("wordtwo")); } } @Test public void testValidatePasswordEmptyDictionaryFile() throws IOException, AnalysisException { // Set security_plugins_dir to temp folder - Config.security_plugins_dir = tempFolder.getRoot().getAbsolutePath(); + Config.security_plugins_dir = tempFolder.toFile().getAbsolutePath(); // Use just the filename GlobalVariable.validatePasswordDictionaryFile = "empty_dict.txt"; @@ -385,25 +389,25 @@ public void testValidatePasswordEmptyDictionaryFile() throws IOException, Analys // With empty dictionary, only character requirements should be checked try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Test@123X"); - Assert.fail("Expected AnalysisException for test"); + Assertions.fail("Expected AnalysisException for test"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("test")); + Assertions.assertTrue(e.getMessage().contains("test")); } try { MysqlPassword.validatePlainPassword(GlobalVariable.VALIDATE_PASSWORD_POLICY_STRONG, "Admin@12X"); - Assert.fail("Expected AnalysisException for admin"); + Assertions.fail("Expected AnalysisException for admin"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("admin")); + Assertions.assertTrue(e.getMessage().contains("admin")); } } @Test public void testValidatePasswordDictionaryWithCommentsOnly() throws IOException, AnalysisException { // Set security_plugins_dir to temp folder - Config.security_plugins_dir = tempFolder.getRoot().getAbsolutePath(); + Config.security_plugins_dir = tempFolder.toFile().getAbsolutePath(); // Create a dictionary file with only comments - File dictFile = tempFolder.newFile("comments_dict.txt"); + File dictFile = Files.createFile(tempFolder.resolve("comments_dict.txt")).toFile(); try (FileWriter writer = new FileWriter(dictFile)) { writer.write("# comment 1\n"); writer.write("# comment 2\n"); diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoLenEncStringTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoLenEncStringTest.java index 237632eb00b617..86962094cd410d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoLenEncStringTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoLenEncStringTest.java @@ -17,8 +17,8 @@ package org.apache.doris.mysql; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -35,7 +35,7 @@ public void readLenEncodedStringRejectsOversizedLength() { buffer.put((byte) 0xFE); // 8-byte length follows buffer.put(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x7F, 0, 0, 0, 0}); // 0x7FFFFFFF buffer.flip(); - Assert.assertThrows(IllegalArgumentException.class, + Assertions.assertThrows(IllegalArgumentException.class, () -> MysqlProto.readLenEncodedString(buffer)); } @@ -45,7 +45,7 @@ public void readLenEncodedStringRejectsNegativeCastLength() { buffer.put((byte) 0xFE); buffer.put(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0, 0, 0, 0}); // (int) -> -1 buffer.flip(); - Assert.assertThrows(IllegalArgumentException.class, + Assertions.assertThrows(IllegalArgumentException.class, () -> MysqlProto.readLenEncodedString(buffer)); } @@ -56,6 +56,6 @@ public void readLenEncodedStringAcceptsValidPayload() { buffer.put((byte) payload.length); // single-byte length < 251 buffer.put(payload); buffer.flip(); - Assert.assertArrayEquals(payload, MysqlProto.readLenEncodedString(buffer)); + Assertions.assertArrayEquals(payload, MysqlProto.readLenEncodedString(buffer)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoTest.java index f785aaa5f219e5..a42822fcd580ed 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlProtoTest.java @@ -37,10 +37,10 @@ import org.apache.doris.mysql.privilege.PrivPredicate; import org.apache.doris.qe.ConnectContext; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.slf4j.Logger; @@ -70,7 +70,7 @@ public class MysqlProtoTest { private MockedStatic mockedMysqlPassword; private MockedStatic mockedEnv; - @Before + @BeforeEach public void setUp() throws DdlException, AuthenticationException, IOException { FeConstants.runningUnitTest = true; @@ -113,7 +113,7 @@ public void setUp() throws DdlException, AuthenticationException, IOException { Mockito.when(channel.getSerializer()).thenReturn(MysqlSerializer.newInstance()); } - @After + @AfterEach public void tearDown() { if (mockedMysqlPassword != null) { mockedMysqlPassword.close(); @@ -209,7 +209,7 @@ public void testNegotiate() throws Exception { ConnectContext context = createContext(); context.setEnv(env); context.setThreadLocalInfo(); - Assert.assertTrue(MysqlProto.negotiate(context)); + Assertions.assertTrue(MysqlProto.negotiate(context)); } @Test @@ -223,7 +223,7 @@ public void testNegotiateInitCatalog() throws Exception { context.setThreadLocalInfo(); String initCatalog = "external_catalog"; mockInitCatalog(catalogMgr, context, initCatalog); - Assert.assertTrue(MysqlProto.negotiate(context)); + Assertions.assertTrue(MysqlProto.negotiate(context)); Mockito.verify(env, Mockito.times(1)).changeCatalog(context, initCatalog); } @@ -235,7 +235,7 @@ public void testNegotiateSendFail() throws Exception { mockAccess(); ConnectContext context = createContext(); MysqlProto.negotiate(context); - Assert.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertFalse(MysqlProto.negotiate(context)); } @Test @@ -244,7 +244,7 @@ public void testNegotiateNoUser() throws Exception { mockPassword(true); mockAccess(); ConnectContext context = createContext(); - Assert.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertFalse(MysqlProto.negotiate(context)); } @Test @@ -252,9 +252,9 @@ public void testNegotiateClientClosedConnectionDuringHandshake() throws Exceptio Mockito.when(channel.fetchOnePacket()).thenReturn(null); ConnectContext context = createContext(); - Assert.assertFalse(MysqlProto.negotiate(context)); - Assert.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, context.getState().getErrorCode()); - Assert.assertEquals("Client closed connection during handshake", context.getState().getErrorMessage()); + Assertions.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, context.getState().getErrorCode()); + Assertions.assertEquals("Client closed connection during handshake", context.getState().getErrorMessage()); } @Test @@ -265,9 +265,9 @@ public void testNegotiateRejectsSslRequestWhenServerSslDisabled() throws Excepti Mockito.when(channel.fetchOnePacket()).thenReturn(serializer.toByteBuffer()); ConnectContext context = createContext(); - Assert.assertFalse(MysqlProto.negotiate(context)); - Assert.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, context.getState().getErrorCode()); - Assert.assertEquals("Client requested TLS/SSL, but Doris FE MySQL SSL is disabled", + Assertions.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, context.getState().getErrorCode()); + Assertions.assertEquals("Client requested TLS/SSL, but Doris FE MySQL SSL is disabled", context.getState().getErrorMessage()); } @@ -288,8 +288,8 @@ public void testNegotiateSendsAuthenticatorErrorWhenResponseNotSent() throws Exc Mockito.when(channel.isSend()).thenReturn(false); ConnectContext context = createContext(); - Assert.assertFalse(MysqlProto.negotiate(context)); - Assert.assertEquals(ErrorCode.ERR_ACCESS_DENIED_ERROR, context.getState().getErrorCode()); + Assertions.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertEquals(ErrorCode.ERR_ACCESS_DENIED_ERROR, context.getState().getErrorCode()); Mockito.verify(channel, Mockito.times(2)).sendAndFlush(Mockito.any(ByteBuffer.class)); } @@ -311,7 +311,7 @@ public void testNegotiateDoesNotResendAuthenticatorErrorWhenResponseAlreadySent( Mockito.when(channel.isSend()).thenReturn(true); ConnectContext context = createContext(); - Assert.assertFalse(MysqlProto.negotiate(context)); + Assertions.assertFalse(MysqlProto.negotiate(context)); Mockito.verify(channel, Mockito.times(1)).sendAndFlush(Mockito.any(ByteBuffer.class)); } @@ -326,7 +326,7 @@ public void testNegotiateLdap() throws Exception { ConnectContext context = createContext(); context.setEnv(env); context.setThreadLocalInfo(); - Assert.assertTrue(MysqlProto.negotiate(context)); + Assertions.assertTrue(MysqlProto.negotiate(context)); Config.authentication_type = "default"; } @@ -340,7 +340,7 @@ public void testNegotiateLdapRoot() throws Exception { ConnectContext context = createContext(); context.setEnv(env); context.setThreadLocalInfo(); - Assert.assertTrue(MysqlProto.negotiate(context)); + Assertions.assertTrue(MysqlProto.negotiate(context)); Config.authentication_type = "default"; } @@ -361,17 +361,17 @@ public void testRead() throws UnsupportedEncodingException { serializer.writeEofString("you have dream too"); ByteBuffer buffer = serializer.toByteBuffer(); - Assert.assertEquals(200, MysqlProto.readInt1(buffer)); - Assert.assertEquals(65535, MysqlProto.readInt2(buffer)); - Assert.assertEquals(65537, MysqlProto.readInt3(buffer)); - Assert.assertEquals(123456789, MysqlProto.readInt4(buffer)); - Assert.assertEquals(1234567896, MysqlProto.readInt6(buffer)); - Assert.assertEquals(1234567898, MysqlProto.readInt8(buffer)); - Assert.assertEquals(1111123452, MysqlProto.readVInt(buffer)); - - Assert.assertEquals("hello", new String(MysqlProto.readFixedString(buffer, 5))); - Assert.assertEquals("world", new String(MysqlProto.readLenEncodedString(buffer))); - Assert.assertEquals("i have dream", new String(MysqlProto.readNulTerminateString(buffer))); - Assert.assertEquals("you have dream too", new String(MysqlProto.readEofString(buffer))); + Assertions.assertEquals(200, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(65535, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(65537, MysqlProto.readInt3(buffer)); + Assertions.assertEquals(123456789, MysqlProto.readInt4(buffer)); + Assertions.assertEquals(1234567896, MysqlProto.readInt6(buffer)); + Assertions.assertEquals(1234567898, MysqlProto.readInt8(buffer)); + Assertions.assertEquals(1111123452, MysqlProto.readVInt(buffer)); + + Assertions.assertEquals("hello", new String(MysqlProto.readFixedString(buffer, 5))); + Assertions.assertEquals("world", new String(MysqlProto.readLenEncodedString(buffer))); + Assertions.assertEquals("i have dream", new String(MysqlProto.readNulTerminateString(buffer))); + Assertions.assertEquals("you have dream too", new String(MysqlProto.readEofString(buffer))); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlResultSetEndPacketTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlResultSetEndPacketTest.java index 8dc0d18877fde4..5462d6aee2c9c8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlResultSetEndPacketTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/MysqlResultSetEndPacketTest.java @@ -19,16 +19,16 @@ import org.apache.doris.qe.QueryState; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; public class MysqlResultSetEndPacketTest { private MysqlCapability capability; - @Before + @BeforeEach public void setUp() { capability = new MysqlCapability(MysqlCapability.Flag.CLIENT_PROTOCOL_41.getFlagBit()); } @@ -43,7 +43,7 @@ public void testWriteHeader() { ByteBuffer buffer = serializer.toByteBuffer(); // assert header: 0xFE - Assert.assertEquals(0xFE, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0xFE, MysqlProto.readInt1(buffer)); } @Test @@ -56,25 +56,25 @@ public void testWriteFields() { ByteBuffer buffer = serializer.toByteBuffer(); // header: 0xFE - Assert.assertEquals(0xFE, MysqlProto.readInt1(buffer)); + Assertions.assertEquals(0xFE, MysqlProto.readInt1(buffer)); // affected_rows: int = 0 - Assert.assertEquals(0, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0, MysqlProto.readVInt(buffer)); // last_insert_id: int = 0 - Assert.assertEquals(0, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0, MysqlProto.readVInt(buffer)); // status_flags: int<2> = 0 - Assert.assertEquals(0, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0, MysqlProto.readInt2(buffer)); // warnings: int<2> = 0 - Assert.assertEquals(0, MysqlProto.readInt2(buffer)); + Assertions.assertEquals(0, MysqlProto.readInt2(buffer)); // info: string (empty, length = 0) - Assert.assertEquals(0, MysqlProto.readVInt(buffer)); + Assertions.assertEquals(0, MysqlProto.readVInt(buffer)); // no remaining bytes - Assert.assertEquals(0, buffer.remaining()); + Assertions.assertEquals(0, buffer.remaining()); } @Test @@ -92,8 +92,8 @@ public void testPayloadSizeGreaterThan5() { int payloadLength = buffer.remaining(); // Payload: 0xFE(1) + affected_rows(1) + last_insert_id(1) + status(2) + warnings(2) + info(1) = 8 - Assert.assertTrue("ResultSet OK packet payload must be > 5 for isResultSetOKPacket(), got: " - + payloadLength, payloadLength > 5); + Assertions.assertTrue(payloadLength > 5, "ResultSet OK packet payload must be > 5 for isResultSetOKPacket(), got: " + + payloadLength); } @Test @@ -111,10 +111,8 @@ public void testDiffersFromEofPacket() { int rsEndPayloadLength = rsEndSerializer.toByteBuffer().remaining(); // EOF payload should be <= 5 - Assert.assertTrue("EOF packet payload should be <= 5, got: " + eofPayloadLength, - eofPayloadLength <= 5); + Assertions.assertTrue(eofPayloadLength <= 5, "EOF packet payload should be <= 5, got: " + eofPayloadLength); // ResultSet OK payload should be > 5 - Assert.assertTrue("ResultSet OK packet payload should be > 5, got: " + rsEndPayloadLength, - rsEndPayloadLength > 5); + Assertions.assertTrue(rsEndPayloadLength > 5, "ResultSet OK packet payload should be > 5, got: " + rsEndPayloadLength); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/DefaultAuthenticatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/DefaultAuthenticatorTest.java index 5a813392ec17f3..b500272fe23688 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/DefaultAuthenticatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/DefaultAuthenticatorTest.java @@ -25,10 +25,10 @@ import org.apache.doris.mysql.authenticate.password.NativePasswordResolver; import org.apache.doris.mysql.privilege.Auth; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -48,7 +48,7 @@ public class DefaultAuthenticatorTest { private AuthenticateRequest request = new AuthenticateRequest(USER_NAME, new NativePassword(new byte[2], new byte[2]), IP); - @Before + @BeforeEach public void setUp() throws DdlException, AuthenticationException, IOException { mockedEnvStatic = Mockito.mockStatic(Env.class); mockedEnvStatic.when(Env::getCurrentEnv).thenReturn(env); @@ -62,7 +62,7 @@ public void setUp() throws DdlException, AuthenticationException, IOException { }).when(auth).checkPassword(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(byte[].class), ArgumentMatchers.any(byte[].class), ArgumentMatchers.any(List.class)); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -70,9 +70,9 @@ public void tearDown() { @Test public void testAuthenticate() throws IOException { AuthenticateResponse response = defaultAuthenticator.authenticate(request); - Assert.assertTrue(response.isSuccess()); - Assert.assertFalse(response.isTemp()); - Assert.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); + Assertions.assertTrue(response.isSuccess()); + Assertions.assertFalse(response.isTemp()); + Assertions.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); } @Test @@ -80,16 +80,16 @@ public void testAuthenticateFailed() throws IOException, AuthenticationException Mockito.doThrow(new AuthenticationException("exception")) .when(auth).checkPassword(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(byte[].class), ArgumentMatchers.any(byte[].class), ArgumentMatchers.any(List.class)); AuthenticateResponse response = defaultAuthenticator.authenticate(request); - Assert.assertFalse(response.isSuccess()); + Assertions.assertFalse(response.isSuccess()); } @Test public void testCanDeal() { - Assert.assertTrue(defaultAuthenticator.canDeal("ss")); + Assertions.assertTrue(defaultAuthenticator.canDeal("ss")); } @Test public void testGetPasswordResolver() { - Assert.assertTrue(defaultAuthenticator.getPasswordResolver() instanceof NativePasswordResolver); + Assertions.assertTrue(defaultAuthenticator.getPasswordResolver() instanceof NativePasswordResolver); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticatorTest.java index 6045b1ff339189..8f0f2d69f66662 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapAuthenticatorTest.java @@ -26,10 +26,10 @@ import org.apache.doris.mysql.privilege.Auth; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -48,7 +48,7 @@ public class LdapAuthenticatorTest { private LdapAuthenticator ldapAuthenticator = new LdapAuthenticator(); private AuthenticateRequest request = new AuthenticateRequest(USER_NAME, new ClearPassword("123"), IP); - @Before + @BeforeEach public void setUp() { mockedEnvStatic = Mockito.mockStatic(Env.class); mockedEnvStatic.when(Env::getCurrentEnv).thenReturn(env); @@ -56,7 +56,7 @@ public void setUp() { Mockito.when(auth.getLdapManager()).thenReturn(ldapManager); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -90,9 +90,9 @@ public void testAuthenticate() throws IOException { setCheckPassword(true); setGetUserInDoris(true); AuthenticateResponse response = ldapAuthenticator.authenticate(request); - Assert.assertTrue(response.isSuccess()); - Assert.assertFalse(response.isTemp()); - Assert.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); + Assertions.assertTrue(response.isSuccess()); + Assertions.assertFalse(response.isTemp()); + Assertions.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); } @Test @@ -100,7 +100,7 @@ public void testAuthenticateWithWrongPassword() throws IOException { setCheckPassword(false); setGetUserInDoris(true); AuthenticateResponse response = ldapAuthenticator.authenticate(request); - Assert.assertFalse(response.isSuccess()); + Assertions.assertFalse(response.isSuccess()); } @Test @@ -108,7 +108,7 @@ public void testAuthenticateWithCheckPasswordException() throws IOException { setCheckPasswordException(); setGetUserInDoris(true); AuthenticateResponse response = ldapAuthenticator.authenticate(request); - Assert.assertFalse(response.isSuccess()); + Assertions.assertFalse(response.isSuccess()); } @Test @@ -116,23 +116,23 @@ public void testAuthenticateUserNotExistInDoris() throws IOException { setCheckPassword(true); setGetUserInDoris(false); AuthenticateResponse response = ldapAuthenticator.authenticate(request); - Assert.assertTrue(response.isSuccess()); - Assert.assertTrue(response.isTemp()); - Assert.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); + Assertions.assertTrue(response.isSuccess()); + Assertions.assertTrue(response.isTemp()); + Assertions.assertEquals("'user'@'192.168.1.1'", response.getUserIdentity().toString()); } @Test public void testCanDeal() { setLdapUserExist(true); - Assert.assertFalse(ldapAuthenticator.canDeal(Auth.ROOT_USER)); - Assert.assertFalse(ldapAuthenticator.canDeal(Auth.ADMIN_USER)); - Assert.assertTrue(ldapAuthenticator.canDeal("ss")); + Assertions.assertFalse(ldapAuthenticator.canDeal(Auth.ROOT_USER)); + Assertions.assertFalse(ldapAuthenticator.canDeal(Auth.ADMIN_USER)); + Assertions.assertTrue(ldapAuthenticator.canDeal("ss")); setLdapUserExist(false); - Assert.assertFalse(ldapAuthenticator.canDeal("ss")); + Assertions.assertFalse(ldapAuthenticator.canDeal("ss")); } @Test public void testGetPasswordResolver() { - Assert.assertTrue(ldapAuthenticator.getPasswordResolver() instanceof ClearPasswordResolver); + Assertions.assertTrue(ldapAuthenticator.getPasswordResolver() instanceof ClearPasswordResolver); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapClientTest.java index 886d8bcfb817aa..72cf5beff6edb8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapClientTest.java @@ -21,10 +21,10 @@ import org.apache.doris.common.LdapConfig; import org.apache.doris.common.util.NetUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.ldap.query.LdapQuery; import org.springframework.ldap.support.LdapEncoder; @@ -35,7 +35,7 @@ public class LdapClientTest { private LdapClient ldapClient = Mockito.spy(new LdapClient()); - @Before + @BeforeEach public void setUp() { Config.authentication_type = "ldap"; LdapConfig.ldap_host = "127.0.0.1"; @@ -53,28 +53,30 @@ public void testDoesUserExist() { Mockito.doReturn(list).when(ldapClient).getDn(Mockito.any(LdapQuery.class)); boolean result = ldapClient.doesUserExist("zhangsan"); - Assert.assertTrue(result); + Assertions.assertTrue(result); } @Test public void testDoesUserExistFail() { Mockito.doReturn(null).when(ldapClient).getDn(Mockito.any(LdapQuery.class)); - Assert.assertFalse(ldapClient.doesUserExist("zhangsan")); + Assertions.assertFalse(ldapClient.doesUserExist("zhangsan")); } - @Test(expected = RuntimeException.class) + @Test public void testDoesUserExistException() { - List list = Arrays.asList("zhangsan", "zhangsan"); - Mockito.doReturn(list).when(ldapClient).getDn(Mockito.any(LdapQuery.class)); - Assert.assertTrue(ldapClient.doesUserExist("zhangsan")); - Assert.fail("No Exception throws."); + Assertions.assertThrows(RuntimeException.class, () -> { + List list = Arrays.asList("zhangsan", "zhangsan"); + Mockito.doReturn(list).when(ldapClient).getDn(Mockito.any(LdapQuery.class)); + Assertions.assertTrue(ldapClient.doesUserExist("zhangsan")); + Assertions.fail("No Exception throws."); + }); } @Test public void testGetGroups() { List list = Arrays.asList("cn=groupName,ou=groups,dc=example,dc=com"); Mockito.doReturn(list).when(ldapClient).getDn(Mockito.any(LdapQuery.class)); - Assert.assertEquals(1, ldapClient.getGroups("zhangsan").size()); + Assertions.assertEquals(1, ldapClient.getGroups("zhangsan").size()); } @Test @@ -82,16 +84,14 @@ public void testSecuredProtocolIsUsed() { String insecureUrl = LdapConfig.getConnectionURL( NetUtils.getHostPortInAccessibleFormat(LdapConfig.ldap_host, LdapConfig.ldap_port)); - Assert.assertNotNull("connection URL should not be null", insecureUrl); - Assert.assertTrue("with ldap_use_ssl = false or not specified URL should start with ldap, but received: " + insecureUrl, - insecureUrl.startsWith("ldap://")); + Assertions.assertNotNull(insecureUrl, "connection URL should not be null"); + Assertions.assertTrue(insecureUrl.startsWith("ldap://"), "with ldap_use_ssl = false or not specified URL should start with ldap, but received: " + insecureUrl); LdapConfig.ldap_use_ssl = true; String secureUrl = LdapConfig.getConnectionURL( NetUtils.getHostPortInAccessibleFormat(LdapConfig.ldap_host, LdapConfig.ldap_port)); - Assert.assertNotNull("connection URL should not be null", secureUrl); - Assert.assertTrue("with ldap_use_ssl = true URL should start with ldaps, but received: " + secureUrl, - secureUrl.startsWith("ldaps://")); + Assertions.assertNotNull(secureUrl, "connection URL should not be null"); + Assertions.assertTrue(secureUrl.startsWith("ldaps://"), "with ldap_use_ssl = true URL should start with ldaps, but received: " + secureUrl); } @Test @@ -99,31 +99,31 @@ public void testLdapFilterEncoding() { // Combined special characters String input = "test*()\\\u0000"; String expected = "test\\2a\\28\\29\\5c\\00"; - Assert.assertEquals(expected, LdapEncoder.filterEncode(input)); + Assertions.assertEquals(expected, LdapEncoder.filterEncode(input)); // Null input - Assert.assertNull(LdapEncoder.filterEncode(null)); + Assertions.assertNull(LdapEncoder.filterEncode(null)); // Normal username should not be altered - Assert.assertEquals("zhangsan", LdapEncoder.filterEncode("zhangsan")); - Assert.assertEquals("user.name@example.com", LdapEncoder.filterEncode("user.name@example.com")); + Assertions.assertEquals("zhangsan", LdapEncoder.filterEncode("zhangsan")); + Assertions.assertEquals("user.name@example.com", LdapEncoder.filterEncode("user.name@example.com")); // Empty string - Assert.assertEquals("", LdapEncoder.filterEncode("")); + Assertions.assertEquals("", LdapEncoder.filterEncode("")); // Each special character individually - Assert.assertEquals("\\2a", LdapEncoder.filterEncode("*")); - Assert.assertEquals("\\28", LdapEncoder.filterEncode("(")); - Assert.assertEquals("\\29", LdapEncoder.filterEncode(")")); - Assert.assertEquals("\\5c", LdapEncoder.filterEncode("\\")); - Assert.assertEquals("\\00", LdapEncoder.filterEncode("\u0000")); + Assertions.assertEquals("\\2a", LdapEncoder.filterEncode("*")); + Assertions.assertEquals("\\28", LdapEncoder.filterEncode("(")); + Assertions.assertEquals("\\29", LdapEncoder.filterEncode(")")); + Assertions.assertEquals("\\5c", LdapEncoder.filterEncode("\\")); + Assertions.assertEquals("\\00", LdapEncoder.filterEncode("\u0000")); // Injection payload: dorisuser6)(mail=testp* - Assert.assertEquals("dorisuser6\\29\\28mail=testp\\2a", + Assertions.assertEquals("dorisuser6\\29\\28mail=testp\\2a", LdapEncoder.filterEncode("dorisuser6)(mail=testp*")); } - @After + @AfterEach public void tearDown() { LdapConfig.ldap_use_ssl = false; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapManagerTest.java index afe9d034b57edf..440e0dd10d76d8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapManagerTest.java @@ -24,10 +24,10 @@ import org.apache.doris.mysql.privilege.Auth; import org.apache.doris.mysql.privilege.Role; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -44,13 +44,13 @@ public class LdapManagerTest { private LdapClient ldapClient = Mockito.mock(LdapClient.class); - @Before + @BeforeEach public void setUp() { Config.authentication_type = "ldap"; LdapConfig.ldap_default_roles = new String[0]; } - @After + @AfterEach public void tearDown() { LdapConfig.ldap_allow_empty_pass = false; } @@ -90,13 +90,13 @@ public void testGetUserInfo() { Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); + Assertions.assertNotNull(ldapUserInfo); String paloRoleString = ldapUserInfo.getRoles().toString(); - Assert.assertTrue(paloRoleString.contains("information_schema")); - Assert.assertTrue(paloRoleString.contains("Select_priv")); + Assertions.assertTrue(paloRoleString.contains("information_schema")); + Assertions.assertTrue(paloRoleString.contains("Select_priv")); mockClient(false, false); - Assert.assertNull(ldapManager.getUserInfo(USER2)); + Assertions.assertNull(ldapManager.getUserInfo(USER2)); } @Test @@ -104,14 +104,14 @@ public void testCheckUserPasswd() { LdapManager ldapManager = new LdapManager(); Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); - Assert.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); + Assertions.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertTrue(ldapUserInfo.isSetPasswd()); - Assert.assertEquals("123", ldapUserInfo.getPasswd()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertTrue(ldapUserInfo.isSetPasswd()); + Assertions.assertEquals("123", ldapUserInfo.getPasswd()); mockClient(true, false); - Assert.assertFalse(ldapManager.checkUserPasswd(USER2, "123")); + Assertions.assertFalse(ldapManager.checkUserPasswd(USER2, "123")); } @Test @@ -121,11 +121,11 @@ public void testCheckUserEmptyPasswdAllowed() throws Exception { LdapManager ldapManager = new LdapManager(); Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); - Assert.assertTrue(ldapManager.checkUserPasswd(USER1, "")); + Assertions.assertTrue(ldapManager.checkUserPasswd(USER1, "")); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertTrue(ldapUserInfo.isSetPasswd()); - Assert.assertEquals("", ldapUserInfo.getPasswd()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertTrue(ldapUserInfo.isSetPasswd()); + Assertions.assertEquals("", ldapUserInfo.getPasswd()); } @Test @@ -136,13 +136,13 @@ public void testCheckUserEmptyPasswdDisabled() throws Exception { LdapManager ldapManager = new LdapManager(); Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); - Assert.assertFalse(ldapManager.checkUserPasswd(USER1, "")); + Assertions.assertFalse(ldapManager.checkUserPasswd(USER1, "")); - Assert.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); + Assertions.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertTrue(ldapUserInfo.isSetPasswd()); - Assert.assertEquals("123", ldapUserInfo.getPasswd()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertTrue(ldapUserInfo.isSetPasswd()); + Assertions.assertEquals("123", ldapUserInfo.getPasswd()); } @Test @@ -152,14 +152,14 @@ public void testCachedEmptyPasswordIsRejectedAfterFlagDisabled() { Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); //empty password succeeds and gets cached while the flag is still enabled. - Assert.assertTrue(ldapManager.checkUserPasswd(USER1, "")); - Assert.assertEquals("", ldapManager.getUserInfo(USER1).getPasswd()); + Assertions.assertTrue(ldapManager.checkUserPasswd(USER1, "")); + Assertions.assertEquals("", ldapManager.getUserInfo(USER1).getPasswd()); //once disabled, the cached entry must not short-circuit the new check LdapConfig.ldap_allow_empty_pass = false; - Assert.assertFalse(ldapManager.checkUserPasswd(USER1, "")); + Assertions.assertFalse(ldapManager.checkUserPasswd(USER1, "")); //a non-empty password still authenticates against the same cached entry - Assert.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); + Assertions.assertTrue(ldapManager.checkUserPasswd(USER1, "123")); } @Test @@ -171,7 +171,7 @@ public void testEmptyPasswordIsRejectedBeforeCacheLookup() throws Exception { mockClient(true, true); LdapManager spyManager = Mockito.spy(ldapManager); - Assert.assertFalse(spyManager.checkUserPasswd(USER1, "")); + Assertions.assertFalse(spyManager.checkUserPasswd(USER1, "")); Mockito.verify(spyManager, Mockito.times(0)).getUserInfo(USER1); } @@ -182,7 +182,7 @@ public void testCheckUserNullPasswd() throws Exception { LdapManager ldapManager = new LdapManager(); Deencapsulation.setField(ldapManager, "ldapClient", ldapClient); mockClient(true, true); - Assert.assertFalse(ldapManager.checkUserPasswd(USER1, null)); + Assertions.assertFalse(ldapManager.checkUserPasswd(USER1, null)); } @Test @@ -197,10 +197,10 @@ public void testGetUserInfoWithLdapDefaultRolesWithoutLdapGroups() { mockAuth(envMockedStatic, ldapGroupRole, ldapDefaultRole); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertFalse(ldapUserInfo.getRoles().contains(ldapGroupRole)); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); - Assert.assertEquals(2, ldapUserInfo.getRoles().size()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertFalse(ldapUserInfo.getRoles().contains(ldapGroupRole)); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); + Assertions.assertEquals(2, ldapUserInfo.getRoles().size()); } } @@ -216,10 +216,10 @@ public void testGetUserInfoWithLdapDefaultRolesWhenLdapGroupRoleMissing() { mockAuth(envMockedStatic, ldapGroupRole, ldapDefaultRole, false); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertFalse(ldapUserInfo.getRoles().contains(ldapGroupRole)); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); - Assert.assertEquals(2, ldapUserInfo.getRoles().size()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertFalse(ldapUserInfo.getRoles().contains(ldapGroupRole)); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); + Assertions.assertEquals(2, ldapUserInfo.getRoles().size()); } } @@ -235,10 +235,10 @@ public void testGetUserInfoWithBlankLdapDefaultRoles() { mockAuth(envMockedStatic, ldapGroupRole, ldapDefaultRole); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapGroupRole)); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); - Assert.assertEquals(3, ldapUserInfo.getRoles().size()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapGroupRole)); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); + Assertions.assertEquals(3, ldapUserInfo.getRoles().size()); } } @@ -254,10 +254,10 @@ public void testGetUserInfoWithLdapDefaultRoles() { mockAuth(envMockedStatic, ldapGroupRole, ldapDefaultRole); LdapUserInfo ldapUserInfo = ldapManager.getUserInfo(USER1); - Assert.assertNotNull(ldapUserInfo); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapGroupRole)); - Assert.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); - Assert.assertEquals(3, ldapUserInfo.getRoles().size()); + Assertions.assertNotNull(ldapUserInfo); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapGroupRole)); + Assertions.assertTrue(ldapUserInfo.getRoles().contains(ldapDefaultRole)); + Assertions.assertEquals(3, ldapUserInfo.getRoles().size()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapUserInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapUserInfoTest.java index 24630a3f1cfcae..ee125789a7fe48 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapUserInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/authenticate/ldap/LdapUserInfoTest.java @@ -17,14 +17,14 @@ package org.apache.doris.mysql.authenticate.ldap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class LdapUserInfoTest { @Test public void testNonExistUserRoles() { LdapUserInfo u1 = new LdapUserInfo("u1"); - Assert.assertFalse(u1.getRoles() == null); + Assertions.assertFalse(u1.getRoles() == null); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AccessControllerManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AccessControllerManagerTest.java index a6b2514b43aa45..6428a8b20c0614 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AccessControllerManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AccessControllerManagerTest.java @@ -26,10 +26,10 @@ import org.apache.doris.datasource.ExternalCatalog; import com.google.common.collect.ImmutableMap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -40,12 +40,12 @@ public class AccessControllerManagerTest { private boolean originalSkipCatalogPrivCheck; - @Before + @BeforeEach public void setUp() { originalSkipCatalogPrivCheck = Config.skip_catalog_priv_check; } - @After + @AfterEach public void tearDown() { Config.skip_catalog_priv_check = originalSkipCatalogPrivCheck; } @@ -70,7 +70,7 @@ public void testCheckCtlPrivSkipCatalogPrivCheckWithCustomAccessControllerForSel Mockito.when(catalog.getProperties()).thenReturn( ImmutableMap.of(CatalogMgr.ACCESS_CONTROLLER_CLASS_PROP, "mock.access.controller")); - Assert.assertTrue(accessControllerManager.checkCtlPriv( + Assertions.assertTrue(accessControllerManager.checkCtlPriv( userIdentity, "custom_catalog", PrivPredicate.SELECT)); } } @@ -95,7 +95,7 @@ public void testCheckCtlPrivSkipCatalogPrivCheckWithCustomAccessControllerForSho Mockito.when(catalog.getProperties()).thenReturn( ImmutableMap.of(CatalogMgr.ACCESS_CONTROLLER_CLASS_PROP, "mock.access.controller")); - Assert.assertTrue(accessControllerManager.checkCtlPriv( + Assertions.assertTrue(accessControllerManager.checkCtlPriv( userIdentity, "custom_catalog", PrivPredicate.SHOW)); } } @@ -121,7 +121,7 @@ public void testCheckCtlPrivSkipCatalogPrivCheckWithoutCustomAccessController() Mockito.when(catalog.isInternalCatalog()).thenReturn(false); Mockito.when(catalog.getProperties()).thenReturn(ImmutableMap.of("type", "test")); - Assert.assertFalse(accessControllerManager.checkCtlPriv( + Assertions.assertFalse(accessControllerManager.checkCtlPriv( userIdentity, "custom_catalog", PrivPredicate.SELECT)); } } @@ -144,7 +144,7 @@ public void testCheckCtlPrivCreateMustCheckDefaultAccessController() { Mockito.when(env.getCatalogMgr()).thenReturn(catalogMgr); Mockito.when(catalogMgr.getCatalog("not_exist_catalog")).thenReturn(null); - Assert.assertTrue(accessControllerManager.checkCtlPriv( + Assertions.assertTrue(accessControllerManager.checkCtlPriv( userIdentity, "not_exist_catalog", PrivPredicate.CREATE)); } } @@ -171,7 +171,7 @@ public void testCheckCtlPrivLoadMustCheckDefaultAccessController() { Mockito.when(catalog.getProperties()).thenReturn( ImmutableMap.of(CatalogMgr.ACCESS_CONTROLLER_CLASS_PROP, "mock.access.controller")); - Assert.assertFalse(accessControllerManager.checkCtlPriv( + Assertions.assertFalse(accessControllerManager.checkCtlPriv( userIdentity, "custom_catalog", PrivPredicate.LOAD)); } } @@ -192,7 +192,7 @@ public void testCheckCtlPrivSkipCatalogPrivCheckWhenCatalogNotExist() { Mockito.when(env.getCatalogMgr()).thenReturn(catalogMgr); Mockito.when(catalogMgr.getCatalog("not_exist_catalog")).thenReturn(null); - Assert.assertFalse(accessControllerManager.checkCtlPriv( + Assertions.assertFalse(accessControllerManager.checkCtlPriv( userIdentity, "not_exist_catalog", PrivPredicate.SELECT)); } } @@ -213,7 +213,7 @@ public void testDryRunClosesTemporaryAccessController() { catalog, "test-controller", ImmutableMap.of(), true); Mockito.verify(temporaryAccessController).close(); - Assert.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); + Assertions.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); } @Test @@ -233,7 +233,7 @@ public void testRemoveClosesRegisteredAccessController() { accessControllerManager.removeAccessController("test_catalog", catalog.getId()); Mockito.verify(registeredAccessController).close(); - Assert.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); + Assertions.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); } @Test @@ -254,7 +254,7 @@ public void testRemoveContinuesWhenAccessControllerCloseFails() { accessControllerManager.removeAccessController("test_catalog", catalog.getId()); Mockito.verify(registeredAccessController).close(); - Assert.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); + Assertions.assertFalse(accessControllerManager.checkIfAccessControllerExist("test_catalog")); } @Test @@ -284,7 +284,7 @@ public void testOldGenerationCannotRemoveReplacementController() { manager.createAccessController(newCatalog, "test-controller", ImmutableMap.of(), false); manager.removeAccessController("same_name", oldCatalog.getId()); - Assert.assertSame(newController, manager.getAccessControllerOrDefault("same_name")); + Assertions.assertSame(newController, manager.getAccessControllerOrDefault("same_name")); } Mockito.verify(oldController).close(); @@ -314,7 +314,7 @@ public void testControllerPublishedAfterDropIsClosedInsteadOfCached() { } Mockito.verify(orphanController).close(); - Assert.assertFalse(manager.checkIfAccessControllerExist("dropped")); + Assertions.assertFalse(manager.checkIfAccessControllerExist("dropped")); } @Test @@ -330,7 +330,7 @@ public void testRemovingFallbackAliasDoesNotCloseSharedDefaultController() { Mockito.when(env.getCatalogMgr()).thenReturn(catalogMgr); Mockito.when(catalogMgr.getCatalog("fallback")).thenReturn(catalog); - Assert.assertSame(defaultAccessController, manager.getAccessControllerOrDefault("fallback")); + Assertions.assertSame(defaultAccessController, manager.getAccessControllerOrDefault("fallback")); manager.removeAccessController("fallback", catalog.getId()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AuthTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AuthTest.java index cce4e9ef257ef7..993973a905d8f3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AuthTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/AuthTest.java @@ -24,7 +24,7 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.utframe.TestWithFeService; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; @@ -49,7 +49,7 @@ public void testMergeRolePriv() throws Exception { .checkDbPriv(UserIdentity.createAnalyzedUserIdentWithIp("u1", "%"), InternalCatalog.INTERNAL_CATALOG_NAME, "test", PrivPredicate.of(PrivBitSet.of(Privilege.GRANT_PRIV, Privilege.LOAD_PRIV), Operator.AND)); - Assert.assertTrue(hasPriv); + Assertions.assertTrue(hasPriv); } @Test @@ -61,9 +61,9 @@ public void testGetRoleNamesByUserWithLdap() throws Exception { grantRole("GRANT 'role3','role4' TO 'u2'@'%'"); Set roleNames = Env.getCurrentEnv().getAuth() .getRoleNamesByUserWithLdap(new UserIdentity("u2", "%"), true); - Assert.assertEquals(3, roleNames.size()); + Assertions.assertEquals(3, roleNames.size()); roleNames = Env.getCurrentEnv().getAuth().getRoleNamesByUserWithLdap(new UserIdentity("u2", "%"), false); - Assert.assertEquals(2, roleNames.size()); + Assertions.assertEquals(2, roleNames.size()); } @Test @@ -72,7 +72,7 @@ public void testCheckDbPrivWithSessionMappedRoleForTempUser() throws Exception { grantPriv("GRANT SELECT_PRIV ON internal.test.* TO ROLE 'jit_role_auth_test';"); UserIdentity tempUserIdentity = UserIdentity.createAnalyzedUserIdentWithIp("jit_user", "%"); - Assert.assertFalse(Env.getCurrentEnv().getAuth().checkDbPriv(tempUserIdentity, + Assertions.assertFalse(Env.getCurrentEnv().getAuth().checkDbPriv(tempUserIdentity, InternalCatalog.INTERNAL_CATALOG_NAME, "test", PrivPredicate.SELECT)); ConnectContext ctx = new ConnectContext(); @@ -80,7 +80,7 @@ public void testCheckDbPrivWithSessionMappedRoleForTempUser() throws Exception { ctx.setThreadLocalInfo(); try { ctx.setAuthenticatedRoles(Collections.singleton("jit_role_auth_test")); - Assert.assertTrue(Env.getCurrentEnv().getAccessManager() + Assertions.assertTrue(Env.getCurrentEnv().getAccessManager() .checkDbPriv(ctx, InternalCatalog.INTERNAL_CATALOG_NAME, "test", PrivPredicate.SELECT)); } finally { ConnectContext.remove(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CatalogAccessControllerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CatalogAccessControllerTest.java index 163518b33a594c..262e0ddc1c2d00 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CatalogAccessControllerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CatalogAccessControllerTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; @@ -134,8 +134,8 @@ public void testCheckCtlPrivShortCircuitOnHasGlobal() { boolean result = controller.checkCtlPriv(true, user, "ctl", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertFalse(controller.ctlPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertFalse(controller.ctlPrivCalled.get()); } @Test @@ -145,8 +145,8 @@ public void testCheckCtlPrivFallsThroughWithoutHasGlobal() { boolean result = controller.checkCtlPriv(false, user, "ctl", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertTrue(controller.ctlPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertTrue(controller.ctlPrivCalled.get()); } @Test @@ -156,8 +156,8 @@ public void testCheckCtlPrivFallsThroughAndReturnsFalse() { boolean result = controller.checkCtlPriv(false, user, "ctl", PrivPredicate.SELECT); - Assert.assertFalse(result); - Assert.assertTrue(controller.ctlPrivCalled.get()); + Assertions.assertFalse(result); + Assertions.assertTrue(controller.ctlPrivCalled.get()); } @Test @@ -167,8 +167,8 @@ public void testCheckDbPrivShortCircuitOnHasGlobal() { boolean result = controller.checkDbPriv(true, user, "ctl", "db", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertFalse(controller.dbPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertFalse(controller.dbPrivCalled.get()); } @Test @@ -178,8 +178,8 @@ public void testCheckDbPrivFallsThroughWithoutHasGlobal() { boolean result = controller.checkDbPriv(false, user, "ctl", "db", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertTrue(controller.dbPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertTrue(controller.dbPrivCalled.get()); } @Test @@ -189,8 +189,8 @@ public void testCheckDbPrivFallsThroughAndReturnsFalse() { boolean result = controller.checkDbPriv(false, user, "ctl", "db", PrivPredicate.SELECT); - Assert.assertFalse(result); - Assert.assertTrue(controller.dbPrivCalled.get()); + Assertions.assertFalse(result); + Assertions.assertTrue(controller.dbPrivCalled.get()); } @Test @@ -200,8 +200,8 @@ public void testCheckTblPrivShortCircuitOnHasGlobal() { boolean result = controller.checkTblPriv(true, user, "ctl", "db", "tbl", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertFalse(controller.tblPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertFalse(controller.tblPrivCalled.get()); } @Test @@ -211,8 +211,8 @@ public void testCheckTblPrivFallsThroughWithoutHasGlobal() { boolean result = controller.checkTblPriv(false, user, "ctl", "db", "tbl", PrivPredicate.SELECT); - Assert.assertTrue(result); - Assert.assertTrue(controller.tblPrivCalled.get()); + Assertions.assertTrue(result); + Assertions.assertTrue(controller.tblPrivCalled.get()); } @Test @@ -222,8 +222,8 @@ public void testCheckTblPrivFallsThroughAndReturnsFalse() { boolean result = controller.checkTblPriv(false, user, "ctl", "db", "tbl", PrivPredicate.SELECT); - Assert.assertFalse(result); - Assert.assertTrue(controller.tblPrivCalled.get()); + Assertions.assertFalse(result); + Assertions.assertTrue(controller.tblPrivCalled.get()); } @Test @@ -233,7 +233,7 @@ public void testCheckColsPrivShortCircuitOnHasGlobal() throws AuthorizationExcep controller.checkColsPriv(true, user, "ctl", "db", "tbl", ImmutableSet.of("col1"), PrivPredicate.SELECT); - Assert.assertFalse(controller.colsPrivCalled.get()); + Assertions.assertFalse(controller.colsPrivCalled.get()); } @Test @@ -243,7 +243,7 @@ public void testCheckColsPrivFallsThroughWithoutHasGlobal() throws Authorization controller.checkColsPriv(false, user, "ctl", "db", "tbl", ImmutableSet.of("col1"), PrivPredicate.SELECT); - Assert.assertTrue(controller.colsPrivCalled.get()); + Assertions.assertTrue(controller.colsPrivCalled.get()); } @Test @@ -251,8 +251,8 @@ public void testCheckColsPrivFallsThroughAndThrows() { StubAccessController controller = new StubAccessController(false, false, false, false); UserIdentity user = UserIdentity.createAnalyzedUserIdentWithIp("test_user", "%"); - Assert.assertThrows(AuthorizationException.class, () -> + Assertions.assertThrows(AuthorizationException.class, () -> controller.checkColsPriv(false, user, "ctl", "db", "tbl", ImmutableSet.of("col1"), PrivPredicate.SELECT)); - Assert.assertTrue(controller.colsPrivCalled.get()); + Assertions.assertTrue(controller.colsPrivCalled.get()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CloudAuthTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CloudAuthTest.java index 1c8d739aeac2d1..dcee2af9769b8c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CloudAuthTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CloudAuthTest.java @@ -43,21 +43,33 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.qe.QueryState; import org.apache.doris.qe.ShowResultSet; -import org.apache.doris.utframe.TestWithFeService; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import java.util.List; import java.util.Optional; -public class CloudAuthTest extends TestWithFeService { +/* + * NOTE ON THE MISSING `extends TestWithFeService`. + * + * This class used to extend it, but it never used it: TestWithFeService drives its setup from + * JUnit 5 annotations, this class ran on JUnit 4, and the JUnit 4 engine does not see them - so + * the base class never started a cluster and the inherited `connectContext` field stayed null. + * Every command below has therefore always been handed a null context, and that is deliberate + * here: the tests mock Env and ConnectContext statically, which is incompatible with the real FE + * the base class would otherwise bring up. Moving the class to JUnit 5 would have activated that + * setup for the first time, so the vestigial inheritance is dropped instead. + */ +public class CloudAuthTest { + + /** See the class comment: the commands under test read ConnectContext.get(), not this. */ + private static final ConnectContext connectContext = null; private Auth auth; private AccessControllerManager accessManager; @@ -68,7 +80,7 @@ public class CloudAuthTest extends TestWithFeService { private MockedStatic mockedEnvStatic; private MockedStatic mockedCtxStatic; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException { auth = new Auth(); accessManager = new AccessControllerManager(auth); @@ -88,7 +100,7 @@ public void setUp() throws NoSuchMethodException, SecurityException { mockedEnvStatic.when(Env::getCurrentSystemInfo).thenReturn(systemInfoService); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); mockedCtxStatic.close(); @@ -112,7 +124,7 @@ public void testComputeGroup() throws Exception { auth.createUser(createUserInfo); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // 2. grant usage_priv on cluster 'cg1' to 'testUser'@'%' GrantResourcePrivilegeCommand grantResourcePrivilegeCommand = new GrantResourcePrivilegeCommand(usagePrivileges, @@ -122,11 +134,11 @@ public void testComputeGroup() throws Exception { auth.grantResourcePrivilegeCommand(grantResourcePrivilegeCommand); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } - Assert.assertTrue(accessManager.checkCloudPriv(userIdentity, computeGroup1, + Assertions.assertTrue(accessManager.checkCloudPriv(userIdentity, computeGroup1, PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); // 3. revoke usage_priv on cluster 'cg1' from 'testUser'@'%' RevokeResourcePrivilegeCommand revokeResourcePrivilegeCommand = new RevokeResourcePrivilegeCommand(usagePrivileges, @@ -136,11 +148,11 @@ public void testComputeGroup() throws Exception { auth.revokeResourcePrivilegeCommand(revokeResourcePrivilegeCommand); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } - Assert.assertFalse(accessManager.checkCloudPriv(userIdentity, computeGroup1, + Assertions.assertFalse(accessManager.checkCloudPriv(userIdentity, computeGroup1, PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); // 3.1 grant 'notBelongToResourcePrivileges' on cluster 'cg1' to 'testUser'@'%' for (int i = 0; i < Privilege.notBelongToResourcePrivileges.length; i++) { List notAllowedPrivileges = Lists @@ -150,7 +162,7 @@ public void testComputeGroup() throws Exception { Optional.of(resourcePattern), Optional.empty(), Optional.of(""), Optional.of(userIdentity)); try { grantResourcePrivilegeCommand.validate(); - Assert.fail(String.format("Can not grant/revoke %s to/from any other users or roles", + Assertions.fail(String.format("Can not grant/revoke %s to/from any other users or roles", Privilege.notBelongToWorkloadGroupPrivileges[i])); } catch (AnalysisException e) { e.printStackTrace(); @@ -162,7 +174,7 @@ public void testComputeGroup() throws Exception { dropUserCommand.doRun(connectContext, null); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // ------ grant|revoke cluster to|from role ------ @@ -184,9 +196,9 @@ public void testComputeGroup() throws Exception { Assertions.assertDoesNotThrow(() -> info2.validate()); Assertions.assertEquals(new String(info2.getRole()), "role1"); Env.getCurrentEnv().getAuth().createUser(createUserCommand1.getInfo()); - Assert.assertTrue(accessManager.checkCloudPriv(userWithRole, "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(userWithRole, "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkGlobalPriv(userWithRole, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userWithRole, PrivPredicate.USAGE)); // 3. revoke usage_priv on cluster 'cg1' from role 'role1' String revokeSql = "REVOKE USAGE_PRIV ON CLUSTER 'cg1' FROM ROLE 'role1';"; @@ -194,8 +206,8 @@ public void testComputeGroup() throws Exception { Assertions.assertTrue(revokeplan1 instanceof RevokeResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((RevokeResourcePrivilegeCommand) revokeplan1).run(connectContext, null)); // also revoke from user with this role - Assert.assertFalse(accessManager.checkResourcePriv(userWithRole, "cg1", PrivPredicate.USAGE)); - Assert.assertFalse(accessManager.checkGlobalPriv(userWithRole, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkResourcePriv(userWithRole, "cg1", PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userWithRole, PrivPredicate.USAGE)); // 4. drop user and role String dropUserSql = "DROP USER test_user1"; @@ -221,23 +233,23 @@ public void testComputeGroup() throws Exception { LogicalPlan grantAnyPlan1 = nereidsParser.parseSingle(grantAnyCgUser); Assertions.assertTrue(grantAnyPlan1 instanceof GrantResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((GrantResourcePrivilegeCommand) grantAnyPlan1).run(connectContext, null)); - Assert.assertTrue(accessManager.checkCloudPriv(userIdentity, "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(userIdentity, "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // anyResource not belong to global auth - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW_RESOURCES)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW_RESOURCES)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW)); // 3. revoke usage_priv on cluster '*' from 'testUser'@'%' String revokeAnyCgUser = "revoke usage_priv on cluster '*' from 'testUser'@'%'"; LogicalPlan revokeAnyPlan1 = nereidsParser.parseSingle(revokeAnyCgUser); Assertions.assertTrue(revokeAnyPlan1 instanceof RevokeResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> (RevokeResourcePrivilegeCommand) revokeAnyPlan1).run(connectContext, null); - Assert.assertFalse(accessManager.checkCloudPriv(userIdentity, "cg1", + Assertions.assertFalse(accessManager.checkCloudPriv(userIdentity, "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW_RESOURCES)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW_RESOURCES)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.SHOW)); // 4. drop user String dropUserSql1 = "DROP USER testUser"; @@ -263,9 +275,9 @@ public void testComputeGroup() throws Exception { Assertions.assertTrue(createUserPlan3 instanceof CreateUserCommand); Assertions.assertDoesNotThrow(() -> ((CreateUserCommand) createUserPlan3).run(connectContext, null)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser3", "%"), computeGroup1, + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser3", "%"), computeGroup1, PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkGlobalPriv(new UserIdentity("testUser3", "%"), PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(new UserIdentity("testUser3", "%"), PrivPredicate.USAGE)); // 3. revoke usage_priv on cluster '*' from role 'role1' String revokeCgRoleSql = "revoke usage_priv on cluster '*' from role 'role1'"; @@ -274,8 +286,8 @@ public void testComputeGroup() throws Exception { Assertions.assertDoesNotThrow(() -> ((RevokeResourcePrivilegeCommand) revokeCgRolePlan).run(connectContext, null)); // also revoke from user with this role - Assert.assertFalse(accessManager.checkResourcePriv(userIdentity, computeGroup1, PrivPredicate.USAGE)); - Assert.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkResourcePriv(userIdentity, computeGroup1, PrivPredicate.USAGE)); + Assertions.assertFalse(accessManager.checkGlobalPriv(userIdentity, PrivPredicate.USAGE)); // 4. drop user and role String dropUserSql2 = "DROP USER testUser3"; @@ -333,7 +345,7 @@ public void testVirtualComputeGroup() throws Exception { LogicalPlan grantAnyPlan1 = nereidsParser.parseSingle(grantVcgUser); Assertions.assertTrue(grantAnyPlan1 instanceof GrantResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((GrantResourcePrivilegeCommand) grantAnyPlan1).run(connectContext, null)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // create vcg, sub cg(cg1, cg2), add to systemInfoService CloudComputeGroupMeta vcg = new CloudComputeGroupMeta("vcg_id", "vcg", CloudComputeGroupMeta.ComputeTypeEnum.VIRTUAL); @@ -346,22 +358,22 @@ public void testVirtualComputeGroup() throws Exception { policy.setStandbyComputeGroup("cg2"); vcg.setPolicy(policy); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // testUser has vcg, but not have cg1,cg2, he can use cg1,cg2 - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); ShowGrantsCommand sg = new ShowGrantsCommand(new UserIdentity("testUser", "%"), false); ShowResultSet showResultSet = sg.doRun(connectContext, null); // cluster field - Assert.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(11)); + Assertions.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(11)); // compute group field - Assert.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(15)); + Assertions.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(15)); // -------------------- case 2 ------------------------- // grant usage_priv on cluster 'cg1' to 'testUser'@'%' @@ -369,18 +381,18 @@ public void testVirtualComputeGroup() throws Exception { LogicalPlan grantAnyPlan2 = nereidsParser.parseSingle(grantVcgUser2); Assertions.assertTrue(grantAnyPlan2 instanceof GrantResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((GrantResourcePrivilegeCommand) grantAnyPlan2).run(connectContext, null)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // testUser can use cg1, because he has vcg,cg1 auth - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); showResultSet = sg.doRun(connectContext, null); // cluster field - Assert.assertEquals("cg1: Cluster_usage_priv; vcg: Cluster_usage_priv", + Assertions.assertEquals("cg1: Cluster_usage_priv; vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(11)); // compute group field - Assert.assertEquals("cg1: Cluster_usage_priv; vcg: Cluster_usage_priv", + Assertions.assertEquals("cg1: Cluster_usage_priv; vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(15)); // revoke cg1 from test user @@ -390,14 +402,14 @@ public void testVirtualComputeGroup() throws Exception { Assertions.assertDoesNotThrow(() -> ((RevokeResourcePrivilegeCommand) revokeplan1).run(connectContext, null)); // testUser can use cg1, because he has vcg auth - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); showResultSet = sg.doRun(connectContext, null); // cluster field - Assert.assertEquals("vcg: Cluster_usage_priv", + Assertions.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(11)); // compute group field - Assert.assertEquals("vcg: Cluster_usage_priv", + Assertions.assertEquals("vcg: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(15)); // grant cg2 to user @@ -405,7 +417,7 @@ public void testVirtualComputeGroup() throws Exception { LogicalPlan grantAnyPlan3 = nereidsParser.parseSingle(grantVcgUser3); Assertions.assertTrue(grantAnyPlan3 instanceof GrantResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((GrantResourcePrivilegeCommand) grantAnyPlan3).run(connectContext, null)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // revoke vcg from test user @@ -415,20 +427,20 @@ public void testVirtualComputeGroup() throws Exception { Assertions.assertDoesNotThrow(() -> ((RevokeResourcePrivilegeCommand) revokeplan2).run(connectContext, null)); // currently, user has cg2 auth, not have vcg auth - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // testUser has cg2, but not have vcg, he can use cg2, can't use cg1, vcg - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", + Assertions.assertTrue(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); showResultSet = sg.doRun(connectContext, null); // cluster field - Assert.assertEquals("cg2: Cluster_usage_priv", + Assertions.assertEquals("cg2: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(11)); // compute group field - Assert.assertEquals("cg2: Cluster_usage_priv", + Assertions.assertEquals("cg2: Cluster_usage_priv", showResultSet.getResultRows().get(0).get(15)); // revoke cg2 from user @@ -443,19 +455,19 @@ public void testVirtualComputeGroup() throws Exception { Assertions.assertTrue(revokeplan4 instanceof RevokeResourcePrivilegeCommand); Assertions.assertDoesNotThrow(() -> ((RevokeResourcePrivilegeCommand) revokeplan4).run(connectContext, null)); - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "vcg", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); // testUser after revoke vcg, not have cg1,cg2, it should can use, vcg,cg1,cg2 - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg1", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); - Assert.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", + Assertions.assertFalse(accessManager.checkCloudPriv(new UserIdentity("testUser", "%"), "cg2", PrivPredicate.USAGE, ResourceTypeEnum.CLUSTER)); showResultSet = sg.doRun(connectContext, null); // cluster field - Assert.assertEquals("\\N", showResultSet.getResultRows().get(0).get(11)); + Assertions.assertEquals("\\N", showResultSet.getResultRows().get(0).get(11)); // compute group field - Assert.assertEquals("\\N", showResultSet.getResultRows().get(0).get(15)); + Assertions.assertEquals("\\N", showResultSet.getResultRows().get(0).get(15)); // drop user String dropUserSql5 = "DROP USER testUser"; diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CommonUserPropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CommonUserPropertiesTest.java index dcaab9c2ac436b..c79d27da62a009 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CommonUserPropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/CommonUserPropertiesTest.java @@ -20,8 +20,8 @@ import org.apache.doris.persist.gson.GsonUtils; import org.apache.doris.resource.Tag; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; @@ -34,7 +34,7 @@ public void testDeserializeResourceTagsFromAllFieldNames() { String json = String.format("{\"%s\":%s}", fieldName, RESOURCE_TAG_JSON); CommonUserProperties properties = GsonUtils.GSON.fromJson(json, CommonUserProperties.class); - Assert.assertEquals(Collections.singleton(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_a")), + Assertions.assertEquals(Collections.singleton(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_a")), properties.getResourceTags()); } } @@ -45,8 +45,8 @@ public void testDeserializeSqlBlockRulesFromAllFieldNames() { String json = String.format("{\"%s\":\"rule_a, rule_b\"}", fieldName); CommonUserProperties properties = GsonUtils.GSON.fromJson(json, CommonUserProperties.class); - Assert.assertEquals("rule_a, rule_b", properties.getSqlBlockRules()); - Assert.assertArrayEquals(new String[] {"rule_a", "rule_b"}, properties.getSqlBlockRulesSplit()); + Assertions.assertEquals("rule_a, rule_b", properties.getSqlBlockRules()); + Assertions.assertArrayEquals(new String[] {"rule_a", "rule_b"}, properties.getSqlBlockRulesSplit()); } } @@ -68,19 +68,19 @@ public void testDeserializeLegacyCommonUserProperties() { + "}"; CommonUserProperties properties = GsonUtils.GSON.fromJson(json, CommonUserProperties.class); - Assert.assertEquals(101L, properties.getMaxConn()); - Assert.assertEquals(102L, properties.getMaxQueryInstances()); - Assert.assertEquals(103, properties.getParallelFragmentExecInstanceNum()); - Assert.assertEquals("rule_a, rule_b", properties.getSqlBlockRules()); - Assert.assertArrayEquals(new String[] {"rule_a", "rule_b"}, properties.getSqlBlockRulesSplit()); - Assert.assertEquals(104, properties.getCpuResourceLimit()); - Assert.assertEquals(Collections.singleton(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_a")), + Assertions.assertEquals(101L, properties.getMaxConn()); + Assertions.assertEquals(102L, properties.getMaxQueryInstances()); + Assertions.assertEquals(103, properties.getParallelFragmentExecInstanceNum()); + Assertions.assertEquals("rule_a, rule_b", properties.getSqlBlockRules()); + Assertions.assertArrayEquals(new String[] {"rule_a", "rule_b"}, properties.getSqlBlockRulesSplit()); + Assertions.assertEquals(104, properties.getCpuResourceLimit()); + Assertions.assertEquals(Collections.singleton(Tag.createNotCheck(Tag.TYPE_LOCATION, "group_a")), properties.getResourceTags()); - Assert.assertEquals(105L, properties.getExecMemLimit()); - Assert.assertEquals(106, properties.getQueryTimeout()); - Assert.assertEquals(107, properties.getInsertTimeout()); - Assert.assertEquals("legacy_group", properties.getWorkloadGroup()); - Assert.assertTrue(properties.getEnablePreferCachedRowset()); - Assert.assertEquals(108L, properties.getQueryFreshnessToleranceMs()); + Assertions.assertEquals(105L, properties.getExecMemLimit()); + Assertions.assertEquals(106, properties.getQueryTimeout()); + Assertions.assertEquals(107, properties.getInsertTimeout()); + Assertions.assertEquals("legacy_group", properties.getWorkloadGroup()); + Assertions.assertTrue(properties.getEnablePreferCachedRowset()); + Assertions.assertEquals(108L, properties.getQueryFreshnessToleranceMs()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PasswordPolicyTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PasswordPolicyTest.java index 942a098182bb79..692081bd41329f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PasswordPolicyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PasswordPolicyTest.java @@ -19,8 +19,8 @@ import org.apache.doris.mysql.privilege.PasswordPolicy.FailedLoginPolicy; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PasswordPolicyTest { @@ -31,11 +31,11 @@ public void testFailedLoginPolicyBasicLock() { policy.passwordLockSeconds = 60; // First 2 failures should not lock - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.onFailedLogin()); // 3rd failure should lock - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); } @Test @@ -45,25 +45,25 @@ public void testFailedLoginPolicyRelockAfterExpiry() { policy.passwordLockSeconds = 5; // Trigger first lock - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); // Simulate lock expiry by setting lockTime to the past policy.lockTime.set(System.currentTimeMillis() - 6000); - Assert.assertFalse(policy.isLocked()); + Assertions.assertFalse(policy.isLocked()); // Now trigger re-lock: counter should reset and start counting again // 1st failed login after expiry — counter resets from 3 to 0, then increments to 1 - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertFalse(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.isLocked()); // 2nd - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertFalse(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.isLocked()); // 3rd should lock again - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); } @Test @@ -73,13 +73,13 @@ public void testFailedLoginPolicyStillLockedWhileActive() { policy.passwordLockSeconds = 60; // Lock the account - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); // While still locked, onFailedLogin should still return true - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); } @Test @@ -89,35 +89,35 @@ public void testFailedLoginPolicyManualUnlock() { policy.passwordLockSeconds = 60; // Lock the account - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); // Manual unlock policy.unlock(); - Assert.assertFalse(policy.isLocked()); + Assertions.assertFalse(policy.isLocked()); // Should be able to re-lock - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertTrue(policy.onFailedLogin()); - Assert.assertTrue(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertTrue(policy.onFailedLogin()); + Assertions.assertTrue(policy.isLocked()); } @Test public void testFailedLoginPolicyDisabled() { FailedLoginPolicy policy = new FailedLoginPolicy(); // Both disabled by default (0) - Assert.assertFalse(policy.onFailedLogin()); - Assert.assertFalse(policy.isLocked()); + Assertions.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.isLocked()); // Only numFailedLogin set policy.numFailedLogin = 3; policy.passwordLockSeconds = 0; - Assert.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.onFailedLogin()); // Only passwordLockSeconds set policy.numFailedLogin = 0; policy.passwordLockSeconds = 60; - Assert.assertFalse(policy.onFailedLogin()); + Assertions.assertFalse(policy.onFailedLogin()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PrivEntryTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PrivEntryTest.java index e0821280d29327..a677a959fc0bd2 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PrivEntryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/PrivEntryTest.java @@ -17,8 +17,8 @@ package org.apache.doris.mysql.privilege; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PrivEntryTest { @Test @@ -47,15 +47,15 @@ public void testNameWithUnderscores() throws Exception { @Test public void testPrivBitSet() { PrivBitSet privBitSet = PrivBitSet.of(Privilege.ADMIN_PRIV, Privilege.NODE_PRIV); - Assert.assertTrue(privBitSet.containsPrivs(Privilege.ADMIN_PRIV)); - Assert.assertTrue(privBitSet.containsPrivs(Privilege.NODE_PRIV)); + Assertions.assertTrue(privBitSet.containsPrivs(Privilege.ADMIN_PRIV)); + Assertions.assertTrue(privBitSet.containsPrivs(Privilege.NODE_PRIV)); privBitSet.set(Privilege.DROP_PRIV.getIdx()); - Assert.assertTrue(privBitSet.containsPrivs(Privilege.DROP_PRIV)); + Assertions.assertTrue(privBitSet.containsPrivs(Privilege.DROP_PRIV)); privBitSet.set(Privilege.DROP_PRIV.getIdx()); - Assert.assertTrue(privBitSet.containsPrivs(Privilege.DROP_PRIV)); + Assertions.assertTrue(privBitSet.containsPrivs(Privilege.DROP_PRIV)); privBitSet.unset(Privilege.NODE_PRIV.getIdx()); - Assert.assertFalse(privBitSet.containsPrivs(Privilege.NODE_PRIV)); + Assertions.assertFalse(privBitSet.containsPrivs(Privilege.NODE_PRIV)); privBitSet.unset(Privilege.NODE_PRIV.getIdx()); - Assert.assertFalse(privBitSet.containsPrivs(Privilege.NODE_PRIV)); + Assertions.assertFalse(privBitSet.containsPrivs(Privilege.NODE_PRIV)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerDorisAccessControllerFactoryTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerDorisAccessControllerFactoryTest.java index 7029f8e4389f8e..4721e62513fbc0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerDorisAccessControllerFactoryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerDorisAccessControllerFactoryTest.java @@ -19,8 +19,8 @@ import org.apache.doris.catalog.authorizer.ranger.doris.RangerDorisAccessController; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.Mockito; @@ -36,8 +36,8 @@ public void testCreateAccessControllerReturnsSingleton() { RangerDorisAccessController second = new RangerDorisAccessControllerFactory() .createAccessController(Collections.emptyMap()); - Assert.assertEquals(1, mockedConstruction.constructed().size()); - Assert.assertSame(first, second); + Assertions.assertEquals(1, mockedConstruction.constructed().size()); + Assertions.assertSame(first, second); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerTest.java index e0e1dd36b2a4d6..79f62b433d20b8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/RangerTest.java @@ -31,8 +31,8 @@ import org.apache.ranger.plugin.policyengine.RangerAccessResult; import org.apache.ranger.plugin.policyengine.RangerAccessResultProcessor; import org.apache.ranger.plugin.service.RangerBasePlugin; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.List; @@ -129,15 +129,17 @@ private RangerAccessResult returnAccessResult( } // Does not have priv on ctl1.db1.tbl1.col3 - @Test(expected = AuthorizationException.class) + @Test public void testNoAuthCol() throws AuthorizationException { - DorisTestPlugin plugin = new DorisTestPlugin("test"); - RangerDorisAccessController ac = new RangerDorisAccessController(plugin); - UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); - Set cols = Sets.newHashSet(); - cols.add("col1"); - cols.add("col3"); - ac.checkColsPriv(ui, "ctl1", "db1", "tbl1", cols, PrivPredicate.SELECT); + Assertions.assertThrows(AuthorizationException.class, () -> { + DorisTestPlugin plugin = new DorisTestPlugin("test"); + RangerDorisAccessController ac = new RangerDorisAccessController(plugin); + UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); + Set cols = Sets.newHashSet(); + cols.add("col1"); + cols.add("col3"); + ac.checkColsPriv(ui, "ctl1", "db1", "tbl1", cols, PrivPredicate.SELECT); + }); } // Have priv on ctl1.db1.tbl1.col1 & col2 @@ -165,15 +167,17 @@ public void testUsingTableAuthAsColAuth() throws AuthorizationException { } // Does not have priv on ctl2.db2.tbl3, so when checking auth on col1 & col2, can not pass - @Test(expected = AuthorizationException.class) + @Test public void testUsingNoTableAuthAsColAuth() throws AuthorizationException { - DorisTestPlugin plugin = new DorisTestPlugin("test"); - RangerDorisAccessController ac = new RangerDorisAccessController(plugin); - UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); - Set cols = Sets.newHashSet(); - cols.add("col1"); - cols.add("col2"); - ac.checkColsPriv(ui, "ctl2", "db2", "tbl3", cols, PrivPredicate.SELECT); + Assertions.assertThrows(AuthorizationException.class, () -> { + DorisTestPlugin plugin = new DorisTestPlugin("test"); + RangerDorisAccessController ac = new RangerDorisAccessController(plugin); + UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); + Set cols = Sets.newHashSet(); + cols.add("col1"); + cols.add("col2"); + ac.checkColsPriv(ui, "ctl2", "db2", "tbl3", cols, PrivPredicate.SELECT); + }); } // Have priv on ctl3.db3, so when checking auth on tbl1 and (tbl1.col1 & tbl1.col2), can pass @@ -191,15 +195,17 @@ public void testUsingDbAuthAsColAndTableAuth() throws AuthorizationException { // Does not have priv on ctl2.db3, so when checking auth on col1 & col2, can not pass - @Test(expected = AuthorizationException.class) + @Test public void testNoDbAuthAsColAndTableAuth() throws AuthorizationException { - DorisTestPlugin plugin = new DorisTestPlugin("test"); - RangerDorisAccessController ac = new RangerDorisAccessController(plugin); - UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); - Set cols = Sets.newHashSet(); - cols.add("col1"); - cols.add("col2"); - ac.checkColsPriv(ui, "ctl2", "db3", "tbl3", cols, PrivPredicate.SELECT); + Assertions.assertThrows(AuthorizationException.class, () -> { + DorisTestPlugin plugin = new DorisTestPlugin("test"); + RangerDorisAccessController ac = new RangerDorisAccessController(plugin); + UserIdentity ui = UserIdentity.createAnalyzedUserIdentWithIp("user1", "%"); + Set cols = Sets.newHashSet(); + cols.add("col1"); + cols.add("col2"); + ac.checkColsPriv(ui, "ctl2", "db3", "tbl3", cols, PrivPredicate.SELECT); + }); } // Have priv on ctl4, so when checking auth on objs under ctl4, can pass diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/SetPasswordTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/SetPasswordTest.java index 746cde1510beb3..b2a87e960fa311 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/SetPasswordTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/SetPasswordTest.java @@ -30,10 +30,10 @@ import org.apache.doris.persist.EditLog; import org.apache.doris.qe.ConnectContext; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -45,7 +45,7 @@ public class SetPasswordTest { private MockedStatic mockedEnvStatic; private MockedStatic mockedMysqlPassword; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { auth = new Auth(); mockedEnvStatic = Mockito.mockStatic(Env.class); @@ -57,7 +57,7 @@ public void setUp() throws NoSuchMethodException, SecurityException, AnalysisExc mockedMysqlPassword.when(() -> MysqlPassword.checkPassword(Mockito.anyString())).thenReturn(new byte[10]); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); mockedMysqlPassword.close(); @@ -84,7 +84,7 @@ public void test() throws DdlException, AnalysisException { setPassVarOp.validate(ctx); } catch (UserException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // set password without for @@ -93,7 +93,7 @@ public void test() throws DdlException, AnalysisException { setPassVarOp2.validate(ctx); } catch (UserException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // create user cmy2@'192.168.1.1' @@ -113,7 +113,7 @@ public void test() throws DdlException, AnalysisException { setPassVarOp3.validate(ctx); } catch (UserException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // set password for cmy2@'192.168.1.1' @@ -124,7 +124,7 @@ public void test() throws DdlException, AnalysisException { setPassVarOp4.validate(ctx); } catch (UserException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/UserIdentityTest.java b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/UserIdentityTest.java index eff2b54135bc69..e715a0d1374f96 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/UserIdentityTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/mysql/privilege/UserIdentityTest.java @@ -19,8 +19,8 @@ import org.apache.doris.analysis.UserIdentity; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class UserIdentityTest { @@ -31,17 +31,17 @@ public void test() { userIdent.setIsAnalyzed(); String str = "'" + "cmy" + "'@'192.%'"; - Assert.assertEquals(str, userIdent.toString()); + Assertions.assertEquals(str, userIdent.toString()); UserIdentity userIdent2 = UserIdentity.fromString(str); - Assert.assertEquals(userIdent2.toString(), userIdent.toString()); + Assertions.assertEquals(userIdent2.toString(), userIdent.toString()); String str2 = "'walletdc_write'@['cluster-leida.orp.all']"; userIdent = UserIdentity.fromString(str2); - Assert.assertNotNull(userIdent); - Assert.assertTrue(userIdent.isDomain()); + Assertions.assertNotNull(userIdent); + Assertions.assertTrue(userIdent.isDomain()); userIdent.setIsAnalyzed(); - Assert.assertEquals(str2, userIdent.toString()); + Assertions.assertEquals(str2, userIdent.toString()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java index ae6d93e17fc8e3..7b1a987fb2934e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/StatsCalculatorTest.java @@ -143,7 +143,7 @@ public void testFilter() { // a, b are in (0,100) // a=200 and b=300 => output: 0 rows - @org.junit.Test + @Test public void testFilterOutofRange() { List qualifier = ImmutableList.of("test", "t"); SlotReference slot1 = new SlotReference("c1", IntegerType.INSTANCE, true, qualifier); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/AlterRoutineLoadOperationLogTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/AlterRoutineLoadOperationLogTest.java index 8a1550d48f5d13..35cf14fae66fe7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/AlterRoutineLoadOperationLogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/AlterRoutineLoadOperationLogTest.java @@ -24,8 +24,8 @@ import org.apache.doris.nereids.trees.plans.commands.info.CreateRoutineLoadInfo; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -70,16 +70,16 @@ public void testSerializeAlterRoutineLoadOperationLog() throws IOException, User DataInputStream in = new DataInputStream(new FileInputStream(file)); AlterRoutineLoadJobOperationLog log2 = AlterRoutineLoadJobOperationLog.read(in); - Assert.assertEquals(1, log2.getJobProperties().size()); - Assert.assertEquals("5", log2.getJobProperties().get(CreateRoutineLoadInfo.DESIRED_CONCURRENT_NUMBER_PROPERTY)); + Assertions.assertEquals(1, log2.getJobProperties().size()); + Assertions.assertEquals("5", log2.getJobProperties().get(CreateRoutineLoadInfo.DESIRED_CONCURRENT_NUMBER_PROPERTY)); KafkaDataSourceProperties kafkaDataSourceProperties = (KafkaDataSourceProperties) log2.getDataSourceProperties(); - Assert.assertEquals(null, kafkaDataSourceProperties.getBrokerList()); - Assert.assertEquals(null, kafkaDataSourceProperties.getTopic()); - Assert.assertEquals(1, kafkaDataSourceProperties.getCustomKafkaProperties().size()); - Assert.assertEquals("mygroup", kafkaDataSourceProperties.getCustomKafkaProperties().get("group.id")); - Assert.assertEquals(routineLoadDataSourceProperties.getKafkaPartitionOffsets().get(0), + Assertions.assertEquals(null, kafkaDataSourceProperties.getBrokerList()); + Assertions.assertEquals(null, kafkaDataSourceProperties.getTopic()); + Assertions.assertEquals(1, kafkaDataSourceProperties.getCustomKafkaProperties().size()); + Assertions.assertEquals("mygroup", kafkaDataSourceProperties.getCustomKafkaProperties().get("group.id")); + Assertions.assertEquals(routineLoadDataSourceProperties.getKafkaPartitionOffsets().get(0), kafkaDataSourceProperties.getKafkaPartitionOffsets().get(0)); - Assert.assertEquals(routineLoadDataSourceProperties.getKafkaPartitionOffsets().get(1), + Assertions.assertEquals(routineLoadDataSourceProperties.getKafkaPartitionOffsets().get(1), kafkaDataSourceProperties.getKafkaPartitionOffsets().get(1)); in.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/AlterViewInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/AlterViewInfoTest.java index 8ca5573c2acea0..957a5f4dca5d4a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/AlterViewInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/AlterViewInfoTest.java @@ -22,9 +22,9 @@ import org.apache.doris.common.AnalysisException; import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -42,7 +42,7 @@ public class AlterViewInfoTest { private final String inlineViewDef = "Select a1, a2 From test_tbl Order By a1"; private final long sqlMode = 0L; - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -67,7 +67,7 @@ public void testSerializeAlterViewInfo() throws IOException, AnalysisException { DataInputStream in = new DataInputStream(new FileInputStream(file)); AlterViewInfo readAlterViewInfo = AlterViewInfo.read(in); - Assert.assertEquals(alterViewInfo, readAlterViewInfo); + Assertions.assertEquals(alterViewInfo, readAlterViewInfo); in.close(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/BackendReplicaInfosTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/BackendReplicaInfosTest.java index e5a29a9860d394..d0dee961175fc5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/BackendReplicaInfosTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/BackendReplicaInfosTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeMetaVersion; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -66,16 +66,16 @@ public void testSerialization() throws Exception { } private void checkInfo(BackendReplicasInfo info) { - Assert.assertTrue(!info.isEmpty()); + Assertions.assertTrue(!info.isEmpty()); List infos = info.getReplicaReportInfos(); for (BackendReplicasInfo.ReplicaReportInfo reportInfo : infos) { if (reportInfo.tabletId == tabletId1) { - Assert.assertEquals(BackendReplicasInfo.ReportInfoType.BAD, reportInfo.type); + Assertions.assertEquals(BackendReplicasInfo.ReportInfoType.BAD, reportInfo.type); } else if (reportInfo.tabletId == tabletId2) { - Assert.assertEquals(BackendReplicasInfo.ReportInfoType.MISSING_VERSION, reportInfo.type); - Assert.assertEquals(11, reportInfo.lastFailedVersion); + Assertions.assertEquals(BackendReplicasInfo.ReportInfoType.MISSING_VERSION, reportInfo.type); + Assertions.assertEquals(11, reportInfo.lastFailedVersion); } else { - Assert.fail("unknown tablet id: " + reportInfo.tabletId); + Assertions.fail("unknown tablet id: " + reportInfo.tabletId); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/BatchModifyPartitionsInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/BatchModifyPartitionsInfoTest.java index 82b0766c76f075..f1fe0abab1a0b5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/BatchModifyPartitionsInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/BatchModifyPartitionsInfoTest.java @@ -23,9 +23,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -44,7 +44,7 @@ public class BatchModifyPartitionsInfoTest { private static final long PARTITION_ID_2 = 40001L; private static final long PARTITION_ID_3 = 40002L; - @After + @AfterEach public void tearDown() { File file = new File(FILE_NAME); file.delete(); @@ -74,7 +74,7 @@ public void testSerializeBatchModifyPartitionsInfo() throws IOException, Analysi DataInputStream in = new DataInputStream(new FileInputStream(file)); BatchModifyPartitionsInfo readBatchModifyPartitionsInfo = BatchModifyPartitionsInfo.read(in); - Assert.assertEquals(batchModifyPartitionsInfo, readBatchModifyPartitionsInfo); + Assertions.assertEquals(batchModifyPartitionsInfo, readBatchModifyPartitionsInfo); in.close(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/BatchRemoveTransactionOperationTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/BatchRemoveTransactionOperationTest.java index d20989c1d42adf..0e56b9f14c0bf7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/BatchRemoveTransactionOperationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/BatchRemoveTransactionOperationTest.java @@ -22,8 +22,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -59,9 +59,9 @@ public void testSerialization() throws Exception { // 2. Read objects from file DataInputStream dis = new DataInputStream(new FileInputStream(file)); BatchRemoveTransactionsOperation op2 = BatchRemoveTransactionsOperation.read(dis); - Assert.assertEquals(1, op2.getDbTxnIds().size()); - Assert.assertEquals(3, op2.getDbTxnIds().get(1000L).size()); - Assert.assertTrue(op2.getDbTxnIds().get(1000L).contains(1L)); + Assertions.assertEquals(1, op2.getDbTxnIds().size()); + Assertions.assertEquals(3, op2.getDbTxnIds().get(1000L).size()); + Assertions.assertTrue(op2.getDbTxnIds().get(1000L).contains(1L)); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ConsistencyCheckInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ConsistencyCheckInfoTest.java index de75d578f49d83..81307257ba9c76 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ConsistencyCheckInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ConsistencyCheckInfoTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.AnalysisException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -46,7 +46,7 @@ public void testSerialization() throws IOException, AnalysisException { ConsistencyCheckInfo consistencyCheckInfo2 = ConsistencyCheckInfo.read(in); - Assert.assertEquals(consistencyCheckInfo1.getDbId(), consistencyCheckInfo2.getDbId()); + Assertions.assertEquals(consistencyCheckInfo1.getDbId(), consistencyCheckInfo2.getDbId()); // 3. delete files in.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/CreateDbInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/CreateDbInfoTest.java index 881c61065be093..2285497403dfb3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/CreateDbInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/CreateDbInfoTest.java @@ -22,8 +22,8 @@ import org.apache.doris.datasource.InternalCatalog; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -56,14 +56,14 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(file.toPath())); CreateDbInfo rInfo1 = CreateDbInfo.read(dis); - Assert.assertEquals(info1.getCtlName(), rInfo1.getCtlName()); - Assert.assertEquals(info1.getDbName(), rInfo1.getDbName()); - Assert.assertEquals(info1.getInternalDb().getId(), rInfo1.getInternalDb().getId()); + Assertions.assertEquals(info1.getCtlName(), rInfo1.getCtlName()); + Assertions.assertEquals(info1.getDbName(), rInfo1.getDbName()); + Assertions.assertEquals(info1.getInternalDb().getId(), rInfo1.getInternalDb().getId()); CreateDbInfo rInfo2 = CreateDbInfo.read(dis); - Assert.assertEquals(info2.getCtlName(), rInfo2.getCtlName()); - Assert.assertEquals(info2.getDbName(), rInfo2.getDbName()); - Assert.assertNull(rInfo2.getInternalDb()); + Assertions.assertEquals(info2.getCtlName(), rInfo2.getCtlName()); + Assertions.assertEquals(info2.getDbName(), rInfo2.getDbName()); + Assertions.assertNull(rInfo2.getInternalDb()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/CreateTableInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/CreateTableInfoTest.java index c07fbf996bb0ca..907533f984ccff 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/CreateTableInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/CreateTableInfoTest.java @@ -36,10 +36,10 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -52,7 +52,7 @@ public class CreateTableInfoTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { fakeEnv = new FakeEnv(); env = Deencapsulation.newInstance(Env.class); @@ -61,7 +61,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -113,9 +113,9 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(path)); CreateTableInfo rInfo1 = CreateTableInfo.read(dis); - Assert.assertEquals(rInfo1.getTable(), table); - Assert.assertEquals(rInfo1, info); - Assert.assertEquals(rInfo1.getDbName(), "db1"); + Assertions.assertEquals(rInfo1.getTable(), table); + Assertions.assertEquals(rInfo1, info); + Assertions.assertEquals(rInfo1.getDbName(), "db1"); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/DataSourcePropertiesTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/DataSourcePropertiesTest.java index ed4852ee6a2c0d..e1845cd09fbf53 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/DataSourcePropertiesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/DataSourcePropertiesTest.java @@ -26,8 +26,8 @@ import com.google.common.collect.Maps; import com.google.gson.JsonParseException; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -65,22 +65,24 @@ public void testKafkaDataSourceSerializatio() throws IOException, UserException } } - @Test(expected = JsonParseException.class) + @Test public void testNotSupportDataSourceSerializatio() throws IOException { - TestDataSourceProperties testDataSourceProperties = new TestDataSourceProperties(Maps.newHashMap()); - File file = new File("./test_datasource_properties"); - - file.createNewFile(); - try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(file.toPath()))) { - String json = GsonUtils.GSON.toJson(testDataSourceProperties); - Text.writeString(out, json); - out.flush(); - } - - try (DataInputStream dis = new DataInputStream(Files.newInputStream(file.toPath()))) { - String json = Text.readString(dis); - GsonUtils.GSON.fromJson(json, AbstractDataSourceProperties.class); - } + Assertions.assertThrows(JsonParseException.class, () -> { + TestDataSourceProperties testDataSourceProperties = new TestDataSourceProperties(Maps.newHashMap()); + File file = new File("./test_datasource_properties"); + + file.createNewFile(); + try (DataOutputStream out = new DataOutputStream(Files.newOutputStream(file.toPath()))) { + String json = GsonUtils.GSON.toJson(testDataSourceProperties); + Text.writeString(out, json); + out.flush(); + } + + try (DataInputStream dis = new DataInputStream(Files.newInputStream(file.toPath()))) { + String json = Text.readString(dis); + GsonUtils.GSON.fromJson(json, AbstractDataSourceProperties.class); + } + }); } class TestDataSourceProperties extends AbstractDataSourceProperties { diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/DatabaseInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/DatabaseInfoTest.java index c965cbd995055e..7cc4b91c2c5555 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/DatabaseInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/DatabaseInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.alter.QuotaType; import org.apache.doris.common.AnalysisException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -47,9 +47,9 @@ public void testSerialization() throws IOException, AnalysisException { DatabaseInfo databaseInfo2 = DatabaseInfo.read(in); - Assert.assertEquals(databaseInfo1.getDbName(), databaseInfo2.getDbName()); - Assert.assertEquals(databaseInfo1.getNewDbName(), databaseInfo2.getNewDbName()); - Assert.assertEquals(databaseInfo1.getQuota(), databaseInfo2.getQuota()); + Assertions.assertEquals(databaseInfo1.getDbName(), databaseInfo2.getDbName()); + Assertions.assertEquals(databaseInfo1.getNewDbName(), databaseInfo2.getNewDbName()); + Assertions.assertEquals(databaseInfo1.getQuota(), databaseInfo2.getQuota()); // 3. delete files in.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/DropAndRecoverInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/DropAndRecoverInfoTest.java index 63afe375548fe0..ded12877261d7a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/DropAndRecoverInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/DropAndRecoverInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeMetaVersion; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -54,21 +54,21 @@ public void testDropInfoSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); DropInfo rInfo1 = DropInfo.read(dis); - Assert.assertEquals(rInfo1, info1); + Assertions.assertEquals(rInfo1, info1); DropInfo rInfo2 = DropInfo.read(dis); - Assert.assertEquals(rInfo2, info2); + Assertions.assertEquals(rInfo2, info2); - Assert.assertEquals(1, rInfo2.getDbId()); - Assert.assertEquals(2, rInfo2.getTableId()); - Assert.assertTrue(rInfo2.isForceDrop()); + Assertions.assertEquals(1, rInfo2.getDbId()); + Assertions.assertEquals(2, rInfo2.getTableId()); + Assertions.assertTrue(rInfo2.isForceDrop()); - Assert.assertEquals(rInfo2, rInfo2); - Assert.assertNotEquals(rInfo2, this); - Assert.assertNotEquals(info2, new DropInfo(0, 2, "t2", -1L, "", false, true, 0)); - Assert.assertNotEquals(info2, new DropInfo(1, 0, "t0", -1L, "", false, true, 0)); - Assert.assertNotEquals(info2, new DropInfo(1, 2, "t2", -1L, "", false, false, 0)); - Assert.assertEquals(info2, new DropInfo(1, 2, "t2", -1L, "", false, true, 0)); + Assertions.assertEquals(rInfo2, rInfo2); + Assertions.assertNotEquals(rInfo2, this); + Assertions.assertNotEquals(info2, new DropInfo(0, 2, "t2", -1L, "", false, true, 0)); + Assertions.assertNotEquals(info2, new DropInfo(1, 0, "t0", -1L, "", false, true, 0)); + Assertions.assertNotEquals(info2, new DropInfo(1, 2, "t2", -1L, "", false, false, 0)); + Assertions.assertEquals(info2, new DropInfo(1, 2, "t2", -1L, "", false, true, 0)); // 3. delete files dis.close(); @@ -95,12 +95,12 @@ public void testRecoveryInfoSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); RecoverInfo rInfo1 = RecoverInfo.read(dis); - Assert.assertEquals(1, rInfo1.getDbId()); - Assert.assertEquals(2, rInfo1.getTableId()); - Assert.assertEquals(3, rInfo1.getPartitionId()); - Assert.assertEquals("a", rInfo1.getNewDbName()); - Assert.assertEquals("b", rInfo1.getNewTableName()); - Assert.assertEquals("c", rInfo1.getNewPartitionName()); + Assertions.assertEquals(1, rInfo1.getDbId()); + Assertions.assertEquals(2, rInfo1.getTableId()); + Assertions.assertEquals(3, rInfo1.getPartitionId()); + Assertions.assertEquals("a", rInfo1.getNewDbName()); + Assertions.assertEquals("b", rInfo1.getNewTableName()); + Assertions.assertEquals("c", rInfo1.getNewPartitionName()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/DropDbInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/DropDbInfoTest.java index aea8530afeb0fd..6f413553853f2e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/DropDbInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/DropDbInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeMetaVersion; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -53,19 +53,19 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(Files.newInputStream(file.toPath())); DropDbInfo rInfo1 = DropDbInfo.read(dis); - Assert.assertEquals(rInfo1, info1); + Assertions.assertEquals(rInfo1, info1); DropDbInfo rInfo2 = DropDbInfo.read(dis); - Assert.assertEquals(rInfo2, info2); + Assertions.assertEquals(rInfo2, info2); - Assert.assertEquals("test_db", rInfo2.getDbName()); - Assert.assertTrue(rInfo2.isForceDrop()); + Assertions.assertEquals("test_db", rInfo2.getDbName()); + Assertions.assertTrue(rInfo2.isForceDrop()); - Assert.assertEquals(rInfo2, rInfo2); - Assert.assertNotEquals(rInfo2, this); - Assert.assertNotEquals(info2, new DropDbInfo("test_db1", true, 0)); - Assert.assertNotEquals(info2, new DropDbInfo("test_db", false, 0)); - Assert.assertEquals(info2, new DropDbInfo("test_db", true, 0)); + Assertions.assertEquals(rInfo2, rInfo2); + Assertions.assertNotEquals(rInfo2, this); + Assertions.assertNotEquals(info2, new DropDbInfo("test_db1", true, 0)); + Assertions.assertNotEquals(info2, new DropDbInfo("test_db", false, 0)); + Assertions.assertEquals(info2, new DropDbInfo("test_db", true, 0)); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/DropPartitionInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/DropPartitionInfoTest.java index ae7c16a02ee80e..6ceeedacc657c4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/DropPartitionInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/DropPartitionInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeMetaVersion; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -52,21 +52,21 @@ public void testSerialization() throws Exception { DropPartitionInfo rInfo1 = DropPartitionInfo.read(dis); - Assert.assertEquals(Long.valueOf(1L), rInfo1.getDbId()); - Assert.assertEquals(Long.valueOf(2L), rInfo1.getTableId()); - Assert.assertEquals(Long.valueOf(3L), rInfo1.getPartitionId()); - Assert.assertEquals("test_partition", rInfo1.getPartitionName()); - Assert.assertFalse(rInfo1.isTempPartition()); - Assert.assertTrue(rInfo1.isForceDrop()); + Assertions.assertEquals(Long.valueOf(1L), rInfo1.getDbId()); + Assertions.assertEquals(Long.valueOf(2L), rInfo1.getTableId()); + Assertions.assertEquals(Long.valueOf(3L), rInfo1.getPartitionId()); + Assertions.assertEquals("test_partition", rInfo1.getPartitionName()); + Assertions.assertFalse(rInfo1.isTempPartition()); + Assertions.assertTrue(rInfo1.isForceDrop()); - Assert.assertEquals(rInfo1, info1); - Assert.assertNotEquals(rInfo1, this); - Assert.assertNotEquals(info1, new DropPartitionInfo(-1L, 2L, 3L, "test_partition", false, true, 0, 0L, 0L)); - Assert.assertNotEquals(info1, new DropPartitionInfo(1L, -2L, 3L, "test_partition", false, true, 0, 0L, 0L)); - Assert.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition1", false, true, 0, 0L, 0L)); - Assert.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", true, true, 0, 0L, 0L)); - Assert.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", false, false, 0, 0L, 0L)); - Assert.assertEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", false, true, 0, 0L, 0L)); + Assertions.assertEquals(rInfo1, info1); + Assertions.assertNotEquals(rInfo1, this); + Assertions.assertNotEquals(info1, new DropPartitionInfo(-1L, 2L, 3L, "test_partition", false, true, 0, 0L, 0L)); + Assertions.assertNotEquals(info1, new DropPartitionInfo(1L, -2L, 3L, "test_partition", false, true, 0, 0L, 0L)); + Assertions.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition1", false, true, 0, 0L, 0L)); + Assertions.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", true, true, 0, 0L, 0L)); + Assertions.assertNotEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", false, false, 0, 0L, 0L)); + Assertions.assertEquals(info1, new DropPartitionInfo(1L, 2L, 3L, "test_partition", false, true, 0, 0L, 0L)); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java index 61b4b786d8cc8a..c1f22307124d43 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java @@ -22,18 +22,19 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.journal.bdbje.Timestamp; -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.mockito.MockedStatic; import org.mockito.Mockito; import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.TimeUnit; public class EditLogTest { @@ -44,10 +45,10 @@ public class EditLogTest { private String originalDeployMode; private String originalCloudUniqueId; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public Path temporaryFolder; - @Before + @BeforeEach public void setUpEditLogRollConfig() { originalEditLogType = Config.edit_log_type; originalEditLogRollNum = Config.edit_log_roll_num; @@ -61,7 +62,7 @@ public void setUpEditLogRollConfig() { Config.cloud_unique_id = ""; } - @After + @AfterEach public void restoreEditLogRollConfig() { Config.edit_log_type = originalEditLogType; Config.edit_log_roll_num = originalEditLogRollNum; @@ -151,7 +152,7 @@ public void test() { public void testCloudModeTimeBasedEditLogRoll() throws Exception { Config.deploy_mode = "cloud"; - File imageDir = temporaryFolder.newFolder("time_based_roll"); + File imageDir = Files.createDirectories(temporaryFolder.resolve("time_based_roll")).toFile(); Env env = Mockito.mock(Env.class); Mockito.when(env.getImageDir()).thenReturn(imageDir.getAbsolutePath()); try (MockedStatic envStatic = Mockito.mockStatic(Env.class)) { @@ -164,9 +165,9 @@ public void testCloudModeTimeBasedEditLogRoll() throws Exception { editLog.logTimestamp(new Timestamp()); - Assert.assertTrue(new File(imageDir, "edits.2").exists()); + Assertions.assertTrue(new File(imageDir, "edits.2").exists()); long txId = Deencapsulation.getField(editLog, "txId"); - Assert.assertEquals(0L, txId); + Assertions.assertEquals(0L, txId); } finally { editLog.close(); } @@ -177,7 +178,7 @@ public void testCloudModeTimeBasedEditLogRoll() throws Exception { public void testNonCloudModeDoesNotRollEditLogByTime() throws Exception { Config.deploy_mode = "share_nothing"; - File imageDir = temporaryFolder.newFolder("non_cloud_time_based_roll"); + File imageDir = Files.createDirectories(temporaryFolder.resolve("non_cloud_time_based_roll")).toFile(); Env env = Mockito.mock(Env.class); Mockito.when(env.getImageDir()).thenReturn(imageDir.getAbsolutePath()); try (MockedStatic envStatic = Mockito.mockStatic(Env.class)) { @@ -190,12 +191,12 @@ public void testNonCloudModeDoesNotRollEditLogByTime() throws Exception { editLog.logTimestamp(new Timestamp()); - Assert.assertFalse(new File(imageDir, "edits.2").exists()); + Assertions.assertFalse(new File(imageDir, "edits.2").exists()); Config.edit_log_roll_num = 2; editLog.logTimestamp(new Timestamp()); - Assert.assertTrue(new File(imageDir, "edits.3").exists()); + Assertions.assertTrue(new File(imageDir, "edits.3").exists()); } finally { editLog.close(); } @@ -206,7 +207,7 @@ public void testNonCloudModeDoesNotRollEditLogByTime() throws Exception { public void testRollEditLogResetsCloudRollTime() throws Exception { Config.deploy_mode = "cloud"; - File imageDir = temporaryFolder.newFolder("reset_time_after_roll"); + File imageDir = Files.createDirectories(temporaryFolder.resolve("reset_time_after_roll")).toFile(); Env env = Mockito.mock(Env.class); Mockito.when(env.getImageDir()).thenReturn(imageDir.getAbsolutePath()); try (MockedStatic envStatic = Mockito.mockStatic(Env.class)) { @@ -221,8 +222,8 @@ public void testRollEditLogResetsCloudRollTime() throws Exception { editLog.rollEditLog(); editLog.logTimestamp(new Timestamp()); - Assert.assertTrue(new File(imageDir, "edits.2").exists()); - Assert.assertFalse(new File(imageDir, "edits.3").exists()); + Assertions.assertTrue(new File(imageDir, "edits.2").exists()); + Assertions.assertFalse(new File(imageDir, "edits.3").exists()); } finally { editLog.close(); } @@ -235,7 +236,7 @@ public void testNonPositiveCloudEditLogRollIntervalDisablesTimeBasedRoll() throw int[] disabledIntervals = {0, -1}; for (int i = 0; i < disabledIntervals.length; i++) { Config.cloud_edit_log_roll_interval_second = disabledIntervals[i]; - File imageDir = temporaryFolder.newFolder("disabled_time_based_roll_" + i); + File imageDir = Files.createDirectories(temporaryFolder.resolve("disabled_time_based_roll_" + i)).toFile(); Env env = Mockito.mock(Env.class); Mockito.when(env.getImageDir()).thenReturn(imageDir.getAbsolutePath()); try (MockedStatic envStatic = Mockito.mockStatic(Env.class)) { @@ -248,12 +249,12 @@ public void testNonPositiveCloudEditLogRollIntervalDisablesTimeBasedRoll() throw editLog.logTimestamp(new Timestamp()); - Assert.assertFalse(new File(imageDir, "edits.2").exists()); + Assertions.assertFalse(new File(imageDir, "edits.2").exists()); Config.edit_log_roll_num = 2; editLog.logTimestamp(new Timestamp()); - Assert.assertTrue(new File(imageDir, "edits.3").exists()); + Assertions.assertTrue(new File(imageDir, "edits.3").exists()); Config.edit_log_roll_num = Integer.MAX_VALUE; } finally { editLog.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/FsBrokerTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/FsBrokerTest.java index a5acc45bba5657..5d49641c20a9e8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/FsBrokerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/FsBrokerTest.java @@ -22,10 +22,10 @@ import org.apache.doris.meta.MetaContext; import org.apache.doris.system.BrokerHbResponse; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -39,14 +39,14 @@ public class FsBrokerTest { private static String fileName1 = "./FsBrokerTest1"; private static String fileName2 = "./FsBrokerTest2"; - @BeforeClass + @BeforeAll public static void setup() { MetaContext context = new MetaContext(); context.setMetaVersion(FeMetaVersion.VERSION_CURRENT); context.setThreadLocalInfo(); } - @AfterClass + @AfterAll public static void tear() { new File(fileName1).delete(); new File(fileName2).delete(); @@ -71,12 +71,12 @@ public void testHeartbeatOk() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); FsBroker readBroker = FsBroker.readIn(dis); - Assert.assertEquals(fsBroker.host, readBroker.host); - Assert.assertEquals(fsBroker.port, readBroker.port); - Assert.assertEquals(fsBroker.isAlive, readBroker.isAlive); - Assert.assertTrue(fsBroker.isAlive); - Assert.assertEquals(time, readBroker.lastStartTime); - Assert.assertEquals(-1, readBroker.lastUpdateTime); + Assertions.assertEquals(fsBroker.host, readBroker.host); + Assertions.assertEquals(fsBroker.port, readBroker.port); + Assertions.assertEquals(fsBroker.isAlive, readBroker.isAlive); + Assertions.assertTrue(fsBroker.isAlive); + Assertions.assertEquals(time, readBroker.lastStartTime); + Assertions.assertEquals(-1, readBroker.lastUpdateTime); dis.close(); } @@ -98,12 +98,12 @@ public void testHeartbeatFailed() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); FsBroker readBroker = FsBroker.readIn(dis); - Assert.assertEquals(fsBroker.host, readBroker.host); - Assert.assertEquals(fsBroker.port, readBroker.port); - Assert.assertEquals(fsBroker.isAlive, readBroker.isAlive); - Assert.assertFalse(fsBroker.isAlive); - Assert.assertEquals(-1, readBroker.lastStartTime); - Assert.assertEquals(-1, readBroker.lastUpdateTime); + Assertions.assertEquals(fsBroker.host, readBroker.host); + Assertions.assertEquals(fsBroker.port, readBroker.port); + Assertions.assertEquals(fsBroker.isAlive, readBroker.isAlive); + Assertions.assertFalse(fsBroker.isAlive); + Assertions.assertEquals(-1, readBroker.lastStartTime); + Assertions.assertEquals(-1, readBroker.lastUpdateTime); dis.close(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/GlobalVarPersistInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/GlobalVarPersistInfoTest.java index 2494f7103b0848..fdc6f3b70356f9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/GlobalVarPersistInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/GlobalVarPersistInfoTest.java @@ -21,8 +21,8 @@ import org.apache.doris.qe.VariableMgr; import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -35,7 +35,7 @@ public class GlobalVarPersistInfoTest { private static String fileName = "./GlobalVarPersistInfoTest"; - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/LdapInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/LdapInfoTest.java index 23a40e93eaab48..e217366c51cdbc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/LdapInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/LdapInfoTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.util.SymmetricEncryption; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -48,7 +48,7 @@ public void test() throws IOException { // 2. Read objects from file DataInputStream dis = new DataInputStream(new FileInputStream(file)); LdapInfo ldapInfo2 = LdapInfo.read(dis); - Assert.assertEquals(passwd, + Assertions.assertEquals(passwd, SymmetricEncryption.decrypt(ldapInfo2.getLdapPasswdEncrypted(), ldapInfo2.getSecretKey(), ldapInfo2.getIv())); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/LoadJobV2PersistTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/LoadJobV2PersistTest.java index b8c530a3bf5528..0963395adefe0b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/LoadJobV2PersistTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/LoadJobV2PersistTest.java @@ -30,8 +30,8 @@ import org.apache.doris.qe.OriginStatement; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -80,7 +80,7 @@ public void testBrokerLoadJob() throws Exception { DataOutputStream dos = new DataOutputStream(new FileOutputStream(file)); BrokerLoadJob job = createJob(); - Assert.assertEquals(5, job.getLoadParallelism()); + Assertions.assertEquals(5, job.getLoadParallelism()); job.write(dos); dos.flush(); @@ -90,8 +90,8 @@ public void testBrokerLoadJob() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); BrokerLoadJob rJob = (BrokerLoadJob) BrokerLoadJob.read(dis); - Assert.assertEquals(5, rJob.getLoadParallelism()); - Assert.assertEquals(EtlJobType.BROKER, rJob.getJobType()); + Assertions.assertEquals(5, rJob.getLoadParallelism()); + Assertions.assertEquals(EtlJobType.BROKER, rJob.getJobType()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCloudWarmUpJobTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCloudWarmUpJobTest.java index bca8c1eb0273e3..3c3f333ef3583e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCloudWarmUpJobTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCloudWarmUpJobTest.java @@ -24,9 +24,9 @@ import org.apache.doris.common.io.Text; import org.apache.doris.persist.gson.GsonUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -89,28 +89,28 @@ public void testSerialization() throws IOException { CloudWarmUpJob warmUpJob2 = GsonUtils.GSON.fromJson(readJson, CloudWarmUpJob.class); - Assert.assertEquals(jobId, warmUpJob2.getJobId()); - Assert.assertEquals(jobState, warmUpJob2.getJobState()); - Assert.assertEquals(createTimeMs, warmUpJob2.getCreateTimeMs()); - Assert.assertEquals(errMsg, warmUpJob2.getErrMsg()); - Assert.assertEquals(finishedTimesMs, warmUpJob2.getFinishedTimeMs()); - Assert.assertEquals(clusterName, warmUpJob2.getDstClusterName()); - Assert.assertEquals(lastBatchId, warmUpJob2.getLastBatchId()); + Assertions.assertEquals(jobId, warmUpJob2.getJobId()); + Assertions.assertEquals(jobState, warmUpJob2.getJobState()); + Assertions.assertEquals(createTimeMs, warmUpJob2.getCreateTimeMs()); + Assertions.assertEquals(errMsg, warmUpJob2.getErrMsg()); + Assertions.assertEquals(finishedTimesMs, warmUpJob2.getFinishedTimeMs()); + Assertions.assertEquals(clusterName, warmUpJob2.getDstClusterName()); + Assertions.assertEquals(lastBatchId, warmUpJob2.getLastBatchId()); Map>> beToTabletIdBatches2 = warmUpJob2.getBeToTabletIdBatches(); - Assert.assertEquals(1, beToTabletIdBatches2.size()); - Assert.assertNotNull(beToTabletIdBatches2.get(999L)); - Assert.assertEquals(1, beToTabletIdBatches2.get(999L).size()); - Assert.assertEquals(1, beToTabletIdBatches2.get(999L).get(0).size()); - Assert.assertEquals(123L, (long) beToTabletIdBatches2.get(999L).get(0).get(0)); + Assertions.assertEquals(1, beToTabletIdBatches2.size()); + Assertions.assertNotNull(beToTabletIdBatches2.get(999L)); + Assertions.assertEquals(1, beToTabletIdBatches2.get(999L).size()); + Assertions.assertEquals(1, beToTabletIdBatches2.get(999L).get(0).size()); + Assertions.assertEquals(123L, (long) beToTabletIdBatches2.get(999L).get(0).get(0)); Map beToThriftAddress2 = warmUpJob2.getBeToThriftAddress(); - Assert.assertEquals(1, beToThriftAddress2.size()); - Assert.assertNotNull(beToThriftAddress2.get(998L)); - Assert.assertEquals("address", beToThriftAddress2.get(998L)); - Assert.assertEquals(jobType, warmUpJob2.getJobType()); + Assertions.assertEquals(1, beToThriftAddress2.size()); + Assertions.assertNotNull(beToThriftAddress2.get(998L)); + Assertions.assertEquals("address", beToThriftAddress2.get(998L)); + Assertions.assertEquals(jobType, warmUpJob2.getJobType()); } - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCommentOperationLogTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCommentOperationLogTest.java index b5ed916ece7aeb..2e02b1e1a89d9c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCommentOperationLogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyCommentOperationLogTest.java @@ -18,8 +18,8 @@ package org.apache.doris.persist; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -49,11 +49,11 @@ public void testColCommentSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); ModifyCommentOperationLog readLog = ModifyCommentOperationLog.read(dis); - Assert.assertTrue(readLog.getType() == ModifyCommentOperationLog.Type.COLUMN); - Assert.assertTrue(readLog.getDbId() == log.getDbId()); - Assert.assertTrue(readLog.getTblId() == log.getTblId()); - Assert.assertTrue(readLog.getTblComment() == null); - Assert.assertTrue(readLog.getColToComment().size() == 2); + Assertions.assertTrue(readLog.getType() == ModifyCommentOperationLog.Type.COLUMN); + Assertions.assertTrue(readLog.getDbId() == log.getDbId()); + Assertions.assertTrue(readLog.getTblId() == log.getTblId()); + Assertions.assertTrue(readLog.getTblComment() == null); + Assertions.assertTrue(readLog.getColToComment().size() == 2); // 3. delete files dis.close(); @@ -77,11 +77,11 @@ public void testTableCommentSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); ModifyCommentOperationLog readLog = ModifyCommentOperationLog.read(dis); - Assert.assertTrue(readLog.getType() == ModifyCommentOperationLog.Type.TABLE); - Assert.assertTrue(readLog.getDbId() == log.getDbId()); - Assert.assertTrue(readLog.getTblId() == log.getTblId()); - Assert.assertEquals("comment", readLog.getTblComment()); - Assert.assertTrue(readLog.getColToComment() == null); + Assertions.assertTrue(readLog.getType() == ModifyCommentOperationLog.Type.TABLE); + Assertions.assertTrue(readLog.getDbId() == log.getDbId()); + Assertions.assertTrue(readLog.getTblId() == log.getTblId()); + Assertions.assertEquals("comment", readLog.getTblComment()); + Assertions.assertTrue(readLog.getColToComment() == null); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyDynamicPartitionInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyDynamicPartitionInfoTest.java index a54f91dd8267fd..af63b1e044ec04 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyDynamicPartitionInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ModifyDynamicPartitionInfoTest.java @@ -19,9 +19,9 @@ import org.apache.doris.catalog.DynamicPartitionProperty; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -34,7 +34,7 @@ public class ModifyDynamicPartitionInfoTest { private String fileName = "./ModifyTablePropertyOperationLogTest"; - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -62,9 +62,9 @@ public void testNormal() throws IOException { // 2. Read objects from file DataInputStream in = new DataInputStream(new FileInputStream(file)); ModifyTablePropertyOperationLog readModifyDynamicPartitionInfo = ModifyTablePropertyOperationLog.read(in); - Assert.assertEquals(readModifyDynamicPartitionInfo.getDbId(), 100L); - Assert.assertEquals(readModifyDynamicPartitionInfo.getTableId(), 200L); - Assert.assertEquals(readModifyDynamicPartitionInfo.getProperties(), properties); + Assertions.assertEquals(readModifyDynamicPartitionInfo.getDbId(), 100L); + Assertions.assertEquals(readModifyDynamicPartitionInfo.getTableId(), 200L); + Assertions.assertEquals(readModifyDynamicPartitionInfo.getProperties(), properties); in.close(); } @@ -76,8 +76,8 @@ public void testToSql() { properties.put(DynamicPartitionProperty.START, "-3"); ModifyTablePropertyOperationLog modifyDynamicPartitionInfo = new ModifyTablePropertyOperationLog(100L, 200L, "test", properties); - Assert.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.enable\" = \"true\"")); - Assert.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.time_unit\" = \"day\"")); - Assert.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.start\" = \"-3\"")); + Assertions.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.enable\" = \"true\"")); + Assertions.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.time_unit\" = \"day\"")); + Assertions.assertTrue(modifyDynamicPartitionInfo.toSql().contains("\"dynamic_partition.start\" = \"-3\"")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/PrivInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/PrivInfoTest.java index a00088f0ff427f..c3d551540f6c92 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/PrivInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/PrivInfoTest.java @@ -27,9 +27,9 @@ import org.apache.doris.mysql.privilege.PrivBitSet; import org.apache.doris.mysql.privilege.Privilege; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -41,7 +41,7 @@ public class PrivInfoTest { - @Before + @BeforeEach public void setUp() { MetaContext metaContext = new MetaContext(); metaContext.setMetaVersion(FeMetaVersion.VERSION_CURRENT); @@ -64,8 +64,8 @@ public void test() throws IOException { // 2. Read objects from file DataInputStream dis = new DataInputStream(new FileInputStream(file)); PrivInfo anotherPrivInfo = PrivInfo.read(dis); - Assert.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); - Assert.assertEquals(privInfo.getPasswordOptions().getExpirePolicySecond(), anotherPrivInfo.getPasswordOptions() + Assertions.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); + Assertions.assertEquals(privInfo.getPasswordOptions().getExpirePolicySecond(), anotherPrivInfo.getPasswordOptions() .getExpirePolicySecond()); // 3. delete files dis.close(); @@ -88,9 +88,9 @@ public void testWithTablePattern() throws IOException { // 2. Read objects from file DataInputStream dis = new DataInputStream(new FileInputStream(file)); PrivInfo anotherPrivInfo = PrivInfo.read(dis); - Assert.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); - Assert.assertEquals(PasswordOptions.UNSET, anotherPrivInfo.getPasswordOptions().getExpirePolicySecond()); - Assert.assertEquals(privInfo.getTblPattern().getTbl(), anotherPrivInfo.getTblPattern().getTbl()); + Assertions.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); + Assertions.assertEquals(PasswordOptions.UNSET, anotherPrivInfo.getPasswordOptions().getExpirePolicySecond()); + Assertions.assertEquals(privInfo.getTblPattern().getTbl(), anotherPrivInfo.getTblPattern().getTbl()); // 3. delete files dis.close(); @@ -113,9 +113,9 @@ public void testWithResourcePattern() throws IOException { // 2. Read objects from file DataInputStream dis = new DataInputStream(new FileInputStream(file)); PrivInfo anotherPrivInfo = PrivInfo.read(dis); - Assert.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); - Assert.assertEquals(PasswordOptions.UNSET, anotherPrivInfo.getPasswordOptions().getExpirePolicySecond()); - Assert.assertEquals(privInfo.getResourcePattern(), anotherPrivInfo.getResourcePattern()); + Assertions.assertTrue(Arrays.equals(privInfo.getPasswd(), anotherPrivInfo.getPasswd())); + Assertions.assertEquals(PasswordOptions.UNSET, anotherPrivInfo.getPasswordOptions().getExpirePolicySecond()); + Assertions.assertEquals(privInfo.getResourcePattern(), anotherPrivInfo.getResourcePattern()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/RefreshExternalTableInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/RefreshExternalTableInfoTest.java index 3fbc4c58f4cc5e..20c5e928e6e508 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/RefreshExternalTableInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/RefreshExternalTableInfoTest.java @@ -26,10 +26,10 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.common.jmockit.Deencapsulation; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -44,7 +44,7 @@ public class RefreshExternalTableInfoTest { private FakeEnv fakeEnv; - @Before + @BeforeEach public void setUp() { fakeEnv = new FakeEnv(); env = Deencapsulation.newInstance(Env.class); @@ -53,7 +53,7 @@ public void setUp() { FakeEnv.setMetaVersion(FeConstants.meta_version); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -96,9 +96,9 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); RefreshExternalTableInfo rInfo1 = RefreshExternalTableInfo.read(dis); - Assert.assertEquals(rInfo1.getDbName(), info.getDbName()); - Assert.assertEquals(rInfo1.getTableName(), info.getTableName()); - Assert.assertEquals(rInfo1.getNewSchema(), info.getNewSchema()); + Assertions.assertEquals(rInfo1.getDbName(), info.getDbName()); + Assertions.assertEquals(rInfo1.getTableName(), info.getTableName()); + Assertions.assertEquals(rInfo1.getNewSchema(), info.getNewSchema()); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ReplaceTableOperationLogTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ReplaceTableOperationLogTest.java index ed56e4c7941342..4c3e67d7e73fe3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ReplaceTableOperationLogTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ReplaceTableOperationLogTest.java @@ -17,8 +17,8 @@ package org.apache.doris.persist; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -44,12 +44,12 @@ public void testSerialization() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(file)); ReplaceTableOperationLog readLog = ReplaceTableOperationLog.read(dis); - Assert.assertTrue(readLog.getDbId() == log.getDbId()); - Assert.assertTrue(readLog.getNewTblId() == log.getNewTblId()); - Assert.assertTrue(readLog.getOrigTblId() == log.getOrigTblId()); - Assert.assertTrue(readLog.isSwapTable() == log.isSwapTable()); - Assert.assertTrue(readLog.getOrigTblName().equals(log.getOrigTblName())); - Assert.assertTrue(readLog.getNewTblName().equals(log.getNewTblName())); + Assertions.assertTrue(readLog.getDbId() == log.getDbId()); + Assertions.assertTrue(readLog.getNewTblId() == log.getNewTblId()); + Assertions.assertTrue(readLog.getOrigTblId() == log.getOrigTblId()); + Assertions.assertTrue(readLog.isSwapTable() == log.isSwapTable()); + Assertions.assertTrue(readLog.getOrigTblName().equals(log.getOrigTblName())); + Assertions.assertTrue(readLog.getNewTblName().equals(log.getNewTblName())); // 3. delete files dis.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ReplicaPersistInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ReplicaPersistInfoTest.java index ce621d7e1f2a12..8a54895d812485 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ReplicaPersistInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ReplicaPersistInfoTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.meta.MetaContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -60,13 +60,13 @@ public void testSerialization() throws Exception { @Test public void testGet() throws Exception { ReplicaPersistInfo info = ReplicaPersistInfo.createForLoad(0, 1, 2, 3, 4, 5, 7, 0, 0, 8); - Assert.assertEquals(0, info.getTableId()); - Assert.assertEquals(1, info.getPartitionId()); - Assert.assertEquals(2, info.getIndexId()); - Assert.assertEquals(3, info.getTabletId()); - Assert.assertEquals(4, info.getReplicaId()); - Assert.assertEquals(5, info.getVersion()); - Assert.assertEquals(0, info.getDataSize()); - Assert.assertEquals(8, info.getRowCount()); + Assertions.assertEquals(0, info.getTableId()); + Assertions.assertEquals(1, info.getPartitionId()); + Assertions.assertEquals(2, info.getIndexId()); + Assertions.assertEquals(3, info.getTabletId()); + Assertions.assertEquals(4, info.getReplicaId()); + Assertions.assertEquals(5, info.getVersion()); + Assertions.assertEquals(0, info.getDataSize()); + Assertions.assertEquals(8, info.getRowCount()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ResourcePersistTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ResourcePersistTest.java index 8a542a0897d918..624dbf363f6422 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ResourcePersistTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ResourcePersistTest.java @@ -23,8 +23,8 @@ import org.apache.doris.catalog.S3Resource; import org.apache.doris.common.io.Text; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -37,7 +37,7 @@ public class ResourcePersistTest { public void test() throws IOException { Resource resource = new S3Resource("s3_resource"); S3Resource resource1 = (S3Resource) readWrittenResource(resource); - Assert.assertEquals(resource1.toString(), resource.toString()); + Assertions.assertEquals(resource1.toString(), resource.toString()); resource1.readLock(); resource1.readUnlock(); } @@ -45,12 +45,12 @@ public void test() throws IOException { @Test public void testAzureResourcePersist() throws IOException { Resource resource = new AzureResource("azure_resource"); - Assert.assertTrue(resource.toString().contains("\"clazz\":\"AzureResource\"")); + Assertions.assertTrue(resource.toString().contains("\"clazz\":\"AzureResource\"")); Resource readResource = readWrittenResource(resource); - Assert.assertTrue(readResource instanceof AzureResource); - Assert.assertEquals("azure_resource", readResource.getName()); - Assert.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); + Assertions.assertTrue(readResource instanceof AzureResource); + Assertions.assertEquals("azure_resource", readResource.getName()); + Assertions.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); readResource.readLock(); readResource.readUnlock(); } @@ -61,9 +61,9 @@ public void testReadLegacyAzureResourceWithoutClazz() throws IOException { + "\"references\":{},\"id\":123,\"version\":0}"; Resource readResource = readResourceFromJson(json); - Assert.assertTrue(readResource instanceof AzureResource); - Assert.assertEquals("legacy_azure_resource", readResource.getName()); - Assert.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); + Assertions.assertTrue(readResource instanceof AzureResource); + Assertions.assertEquals("legacy_azure_resource", readResource.getName()); + Assertions.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); readResource.readLock(); readResource.readUnlock(); } @@ -75,9 +75,9 @@ public void testReadLegacyAzureResourceMgrWithoutClazz() throws IOException { ResourceMgr resourceMgr = readResourceMgrFromJson(json); Resource readResource = resourceMgr.getResource("legacy_azure_resource"); - Assert.assertTrue(readResource instanceof AzureResource); - Assert.assertEquals("legacy_azure_resource", readResource.getName()); - Assert.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); + Assertions.assertTrue(readResource instanceof AzureResource); + Assertions.assertEquals("legacy_azure_resource", readResource.getName()); + Assertions.assertEquals(Resource.ResourceType.AZURE, readResource.getType()); readResource.readLock(); readResource.readUnlock(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/ScalarTypeTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/ScalarTypeTest.java index 3fac71bfc33d2d..6f9739c2417108 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/ScalarTypeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/ScalarTypeTest.java @@ -22,8 +22,8 @@ import org.apache.doris.catalog.VariantType; import org.apache.doris.persist.gson.GsonUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ScalarTypeTest { @Test @@ -32,10 +32,10 @@ public void testScalarType() { String json = GsonUtils.GSON.toJson(scalarType); System.out.println(json); ScalarType scalarType2 = GsonUtils.GSON.fromJson(json, ScalarType.class); - Assert.assertFalse(scalarType2 instanceof VariantType); - Assert.assertEquals(scalarType.getPrimitiveType(), scalarType2.getPrimitiveType()); - Assert.assertEquals(scalarType.getVariantMaxSubcolumnsCount(), 0); - Assert.assertEquals(scalarType.getVariantEnableTypedPathsToSparse(), false); - Assert.assertEquals(scalarType.getVariantMaxSparseColumnStatisticsSize(), 0); + Assertions.assertFalse(scalarType2 instanceof VariantType); + Assertions.assertEquals(scalarType.getPrimitiveType(), scalarType2.getPrimitiveType()); + Assertions.assertEquals(scalarType.getVariantMaxSubcolumnsCount(), 0); + Assertions.assertEquals(scalarType.getVariantEnableTypedPathsToSparse(), false); + Assertions.assertEquals(scalarType.getVariantMaxSparseColumnStatisticsSize(), 0); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/StorageInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/StorageInfoTest.java index 7adf1c0b6f5060..3c7a9cf98ebbb9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/StorageInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/StorageInfoTest.java @@ -17,28 +17,28 @@ package org.apache.doris.persist; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class StorageInfoTest { @Test public void test() { StorageInfo info = new StorageInfo(); - Assert.assertEquals(-1, info.getClusterID()); - Assert.assertEquals(0, info.getImageSeq()); - Assert.assertEquals(0, info.getEditsSeq()); + Assertions.assertEquals(-1, info.getClusterID()); + Assertions.assertEquals(0, info.getImageSeq()); + Assertions.assertEquals(0, info.getEditsSeq()); info = new StorageInfo(10, 20, 30); - Assert.assertEquals(10, info.getClusterID()); - Assert.assertEquals(20, info.getImageSeq()); - Assert.assertEquals(30, info.getEditsSeq()); + Assertions.assertEquals(10, info.getClusterID()); + Assertions.assertEquals(20, info.getImageSeq()); + Assertions.assertEquals(30, info.getEditsSeq()); info.setClusterID(100); info.setImageSeq(200); info.setEditsSeq(300); - Assert.assertEquals(100, info.getClusterID()); - Assert.assertEquals(200, info.getImageSeq()); - Assert.assertEquals(300, info.getEditsSeq()); + Assertions.assertEquals(100, info.getClusterID()); + Assertions.assertEquals(200, info.getImageSeq()); + Assertions.assertEquals(300, info.getEditsSeq()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/StoragePolicyPersistTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/StoragePolicyPersistTest.java index 1eeabcf9a417d6..c3892f8e39d2e7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/StoragePolicyPersistTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/StoragePolicyPersistTest.java @@ -19,8 +19,8 @@ import org.apache.doris.policy.StoragePolicy; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -48,11 +48,11 @@ public void test() throws IOException { DataInputStream dis = new DataInputStream(new FileInputStream(file)); StoragePolicy storagePolicy1 = (StoragePolicy) StoragePolicy.read(dis); dis.close(); - Assert.assertEquals(cooldownTime, storagePolicy1.getCooldownTimestampMs()); - Assert.assertTrue(storagePolicy1.getLock() != null); + Assertions.assertEquals(cooldownTime, storagePolicy1.getCooldownTimestampMs()); + Assertions.assertTrue(storagePolicy1.getLock() != null); StoragePolicy clonePolicy = storagePolicy1.clone(); - Assert.assertEquals(cooldownTime, clonePolicy.getCooldownTimestampMs()); + Assertions.assertEquals(cooldownTime, clonePolicy.getCooldownTimestampMs()); } finally { file.delete(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/StorageTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/StorageTest.java index 78dd2bcb07a9b6..d27cf38d39be24 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/StorageTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/StorageTest.java @@ -17,8 +17,8 @@ package org.apache.doris.persist; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileWriter; @@ -99,14 +99,14 @@ public void deleteDir() { @Test public void testConstruct() { Storage storage1 = new Storage(1, "token", "test"); - Assert.assertEquals(1, storage1.getClusterID()); - Assert.assertEquals("test", storage1.getMetaDir()); + Assertions.assertEquals(1, storage1.getClusterID()); + Assertions.assertEquals("test", storage1.getMetaDir()); Storage storage2 = new Storage(1, "token", 2, 3, "test"); - Assert.assertEquals(1, storage2.getClusterID()); - Assert.assertEquals(2, storage2.getLatestImageSeq()); - Assert.assertEquals(3, storage2.getEditsSeq()); - Assert.assertEquals("test", storage2.getMetaDir()); + Assertions.assertEquals(1, storage2.getClusterID()); + Assertions.assertEquals(2, storage2.getLatestImageSeq()); + Assertions.assertEquals(3, storage2.getEditsSeq()); + Assertions.assertEquals("test", storage2.getMetaDir()); } @Test @@ -114,30 +114,30 @@ public void testStorage() throws Exception { mkdir(); addFiles(5, 10); Storage storage = new Storage("storageTestDir"); - Assert.assertEquals(966271669, storage.getClusterID()); - Assert.assertEquals(5, storage.getLatestImageSeq()); - Assert.assertEquals(4, storage.getLatestValidatedImageSeq()); - Assert.assertEquals(10, Storage.getMetaSeq(new File("storageTestDir/edits.10"))); - Assert.assertEquals( + Assertions.assertEquals(966271669, storage.getClusterID()); + Assertions.assertEquals(5, storage.getLatestImageSeq()); + Assertions.assertEquals(4, storage.getLatestValidatedImageSeq()); + Assertions.assertEquals(10, Storage.getMetaSeq(new File("storageTestDir/edits.10"))); + Assertions.assertEquals( Storage.getCurrentEditsFile(new File("storageTestDir")), new File("storageTestDir/edits")); - Assert.assertEquals(storage.getCurrentImageFile(), new File("storageTestDir/image.5")); - Assert.assertEquals(storage.getImageFile(0), new File("storageTestDir/image.0")); - Assert.assertEquals( + Assertions.assertEquals(storage.getCurrentImageFile(), new File("storageTestDir/image.5")); + Assertions.assertEquals(storage.getImageFile(0), new File("storageTestDir/image.0")); + Assertions.assertEquals( Storage.getImageFile(new File("storageTestDir"), 0), new File("storageTestDir/image.0")); - Assert.assertEquals(storage.getCurrentEditsFile(), new File("storageTestDir/edits")); - Assert.assertEquals(storage.getEditsFile(5), new File("storageTestDir/edits.5")); - Assert.assertEquals( + Assertions.assertEquals(storage.getCurrentEditsFile(), new File("storageTestDir/edits")); + Assertions.assertEquals(storage.getEditsFile(5), new File("storageTestDir/edits.5")); + Assertions.assertEquals( Storage.getEditsFile(new File("storageTestDir"), 3), new File("storageTestDir/edits.3")); - Assert.assertEquals(storage.getVersionFile(), new File("storageTestDir/VERSION")); + Assertions.assertEquals(storage.getVersionFile(), new File("storageTestDir/VERSION")); - Assert.assertEquals("storageTestDir", storage.getMetaDir()); + Assertions.assertEquals("storageTestDir", storage.getMetaDir()); storage.clear(); File file = new File(storage.getMetaDir()); - Assert.assertEquals(0, file.list().length); + Assertions.assertEquals(0, file.list().length); deleteDir(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/TableAddOrDropColumnsInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/TableAddOrDropColumnsInfoTest.java index 325d10a92f1e39..059b00687e4569 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/TableAddOrDropColumnsInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/TableAddOrDropColumnsInfoTest.java @@ -26,9 +26,9 @@ import org.apache.doris.persist.gson.GsonUtils; import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -89,14 +89,14 @@ public void testSerialization() throws IOException { TableAddOrDropColumnsInfo tableAddOrDropColumnsInfo2 = GsonUtils.GSON.fromJson(readJson, TableAddOrDropColumnsInfo.class); - Assert.assertEquals(tableAddOrDropColumnsInfo1.getDbId(), tableAddOrDropColumnsInfo2.getDbId()); - Assert.assertEquals(tableAddOrDropColumnsInfo1.getTableId(), tableAddOrDropColumnsInfo2.getTableId()); - Assert.assertEquals(tableAddOrDropColumnsInfo1.getIndexSchemaMap(), + Assertions.assertEquals(tableAddOrDropColumnsInfo1.getDbId(), tableAddOrDropColumnsInfo2.getDbId()); + Assertions.assertEquals(tableAddOrDropColumnsInfo1.getTableId(), tableAddOrDropColumnsInfo2.getTableId()); + Assertions.assertEquals(tableAddOrDropColumnsInfo1.getIndexSchemaMap(), tableAddOrDropColumnsInfo2.getIndexSchemaMap()); } - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/TableInfoTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/TableInfoTest.java index ae6d1ec09237b2..0944d41e37042e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/TableInfoTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/TableInfoTest.java @@ -19,8 +19,8 @@ import org.apache.doris.common.AnalysisException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -46,9 +46,9 @@ public void testSerialization() throws IOException, AnalysisException { TableInfo tableInfo2 = TableInfo.read(in); - Assert.assertEquals(tableInfo1.getTableId(), tableInfo2.getTableId()); - Assert.assertEquals(tableInfo1.getDbId(), tableInfo2.getDbId()); - Assert.assertEquals(tableInfo1.getNewTableName(), tableInfo2.getNewTableName()); + Assertions.assertEquals(tableInfo1.getTableId(), tableInfo2.getTableId()); + Assertions.assertEquals(tableInfo1.getDbId(), tableInfo2.getDbId()); + Assertions.assertEquals(tableInfo1.getNewTableName(), tableInfo2.getNewTableName()); // 3. delete files in.close(); diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonDerivedClassSerializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonDerivedClassSerializationTest.java index b35fb459795ea5..d31938eea6e1da 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonDerivedClassSerializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonDerivedClassSerializationTest.java @@ -26,9 +26,9 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInput; import java.io.DataInputStream; @@ -57,7 +57,7 @@ public class GsonDerivedClassSerializationTest { private static String fileName = "./GsonDerivedClassSerializationTest"; - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -168,10 +168,10 @@ public void testDerivedClassA() throws IOException { // 2. Read objects from file DataInputStream in = new DataInputStream(new FileInputStream(file)); ParentClass parentClass = ParentClass.read(in); - Assert.assertTrue(parentClass instanceof ChildClassA); - Assert.assertEquals(1, ((ChildClassA) parentClass).flag); - Assert.assertEquals("A", ((ChildClassA) parentClass).tagA); - Assert.assertEquals("after post", ((ChildClassA) parentClass).postTagA); + Assertions.assertTrue(parentClass instanceof ChildClassA); + Assertions.assertEquals(1, ((ChildClassA) parentClass).flag); + Assertions.assertEquals("A", ((ChildClassA) parentClass).tagA); + Assertions.assertEquals("after post", ((ChildClassA) parentClass).postTagA); } @Test @@ -189,11 +189,11 @@ public void testDerivedClassB() throws IOException { // 2. Read objects from file DataInputStream in = new DataInputStream(new FileInputStream(file)); ParentClass parentClass = ParentClass.read(in); - Assert.assertTrue(parentClass instanceof ChildClassB); - Assert.assertEquals(2, ((ChildClassB) parentClass).flag); - Assert.assertEquals(2, ((ChildClassB) parentClass).mapB.size()); - Assert.assertEquals("B1", ((ChildClassB) parentClass).mapB.get(1L)); - Assert.assertEquals("B2", ((ChildClassB) parentClass).mapB.get(2L)); + Assertions.assertTrue(parentClass instanceof ChildClassB); + Assertions.assertEquals(2, ((ChildClassB) parentClass).flag); + Assertions.assertEquals(2, ((ChildClassB) parentClass).mapB.size()); + Assertions.assertEquals("B1", ((ChildClassB) parentClass).mapB.get(1L)); + Assertions.assertEquals("B2", ((ChildClassB) parentClass).mapB.get(2L)); } @Test @@ -211,7 +211,7 @@ public void testWrapperClass() throws IOException { // 2. Read objects from file DataInputStream in = new DataInputStream(new FileInputStream(file)); WrapperClass readWrapperClass = WrapperClass.read(in); - Assert.assertEquals(1, ((ChildClassA) readWrapperClass.clz).flag); + Assertions.assertEquals(1, ((ChildClassA) readWrapperClass.clz).flag); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonProtobufCompatibilityTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonProtobufCompatibilityTest.java index 2239a23b3b9bdf..444b721e31d044 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonProtobufCompatibilityTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonProtobufCompatibilityTest.java @@ -19,8 +19,8 @@ import com.google.gson.annotations.SerializedName; import doris.segment_v2.SegmentV2; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class GsonProtobufCompatibilityTest { private static class ProtobufBuilderHolder { @@ -34,7 +34,7 @@ private static class ProtobufBuilderHolder { @Test public void testSerializeGeneratedProtobufBuilder() { String json = GsonUtils.GSON.toJson(new ProtobufBuilderHolder()); - Assert.assertTrue(json, json.contains("\"name\":\"holder\"")); - Assert.assertFalse(json, json.contains("\"builder\"")); + Assertions.assertTrue(json.contains("\"name\":\"holder\""), json); + Assertions.assertFalse(json.contains("\"builder\""), json); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonSerializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonSerializationTest.java index 0f622afe2ecbf6..890aabd8f4d926 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonSerializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/GsonSerializationTest.java @@ -30,9 +30,9 @@ import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.gson.annotations.SerializedName; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInput; import java.io.DataInputStream; @@ -232,7 +232,7 @@ public static OriginClassADifferentMemberName read(DataInput in) throws IOExcept } } - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -257,31 +257,31 @@ public void testNormal() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); OrigClassA readClassA = OrigClassA.read(in); - Assert.assertEquals(1, readClassA.flag); - Assert.assertEquals(1, readClassA.classA1.flag); - Assert.assertNull(readClassA.ignoreClassA2); - - Assert.assertEquals(Lists.newArrayList("string1", "string2"), readClassA.classA1.list1); - Assert.assertTrue(readClassA.classA1.map1.containsKey(1L)); - Assert.assertTrue(readClassA.classA1.map1.containsKey(2L)); - Assert.assertEquals("value1", readClassA.classA1.map1.get(1L)); - Assert.assertEquals("value2", readClassA.classA1.map1.get(2L)); - - Assert.assertTrue(readClassA.classA1.map2.containsKey(1)); - Assert.assertTrue(readClassA.classA1.map2.containsKey(2)); - Assert.assertEquals(1, readClassA.classA1.map2.get(1).flag); - Assert.assertEquals(2, readClassA.classA1.map2.get(2).flag); - Assert.assertEquals(0, readClassA.classA1.map2.get(1).ignoreField); - Assert.assertEquals(0, readClassA.classA1.map2.get(2).ignoreField); - Assert.assertEquals(Sets.newHashSet("set1", "set2"), readClassA.classA1.set1); + Assertions.assertEquals(1, readClassA.flag); + Assertions.assertEquals(1, readClassA.classA1.flag); + Assertions.assertNull(readClassA.ignoreClassA2); + + Assertions.assertEquals(Lists.newArrayList("string1", "string2"), readClassA.classA1.list1); + Assertions.assertTrue(readClassA.classA1.map1.containsKey(1L)); + Assertions.assertTrue(readClassA.classA1.map1.containsKey(2L)); + Assertions.assertEquals("value1", readClassA.classA1.map1.get(1L)); + Assertions.assertEquals("value2", readClassA.classA1.map1.get(2L)); + + Assertions.assertTrue(readClassA.classA1.map2.containsKey(1)); + Assertions.assertTrue(readClassA.classA1.map2.containsKey(2)); + Assertions.assertEquals(1, readClassA.classA1.map2.get(1).flag); + Assertions.assertEquals(2, readClassA.classA1.map2.get(2).flag); + Assertions.assertEquals(0, readClassA.classA1.map2.get(1).ignoreField); + Assertions.assertEquals(0, readClassA.classA1.map2.get(2).ignoreField); + Assertions.assertEquals(Sets.newHashSet("set1", "set2"), readClassA.classA1.set1); Table hashBasedTable = readClassA.classA1.map2.get(1).hashBasedTable; - Assert.assertEquals("HashBasedTable", hashBasedTable.getClass().getSimpleName()); + Assertions.assertEquals("HashBasedTable", hashBasedTable.getClass().getSimpleName()); Multimap hashMultimap = readClassA.classA1.map2.get(1).hashMultimap; - Assert.assertEquals("HashMultimap", hashMultimap.getClass().getSimpleName()); + Assertions.assertEquals("HashMultimap", hashMultimap.getClass().getSimpleName()); Multimap arrayListMultimap = readClassA.classA1.map2.get(1).arrayListMultimap; - Assert.assertEquals("ArrayListMultimap", arrayListMultimap.getClass().getSimpleName()); - Assert.assertEquals(Lists.newArrayList("value1", "value2"), arrayListMultimap.get(1L)); + Assertions.assertEquals("ArrayListMultimap", arrayListMultimap.getClass().getSimpleName()); + Assertions.assertEquals(Lists.newArrayList("value1", "value2"), arrayListMultimap.get(1L)); in.close(); } @@ -305,9 +305,9 @@ public void testWithDifferentMembers() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); OriginClassADifferentMembers readClassA = OriginClassADifferentMembers.read(in); - Assert.assertEquals(1, readClassA.flag); - Assert.assertNull(readClassA.classA3); - Assert.assertNull(readClassA.ignoreClassA2); + Assertions.assertEquals(1, readClassA.flag); + Assertions.assertNull(readClassA.classA3); + Assertions.assertNull(readClassA.ignoreClassA2); in.close(); } @@ -330,23 +330,23 @@ public void testWithDifferentMemberNames() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); OriginClassADifferentMemberName readClassA = OriginClassADifferentMemberName.read(in); - Assert.assertEquals(1, readClassA.flagChangeName); - Assert.assertEquals(1, readClassA.classA1ChangeName.flag); - Assert.assertNull(readClassA.ignoreClassA2ChangeName); - - Assert.assertEquals(Lists.newArrayList("string1", "string2"), readClassA.classA1ChangeName.list1); - Assert.assertTrue(readClassA.classA1ChangeName.map1.containsKey(1L)); - Assert.assertTrue(readClassA.classA1ChangeName.map1.containsKey(2L)); - Assert.assertEquals("value1", readClassA.classA1ChangeName.map1.get(1L)); - Assert.assertEquals("value2", readClassA.classA1ChangeName.map1.get(2L)); - - Assert.assertTrue(readClassA.classA1ChangeName.map2.containsKey(1)); - Assert.assertTrue(readClassA.classA1ChangeName.map2.containsKey(2)); - Assert.assertEquals(1, readClassA.classA1ChangeName.map2.get(1).flag); - Assert.assertEquals(2, readClassA.classA1ChangeName.map2.get(2).flag); - Assert.assertEquals(0, readClassA.classA1ChangeName.map2.get(1).ignoreField); - Assert.assertEquals(0, readClassA.classA1ChangeName.map2.get(2).ignoreField); - Assert.assertEquals(Sets.newHashSet("set1", "set2"), readClassA.classA1ChangeName.set1); + Assertions.assertEquals(1, readClassA.flagChangeName); + Assertions.assertEquals(1, readClassA.classA1ChangeName.flag); + Assertions.assertNull(readClassA.ignoreClassA2ChangeName); + + Assertions.assertEquals(Lists.newArrayList("string1", "string2"), readClassA.classA1ChangeName.list1); + Assertions.assertTrue(readClassA.classA1ChangeName.map1.containsKey(1L)); + Assertions.assertTrue(readClassA.classA1ChangeName.map1.containsKey(2L)); + Assertions.assertEquals("value1", readClassA.classA1ChangeName.map1.get(1L)); + Assertions.assertEquals("value2", readClassA.classA1ChangeName.map1.get(2L)); + + Assertions.assertTrue(readClassA.classA1ChangeName.map2.containsKey(1)); + Assertions.assertTrue(readClassA.classA1ChangeName.map2.containsKey(2)); + Assertions.assertEquals(1, readClassA.classA1ChangeName.map2.get(1).flag); + Assertions.assertEquals(2, readClassA.classA1ChangeName.map2.get(2).flag); + Assertions.assertEquals(0, readClassA.classA1ChangeName.map2.get(1).ignoreField); + Assertions.assertEquals(0, readClassA.classA1ChangeName.map2.get(2).ignoreField); + Assertions.assertEquals(Sets.newHashSet("set1", "set2"), readClassA.classA1ChangeName.set1); in.close(); } @@ -428,7 +428,7 @@ public void testMultiMapWithCustomKey() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); MultiMapClassA readClassA = MultiMapClassA.read(in); - Assert.assertEquals(Sets.newHashSet(new Key(MyEnum.TYPE_A, "key1"), new Key(MyEnum.TYPE_B, "key2")), + Assertions.assertEquals(Sets.newHashSet(new Key(MyEnum.TYPE_A, "key1"), new Key(MyEnum.TYPE_B, "key2")), readClassA.map.keySet()); } @@ -493,13 +493,13 @@ public void testConcurrentMap() throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); ConcurrentMapClassA readClassA = ConcurrentMapClassA.read(in); - Assert.assertTrue(readClassA.map1 instanceof ConcurrentHashMap); - Assert.assertTrue(readClassA.map2 instanceof ConcurrentHashMap); - Assert.assertTrue(readClassA.map3 instanceof ConcurrentHashMap); - Assert.assertTrue(readClassA.map3.get("b") instanceof ConcurrentHashMap); - Assert.assertTrue(readClassA.map4 instanceof ConcurrentHashMap); - Assert.assertFalse(readClassA.map4.get("b") instanceof ConcurrentHashMap); - Assert.assertFalse(readClassA.map5 instanceof ConcurrentHashMap); - Assert.assertFalse(readClassA.map6 instanceof ConcurrentHashMap); + Assertions.assertTrue(readClassA.map1 instanceof ConcurrentHashMap); + Assertions.assertTrue(readClassA.map2 instanceof ConcurrentHashMap); + Assertions.assertTrue(readClassA.map3 instanceof ConcurrentHashMap); + Assertions.assertTrue(readClassA.map3.get("b") instanceof ConcurrentHashMap); + Assertions.assertTrue(readClassA.map4 instanceof ConcurrentHashMap); + Assertions.assertFalse(readClassA.map4.get("b") instanceof ConcurrentHashMap); + Assertions.assertFalse(readClassA.map5 instanceof ConcurrentHashMap); + Assertions.assertFalse(readClassA.map6 instanceof ConcurrentHashMap); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/ThriftToJsonTest.java b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/ThriftToJsonTest.java index f8c5d46bc44b90..56f80ff187d73d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/persist/gson/ThriftToJsonTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/persist/gson/ThriftToJsonTest.java @@ -19,8 +19,8 @@ import org.apache.doris.thrift.TStorageFormat; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ThriftToJsonTest { @@ -30,6 +30,6 @@ public void testTEnumToJson() { String serializeString = GsonUtils.GSON.toJson(TStorageFormat.V1); // read TStorageFormat tStorageFormat = GsonUtils.GSON.fromJson(serializeString, TStorageFormat.class); - Assert.assertEquals(TStorageFormat.V1, tStorageFormat); + Assertions.assertEquals(TStorageFormat.V1, tStorageFormat); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java index 34ec8355a9645d..d28dc0ffe59f01 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/FederationBackendPolicyTest.java @@ -32,11 +32,10 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -56,14 +55,14 @@ public class FederationBackendPolicyTest { private Env env = Mockito.mock(Env.class); private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setUp() { mockedEnvStatic = Mockito.mockStatic(Env.class); mockedEnvStatic.when(Env::getCurrentEnv).thenReturn(env); Mockito.when(env.getEditLog()).thenReturn(Mockito.mock(org.apache.doris.persist.EditLog.class)); } - @After + @AfterEach public void tearDown() { mockedEnvStatic.close(); } @@ -155,16 +154,16 @@ public void testHasLocalSplits() throws UserException { FileSplit fileSplit = (FileSplit) split; ++totalSplitNum; if (fileSplit.getPath().getNormalizedLocation().equals("hdfs://HDFS8000871/usr/hive/warehouse/clickbench.db/hits_orc/part-00000-3e24f7d5-f658-4a80-a168-7b215c5a35bf-c000.snappy.orc")) { - Assert.assertEquals("172.30.0.100", backend.getHost()); + Assertions.assertEquals("172.30.0.100", backend.getHost()); checkedLocalSplit.add(true); } else if (fileSplit.getPath().getNormalizedLocation().equals("hdfs://HDFS8000871/usr/hive/warehouse/clickbench.db/hits_orc/part-00003-3e24f7d5-f658-4a80-a168-7b215c5a35bf-c000.snappy.orc")) { - Assert.assertEquals("172.30.0.106", backend.getHost()); + Assertions.assertEquals("172.30.0.106", backend.getHost()); checkedLocalSplit.add(true); } } } - Assert.assertEquals(2, checkedLocalSplit.size()); - Assert.assertEquals(8, totalSplitNum); + Assertions.assertEquals(2, checkedLocalSplit.size()); + Assertions.assertEquals(8, totalSplitNum); int maxAssignedSplitNum = Integer.MIN_VALUE; int minAssignedSplitNum = Integer.MAX_VALUE; @@ -183,7 +182,7 @@ public void testHasLocalSplits() throws UserException { } System.out.printf("%s -> %d splits, %d bytes\n", backend, assignedSplits.size(), scanBytes); } - Assert.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); + Assertions.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); } @@ -239,7 +238,7 @@ public void testConsistentHash() throws UserException { } System.out.printf("%s -> %d splits, %d bytes\n", backend, assignedSplits.size(), scanBytes); } - Assert.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); + Assertions.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); } @@ -356,15 +355,15 @@ public void testGenerateRandomly() throws UserException { ++totalSplitNum; if (fileSplit.getHosts() != null && fileSplit.getHosts().length > 0) { for (String host : fileSplit.getHosts()) { - Assert.assertTrue(totalLocalHosts.contains(host)); + Assertions.assertTrue(totalLocalHosts.contains(host)); } } } System.out.printf("%s -> %d splits, %d bytes\n", backend, assignedSplits.size(), scanBytes); } - Assert.assertEquals(totalSplits.size(), totalSplitNum); + Assertions.assertEquals(totalSplits.size(), totalSplitNum); - Assert.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); + Assertions.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); } } @@ -470,15 +469,15 @@ public void testNonAliveNodes() throws UserException { ++totalSplitNum; if (fileSplit.getHosts() != null && fileSplit.getHosts().length > 0) { for (String host : fileSplit.getHosts()) { - Assert.assertTrue(totalLocalHosts.contains(host)); + Assertions.assertTrue(totalLocalHosts.contains(host)); } } } System.out.printf("%s -> %d splits, %d bytes\n", backend, assignedSplits.size(), scanBytes); } - Assert.assertEquals(totalSplits.size(), totalSplitNum); + Assertions.assertEquals(totalSplits.size(), totalSplitNum); - Assert.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); + Assertions.assertTrue(Math.abs(maxAssignedSplitNum - minAssignedSplitNum) <= Config.split_assigner_max_split_num_variance); } } @@ -662,13 +661,13 @@ public void testSplitWeight() { fileSplit.setSelfSplitWeight(1000L); fileSplit.setTargetSplitSize(10L); - Assert.assertEquals(100L, fileSplit.getSplitWeight().getRawValue(), 100L); + Assertions.assertEquals(100L, fileSplit.getSplitWeight().getRawValue(), 100L); fileSplit.setTargetSplitSize(10000000L); - Assert.assertEquals(1L, fileSplit.getSplitWeight().getRawValue()); + Assertions.assertEquals(1L, fileSplit.getSplitWeight().getRawValue()); fileSplit.setTargetSplitSize(2000L); - Assert.assertEquals(50, fileSplit.getSplitWeight().getRawValue()); + Assertions.assertEquals(50, fileSplit.getSplitWeight().getRawValue()); } // Regression for the NPE in testGenerateRandomly: FileSplit is Lombok @Data, whose generated @@ -682,9 +681,9 @@ public void testFileSplitEqualsHashCodeWithUnsetWeight() { // proceeds past the identity short-circuit and exercises getSelfSplitWeight(). FileSplit a = new FileSplit(path, 0, 1000, 1000, 0, null, Collections.emptyList()); FileSplit b = new FileSplit(path, 0, 1000, 1000, 0, null, Collections.emptyList()); - Assert.assertEquals(-1L, a.getSelfSplitWeight()); - Assert.assertEquals(a, b); - Assert.assertEquals(a.hashCode(), b.hashCode()); + Assertions.assertEquals(-1L, a.getSelfSplitWeight()); + Assertions.assertEquals(a, b); + Assertions.assertEquals(a.hashCode(), b.hashCode()); } @Test @@ -721,9 +720,9 @@ public void testBiggerSplit() throws UserException { Map> backendListMap = mergeAssignment(assignment); backendListMap.forEach((k, v) -> { if (k.getId() == 1) { - Assert.assertEquals(800000, v.stream().mapToLong(Split::getLength).sum()); + Assertions.assertEquals(800000, v.stream().mapToLong(Split::getLength).sum()); } else if (k.getId() == 2) { - Assert.assertEquals(1600000, v.stream().mapToLong(Split::getLength).sum()); + Assertions.assertEquals(1600000, v.stream().mapToLong(Split::getLength).sum()); } }); @@ -734,11 +733,11 @@ public void testBiggerSplit() throws UserException { Map> backendListMap2 = mergeAssignment(assignment2); backendListMap2.forEach((k, v) -> { if (k.getId() == 1) { - Assert.assertEquals(1000000L, v.stream().mapToLong(Split::getLength).sum()); + Assertions.assertEquals(1000000L, v.stream().mapToLong(Split::getLength).sum()); } else if (k.getId() == 2) { - Assert.assertEquals(400000L, v.stream().mapToLong(Split::getLength).sum()); + Assertions.assertEquals(400000L, v.stream().mapToLong(Split::getLength).sum()); } else if (k.getId() == 3) { - Assert.assertEquals(1000000L, v.stream().mapToLong(Split::getLength).sum()); + Assertions.assertEquals(1000000L, v.stream().mapToLong(Split::getLength).sum()); } }); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/GroupCommitBlockSinkTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/GroupCommitBlockSinkTest.java index 3357c05554daea..46b82340e9492d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/GroupCommitBlockSinkTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/GroupCommitBlockSinkTest.java @@ -25,8 +25,8 @@ import org.apache.doris.thrift.TOlapTableSink; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -41,23 +41,23 @@ public void testInitLocationParamsSkipsCreateLocation() throws UserException { TOlapTableLocationParam location = sink.initLocationParam(new TOlapTableSink()); - Assert.assertNotNull(location.getTablets()); - Assert.assertTrue("location should be empty placeholder", location.getTablets().isEmpty()); + Assertions.assertNotNull(location.getTablets()); + Assertions.assertTrue(location.getTablets().isEmpty(), "location should be empty placeholder"); Mockito.verifyNoInteractions(dstTable); Mockito.verifyNoInteractions(tuple); } @Test public void testParseGroupCommit() { - Assert.assertEquals(TGroupCommitMode.ASYNC_MODE, + Assertions.assertEquals(TGroupCommitMode.ASYNC_MODE, GroupCommitBlockSink.parseGroupCommit("async_mode")); - Assert.assertEquals(TGroupCommitMode.ASYNC_MODE, + Assertions.assertEquals(TGroupCommitMode.ASYNC_MODE, GroupCommitBlockSink.parseGroupCommit("ASYNC_MODE")); - Assert.assertEquals(TGroupCommitMode.SYNC_MODE, + Assertions.assertEquals(TGroupCommitMode.SYNC_MODE, GroupCommitBlockSink.parseGroupCommit("sync_mode")); - Assert.assertEquals(TGroupCommitMode.OFF_MODE, + Assertions.assertEquals(TGroupCommitMode.OFF_MODE, GroupCommitBlockSink.parseGroupCommit("off_mode")); - Assert.assertNull(GroupCommitBlockSink.parseGroupCommit(null)); - Assert.assertNull(GroupCommitBlockSink.parseGroupCommit("invalid")); + Assertions.assertNull(GroupCommitBlockSink.parseGroupCommit(null)); + Assertions.assertNull(GroupCommitBlockSink.parseGroupCommit("invalid")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/HashDistributionPrunerTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/HashDistributionPrunerTest.java index 6cc4194dfe7cc7..a475b923874553 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/HashDistributionPrunerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/HashDistributionPrunerTest.java @@ -31,8 +31,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.List; @@ -103,13 +103,13 @@ public void test() { Collection results = pruner.prune(); // 20 = 1 * 5 * 2 * 2 * 1 (element num of each filter) - Assert.assertEquals(20, results.size()); + Assertions.assertEquals(20, results.size()); filters.get("SHOP_TYPE").getInPredicate().addChild(new StringLiteral("4")); results = pruner.prune(); // 40 = 1 * 5 * 2 * 2 * 2 (element num of each filter) // 39 is because these is hash conflict - Assert.assertEquals(39, results.size()); + Assertions.assertEquals(39, results.size()); filters.get("SHOP_TYPE").getInPredicate().addChild(new StringLiteral("5")); filters.get("SHOP_TYPE").getInPredicate().addChild(new StringLiteral("6")); @@ -117,7 +117,7 @@ public void test() { filters.get("SHOP_TYPE").getInPredicate().addChild(new StringLiteral("8")); results = pruner.prune(); // 120 = 1 * 5 * 2 * 2 * 6 (element num of each filter) > 100 - Assert.assertEquals(300, results.size()); + Assertions.assertEquals(300, results.size()); // check hash conflict inList4.add(new StringLiteral("4")); @@ -143,7 +143,7 @@ public void test() { hashKey.popColumn(); } - Assert.assertEquals(39, tablets.size()); + Assertions.assertEquals(39, tablets.size()); } @Test @@ -177,12 +177,12 @@ public void testPruneWithMaterializedIndex() { long hashValue = hashKey.getHashValue(); expectedTabletIds.add(tabletIds.get((int) ((hashValue & 0xffffffff) % tabletIds.size()))); } - Assert.assertEquals(expectedTabletIds, Sets.newHashSet(indexResult)); + Assertions.assertEquals(expectedTabletIds, Sets.newHashSet(indexResult)); Map emptyFilters = new CaseInsensitiveMap(); Collection allIndexTablets = new HashDistributionPruner(null, index, columns, emptyFilters, tabletIds.size(), true).prune(); - Assert.assertEquals(tabletIds, Lists.newArrayList(allIndexTablets)); + Assertions.assertEquals(tabletIds, Lists.newArrayList(allIndexTablets)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/ListPartitionPrunerV2Test.java b/fe/fe-core/src/test/java/org/apache/doris/planner/ListPartitionPrunerV2Test.java index 17954bbf9ae1bc..1cfd48859da7dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/ListPartitionPrunerV2Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/ListPartitionPrunerV2Test.java @@ -27,8 +27,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -54,7 +54,7 @@ public void testPartitionValuesMap() throws AnalysisException { idToPartitionItem.put(2L, listPartitionItem2); Map> partitionValuesMap = ListPartitionPrunerV2.getPartitionValuesMap(idToPartitionItem); - Assert.assertEquals("1.123000", partitionValuesMap.get(1L).get(0)); - Assert.assertEquals("1.123", partitionValuesMap.get(2L).get(0)); + Assertions.assertEquals("1.123000", partitionValuesMap.get(1L).get(0)); + Assertions.assertEquals("1.123", partitionValuesMap.get(2L).get(0)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapScanNodeTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapScanNodeTest.java index eaba851f69aba1..99b274bf381847 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapScanNodeTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapScanNodeTest.java @@ -57,8 +57,8 @@ import com.google.common.collect.Maps; import com.google.common.collect.Range; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.Collection; @@ -111,10 +111,10 @@ public void testHashDistributionOneUser() throws AnalysisException { true); Collection ids = partitionPruner.prune(); - Assert.assertEquals(ids.size(), 1); + Assertions.assertEquals(ids.size(), 1); for (Long id : ids) { - Assert.assertEquals((1 & 0xffffffff) % 3, id.intValue()); + Assertions.assertEquals((1 & 0xffffffff) % 3, id.intValue()); } } @@ -153,7 +153,7 @@ public void testHashPartitionManyUser() throws AnalysisException { true); Collection ids = partitionPruner.prune(); - Assert.assertEquals(ids.size(), 3); + Assertions.assertEquals(ids.size(), 3); } @Test @@ -163,42 +163,42 @@ public void testHashForIntLiteral() { hashKey.pushColumn(new IntLiteral(1), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 1); + Assertions.assertEquals(mod, 1); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE PartitionKey hashKey = new PartitionKey(); hashKey.pushColumn(new IntLiteral(2), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 0); + Assertions.assertEquals(mod, 0); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE PartitionKey hashKey = new PartitionKey(); hashKey.pushColumn(new IntLiteral(3), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 0); + Assertions.assertEquals(mod, 0); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE PartitionKey hashKey = new PartitionKey(); hashKey.pushColumn(new IntLiteral(4), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 1); + Assertions.assertEquals(mod, 1); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE PartitionKey hashKey = new PartitionKey(); hashKey.pushColumn(new IntLiteral(5), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 2); + Assertions.assertEquals(mod, 2); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE PartitionKey hashKey = new PartitionKey(); hashKey.pushColumn(new IntLiteral(6), PrimitiveType.BIGINT); long hashValue = hashKey.getHashValue(); long mod = (int) ((hashValue & 0xffffffff) % 3); - Assert.assertEquals(mod, 2); + Assertions.assertEquals(mod, 2); } // CHECKSTYLE IGNORE THIS LINE } @@ -211,7 +211,7 @@ public void testHasPartitionPredicateWithEquality() { List conjuncts = Lists.newArrayList(new BinaryPredicate(BinaryPredicate.Operator.EQ, new SlotRef(partitionSlot), new IntLiteral(1))); - Assert.assertTrue(ScanNode.containsPartitionPredicate( + Assertions.assertTrue(ScanNode.containsPartitionPredicate( Lists.newArrayList(partitionSlot.getColumn()), tupleDescriptor, conjuncts, null)); } @@ -224,7 +224,7 @@ public void testHasPartitionPredicateWithInPredicate() { List inList = Lists.newArrayList(new IntLiteral(1), new IntLiteral(2)); List conjuncts = Lists.newArrayList(new InPredicate(new SlotRef(partitionSlot), inList, false)); - Assert.assertTrue(ScanNode.containsPartitionPredicate( + Assertions.assertTrue(ScanNode.containsPartitionPredicate( Lists.newArrayList(partitionSlot.getColumn()), tupleDescriptor, conjuncts, null)); } @@ -237,7 +237,7 @@ public void testHasPartitionPredicateIgnoresNonPartitionColumn() { List conjuncts = Lists.newArrayList(new BinaryPredicate(BinaryPredicate.Operator.EQ, new SlotRef(nonPartitionSlot), new IntLiteral(1))); - Assert.assertFalse(ScanNode.containsPartitionPredicate( + Assertions.assertFalse(ScanNode.containsPartitionPredicate( Lists.newArrayList(partitionSlot.getColumn()), tupleDescriptor, conjuncts, null)); } @@ -289,9 +289,9 @@ public void testRuntimeFilterPartitionBoundariesUsePlanningSnapshot() throws Ana .map(TPartitionBoundary::getPartitionId) .collect(Collectors.toList()); - Assert.assertEquals(Lists.newArrayList(oldTargetPartitionId, afterPartitionId), serializedPartitionIds); + Assertions.assertEquals(Lists.newArrayList(oldTargetPartitionId, afterPartitionId), serializedPartitionIds); - Assert.assertEquals("p_target,p_after", scanNode.getSelectedPartitionNamesForExplain()); + Assertions.assertEquals("p_target,p_after", scanNode.getSelectedPartitionNamesForExplain()); } @Test @@ -306,8 +306,8 @@ public void testRuntimeFilterBucketMetadataAttachedOnceAcrossWorkers() throws Ex bucketInfo.clear(); scanNode.setRuntimeFilterBucketPruneParameters(); - Assert.assertEquals(2, paloScanRange.getBucketSeq()); - Assert.assertEquals(4, paloScanRange.getBucketNum()); + Assertions.assertEquals(2, paloScanRange.getBucketSeq()); + Assertions.assertEquals(4, paloScanRange.getBucketNum()); } @Test @@ -329,10 +329,10 @@ public void testMissingRuntimeFilterBucketMetadataDisablesScanPruning() throws E scanNode.setRuntimeFilterBucketPruneParameters(); - Assert.assertFalse(firstScanRange.isSetBucketSeq()); - Assert.assertFalse(firstScanRange.isSetBucketNum()); - Assert.assertFalse(secondScanRange.isSetBucketSeq()); - Assert.assertFalse(secondScanRange.isSetBucketNum()); + Assertions.assertFalse(firstScanRange.isSetBucketSeq()); + Assertions.assertFalse(firstScanRange.isSetBucketNum()); + Assertions.assertFalse(secondScanRange.isSetBucketSeq()); + Assertions.assertFalse(secondScanRange.isSetBucketNum()); } finally { DebugPointUtil.removeDebugPoint(OlapScanNode.MISSING_RF_BUCKET_METADATA_DEBUG_POINT); Config.enable_debug_points = previousEnableDebugPoints; @@ -386,11 +386,11 @@ public void testPointQueryBackendAlivePathsOnlyUseSelectedTabletBackends() { Map> alivePathHashes = OlapScanNode.getBackendAlivePathHashes( backends, Lists.newArrayList(selectedTablet)); - Assert.assertEquals(2, alivePathHashes.size()); - Assert.assertEquals(Collections.singleton(11L), alivePathHashes.get(firstBackend.getId())); - Assert.assertEquals(Collections.singleton(21L), alivePathHashes.get(secondBackend.getId())); - Assert.assertFalse(alivePathHashes.containsKey(unrelatedBackend.getId())); - Assert.assertFalse(alivePathHashes.containsKey(4L)); + Assertions.assertEquals(2, alivePathHashes.size()); + Assertions.assertEquals(Collections.singleton(11L), alivePathHashes.get(firstBackend.getId())); + Assertions.assertEquals(Collections.singleton(21L), alivePathHashes.get(secondBackend.getId())); + Assertions.assertFalse(alivePathHashes.containsKey(unrelatedBackend.getId())); + Assertions.assertFalse(alivePathHashes.containsKey(4L)); } private Backend backendWithDisks(long backendId, long alivePathHash, long offlinePathHash) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkBackendSelectionExplainTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkBackendSelectionExplainTest.java index ab57b23f65748d..91886a93f3e601 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkBackendSelectionExplainTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkBackendSelectionExplainTest.java @@ -23,15 +23,15 @@ import org.apache.doris.resource.BackendSelectionManager; import org.apache.doris.resource.spi.BackendSelectionProvider; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; public class OlapTableSinkBackendSelectionExplainTest { - @After + @AfterEach public void resetBackendSelectionProvider() { BackendSelectionManager.resetProviderForTest(); } @@ -48,8 +48,8 @@ public void testExplainSkipsLoadDecisionWhenLoadSelectionDisabled() { StringBuilder explain = new StringBuilder(); Deencapsulation.invoke(sink, "appendSinkSelectionExplain", explain, ""); - Assert.assertEquals("", explain.toString()); - Assert.assertEquals(0, policy.getLoadSelectionHintCalls); + Assertions.assertEquals("", explain.toString()); + Assertions.assertEquals(0, policy.getLoadSelectionHintCalls); } finally { ConnectContext.remove(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkTest.java index 7c4c7d20c1af9e..7713a687fa9c6a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/OlapTableSinkTest.java @@ -29,8 +29,8 @@ import org.apache.doris.thrift.TTabletLocation; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -62,7 +62,7 @@ public void testCreateDummyLocationUsesLoadAvailableBackendInCurrentComputeGroup OlapTableSink sink = new OlapTableSink(table, null, Collections.emptyList()); TOlapTableLocationParam location = sink.createDummyLocation(table); - Assert.assertEquals(Collections.singletonList(1L), + Assertions.assertEquals(Collections.singletonList(1L), location.getTablets().get(0).getNodeIds()); Mockito.verify(systemInfoService, Mockito.never()).getAllBackendIds(true); Mockito.verify(systemInfoService).getBackendsByCurrentCluster(); @@ -87,10 +87,10 @@ public void testCreateDummyLocationDoesNotShareBackendCandidatesAcrossIndexes() OlapTableSink sink = new OlapTableSink(table, null, Collections.emptyList()); TOlapTableLocationParam location = sink.createDummyLocation(table); - Assert.assertEquals(2, location.getTabletsSize()); - Assert.assertEquals(Collections.singletonList(1L), + Assertions.assertEquals(2, location.getTabletsSize()); + Assertions.assertEquals(Collections.singletonList(1L), location.getTablets().get(0).getNodeIds()); - Assert.assertEquals(Collections.singletonList(1L), + Assertions.assertEquals(Collections.singletonList(1L), location.getTablets().get(1).getNodeIds()); } } @@ -115,26 +115,26 @@ public void testAdaptiveRandomBucketAssignmentIsPerIndex() { Arrays.asList(10L, 20L), Arrays.asList(partition), locations, 2); AdaptiveBucketAssignment be10Assignment = assignments.get(10L).get(1000L); - Assert.assertEquals(0, be10Assignment.getLoadTabletIdx()); - Assert.assertEquals(10L, be10Assignment.getBucketBeId()); - Assert.assertEquals(Arrays.asList(0), be10Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(0, be10Assignment.getLoadTabletIdx()); + Assertions.assertEquals(10L, be10Assignment.getBucketBeId()); + Assertions.assertEquals(Arrays.asList(0), be10Assignment.getLocalBucketSeqs()); assertIndexAssignment(be10Assignment, 1L, 10L, Arrays.asList(0)); assertIndexAssignment(be10Assignment, 2L, 20L, Arrays.asList(0)); AdaptiveBucketAssignment be20Assignment = assignments.get(20L).get(1000L); - Assert.assertEquals(1, be20Assignment.getLoadTabletIdx()); - Assert.assertEquals(20L, be20Assignment.getBucketBeId()); - Assert.assertEquals(Arrays.asList(1), be20Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(1, be20Assignment.getLoadTabletIdx()); + Assertions.assertEquals(20L, be20Assignment.getBucketBeId()); + Assertions.assertEquals(Arrays.asList(1), be20Assignment.getLocalBucketSeqs()); assertIndexAssignment(be20Assignment, 1L, 20L, Arrays.asList(1)); assertIndexAssignment(be20Assignment, 2L, 10L, Arrays.asList(1)); OlapTableSink.applyAdaptiveRandomBucketAssignments(Arrays.asList(partition), assignments.get(10L)); - Assert.assertEquals(10L, partition.getBucketBeId()); - Assert.assertEquals(Arrays.asList(0), partition.getLocalBucketSeqs()); - Assert.assertEquals(10L, partition.getIndexes().get(0).getBucketBeId()); - Assert.assertEquals(Arrays.asList(0), partition.getIndexes().get(0).getLocalBucketSeqs()); - Assert.assertEquals(20L, partition.getIndexes().get(1).getBucketBeId()); - Assert.assertEquals(Arrays.asList(0), partition.getIndexes().get(1).getLocalBucketSeqs()); + Assertions.assertEquals(10L, partition.getBucketBeId()); + Assertions.assertEquals(Arrays.asList(0), partition.getLocalBucketSeqs()); + Assertions.assertEquals(10L, partition.getIndexes().get(0).getBucketBeId()); + Assertions.assertEquals(Arrays.asList(0), partition.getIndexes().get(0).getLocalBucketSeqs()); + Assertions.assertEquals(20L, partition.getIndexes().get(1).getBucketBeId()); + Assertions.assertEquals(Arrays.asList(0), partition.getIndexes().get(1).getLocalBucketSeqs()); } @Test @@ -161,28 +161,28 @@ public void testAdaptiveRandomBucketAssignmentIsSharedByReceiverPartition() { Arrays.asList(10L, 20L, 30L, 40L), Arrays.asList(partition), locations, 4); AdaptiveBucketAssignment be10Assignment = assignments.get(10L).get(1001L); - Assert.assertEquals(0, be10Assignment.getLoadTabletIdx()); - Assert.assertEquals(10L, be10Assignment.getBucketBeId()); - Assert.assertEquals(Arrays.asList(0, 1), be10Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(0, be10Assignment.getLoadTabletIdx()); + Assertions.assertEquals(10L, be10Assignment.getBucketBeId()); + Assertions.assertEquals(Arrays.asList(0, 1), be10Assignment.getLocalBucketSeqs()); assertIndexAssignment(be10Assignment, 2L, 30L, Arrays.asList(0, 1, 2, 3)); AdaptiveBucketAssignment be20Assignment = assignments.get(20L).get(1001L); - Assert.assertEquals(2, be20Assignment.getLoadTabletIdx()); - Assert.assertEquals(20L, be20Assignment.getBucketBeId()); - Assert.assertEquals(Arrays.asList(2, 3), be20Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(2, be20Assignment.getLoadTabletIdx()); + Assertions.assertEquals(20L, be20Assignment.getBucketBeId()); + Assertions.assertEquals(Arrays.asList(2, 3), be20Assignment.getLocalBucketSeqs()); assertIndexAssignment(be20Assignment, 2L, 30L, Arrays.asList(0, 1, 2, 3)); AdaptiveBucketAssignment be30Assignment = assignments.get(30L).get(1001L); - Assert.assertEquals(be10Assignment.getLoadTabletIdx(), be30Assignment.getLoadTabletIdx()); - Assert.assertEquals(be10Assignment.getBucketBeId(), be30Assignment.getBucketBeId()); - Assert.assertEquals(be10Assignment.getLocalBucketSeqs(), be30Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(be10Assignment.getLoadTabletIdx(), be30Assignment.getLoadTabletIdx()); + Assertions.assertEquals(be10Assignment.getBucketBeId(), be30Assignment.getBucketBeId()); + Assertions.assertEquals(be10Assignment.getLocalBucketSeqs(), be30Assignment.getLocalBucketSeqs()); assertIndexAssignment(be30Assignment, 1L, 10L, Arrays.asList(0, 1)); assertIndexAssignment(be30Assignment, 2L, 30L, Arrays.asList(0, 1, 2, 3)); AdaptiveBucketAssignment be40Assignment = assignments.get(40L).get(1001L); - Assert.assertEquals(be20Assignment.getLoadTabletIdx(), be40Assignment.getLoadTabletIdx()); - Assert.assertEquals(be20Assignment.getBucketBeId(), be40Assignment.getBucketBeId()); - Assert.assertEquals(be20Assignment.getLocalBucketSeqs(), be40Assignment.getLocalBucketSeqs()); + Assertions.assertEquals(be20Assignment.getLoadTabletIdx(), be40Assignment.getLoadTabletIdx()); + Assertions.assertEquals(be20Assignment.getBucketBeId(), be40Assignment.getBucketBeId()); + Assertions.assertEquals(be20Assignment.getLocalBucketSeqs(), be40Assignment.getLocalBucketSeqs()); assertIndexAssignment(be40Assignment, 1L, 20L, Arrays.asList(2, 3)); assertIndexAssignment(be40Assignment, 2L, 30L, Arrays.asList(0, 1, 2, 3)); } @@ -190,9 +190,9 @@ public void testAdaptiveRandomBucketAssignmentIsSharedByReceiverPartition() { private void assertIndexAssignment(AdaptiveBucketAssignment assignment, long indexId, long bucketBeId, List localBucketSeqs) { AdaptiveIndexBucketAssignment indexAssignment = assignment.getIndexAssignments().get(indexId); - Assert.assertNotNull(indexAssignment); - Assert.assertEquals(indexId, indexAssignment.getIndexId()); - Assert.assertEquals(bucketBeId, indexAssignment.getBucketBeId()); - Assert.assertEquals(localBucketSeqs, indexAssignment.getLocalBucketSeqs()); + Assertions.assertNotNull(indexAssignment); + Assertions.assertEquals(indexId, indexAssignment.getIndexId()); + Assertions.assertEquals(bucketBeId, indexAssignment.getBucketBeId()); + Assertions.assertEquals(localBucketSeqs, indexAssignment.getLocalBucketSeqs()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/PluginDrivenTableSinkTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/PluginDrivenTableSinkTest.java index 743f60fd668cf2..a8b9c5e6b1174c 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/PluginDrivenTableSinkTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/PluginDrivenTableSinkTest.java @@ -34,8 +34,8 @@ import org.apache.doris.thrift.TExplainLevel; import org.apache.doris.thrift.TSortInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; @@ -97,15 +97,15 @@ public void bindDataSinkDelegatesToWritePlanProvider() throws AnalysisException sink.bindDataSink(Optional.empty()); // The connector-built opaque sink is adopted verbatim. - Assert.assertSame(expected, sink.toThrift()); + Assertions.assertSame(expected, sink.toThrift()); // The bound facts reach the connector through the write handle. - Assert.assertNotNull(provider.seenHandle); - Assert.assertSame(tableHandle, provider.seenHandle.getTableHandle()); - Assert.assertSame(columns, provider.seenHandle.getColumns()); - Assert.assertFalse(provider.seenHandle.isOverwrite()); - Assert.assertTrue(provider.seenHandle.getStaticPartitionSpec().isEmpty()); + Assertions.assertNotNull(provider.seenHandle); + Assertions.assertSame(tableHandle, provider.seenHandle.getTableHandle()); + Assertions.assertSame(columns, provider.seenHandle.getColumns()); + Assertions.assertFalse(provider.seenHandle.isOverwrite()); + Assertions.assertTrue(provider.seenHandle.getStaticPartitionSpec().isEmpty()); // No engine-built write sort by default -> the handle carries no sort info. - Assert.assertNull(provider.seenHandle.getSortInfo()); + Assertions.assertNull(provider.seenHandle.getSortInfo()); } @Test @@ -122,9 +122,9 @@ null, provider, null, new ConnectorTableHandle() { }, writeColumns, boundTargetColumns, null, WriteOperation.INSERT, false); sink.bindDataSink(Optional.empty()); - Assert.assertSame(writeColumns, provider.seenHandle.getColumns()); - Assert.assertEquals(boundTargetColumns, provider.seenHandle.getBoundTargetColumns()); - Assert.assertNotSame(boundTargetColumns, provider.seenHandle.getBoundTargetColumns()); + Assertions.assertSame(writeColumns, provider.seenHandle.getColumns()); + Assertions.assertEquals(boundTargetColumns, provider.seenHandle.getBoundTargetColumns()); + Assertions.assertNotSame(boundTargetColumns, provider.seenHandle.getBoundTargetColumns()); } @Test @@ -143,7 +143,7 @@ public void bindDataSinkThreadsEngineBuiltWriteSortInfoToHandle() throws Analysi null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), engineBuilt); sink.bindDataSink(Optional.empty()); - Assert.assertSame(engineBuilt, provider.seenHandle.getSortInfo()); + Assertions.assertSame(engineBuilt, provider.seenHandle.getSortInfo()); } @Test @@ -157,7 +157,7 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), Collections.emptyList(), null, WriteOperation.INSERT, false, metadataIdentity); sink.bindDataSink(Optional.empty()); - Assert.assertEquals(metadataIdentity, provider.seenHandle.getBoundWriteMetadataIdentity()); + Assertions.assertEquals(metadataIdentity, provider.seenHandle.getBoundWriteMetadataIdentity()); } @Test @@ -176,7 +176,7 @@ public void bindDataSinkThreadsBranchNameToHandle() throws AnalysisException { null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>()); sink.bindDataSink(Optional.of(ctx)); - Assert.assertEquals(Optional.of("br_1"), provider.seenHandle.getBranchName()); + Assertions.assertEquals(Optional.of("br_1"), provider.seenHandle.getBranchName()); } @Test @@ -203,14 +203,14 @@ public void appendExplainInfo(StringBuilder output, String prefix, targetTable, provider, null, tableHandle, new ArrayList<>()); String explain = sink.getExplainString("", TExplainLevel.NORMAL); - Assert.assertTrue(explain, explain.contains("PLUGIN-DRIVEN TABLE SINK")); - Assert.assertTrue(explain, explain.contains("TABLE: t1")); + Assertions.assertTrue(explain.contains("PLUGIN-DRIVEN TABLE SINK"), explain); + Assertions.assertTrue(explain.contains("TABLE: t1"), explain); // The source-agnostic sink delegates connector-specific detail through appendExplainInfo. - Assert.assertTrue(explain, explain.contains("INSERT SQL: SELECT 1")); + Assertions.assertTrue(explain.contains("INSERT SQL: SELECT 1"), explain); // BRIEF short-circuits before any connector detail. String brief = sink.getExplainString("", TExplainLevel.BRIEF); - Assert.assertFalse(brief, brief.contains("INSERT SQL")); + Assertions.assertFalse(brief.contains("INSERT SQL"), brief); } @Test @@ -225,7 +225,7 @@ public void bindDataSinkDefaultsWriteOperationToInsert() throws AnalysisExceptio null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>()); sink.bindDataSink(Optional.empty()); - Assert.assertEquals(WriteOperation.INSERT, provider.seenHandle.getWriteOperation()); + Assertions.assertEquals(WriteOperation.INSERT, provider.seenHandle.getWriteOperation()); } @Test @@ -242,7 +242,7 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), null, WriteOperation.MERGE); sink.bindDataSink(Optional.empty()); - Assert.assertEquals(WriteOperation.MERGE, provider.seenHandle.getWriteOperation()); + Assertions.assertEquals(WriteOperation.MERGE, provider.seenHandle.getWriteOperation()); } @Test @@ -257,7 +257,7 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), null, WriteOperation.DELETE); sink.bindDataSink(Optional.empty()); - Assert.assertEquals(WriteOperation.DELETE, provider.seenHandle.getWriteOperation()); + Assertions.assertEquals(WriteOperation.DELETE, provider.seenHandle.getWriteOperation()); } @Test @@ -270,8 +270,8 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), sink.bindDataSink(Optional.empty()); // Delete-only MERGE must bypass data-file validation while retaining cardinality enforcement. - Assert.assertFalse(provider.seenHandle.isWritesDataFiles()); - Assert.assertTrue(provider.seenHandle.isRequireMergeCardinalityCheck()); + Assertions.assertFalse(provider.seenHandle.isWritesDataFiles()); + Assertions.assertTrue(provider.seenHandle.isRequireMergeCardinalityCheck()); } @Test @@ -288,8 +288,8 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), Collections.singletonList(id), null, WriteOperation.MERGE, false, true, null, null); nonVariantSink.bindDataSink(Optional.empty()); - Assert.assertNotNull(provider.seenHandle); - Assert.assertEquals(11, provider.seenHandle.getBeExecVersion()); + Assertions.assertNotNull(provider.seenHandle); + Assertions.assertEquals(11, provider.seenHandle.getBeExecVersion()); ConnectorColumn payload = new ConnectorColumn( "payload", ConnectorType.of("VARIANT_COMPUTE_V2"), null, true, null); @@ -297,9 +297,9 @@ null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), null, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), Collections.singletonList(payload), null, WriteOperation.MERGE, false, true, null, null); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> variantSink.bindDataSink(Optional.empty())); - Assert.assertTrue(exception.getMessage().contains("rolling upgrade")); + Assertions.assertTrue(exception.getMessage().contains("rolling upgrade")); } finally { Config.be_exec_version = original; } @@ -321,7 +321,7 @@ targetTable, provider, null, new ConnectorTableHandle() { }, new ArrayList<>(), sink.getExplainString("", TExplainLevel.NORMAL); - Assert.assertNotNull(provider.seenExplainHandle); - Assert.assertEquals(WriteOperation.MERGE, provider.seenExplainHandle.getWriteOperation()); + Assertions.assertNotNull(provider.seenExplainHandle); + Assertions.assertEquals(WriteOperation.MERGE, provider.seenExplainHandle.getWriteOperation()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/StatisticDeriveTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/StatisticDeriveTest.java index a7dc637a407b35..cefc14770b77b5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/StatisticDeriveTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/StatisticDeriveTest.java @@ -21,7 +21,7 @@ import org.apache.doris.qe.StmtExecutor; import org.apache.doris.utframe.TestWithFeService; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class StatisticDeriveTest extends TestWithFeService { @@ -70,9 +70,9 @@ public void testAggStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); assertSQLPlanOrErrorMsgContains(sql, "AGGREGATE"); assertSQLPlanOrErrorMsgContains(sql, "OlapScanNode"); } @@ -86,9 +86,9 @@ public void testAnalyticEvalStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "ANALYTIC"); assertSQLPlanOrErrorMsgContains(sql, "SORT"); @@ -117,9 +117,9 @@ public void testAssertNumberRowsStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "NESTED LOOP JOIN"); assertSQLPlanOrErrorMsgContains(sql, "EXCHANGE"); @@ -135,9 +135,9 @@ public void testEmptySetStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "EMPTYSET"); } @@ -150,9 +150,9 @@ public void testRepeatStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "REPEAT_NODE"); } @@ -166,9 +166,9 @@ public void testHashJoinStatsDerive() throws Exception { sessionVariable.setEnableJoinReorderBasedCost(true); sessionVariable.setDisableJoinReorder(false); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "HASH JOIN"); } @@ -181,9 +181,9 @@ public void testTableFunctionStatsDerive() throws Exception { sessionVariable.setDisableJoinReorder(false); StmtExecutor stmtExecutor = new StmtExecutor(connectContext, sql); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "TABLE FUNCTION NODE"); } @@ -196,9 +196,9 @@ public void testUnionStatsDerive() throws Exception { sessionVariable.setDisableJoinReorder(false); StmtExecutor stmtExecutor = new StmtExecutor(connectContext, sql); stmtExecutor.execute(); - Assert.assertNotNull(stmtExecutor.planner()); - Assert.assertNotNull(stmtExecutor.planner().getFragments()); - Assert.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); + Assertions.assertNotNull(stmtExecutor.planner()); + Assertions.assertNotNull(stmtExecutor.planner().getFragments()); + Assertions.assertNotEquals(0, stmtExecutor.planner().getFragments().size()); System.out.println(getSQLPlanOrErrorMsg("explain " + sql)); assertSQLPlanOrErrorMsgContains(sql, "UNION"); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/StreamLoadPlannerTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/StreamLoadPlannerTest.java index 098e79b3511bb8..39cff42be39064 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/StreamLoadPlannerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/StreamLoadPlannerTest.java @@ -24,8 +24,8 @@ import org.apache.doris.nereids.trees.expressions.Expression; import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; @@ -34,7 +34,7 @@ public class StreamLoadPlannerTest { public void testParseStmt() throws Exception { String sql = new String("k1, k2, k3=abc(), k4=default_value()"); List expressions = NereidsLoadUtils.parseExpressionSeq(sql); - Assert.assertEquals(4, expressions.size()); + Assertions.assertEquals(4, expressions.size()); } @Test @@ -43,6 +43,6 @@ public void testExprIdGenerator() { CascadesContext context = CascadesContext.initTempContext(); IdGenerator exprIdGenerator2 = context.getStatementContext().getExprIdGenerator(); // we get different IdGenerator instance - Assert.assertTrue(exprIdGenerator1 != exprIdGenerator2); + Assertions.assertTrue(exprIdGenerator1 != exprIdGenerator2); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/planner/TpchTest.java b/fe/fe-core/src/test/java/org/apache/doris/planner/TpchTest.java index 0a3bf03fe32b45..9ed059d2d2a048 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/planner/TpchTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/planner/TpchTest.java @@ -19,7 +19,7 @@ import org.apache.doris.utframe.TestWithFeService; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TpchTest extends TestWithFeService { @@ -221,6 +221,6 @@ public void testExplain() throws Exception { + "ORDER BY\n" + " o_year"); - Assert.assertTrue(explain.contains("db1.lineitem(lineitem)")); + Assertions.assertTrue(explain.contains("db1.lineitem(lineitem)")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/plugin/HttpDialectUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/plugin/HttpDialectUtilsTest.java index de359f79475cc4..e15bce9e385b55 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/plugin/HttpDialectUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/plugin/HttpDialectUtilsTest.java @@ -19,10 +19,10 @@ import org.apache.doris.plugin.dialect.HttpDialectUtils; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.DatagramSocket; @@ -34,14 +34,14 @@ public class HttpDialectUtilsTest { private int port; private SimpleHttpServer server; - @Before + @BeforeEach public void setUp() throws Exception { port = findValidPort(); server = new SimpleHttpServer(port); server.start("/api/v1/convert"); } - @After + @AfterEach public void tearDown() { if (server != null) { server.stop(); @@ -55,20 +55,20 @@ public void testSqlConvert() { String[] features = new String[] {"ctas"}; String targetURL = "http://127.0.0.1:" + port + "/api/v1/convert"; String res = HttpDialectUtils.convertSql(targetURL, originSql, "presto", features, "{}"); - Assert.assertEquals(originSql, res); + Assertions.assertEquals(originSql, res); // test presto server.setResponse("{\"version\": \"v1\", \"data\": \"" + expectedSql + "\", \"code\": 0, \"message\": \"\"}"); res = HttpDialectUtils.convertSql(targetURL, originSql, "presto", features, "{}"); - Assert.assertEquals(expectedSql, res); + Assertions.assertEquals(expectedSql, res); // test response version error server.setResponse("{\"version\": \"v2\", \"data\": \"" + expectedSql + "\", \"code\": 0, \"message\": \"\"}"); res = HttpDialectUtils.convertSql(targetURL, originSql, "presto", features, "{}"); - Assert.assertEquals(originSql, res); + Assertions.assertEquals(originSql, res); // test response code error server.setResponse( "{\"version\": \"v1\", \"data\": \"" + expectedSql + "\", \"code\": 400, \"message\": \"\"}"); res = HttpDialectUtils.convertSql(targetURL, originSql, "presto", features, "{}"); - Assert.assertEquals(originSql, res); + Assertions.assertEquals(originSql, res); } private static int findValidPort() { diff --git a/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLoaderTest.java b/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLoaderTest.java index 2da3c3dfa1abd1..1ad55e3b210e0a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLoaderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLoaderTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.jmockit.Deencapsulation; import org.apache.doris.plugin.AuditEvent; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -51,17 +51,17 @@ public void testAssembleAuditIsSerializedWithLoadLock() throws Exception { synchronized (auditLoader) { assembleThread.start(); - Assert.assertTrue(started.await(5, TimeUnit.SECONDS)); - Assert.assertTrue(waitForBlocked(assembleThread)); - Assert.assertFalse(getAuditLogBuffer(auditLoader).contains(auditEvent.queryId)); + Assertions.assertTrue(started.await(5, TimeUnit.SECONDS)); + Assertions.assertTrue(waitForBlocked(assembleThread)); + Assertions.assertFalse(getAuditLogBuffer(auditLoader).contains(auditEvent.queryId)); } assembleThread.join(5000); - Assert.assertFalse(assembleThread.isAlive()); + Assertions.assertFalse(assembleThread.isAlive()); if (error.get() != null) { throw new AssertionError("failed to assemble audit event", error.get()); } - Assert.assertTrue(getAuditLogBuffer(auditLoader).contains(auditEvent.queryId)); + Assertions.assertTrue(getAuditLogBuffer(auditLoader).contains(auditEvent.queryId)); } private boolean waitForBlocked(Thread thread) throws InterruptedException { @@ -110,13 +110,11 @@ public void testDelimiterInjectionDoesNotAlterFraming() { evil); // Exactly one row, and the same number of columns as the clean event. - Assert.assertEquals("injected 0x1E must not add rows", - count(clean, line), count(evil, line)); - Assert.assertEquals("one row per event", 1, count(evil, line)); - Assert.assertEquals("injected 0x1F must not add columns", - count(clean, col), count(evil, col)); + Assertions.assertEquals(count(clean, line), count(evil, line), "injected 0x1E must not add rows"); + Assertions.assertEquals(1, count(evil, line), "one row per event"); + Assertions.assertEquals(count(clean, col), count(evil, col), "injected 0x1F must not add columns"); // The forged tokens survive only as inert text, never as framing bytes. - Assert.assertTrue(evil.toString().contains("DROP TABLE finance.ledger")); + Assertions.assertTrue(evil.toString().contains("DROP TABLE finance.ledger")); } // The sanitizer must be a no-op for ordinary statements: no data loss, no mutation. @@ -129,8 +127,8 @@ public void testCleanStatementIsPreserved() { .setUser("bob").setDb("sales") .setStmt("select * from t where a = 1 and b = 'x'").build(), buffer); - Assert.assertTrue(buffer.toString().contains("select * from t where a = 1 and b = 'x'")); - Assert.assertEquals(1, count(buffer, AuditLoader.AUDIT_TABLE_LINE_DELIMITER)); + Assertions.assertTrue(buffer.toString().contains("select * from t where a = 1 and b = 'x'")); + Assertions.assertEquals(1, count(buffer, AuditLoader.AUDIT_TABLE_LINE_DELIMITER)); } private static int count(CharSequence s, char c) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLogBuilderTest.java b/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLogBuilderTest.java index c2b53432fbf124..1d39137430d4e4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLogBuilderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/plugin/audit/AuditLogBuilderTest.java @@ -27,8 +27,8 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.qe.GlobalVariable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class AuditLogBuilderTest { @@ -40,12 +40,12 @@ public void testTimestampOutput() { AuditEvent auditEvent = new AuditEvent.AuditEventBuilder() .setTimestamp(currentTime).build(); String result = Deencapsulation.invoke(auditLogBuilder, "getAuditLogString", auditEvent); - Assert.assertTrue(result.contains("Timestamp=2025-03-12 14:19:36.000")); + Assertions.assertTrue(result.contains("Timestamp=2025-03-12 14:19:36.000")); // 2 not set value auditEvent = new AuditEvent.AuditEventBuilder().build(); result = Deencapsulation.invoke(auditLogBuilder, "getAuditLogString", auditEvent); - Assert.assertTrue(result.contains("Timestamp=\\N")); + Assertions.assertTrue(result.contains("Timestamp=\\N")); } @Test @@ -62,35 +62,32 @@ public void testHandleStmtTruncationForNonInsertStmt() { // 1. Test null input String result = AuditLogHelper.handleCommand(null, nonInsertCommand); - Assert.assertNull(result); + Assertions.assertNull(result); // 2. Test short statement not truncated String shortStmt = "SELECT * FROM table1"; result = AuditLogHelper.handleCommand(shortStmt, nonInsertCommand); - Assert.assertEquals(shortStmt, result); + Assertions.assertEquals(shortStmt, result); // 3. Test long statement truncated (using audit_plugin_max_sql_length) String longStmt = "SELECT * FROM very_long_table_name_that_exceeds_the_maximum_length_limit_for_audit_log"; result = AuditLogHelper.handleCommand(longStmt, nonInsertCommand); - Assert.assertTrue("Result should contain truncation message", - result.contains("/* truncated. audit_plugin_max_sql_length=50 */")); - Assert.assertTrue("Result should be shorter than original", - result.getBytes().length < longStmt.getBytes().length + 100); // Add length for truncation message + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=50 */"), "Result should contain truncation message"); + Assertions.assertTrue(result.getBytes().length < longStmt.getBytes().length + 100, "Result should be shorter than original"); // Add length for truncation message // 4. Test statement with newlines, tabs, carriage returns String stmtWithSpecialChars = "SELECT *\nFROM table1\tWHERE id = 1\r"; result = AuditLogHelper.handleCommand(stmtWithSpecialChars, nonInsertCommand); - Assert.assertTrue("Should contain actual newlines", result.contains("\n")); - Assert.assertTrue("Should contain actual tabs", result.contains("\t")); - Assert.assertTrue("Should contain actual carriage returns", result.contains("\r")); + Assertions.assertTrue(result.contains("\n"), "Should contain actual newlines"); + Assertions.assertTrue(result.contains("\t"), "Should contain actual tabs"); + Assertions.assertTrue(result.contains("\r"), "Should contain actual carriage returns"); // 5. Test long statement with Chinese characters truncation String chineseStmt = "SELECT * FROM 表名很长的中文表名字符测试表名很长的中文表名字符测试表名很长的中文表名字符测试"; result = AuditLogHelper.handleCommand(chineseStmt, nonInsertCommand); - Assert.assertTrue("Should contain truncation message for Chinese text", - result.contains("/* truncated. audit_plugin_max_sql_length=50 */")); + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=50 */"), "Should contain truncation message for Chinese text"); // 6. Test boundary case: exactly equal to max length // Create a string exactly equal to max length @@ -100,7 +97,7 @@ public void testHandleStmtTruncationForNonInsertStmt() { } String exactLengthStmt = sb.toString(); result = AuditLogHelper.handleCommand(exactLengthStmt, nonInsertCommand); - Assert.assertEquals("Should not be truncated when exactly at limit", exactLengthStmt, result); + Assertions.assertEquals(exactLengthStmt, result, "Should not be truncated when exactly at limit"); // 7. Test boundary case: exceeding max length by 1 character sb = new StringBuilder(); @@ -109,13 +106,12 @@ public void testHandleStmtTruncationForNonInsertStmt() { } String overLimitStmt = sb.toString(); result = AuditLogHelper.handleCommand(overLimitStmt, nonInsertCommand); - Assert.assertTrue("Should be truncated when over limit by 1 char", - result.contains("/* truncated. audit_plugin_max_sql_length=50 */")); + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=50 */"), "Should be truncated when over limit by 1 char"); // 8. Test empty string String emptyStmt = ""; result = AuditLogHelper.handleCommand(emptyStmt, nonInsertCommand); - Assert.assertEquals("Empty string should remain empty", "", result); + Assertions.assertEquals("", result, "Empty string should remain empty"); } finally { // Restore original values GlobalVariable.auditPluginMaxSqlLength = originalMaxSqlLength; @@ -145,8 +141,7 @@ public void testHandleStmtTruncationForInsertStmt() { String result = AuditLogHelper.handleStmt(longInsertStmt, insertStmt); // Should use audit_plugin_max_insert_stmt_length=80 for truncation - Assert.assertTrue("Should contain insert stmt length truncation message", - result.contains("/* total 3 rows, truncated. audit_plugin_max_insert_stmt_length=80 */")); + Assertions.assertTrue(result.contains("/* total 3 rows, truncated. audit_plugin_max_insert_stmt_length=80 */"), "Should contain insert stmt length truncation message"); // 2. Test short INSERT statement not truncated String shortInsertStmt = "INSERT INTO tbl VALUES (1, 'a')"; @@ -154,9 +149,8 @@ public void testHandleStmtTruncationForInsertStmt() { result = AuditLogHelper.handleStmt(shortInsertStmt, insertStmt); // Should not be truncated, and special characters should be properly escaped - Assert.assertFalse("Short INSERT should not be truncated", - result.contains("/* truncated.")); - Assert.assertEquals("Short INSERT should remain unchanged", shortInsertStmt, result); + Assertions.assertFalse(result.contains("/* truncated."), "Short INSERT should not be truncated"); + Assertions.assertEquals(shortInsertStmt, result, "Short INSERT should remain unchanged"); // 3. Test special character handling in INSERT statements String insertWithSpecialChars = "INSERT INTO tbl\nVALUES\t(1,\r'test')"; @@ -164,9 +158,9 @@ public void testHandleStmtTruncationForInsertStmt() { result = AuditLogHelper.handleStmt(insertWithSpecialChars, insertStmt); // Verify special characters are properly escaped - Assert.assertTrue("Should contain actual newlines", result.contains("\n")); - Assert.assertTrue("Should contain actual tabs", result.contains("\t")); - Assert.assertTrue("Should contain actual carriage returns", result.contains("\r")); + Assertions.assertTrue(result.contains("\n"), "Should contain actual newlines"); + Assertions.assertTrue(result.contains("\t"), "Should contain actual tabs"); + Assertions.assertTrue(result.contains("\r"), "Should contain actual carriage returns"); // 4. Test comparison: same length statements, different handling for INSERT vs non-INSERT // Create a statement with length between 80-200 @@ -187,12 +181,10 @@ public void testHandleStmtTruncationForInsertStmt() { String selectResult = AuditLogHelper.handleStmt(selectStmt, parsedSelectStmt); // INSERT should be truncated (using limit of 80) - Assert.assertTrue("INSERT should be truncated with insert length limit", - insertResult.contains("/* total 1 rows, truncated. audit_plugin_max_insert_stmt_length=80 */")); + Assertions.assertTrue(insertResult.contains("/* total 1 rows, truncated. audit_plugin_max_insert_stmt_length=80 */"), "INSERT should be truncated with insert length limit"); // SELECT should not be truncated (using limit of 200) - Assert.assertFalse("SELECT should not be truncated with sql length limit", - selectResult.contains("/* truncated.")); + Assertions.assertFalse(selectResult.contains("/* truncated."), "SELECT should not be truncated with sql length limit"); // 5. Test boundary case: INSERT statement exactly equal to limit length // Create a statement exactly equal to INSERT limit length @@ -207,10 +199,8 @@ public void testHandleStmtTruncationForInsertStmt() { result = AuditLogHelper.handleStmt(exactLengthInsert, insertStmt); // Should not be truncated - Assert.assertFalse("INSERT at exact limit should not be truncated", - result.contains("/* truncated.")); - Assert.assertEquals("INSERT at exact limit should remain unchanged", - exactLengthInsert, result); + Assertions.assertFalse(result.contains("/* truncated."), "INSERT at exact limit should not be truncated"); + Assertions.assertEquals(exactLengthInsert, result, "INSERT at exact limit should remain unchanged"); } finally { // Restore original values @@ -242,13 +232,11 @@ public void testHandleStmtTruncationWithDifferentLengths() { String result = AuditLogHelper.handleCommand(longStmt, nonInsertCommand); - Assert.assertTrue("Should contain truncation message for length " + maxLength, - result.contains("/* truncated. audit_plugin_max_sql_length=" + maxLength + " */")); + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=" + maxLength + " */"), "Should contain truncation message for length " + maxLength); // Verify truncated length is reasonable (original part + truncation info) String expectedTruncationMsg = " ... /* truncated audit_plugin_max_sql_length=" + maxLength + " */"; - Assert.assertTrue("Truncated. result should be reasonable length", - result.getBytes().length <= maxLength + expectedTruncationMsg.getBytes().length + 10); // Allow some UTF-8 encoding error margin + Assertions.assertTrue(result.getBytes().length <= maxLength + expectedTruncationMsg.getBytes().length + 10, "Truncated. result should be reasonable length"); // Allow some UTF-8 encoding error margin } } finally { @@ -272,23 +260,21 @@ public void testHandleStmtUtf8Truncation() { String result = AuditLogHelper.handleCommand(utf8Stmt, nonInsertCommand); // Verify result is a valid string - Assert.assertNotNull("Result should not be null", result); + Assertions.assertNotNull(result, "Result should not be null"); // If truncated, should contain truncation info if (utf8Stmt.getBytes().length > 20) { - Assert.assertTrue("Should contain truncation message for UTF-8 text", - result.contains("/* truncated. audit_plugin_max_sql_length=20 */")); + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=20 */"), "Should contain truncation message for UTF-8 text"); } else { // If not exceeding character limit, should not be truncated - Assert.assertEquals("Should not be truncated if within character limit", utf8Stmt, result); + Assertions.assertEquals(utf8Stmt, result, "Should not be truncated if within character limit"); } // Test a definitely truncated long Chinese string String longUtf8Stmt = "SELECT * FROM 这是一个很长的中文表名用来测试字符截断功能是否正常工作"; String longResult = AuditLogHelper.handleCommand(longUtf8Stmt, nonInsertCommand); - Assert.assertTrue("Long UTF-8 string should be truncated", - longResult.contains("/* truncated. audit_plugin_max_sql_length=20 */")); + Assertions.assertTrue(longResult.contains("/* truncated. audit_plugin_max_sql_length=20 */"), "Long UTF-8 string should be truncated"); } finally { // Restore original values @@ -319,9 +305,8 @@ public void testHandleStmtInsertVsNonInsertBehavior() { // 1. Test non-INSERT statement behavior String result = AuditLogHelper.handleCommand(testStmt, nonInsertCommand); // Should use audit_plugin_max_sql_length=100, so not truncated - Assert.assertFalse("Non-INSERT statement should not be truncated with sql length limit", - result.contains("/* truncated.")); - Assert.assertEquals("Non-INSERT statement should remain unchanged", testStmt, result); + Assertions.assertFalse(result.contains("/* truncated."), "Non-INSERT statement should not be truncated with sql length limit"); + Assertions.assertEquals(testStmt, result, "Non-INSERT statement should remain unchanged"); // 2. Test behavior when statement exceeds regular limit StringBuilder longSb = new StringBuilder(); @@ -332,10 +317,8 @@ public void testHandleStmtInsertVsNonInsertBehavior() { result = AuditLogHelper.handleCommand(longTestStmt, nonInsertCommand); // Should use audit_plugin_max_sql_length=100 for truncation - Assert.assertTrue("Long non-INSERT statement should be truncated", - result.contains("/* truncated. audit_plugin_max_sql_length=100 */")); - Assert.assertFalse("Should not use insert stmt length limit", - result.contains("audit_plugin_max_insert_stmt_length")); + Assertions.assertTrue(result.contains("/* truncated. audit_plugin_max_sql_length=100 */"), "Long non-INSERT statement should be truncated"); + Assertions.assertFalse(result.contains("audit_plugin_max_insert_stmt_length"), "Should not use insert stmt length limit"); } finally { // Restore original values @@ -367,10 +350,8 @@ public void testHandleStmtInsertLengthLimitLogic() { String result = AuditLogHelper.handleStmt(insertStmt, parsedStmt); if (insertStmt.getBytes().length > 80) { - Assert.assertTrue("Should use insert stmt length limit (80) when it's smaller", - result.contains("audit_plugin_max_insert_stmt_length=80")); - Assert.assertFalse("Should not use sql length limit when insert limit is smaller", - result.contains("audit_plugin_max_sql_length=200")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=80"), "Should use insert stmt length limit (80) when it's smaller"); + Assertions.assertFalse(result.contains("audit_plugin_max_sql_length=200"), "Should not use sql length limit when insert limit is smaller"); } // Test 2: auditPluginMaxInsertStmtLength > auditPluginMaxSqlLength @@ -381,8 +362,7 @@ public void testHandleStmtInsertLengthLimitLogic() { result = AuditLogHelper.handleStmt(insertStmt, parsedStmt); if (insertStmt.getBytes().length > 60) { - Assert.assertTrue("Should use insert stmt length limit (60) when sql limit is smaller", - result.contains("audit_plugin_max_insert_stmt_length=60")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=60"), "Should use insert stmt length limit (60) when sql limit is smaller"); } // Test 3: auditPluginMaxInsertStmtLength = auditPluginMaxSqlLength @@ -393,8 +373,7 @@ public void testHandleStmtInsertLengthLimitLogic() { result = AuditLogHelper.handleStmt(insertStmt, parsedStmt); if (insertStmt.getBytes().length > 100) { - Assert.assertTrue("Should use limit (100) when both limits are equal", - result.contains("audit_plugin_max_insert_stmt_length=100")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=100"), "Should use limit (100) when both limits are equal"); } // Test 4: Test with very small but valid limits @@ -408,8 +387,7 @@ public void testHandleStmtInsertLengthLimitLogic() { // Math.max(0, Math.min(15, 10)) = Math.max(0, 10) = 10 if (shortInsert.getBytes().length > 10) { - Assert.assertTrue("Should use the smaller limit (10) when sql limit is smaller", - result.contains("audit_plugin_max_insert_stmt_length=10")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=10"), "Should use the smaller limit (10) when sql limit is smaller"); } // Test 5: Test with small INSERT limit but larger SQL limit @@ -420,8 +398,7 @@ public void testHandleStmtInsertLengthLimitLogic() { // Math.max(0, Math.min(25, 100)) = Math.max(0, 25) = 25 if (shortInsert.getBytes().length > 25) { - Assert.assertTrue("Should use the insert limit (25) when it's smaller", - result.contains("audit_plugin_max_insert_stmt_length=25")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=25"), "Should use the insert limit (25) when it's smaller"); } // Test 6: Verify the exact boundary behavior @@ -433,16 +410,14 @@ public void testHandleStmtInsertLengthLimitLogic() { parsedStmt = parser.parseSQL(exactLengthInsert).get(0); result = AuditLogHelper.handleStmt(exactLengthInsert, parsedStmt); - Assert.assertFalse("Statement with exactly max length should not be truncated", - result.contains("truncated")); + Assertions.assertFalse(result.contains("truncated"), "Statement with exactly max length should not be truncated"); // Create an INSERT statement with 51 characters (1 over limit) String overLimitInsert = createExactLengthInsertStatement(51); parsedStmt = parser.parseSQL(overLimitInsert).get(0); result = AuditLogHelper.handleStmt(overLimitInsert, parsedStmt); - Assert.assertTrue("Statement exceeding max length by 1 should be truncated", - result.contains("audit_plugin_max_insert_stmt_length=50")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=50"), "Statement exceeding max length by 1 should be truncated"); // Test 7: Test the Math.min logic with different combinations GlobalVariable.auditPluginMaxSqlLength = 120; @@ -454,8 +429,7 @@ public void testHandleStmtInsertLengthLimitLogic() { // Should use Math.max(0, Math.min(80, 120)) = 80 if (mediumInsert.getBytes().length > 80) { - Assert.assertTrue("Should use the smaller insert limit (80)", - result.contains("audit_plugin_max_insert_stmt_length=80")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=80"), "Should use the smaller insert limit (80)"); } } finally { @@ -526,11 +500,10 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 50; String result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when sql length limit is 0", result); + Assertions.assertNotNull(result, "Result should not be null when sql length limit is 0"); // When maxLen = 0, the statement should be heavily truncated if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when effective limit is 0", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when effective limit is 0"); } // Test Case 2: auditPluginMaxSqlLength > 0, auditPluginMaxInsertStmtLength = 0 @@ -539,10 +512,9 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 0; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when insert length limit is 0", result); + Assertions.assertNotNull(result, "Result should not be null when insert length limit is 0"); if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when effective limit is 0", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when effective limit is 0"); } // Test Case 3: Both limits are 0 @@ -551,10 +523,9 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 0; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when both limits are 0", result); + Assertions.assertNotNull(result, "Result should not be null when both limits are 0"); if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when both limits are 0", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when both limits are 0"); } // Test Case 4: Negative auditPluginMaxSqlLength @@ -563,10 +534,9 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 50; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when sql length limit is negative", result); + Assertions.assertNotNull(result, "Result should not be null when sql length limit is negative"); if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when sql limit is negative", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when sql limit is negative"); } // Test Case 5: Negative auditPluginMaxInsertStmtLength @@ -575,10 +545,9 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = -20; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when insert length limit is negative", result); + Assertions.assertNotNull(result, "Result should not be null when insert length limit is negative"); if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when insert limit is negative", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when insert limit is negative"); } // Test Case 6: Both limits are negative @@ -587,10 +556,9 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = -25; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null when both limits are negative", result); + Assertions.assertNotNull(result, "Result should not be null when both limits are negative"); if (testInsertStmt.getBytes().length > 0) { - Assert.assertTrue("Should be truncated when both limits are negative", - result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty()); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=0") || result.isEmpty(), "Should be truncated when both limits are negative"); } // Test Case 7: Test non-INSERT statement with abnormal limits @@ -599,7 +567,7 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 100; // This should be ignored for non-INSERT result = AuditLogHelper.handleCommand(testSelectStmt, nonInsertCommand); - Assert.assertNotNull("Result should not be null for non-INSERT with zero sql limit", result); + Assertions.assertNotNull(result, "Result should not be null for non-INSERT with zero sql limit"); // Non-INSERT statements bypass the Math.max(0, Math.min(...)) logic and go directly to truncateByBytes // Test Case 8: Very large negative numbers @@ -607,14 +575,14 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = Integer.MIN_VALUE; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null with very large negative values", result); + Assertions.assertNotNull(result, "Result should not be null with very large negative values"); // Test Case 9: Mixed extreme values GlobalVariable.auditPluginMaxSqlLength = Integer.MAX_VALUE; GlobalVariable.auditPluginMaxInsertStmtLength = Integer.MIN_VALUE; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null with mixed extreme values", result); + Assertions.assertNotNull(result, "Result should not be null with mixed extreme values"); // Expected: Math.max(0, Math.min(MIN_VALUE, MAX_VALUE)) = Math.max(0, MIN_VALUE) = 0 // Test Case 10: Edge case with very small positive numbers @@ -622,11 +590,10 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = 1; result = AuditLogHelper.handleStmt(testInsertStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null with very small positive limits", result); + Assertions.assertNotNull(result, "Result should not be null with very small positive limits"); // Expected: Math.max(0, Math.min(1, 1)) = Math.max(0, 1) = 1 if (testInsertStmt.getBytes().length > 1) { - Assert.assertTrue("Should be truncated with limit of 1", - result.contains("audit_plugin_max_insert_stmt_length=1")); + Assertions.assertTrue(result.contains("audit_plugin_max_insert_stmt_length=1"), "Should be truncated with limit of 1"); } // Test Case 11: Test empty string with abnormal limits @@ -635,13 +602,13 @@ public void testHandleStmtWithAbnormalLengthLimits() { GlobalVariable.auditPluginMaxInsertStmtLength = -10; result = AuditLogHelper.handleStmt(emptyStmt, parsedInsertStmt); - Assert.assertNotNull("Result should not be null for empty string", result); - Assert.assertEquals("Empty string should remain empty", "", result); + Assertions.assertNotNull(result, "Result should not be null for empty string"); + Assertions.assertEquals("", result, "Empty string should remain empty"); } catch (Exception e) { // If any exception occurs, we want to log it but not fail the test immediately // This helps us identify which specific abnormal values cause issues - Assert.fail("Unexpected exception with abnormal length limits: " + e.getMessage() + Assertions.fail("Unexpected exception with abnormal length limits: " + e.getMessage() + ". sqlLength=" + GlobalVariable.auditPluginMaxSqlLength + ", insertLength=" + GlobalVariable.auditPluginMaxInsertStmtLength); } finally { diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditEventProcessorTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditEventProcessorTest.java index 884f9a5badf222..1bb67630b21930 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditEventProcessorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditEventProcessorTest.java @@ -25,10 +25,10 @@ import org.apache.doris.plugin.audit.AuditLogBuilder; import org.apache.doris.utframe.UtFrameUtils; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -38,12 +38,12 @@ public class AuditEventProcessorTest { private static String runningDir = "fe/mocked/AuditProcessorTest/" + UUID.randomUUID().toString() + "/"; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { UtFrameUtils.createDorisCluster(runningDir); } - @AfterClass + @AfterAll public static void tearDown() { File file = new File(runningDir); file.delete(); @@ -66,18 +66,18 @@ public void testAuditEvent() { .setStmtType("SELECT") .setStmt("select * from tbl1").build(); - Assert.assertEquals("127.0.0.1", event.clientIp); - Assert.assertEquals(200000, event.scanRows); - Assert.assertEquals("SELECT", event.stmtType); - Assert.assertEquals(2000, event.queueTimeMs); + Assertions.assertEquals("127.0.0.1", event.clientIp); + Assertions.assertEquals(200000, event.scanRows); + Assertions.assertEquals("SELECT", event.stmtType); + Assertions.assertEquals(2000, event.queueTimeMs); } @Test public void testAuditLogBuilder() throws IOException { try (AuditLogBuilder auditLogBuilder = new AuditLogBuilder()) { PluginInfo pluginInfo = auditLogBuilder.getPluginInfo(); - Assert.assertEquals(DigitalVersion.fromString("0.12.0"), pluginInfo.getVersion()); - Assert.assertEquals(DigitalVersion.fromString("1.8.31"), pluginInfo.getJavaVersion()); + Assertions.assertEquals(DigitalVersion.fromString("0.12.0"), pluginInfo.getVersion()); + Assertions.assertEquals(DigitalVersion.fromString("1.8.31"), pluginInfo.getJavaVersion()); long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { AuditEvent event = new AuditEvent.AuditEventBuilder().setEventType(EventType.AFTER_QUERY) diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperBackendSelectionTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperBackendSelectionTest.java index ad1bef6ec080e6..5c7cc6ac7b8462 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperBackendSelectionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperBackendSelectionTest.java @@ -38,9 +38,9 @@ import org.apache.doris.resource.spi.BackendSelectionProvider; import org.apache.doris.resource.workloadschedpolicy.WorkloadRuntimeStatusMgr; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -49,7 +49,7 @@ public class AuditLogHelperBackendSelectionTest { - @After + @AfterEach public void resetBackendSelectionProvider() { BackendSelectionManager.resetProviderForTest(); } @@ -103,7 +103,7 @@ public void testFilesInsertWaitsForItsCoordinatorBackends() throws Exception { public void testInternalInsertDoesNotUseExternalDmlBarrier() { StmtExecutor executor = Mockito.mock(StmtExecutor.class, Mockito.CALLS_REAL_METHODS); - Assert.assertTrue(AuditLogHelper.getExternalDmlAuditBackendIds(executor).isEmpty()); + Assertions.assertTrue(AuditLogHelper.getExternalDmlAuditBackendIds(executor).isEmpty()); } @Test @@ -114,7 +114,7 @@ public void testForwardedExternalDmlUsesBackendIdsReturnedByMaster() { StmtExecutor executor = Mockito.mock(StmtExecutor.class, Mockito.CALLS_REAL_METHODS); Deencapsulation.setField(executor, "masterOpExecutor", masterExecutor); - Assert.assertEquals(expectedBackendIds, + Assertions.assertEquals(expectedBackendIds, AuditLogHelper.getExternalDmlAuditBackendIds(executor)); } @@ -126,7 +126,7 @@ public void testResolvedExternalDmlUsesOnlyDispatchedBackends() { executor.setExternalDmlAuditCoordinator(coordinator); - Assert.assertEquals(Set.of(10001L), executor.getExternalDmlAuditBackendIds()); + Assertions.assertEquals(Set.of(10001L), executor.getExternalDmlAuditBackendIds()); } private void assertExternalDmlWaitsForCoordinatorBackends(LogicalPlan command, boolean success) @@ -198,7 +198,7 @@ private void assertAuditComputeGroup(BackendSelection.SelectionHint hint, String ArgumentCaptor captor = ArgumentCaptor.forClass(AuditEvent.class); Mockito.verify(statusMgr).submitFinishQueryToAudit(captor.capture()); - Assert.assertEquals(expectedComputeGroup, captor.getValue().cloudClusterName); + Assertions.assertEquals(expectedComputeGroup, captor.getValue().cloudClusterName); Mockito.verifyNoInteractions(provider); } finally { Config.deploy_mode = oldDeployMode; diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperTest.java index 82afc4a02a1727..1eb6eb4791f20b 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogHelperTest.java @@ -22,13 +22,13 @@ import org.apache.doris.common.FeConstants; import org.apache.doris.metric.MetricRepo; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class AuditLogHelperTest { - @BeforeClass + @BeforeAll public static void setUp() { FeConstants.runningUnitTest = true; MetricRepo.init(); @@ -52,7 +52,7 @@ public void testUpdateMetricsQueryOk() { AuditLogHelper.updateMetrics(ctx); long after = MetricRepo.COUNTER_QUERY_ALL.getValue(); - Assert.assertEquals(1, after - before); + Assertions.assertEquals(1, after - before); } @Test @@ -66,8 +66,8 @@ public void testUpdateMetricsQueryErr() { long afterAll = MetricRepo.COUNTER_QUERY_ALL.getValue(); long afterErr = MetricRepo.COUNTER_QUERY_ERR.getValue(); - Assert.assertEquals(1, afterAll - beforeAll); - Assert.assertEquals(1, afterErr - beforeErr); + Assertions.assertEquals(1, afterAll - beforeAll); + Assertions.assertEquals(1, afterErr - beforeErr); } @Test @@ -80,7 +80,7 @@ public void testUpdateMetricsNotQuery() { AuditLogHelper.updateMetrics(ctx); long after = MetricRepo.COUNTER_QUERY_ALL.getValue(); - Assert.assertEquals(0, after - before); + Assertions.assertEquals(0, after - before); } @Test @@ -96,7 +96,7 @@ public void testUpdateMetricsDebugModeShortCircuit() { AuditLogHelper.updateMetrics(ctx); long after = MetricRepo.COUNTER_QUERY_ALL.getValue(); - Assert.assertEquals(0, after - before); + Assertions.assertEquals(0, after - before); } finally { Config.enable_bdbje_debug_mode = original; } @@ -108,6 +108,6 @@ public void testGetCloudClusterForAuditPrefersEffectiveCluster() throws Exceptio ctx.getSessionVariable().setCloudCluster("session_cluster"); ctx.setEffectiveCloudCluster("hint_cluster"); - Assert.assertEquals("hint_cluster", AuditLogHelper.getCloudClusterForAudit(ctx)); + Assertions.assertEquals("hint_cluster", AuditLogHelper.getCloudClusterForAudit(ctx)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogWorkloadGroupTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogWorkloadGroupTest.java index 4cd7dd5dff85b6..830b9776e17701 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogWorkloadGroupTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/AuditLogWorkloadGroupTest.java @@ -28,10 +28,10 @@ import org.apache.doris.resource.workloadgroup.WorkloadGroupMgr; import org.apache.doris.service.arrowflight.FlightSqlConnectProcessor; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -56,14 +56,14 @@ public class AuditLogWorkloadGroupTest { private boolean originalEnableWorkloadGroup; - @Before + @BeforeEach public void setUp() { FeConstants.runningUnitTest = true; originalEnableWorkloadGroup = Config.enable_workload_group; Config.enable_workload_group = true; } - @After + @AfterEach public void tearDown() { Config.enable_workload_group = originalEnableWorkloadGroup; ConnectContext.remove(); @@ -80,7 +80,7 @@ public void testResolveWorkloadGroupNameDisabled() { runResolveUnderMockEnv(ctx, null); - Assert.assertEquals("", ctx.getWorkloadGroupName()); + Assertions.assertEquals("", ctx.getWorkloadGroupName()); } @Test @@ -90,7 +90,7 @@ public void testResolveWorkloadGroupNameFromSessionVariable() { runResolveUnderMockEnv(ctx, USER_PROPERTY_WORKLOAD_GROUP); // Session variable has highest priority. - Assert.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); + Assertions.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); } @Test @@ -99,7 +99,7 @@ public void testResolveWorkloadGroupNameFromUserProperty() { runResolveUnderMockEnv(ctx, USER_PROPERTY_WORKLOAD_GROUP); - Assert.assertEquals(USER_PROPERTY_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); + Assertions.assertEquals(USER_PROPERTY_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); } @Test @@ -108,7 +108,7 @@ public void testResolveWorkloadGroupNameFallbackToDefault() { runResolveUnderMockEnv(ctx, null); - Assert.assertEquals(WorkloadGroupMgr.DEFAULT_GROUP_NAME, ctx.getWorkloadGroupName()); + Assertions.assertEquals(WorkloadGroupMgr.DEFAULT_GROUP_NAME, ctx.getWorkloadGroupName()); } // ---------- Entry-point tests: every audit-logging code path ---------- // @@ -165,9 +165,8 @@ public void testFlightSqlHandleQueryResolvesWorkloadGroup() throws Exception { } } - Assert.assertTrue("resolveWorkloadGroupName must be called before super.handleQuery", - processor.resolvedBeforeHandleQuery); - Assert.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); + Assertions.assertTrue(processor.resolvedBeforeHandleQuery, "resolveWorkloadGroupName must be called before super.handleQuery"); + Assertions.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); } // ---------- Multi-statement per-iteration re-resolve ---------- // @@ -220,16 +219,15 @@ public void testExecuteQueryResolvesWorkloadGroupPerStatement() throws Exception // resolveWorkloadGroupName() must be called at least once per statement, // in addition to the caller-site invocation verified by the dispatch tests. - Assert.assertTrue("resolveWorkloadGroupName must be called for every statement" - + " in the multi-stmt loop, got " + resolveCallCount[0], - resolveCallCount[0] >= 2); + Assertions.assertTrue(resolveCallCount[0] >= 2, "resolveWorkloadGroupName must be called for every statement" + + " in the multi-stmt loop, got " + resolveCallCount[0]); // Both statements must be audited. - Assert.assertEquals(2, auditedWorkloadGroups.size()); + Assertions.assertEquals(2, auditedWorkloadGroups.size()); // Statement 1 is audited with the initial session-variable value. - Assert.assertEquals(firstStmtWg, auditedWorkloadGroups.get(0)); + Assertions.assertEquals(firstStmtWg, auditedWorkloadGroups.get(0)); // Statement 2 must be audited with the post-change value — *not* the stale // value that the old once-per-packet resolve would have left on ctx. - Assert.assertEquals(secondStmtWg, auditedWorkloadGroups.get(1)); + Assertions.assertEquals(secondStmtWg, auditedWorkloadGroups.get(1)); } // ---------- Helpers ---------- // @@ -255,10 +253,9 @@ private void verifyDispatchResolvesForCommand(ByteBuffer packet) throws Exceptio } } - Assert.assertTrue("resolveWorkloadGroupName must be invoked by dispatch()", - processor.resolveCalled); + Assertions.assertTrue(processor.resolveCalled, "resolveWorkloadGroupName must be invoked by dispatch()"); // The resolution must have set the session-variable value, not left the stale one. - Assert.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); + Assertions.assertEquals(SESSION_WORKLOAD_GROUP, ctx.getWorkloadGroupName()); } private ConnectContext newContextWithSessionWorkloadGroup(String wg) { diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectAttributesForwardTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectAttributesForwardTest.java index 0cea005f9d287a..da4f1a6e10b6ce 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectAttributesForwardTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectAttributesForwardTest.java @@ -19,8 +19,8 @@ import org.apache.doris.thrift.TMasterOpRequest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -46,10 +46,9 @@ public void testSerializeConnectAttributesToRequest() { params.setConnectAttributes(connectAttributes); } - Assert.assertTrue("connect_attributes should be set on request", - params.isSetConnectAttributes()); - Assert.assertEquals(2, params.getConnectAttributes().size()); - Assert.assertEquals( + Assertions.assertTrue(params.isSetConnectAttributes(), "connect_attributes should be set on request"); + Assertions.assertEquals(2, params.getConnectAttributes().size()); + Assertions.assertEquals( "{\"SKYNET_TASKID\":\"523987416281\",\"SKYNET_APP_ID\":\"392426\"}", params.getConnectAttributes().get("scheduleInfo")); } @@ -62,14 +61,14 @@ public void testRestoreConnectAttributesFromRequest() { request.setConnectAttributes(attrs); ConnectContext ctx = new ConnectContext(); - Assert.assertTrue(ctx.getConnectAttributes().isEmpty()); + Assertions.assertTrue(ctx.getConnectAttributes().isEmpty()); if (request.isSetConnectAttributes()) { ctx.setConnectAttributes(request.getConnectAttributes()); } - Assert.assertEquals(1, ctx.getConnectAttributes().size()); - Assert.assertEquals("{\"SKYNET_TASKID\":\"523987416281\"}", + Assertions.assertEquals(1, ctx.getConnectAttributes().size()); + Assertions.assertEquals("{\"SKYNET_TASKID\":\"523987416281\"}", ctx.getConnectAttributes().get("scheduleInfo")); } @@ -95,7 +94,7 @@ public void testScheduleInfoRoundTrip() { receiverCtx.setConnectAttributes(request.getConnectAttributes()); } - Assert.assertEquals(scheduleInfoValue, + Assertions.assertEquals(scheduleInfoValue, receiverCtx.getConnectAttributes().get("scheduleInfo")); } @@ -109,8 +108,7 @@ public void testEmptyConnectAttributesNotSerialized() { params.setConnectAttributes(connectAttributes); } - Assert.assertFalse("connect_attributes should NOT be set for empty attributes", - params.isSetConnectAttributes()); + Assertions.assertFalse(params.isSetConnectAttributes(), "connect_attributes should NOT be set for empty attributes"); } @Test @@ -122,7 +120,7 @@ public void testNoConnectAttributesInRequest() { ctx.setConnectAttributes(request.getConnectAttributes()); } - Assert.assertNotNull(ctx.getConnectAttributes()); - Assert.assertTrue(ctx.getConnectAttributes().isEmpty()); + Assertions.assertNotNull(ctx.getConnectAttributes()); + Assertions.assertTrue(ctx.getConnectAttributes().isEmpty()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java index 509d1823afc415..5808cebd873f74 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectContextTest.java @@ -44,9 +44,9 @@ import org.apache.doris.transaction.TransactionStatus; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -72,7 +72,7 @@ public class ConnectContextTest { private CatalogMgr catalogMgr = Mockito.mock(CatalogMgr.class); - @Before + @BeforeEach public void setUp() throws Exception { Mockito.when(env.getInternalCatalog()).thenReturn(internalCatalog); Mockito.when(internalCatalog.getName()).thenReturn("internal"); @@ -114,32 +114,32 @@ public void testResetConnectionClearsSessionState() throws Exception { ctx.updateReturnRows(10); ctx.setOrUpdateInsertResult(1, "label", "test_db", "test_table", TransactionStatus.VISIBLE, 1, 0); - Assert.assertEquals(0, ctx.getSessionVariable().getSqlSelectLimit()); - Assert.assertEquals(1, ctx.getSessionVariable().getQueryTimeoutS()); - Assert.assertEquals(2, ctx.getSessionVariable().getInsertTimeoutS()); - Assert.assertFalse(ctx.getUserVars().isEmpty()); - Assert.assertNotNull(ctx.getInsertResult()); + Assertions.assertEquals(0, ctx.getSessionVariable().getSqlSelectLimit()); + Assertions.assertEquals(1, ctx.getSessionVariable().getQueryTimeoutS()); + Assertions.assertEquals(2, ctx.getSessionVariable().getInsertTimeoutS()); + Assertions.assertFalse(ctx.getUserVars().isEmpty()); + Assertions.assertNotNull(ctx.getInsertResult()); ctx.resetConnection(); - Assert.assertEquals(-1, ctx.getSessionVariable().getSqlSelectLimit()); - Assert.assertEquals(123, ctx.getSessionVariable().getQueryTimeoutS()); - Assert.assertEquals(456, ctx.getSessionVariable().getInsertTimeoutS()); - Assert.assertTrue(ctx.getUserVars().isEmpty()); - Assert.assertEquals("external_catalog", ctx.getDefaultCatalog()); - Assert.assertEquals("test_db", ctx.getDatabase()); - Assert.assertEquals("test_db", ctx.getLastDBOfCatalog("external_catalog")); - Assert.assertNull(ctx.getPreparedQuery("1")); - Assert.assertNull(ctx.getRunningQuery()); - Assert.assertNull(ctx.queryId()); - Assert.assertNull(ctx.getLastQueryId()); - Assert.assertNull(ctx.traceId()); + Assertions.assertEquals(-1, ctx.getSessionVariable().getSqlSelectLimit()); + Assertions.assertEquals(123, ctx.getSessionVariable().getQueryTimeoutS()); + Assertions.assertEquals(456, ctx.getSessionVariable().getInsertTimeoutS()); + Assertions.assertTrue(ctx.getUserVars().isEmpty()); + Assertions.assertEquals("external_catalog", ctx.getDefaultCatalog()); + Assertions.assertEquals("test_db", ctx.getDatabase()); + Assertions.assertEquals("test_db", ctx.getLastDBOfCatalog("external_catalog")); + Assertions.assertNull(ctx.getPreparedQuery("1")); + Assertions.assertNull(ctx.getRunningQuery()); + Assertions.assertNull(ctx.queryId()); + Assertions.assertNull(ctx.getLastQueryId()); + Assertions.assertNull(ctx.traceId()); Mockito.verify(connectScheduler).removeOldTraceId("old_trace"); - Assert.assertEquals(nextPreparedStmtId, ctx.getPreparedStmtId()); - Assert.assertTrue(initialPreparedStmtId != ctx.getPreparedStmtId()); - Assert.assertNull(ctx.getInsertResult()); - Assert.assertEquals(MysqlCommand.COM_SLEEP, ctx.getCommand()); - Assert.assertEquals(0, ctx.getReturnRows()); + Assertions.assertEquals(nextPreparedStmtId, ctx.getPreparedStmtId()); + Assertions.assertTrue(initialPreparedStmtId != ctx.getPreparedStmtId()); + Assertions.assertNull(ctx.getInsertResult()); + Assertions.assertEquals(MysqlCommand.COM_SLEEP, ctx.getCommand()); + Assertions.assertEquals(0, ctx.getReturnRows()); } @Test @@ -151,7 +151,7 @@ public void testHandleResetConnectionDoesNotSetServerStatus() { ctx.getState().reset(); processor.handleResetConnection(); - Assert.assertEquals(0, ctx.getState().serverStatus); + Assertions.assertEquals(0, ctx.getState().serverStatus); } @Test @@ -165,7 +165,7 @@ public void testHandleStmtResetReturnsOkForKnownStatement() throws Exception { ctx.getState().reset(); processor.handleStmtResetById(1); - Assert.assertEquals(MysqlStateType.OK, ctx.getState().getStateType()); + Assertions.assertEquals(MysqlStateType.OK, ctx.getState().getStateType()); } @Test @@ -177,9 +177,9 @@ public void testHandleStmtResetReturnsErrorForUnknownStatement() { ctx.getState().reset(); processor.handleStmtResetById(1); - Assert.assertEquals(MysqlStateType.ERR, ctx.getState().getStateType()); - Assert.assertEquals(ErrorCode.ERR_UNKNOWN_STMT_HANDLER, ctx.getState().getErrorCode()); - Assert.assertTrue(ctx.getState().getErrorMessage().contains("mysqld_stmt_reset")); + Assertions.assertEquals(MysqlStateType.ERR, ctx.getState().getStateType()); + Assertions.assertEquals(ErrorCode.ERR_UNKNOWN_STMT_HANDLER, ctx.getState().getErrorCode()); + Assertions.assertTrue(ctx.getState().getErrorMessage().contains("mysqld_stmt_reset")); } @Test @@ -196,9 +196,9 @@ public void resetConnection() throws DdlException { ctx.getState().reset(); processor.handleResetConnection(); - Assert.assertEquals(MysqlStateType.ERR, ctx.getState().getStateType()); - Assert.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, ctx.getState().getErrorCode()); - Assert.assertTrue(ctx.getState().getErrorMessage().contains("reset connection failed")); + Assertions.assertEquals(MysqlStateType.ERR, ctx.getState().getStateType()); + Assertions.assertEquals(ErrorCode.ERR_UNKNOWN_ERROR, ctx.getState().getErrorCode()); + Assertions.assertTrue(ctx.getState().getErrorMessage().contains("reset connection failed")); } @Test @@ -235,8 +235,8 @@ public void testResetConnectionDropsMultipleTemporaryTables() throws Exception { ctx.resetConnection(); } - Assert.assertEquals(2, droppedTableCount.get()); - Assert.assertTrue(ctx.getDbToTempTableNamesMap().isEmpty()); + Assertions.assertEquals(2, droppedTableCount.get()); + Assertions.assertTrue(ctx.getDbToTempTableNamesMap().isEmpty()); } @Test @@ -249,79 +249,79 @@ public void testNormal() { ConnectContext ctx = new ConnectContext(); // State - Assert.assertNotNull(ctx.getState()); + Assertions.assertNotNull(ctx.getState()); // Capability - Assert.assertEquals(MysqlCapability.DEFAULT_CAPABILITY, ctx.getServerCapability()); + Assertions.assertEquals(MysqlCapability.DEFAULT_CAPABILITY, ctx.getServerCapability()); ctx.setCapability(new MysqlCapability(10)); - Assert.assertEquals(new MysqlCapability(10), ctx.getCapability()); + Assertions.assertEquals(new MysqlCapability(10), ctx.getCapability()); // Kill flag - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); ctx.setKilled(); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); // Current db - Assert.assertEquals("", ctx.getDatabase()); + Assertions.assertEquals("", ctx.getDatabase()); ctx.setDatabase("testDb"); - Assert.assertEquals("testDb", ctx.getDatabase()); + Assertions.assertEquals("testDb", ctx.getDatabase()); // User ctx.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("testUser", "%")); - Assert.assertEquals("testUser", ctx.getQualifiedUser()); + Assertions.assertEquals("testUser", ctx.getQualifiedUser()); // Serializer - Assert.assertNotNull(ctx.getMysqlChannel().getSerializer()); + Assertions.assertNotNull(ctx.getMysqlChannel().getSerializer()); // Session variable - Assert.assertNotNull(ctx.getSessionVariable()); + Assertions.assertNotNull(ctx.getSessionVariable()); // connect scheduler - Assert.assertNull(ctx.getConnectScheduler()); + Assertions.assertNull(ctx.getConnectScheduler()); ctx.setConnectScheduler(connectScheduler); - Assert.assertNotNull(ctx.getConnectScheduler()); + Assertions.assertNotNull(ctx.getConnectScheduler()); // connection id ctx.setConnectionId(101); - Assert.assertEquals(101, ctx.getConnectionId()); + Assertions.assertEquals(101, ctx.getConnectionId()); // command ctx.setCommand(MysqlCommand.COM_PING); - Assert.assertEquals(MysqlCommand.COM_PING, ctx.getCommand()); + Assertions.assertEquals(MysqlCommand.COM_PING, ctx.getCommand()); // LoginTime ctx.loginTime = 1694002396223L; // Thread info - Assert.assertNotNull(ctx.toThreadInfo(false)); + Assertions.assertNotNull(ctx.toThreadInfo(false)); List row = ctx.toThreadInfo(false).toRow(101, 1000, Optional.of("+08:00")); - Assert.assertEquals(15, row.size()); - Assert.assertEquals("Yes", row.get(0)); - Assert.assertEquals("101", row.get(1)); - Assert.assertEquals("testUser", row.get(2)); - Assert.assertEquals("", row.get(3)); - Assert.assertEquals("2023-09-06 20:13:16", row.get(4)); - Assert.assertEquals("internal", row.get(5)); - Assert.assertEquals("testDb", row.get(6)); - Assert.assertEquals("Ping", row.get(7)); - Assert.assertEquals("1", row.get(8)); - Assert.assertEquals("OK", row.get(9)); - Assert.assertEquals("", row.get(10)); - Assert.assertEquals("", row.get(11)); + Assertions.assertEquals(15, row.size()); + Assertions.assertEquals("Yes", row.get(0)); + Assertions.assertEquals("101", row.get(1)); + Assertions.assertEquals("testUser", row.get(2)); + Assertions.assertEquals("", row.get(3)); + Assertions.assertEquals("2023-09-06 20:13:16", row.get(4)); + Assertions.assertEquals("internal", row.get(5)); + Assertions.assertEquals("testDb", row.get(6)); + Assertions.assertEquals("Ping", row.get(7)); + Assertions.assertEquals("1", row.get(8)); + Assertions.assertEquals("OK", row.get(9)); + Assertions.assertEquals("", row.get(10)); + Assertions.assertEquals("", row.get(11)); // Start time - Assert.assertEquals(0, ctx.getStartTime()); + Assertions.assertEquals(0, ctx.getStartTime()); ctx.setStartTime(); - Assert.assertNotSame(0, ctx.getStartTime()); + Assertions.assertNotSame(0, ctx.getStartTime()); // query id ctx.setQueryId(new TUniqueId(100, 200)); - Assert.assertEquals(new TUniqueId(100, 200), ctx.queryId()); + Assertions.assertEquals(new TUniqueId(100, 200), ctx.queryId()); // Catalog - Assert.assertNull(ctx.getEnv()); + Assertions.assertNull(ctx.getEnv()); ctx.setEnv(env); - Assert.assertNotNull(ctx.getEnv()); + Assertions.assertNotNull(ctx.getEnv()); // clean up ctx.cleanup(); @@ -335,30 +335,30 @@ public void testSleepTimeout() { // sleep no time out ctx.setStartTime(); - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); long now = ctx.getStartTime() + ctx.getSessionVariable().getWaitTimeoutS() * 1000L - 1; ctx.checkTimeout(now); - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); // Timeout ctx.setStartTime(); now = ctx.getStartTime() + ctx.getSessionVariable().getWaitTimeoutS() * 1000L + 1; ctx.setExecutor(executor); ctx.checkTimeout(now); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); // user query timeout ctx.setStartTime(); now = ctx.getStartTime() + auth.getQueryTimeout(qualifiedUser) * 1000L + 1; ctx.setExecutor(executor); ctx.checkTimeout(now); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); // Kill ctx.kill(true); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); ctx.kill(false); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); // clean up ctx.cleanup(); @@ -370,21 +370,21 @@ public void testOtherTimeout() { ctx.setCommand(MysqlCommand.COM_QUERY); // sleep no time out - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); ctx.setExecutor(executor); long now = ctx.getExecTimeoutS() * 1000L - 1; ctx.checkTimeout(now); - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); // Timeout ctx.setExecutor(executor); now = ctx.getExecTimeoutS() * 1000L + 1; ctx.checkTimeout(now); - Assert.assertFalse(ctx.isKilled()); + Assertions.assertFalse(ctx.isKilled()); // Kill ctx.kill(true); - Assert.assertTrue(ctx.isKilled()); + Assertions.assertTrue(ctx.isKilled()); // clean up ctx.cleanup(); @@ -393,10 +393,10 @@ public void testOtherTimeout() { @Test public void testThreadLocal() { ConnectContext ctx = new ConnectContext(); - Assert.assertNull(ConnectContext.get()); + Assertions.assertNull(ConnectContext.get()); ctx.setThreadLocalInfo(); - Assert.assertNotNull(ConnectContext.get()); - Assert.assertEquals(ctx, ConnectContext.get()); + Assertions.assertNotNull(ConnectContext.get()); + Assertions.assertEquals(ctx, ConnectContext.get()); } @Test @@ -409,12 +409,12 @@ public void testGetMaxExecMemByte() { // only session context.getSessionVariable().setMaxExecMemByte(sessionValue); long result = context.getMaxExecMemByte(); - Assert.assertEquals(sessionValue, result); + Assertions.assertEquals(sessionValue, result); // has property Mockito.when(env.getAuth()).thenReturn(auth); Mockito.when(auth.getExecMemLimit(Mockito.anyString())).thenReturn(propertyValue); result = context.getMaxExecMemByte(); - Assert.assertEquals(propertyValue, result); + Assertions.assertEquals(propertyValue, result); } @Test @@ -427,12 +427,12 @@ public void testGetQueryTimeoutS() { // only session context.getSessionVariable().setQueryTimeoutS(sessionValue); long result = context.getQueryTimeoutS(); - Assert.assertEquals(sessionValue, result); + Assertions.assertEquals(sessionValue, result); // has property Mockito.when(env.getAuth()).thenReturn(auth); Mockito.when(auth.getQueryTimeout(Mockito.anyString())).thenReturn(propertyValue); result = context.getQueryTimeoutS(); - Assert.assertEquals(propertyValue, result); + Assertions.assertEquals(propertyValue, result); } @Test @@ -445,35 +445,35 @@ public void testInsertQueryTimeoutS() { // only session context.getSessionVariable().setInsertTimeoutS(sessionValue); long result = context.getInsertTimeoutS(); - Assert.assertEquals(sessionValue, result); + Assertions.assertEquals(sessionValue, result); // has property Mockito.when(env.getAuth()).thenReturn(auth); Mockito.when(auth.getInsertTimeout(Mockito.anyString())).thenReturn(propertyValue); result = context.getInsertTimeoutS(); - Assert.assertEquals(propertyValue, result); + Assertions.assertEquals(propertyValue, result); } @Test public void testResetQueryId() { ConnectContext context = new ConnectContext(); - Assert.assertNull(context.queryId); - Assert.assertNull(context.lastQueryId); + Assertions.assertNull(context.queryId); + Assertions.assertNull(context.lastQueryId); UUID uuid = UUID.randomUUID(); TUniqueId queryId = new TUniqueId(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); context.setQueryId(queryId); - Assert.assertEquals(queryId, context.queryId); - Assert.assertNull(context.lastQueryId); + Assertions.assertEquals(queryId, context.queryId); + Assertions.assertNull(context.lastQueryId); context.resetQueryId(); - Assert.assertNull(context.queryId); - Assert.assertEquals(queryId, context.lastQueryId); + Assertions.assertNull(context.queryId); + Assertions.assertEquals(queryId, context.lastQueryId); UUID uuid2 = UUID.randomUUID(); TUniqueId queryId2 = new TUniqueId(uuid2.getMostSignificantBits(), uuid2.getLeastSignificantBits()); context.setQueryId(queryId2); - Assert.assertEquals(queryId2, context.queryId); - Assert.assertEquals(queryId, context.lastQueryId); + Assertions.assertEquals(queryId2, context.queryId); + Assertions.assertEquals(queryId, context.lastQueryId); } @Test @@ -484,7 +484,7 @@ public void testInitCatalogAndDbSinglePart() throws Exception { // env.changeDb is a void method on a mock - does nothing by default Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "testDb"); - Assert.assertFalse(result.isPresent()); + Assertions.assertFalse(result.isPresent()); } @Test @@ -495,7 +495,7 @@ public void testInitCatalogAndDbTwoParts() throws Exception { // env.changeCatalog and env.changeDb are void methods on a mock - do nothing by default Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "catalog1.testDb"); - Assert.assertFalse(result.isPresent()); + Assertions.assertFalse(result.isPresent()); } @Test @@ -512,7 +512,7 @@ public void testInitCatalogAndDbMultiplePartsWithNestedNamespaceEnabled() throws Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "catalog1.ns1.ns2.testDb"); - Assert.assertFalse(result.isPresent()); + Assertions.assertFalse(result.isPresent()); } finally { GlobalVariable.enableNestedNamespace = originalValue; } @@ -530,9 +530,9 @@ public void testInitCatalogAndDbMultiplePartsWithNestedNamespaceDisabled() throw Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "catalog1.ns1.ns2.testDb"); - Assert.assertTrue(result.isPresent()); - Assert.assertEquals(ErrorCode.ERR_BAD_DB_ERROR, result.get().first); - Assert.assertTrue(result.get().second.contains("Only one dot can be in the name")); + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(ErrorCode.ERR_BAD_DB_ERROR, result.get().first); + Assertions.assertTrue(result.get().second.contains("Only one dot can be in the name")); } finally { GlobalVariable.enableNestedNamespace = originalValue; } @@ -552,7 +552,7 @@ public void testInitCatalogAndDbWithFourPartsNestedNamespaceEnabled() throws Exc Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "catalog1.ns1.ns2.ns3.testDb"); - Assert.assertFalse(result.isPresent()); + Assertions.assertFalse(result.isPresent()); } finally { GlobalVariable.enableNestedNamespace = originalValue; } @@ -566,8 +566,8 @@ public void testInitCatalogAndDbWithChangeCatalogException() throws Exception { Mockito.doThrow(new DdlException("Catalog not found")).when(env).changeCatalog(ctx, "invalidCatalog"); Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "invalidCatalog.testDb"); - Assert.assertTrue(result.isPresent()); - Assert.assertTrue(result.get().second.contains("Catalog not found")); + Assertions.assertTrue(result.isPresent()); + Assertions.assertTrue(result.get().second.contains("Catalog not found")); } @Test @@ -578,8 +578,8 @@ public void testInitCatalogAndDbWithChangeDbException() throws Exception { Mockito.doThrow(new DdlException("Database not found")).when(env).changeDb(ctx, "invalidDb"); Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, "invalidDb"); - Assert.assertTrue(result.isPresent()); - Assert.assertTrue(result.get().second.contains("Database not found")); + Assertions.assertTrue(result.isPresent()); + Assertions.assertTrue(result.get().second.contains("Database not found")); } @Test @@ -590,7 +590,7 @@ public void testInitCatalogAndDbEmptyString() throws Exception { // env.changeDb is a void method on a mock - does nothing by default Optional> result = ConnectContextUtil.initCatalogAndDb(ctx, ""); - Assert.assertFalse(result.isPresent()); + Assertions.assertFalse(result.isPresent()); } @Test @@ -601,7 +601,7 @@ public void testInitCatalogAndDbNullString() { // This should cause a NullPointerException when calling split on null try { ConnectContextUtil.initCatalogAndDb(ctx, null); - Assert.fail("Expected NullPointerException"); + Assertions.fail("Expected NullPointerException"); } catch (NullPointerException e) { // Expected behavior } @@ -623,10 +623,10 @@ public void testGetCloudCluster() throws Exception { // This tests: "Get cluster from session variable (set by `use @` command or setCloudCluster())" ctx.setCloudCluster("session_cluster"); // Verify that setCloudCluster sets session variable - Assert.assertEquals("session_cluster", ctx.getSessionVariable().getCloudCluster()); + Assertions.assertEquals("session_cluster", ctx.getSessionVariable().getCloudCluster()); mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(cloudSystemInfoService); String cluster = ctx.getCloudCluster(false); - Assert.assertEquals("session_cluster", cluster); + Assertions.assertEquals("session_cluster", cluster); // Test 2: Cluster from user default (step 2) // This tests: "Get cluster from user's default cluster property if set" @@ -638,7 +638,7 @@ public void testGetCloudCluster() throws Exception { mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(cloudSystemInfoService); Mockito.when(cloudSystemInfoService.getCloudClusterNames()).thenReturn(Lists.newArrayList("user_default_cluster", "other_cluster")); cluster = ctx.getCloudCluster(false); - Assert.assertEquals("user_default_cluster", cluster); + Assertions.assertEquals("user_default_cluster", cluster); // Test 3: Cluster from this.cloudCluster cache (step 3) // This tests: "Get cluster from cached variable (this.cloudCluster) if available" @@ -649,7 +649,7 @@ public void testGetCloudCluster() throws Exception { Mockito.when(auth.getDefaultCloudCluster("testUser")).thenReturn(null); mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(cloudSystemInfoService); cluster = ctx.getCloudCluster(false); - Assert.assertEquals("cached_cluster", cluster); + Assertions.assertEquals("cached_cluster", cluster); // Test 4: Cluster from policy (step 4) // This tests: "Choose an authorized cluster by policy if all preceding conditions failed" @@ -667,9 +667,9 @@ public void testGetCloudCluster() throws Exception { Mockito.when(cloudSystemInfoService.getBackendsByClusterName("policy_cluster2")).thenReturn(Lists.newArrayList(backend)); Mockito.when(backend.isAlive()).thenReturn(true); cluster = ctx.getCloudCluster(false); - Assert.assertEquals("policy_cluster2", cluster); + Assertions.assertEquals("policy_cluster2", cluster); // Verify cache is set for subsequent calls - Assert.assertEquals("policy_cluster2", ctx.cloudCluster); + Assertions.assertEquals("policy_cluster2", ctx.cloudCluster); // Test 5: Priority order - session variable takes precedence over this.cloudCluster ctx.setCloudCluster("session_cluster2"); @@ -677,7 +677,7 @@ public void testGetCloudCluster() throws Exception { Mockito.reset(auth, cloudSystemInfoService, accessManager, backend); mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(cloudSystemInfoService); cluster = ctx.getCloudCluster(false); - Assert.assertEquals("session_cluster2", cluster); // Session variable wins + Assertions.assertEquals("session_cluster2", cluster); // Session variable wins // Test 6: Priority order - user this.cloudCluster over default takes precedence ctx.setCloudCluster(null); // Clear session cluster @@ -688,7 +688,7 @@ public void testGetCloudCluster() throws Exception { mockedEnv.when(Env::getCurrentSystemInfo).thenReturn(cloudSystemInfoService); Mockito.when(cloudSystemInfoService.getCloudClusterNames()).thenReturn(Lists.newArrayList("user_default_cluster2", "other_cluster")); cluster = ctx.getCloudCluster(false); - Assert.assertEquals("cached_cluster3", cluster); // User this.cloudCluster wins + Assertions.assertEquals("cached_cluster3", cluster); // User this.cloudCluster wins // Test 7: No cluster available - should throw exception ctx.setCloudCluster(null); @@ -703,9 +703,9 @@ public void testGetCloudCluster() throws Exception { Mockito.eq(PrivPredicate.USAGE), Mockito.eq(ResourceTypeEnum.CLUSTER))).thenReturn(false); try { ctx.getCloudCluster(true); - Assert.fail("Expected ComputeGroupException"); + Assertions.fail("Expected ComputeGroupException"); } catch (ComputeGroupException e) { - Assert.assertEquals(ComputeGroupException.FailedTypeEnum.CURRENT_USER_NO_AUTH_TO_USE_ANY_COMPUTE_GROUP, + Assertions.assertEquals(ComputeGroupException.FailedTypeEnum.CURRENT_USER_NO_AUTH_TO_USE_ANY_COMPUTE_GROUP, e.getFailedType()); } } finally { @@ -717,8 +717,8 @@ public void testGetCloudCluster() throws Exception { public void testConnectAttributesDefault() { ConnectContext ctx = new ConnectContext(); Map attrs = ctx.getConnectAttributes(); - Assert.assertNotNull("connectAttributes should never be null", attrs); - Assert.assertTrue("connectAttributes should default to empty", attrs.isEmpty()); + Assertions.assertNotNull(attrs, "connectAttributes should never be null"); + Assertions.assertTrue(attrs.isEmpty(), "connectAttributes should default to empty"); } @Test @@ -730,9 +730,9 @@ public void testConnectAttributesSetAndGet() { ctx.setConnectAttributes(attrs); Map result = ctx.getConnectAttributes(); - Assert.assertEquals(2, result.size()); - Assert.assertEquals("{\"SKYNET_TASKID\":\"523987416281\"}", result.get("scheduleInfo")); - Assert.assertEquals("dataworks-connector", result.get("_client_name")); + Assertions.assertEquals(2, result.size()); + Assertions.assertEquals("{\"SKYNET_TASKID\":\"523987416281\"}", result.get("scheduleInfo")); + Assertions.assertEquals("dataworks-connector", result.get("_client_name")); } @Test @@ -743,15 +743,15 @@ public void testConnectAttributesDefensiveCopy() { ctx.setConnectAttributes(attrs); attrs.put("scheduleInfo", "modified"); - Assert.assertEquals("original", ctx.getConnectAttributes().get("scheduleInfo")); + Assertions.assertEquals("original", ctx.getConnectAttributes().get("scheduleInfo")); } @Test public void testConnectAttributesSetNull() { ConnectContext ctx = new ConnectContext(); ctx.setConnectAttributes(null); - Assert.assertNotNull(ctx.getConnectAttributes()); - Assert.assertTrue(ctx.getConnectAttributes().isEmpty()); + Assertions.assertNotNull(ctx.getConnectAttributes()); + Assertions.assertTrue(ctx.getConnectAttributes().isEmpty()); } // Arrow Flight SQL keeps a query's coordinator alive across GetFlightInfo -> DoGet (see #62259). diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectSchedulerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectSchedulerTest.java index 21d126880f7d93..f65fcf39870360 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectSchedulerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ConnectSchedulerTest.java @@ -22,10 +22,10 @@ import org.apache.doris.mysql.MysqlChannel; import org.apache.doris.mysql.MysqlProto; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.slf4j.Logger; @@ -42,7 +42,7 @@ public class ConnectSchedulerTest { private MysqlChannel channel = Mockito.mock(MysqlChannel.class); private MockedStatic mockedMysqlProto; - @Before + @BeforeEach public void setUp() throws Exception { succSubmit = new AtomicLong(0); mockedMysqlProto = Mockito.mockStatic(MysqlProto.class); @@ -50,7 +50,7 @@ public void setUp() throws Exception { mockedMysqlProto.when(() -> MysqlProto.negotiate(Mockito.nullable(ConnectContext.class))).thenReturn(true); } - @After + @AfterEach public void tearDown() { if (mockedMysqlProto != null) { mockedMysqlProto.close(); @@ -68,8 +68,8 @@ public void testSubmit() throws Exception { context.setEnv(AccessTestUtil.fetchAdminCatalog()); } context.setCurrentUserIdentity(UserIdentity.ROOT); - Assert.assertTrue(scheduler.submit(context)); - Assert.assertEquals(i, context.getConnectionId()); + Assertions.assertTrue(scheduler.submit(context)); + Assertions.assertEquals(i, context.getConnectionId()); } } @@ -80,24 +80,24 @@ public void testProcessException() throws Exception { ConnectContext context = new ConnectContext(); context.setEnv(AccessTestUtil.fetchAdminCatalog()); context.setCurrentUserIdentity(UserIdentity.ROOT); - Assert.assertTrue(scheduler.submit(context)); - Assert.assertEquals(0, context.getConnectionId()); + Assertions.assertTrue(scheduler.submit(context)); + Assertions.assertEquals(0, context.getConnectionId()); Thread.sleep(1000); - Assert.assertNull(scheduler.getContext(0)); + Assertions.assertNull(scheduler.getContext(0)); } @Test public void testSubmitFail() throws InterruptedException { ConnectScheduler scheduler = new ConnectScheduler(10); - Assert.assertFalse(scheduler.submit(null)); + Assertions.assertFalse(scheduler.submit(null)); } @Test public void testSubmitTooMany() throws InterruptedException { ConnectScheduler scheduler = new ConnectScheduler(0); ConnectContext context = new ConnectContext(); - Assert.assertTrue(scheduler.submit(context)); + Assertions.assertTrue(scheduler.submit(context)); } @Test @@ -112,8 +112,8 @@ public void testTimeoutCheckerContinuesAfterContextException() { connectPoolMgr.timeoutChecker(System.currentTimeMillis()); - Assert.assertEquals(1, throwingContext.checkCount.get()); - Assert.assertEquals(1, countingContext.checkCount.get()); + Assertions.assertEquals(1, throwingContext.checkCount.get()); + Assertions.assertEquals(1, countingContext.checkCount.get()); } private static class ThrowingConnectContext extends ConnectContext { diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/FEOpExecutorDelegatedCredentialTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/FEOpExecutorDelegatedCredentialTest.java index 157a6d75667cbb..61ed26335769f6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/FEOpExecutorDelegatedCredentialTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/FEOpExecutorDelegatedCredentialTest.java @@ -26,8 +26,8 @@ import org.apache.doris.thrift.TMasterOpRequest; import org.apache.doris.thrift.TNetworkAddress; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -49,14 +49,14 @@ public void testBuildStmtForwardParamsCarriesDelegatedCredential() throws Except String delegatedCredentialSessionId = context.getSessionContext().getSessionId(); TMasterOpRequest request = new TestFEOpExecutor(context).build(); - Assert.assertTrue(request.isSetDelegatedCredentialSessionId()); - Assert.assertEquals(delegatedCredentialSessionId, request.getDelegatedCredentialSessionId()); - Assert.assertTrue(request.isSetDelegatedCredentialType()); - Assert.assertTrue(request.isSetDelegatedCredentialToken()); - Assert.assertTrue(request.isSetDelegatedCredentialExpiresAtMillis()); - Assert.assertEquals(DelegatedCredential.Type.ID_TOKEN.name(), request.getDelegatedCredentialType()); - Assert.assertEquals("forwarded-id-token", request.getDelegatedCredentialToken()); - Assert.assertEquals(12345L, request.getDelegatedCredentialExpiresAtMillis()); + Assertions.assertTrue(request.isSetDelegatedCredentialSessionId()); + Assertions.assertEquals(delegatedCredentialSessionId, request.getDelegatedCredentialSessionId()); + Assertions.assertTrue(request.isSetDelegatedCredentialType()); + Assertions.assertTrue(request.isSetDelegatedCredentialToken()); + Assertions.assertTrue(request.isSetDelegatedCredentialExpiresAtMillis()); + Assertions.assertEquals(DelegatedCredential.Type.ID_TOKEN.name(), request.getDelegatedCredentialType()); + Assertions.assertEquals("forwarded-id-token", request.getDelegatedCredentialToken()); + Assertions.assertEquals(12345L, request.getDelegatedCredentialExpiresAtMillis()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ForceForwardAllQueriesTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ForceForwardAllQueriesTest.java index d0ca148e69d926..337daf3d48bfa0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ForceForwardAllQueriesTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ForceForwardAllQueriesTest.java @@ -24,8 +24,8 @@ import org.apache.doris.ha.FrontendNodeType; import org.apache.doris.utframe.TestWithFeService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicBoolean; @@ -51,23 +51,23 @@ public void testSessionForceForwardAllQueries() throws Exception { ctx.getSessionVariable().forceForwardAllQueries = false; Config.force_forward_all_queries = false; boolean forward = Deencapsulation.invoke(executor, "shouldForwardToMaster"); - Assert.assertFalse(forward); + Assertions.assertFalse(forward); // session variable enabled -> forwarded ctx.getSessionVariable().forceForwardAllQueries = true; forward = Deencapsulation.invoke(executor, "shouldForwardToMaster"); - Assert.assertTrue(forward); + Assertions.assertTrue(forward); // session variable disabled but config enabled -> forwarded ctx.getSessionVariable().forceForwardAllQueries = false; Config.force_forward_all_queries = true; forward = Deencapsulation.invoke(executor, "shouldForwardToMaster"); - Assert.assertTrue(forward); + Assertions.assertTrue(forward); // both disabled -> not forwarded Config.force_forward_all_queries = false; forward = Deencapsulation.invoke(executor, "shouldForwardToMaster"); - Assert.assertFalse(forward); + Assertions.assertFalse(forward); } finally { Deencapsulation.setField(env, "feType", originalFeType); canRead.set(false); diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/HelpModuleTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/HelpModuleTest.java index 1700069092371e..ceb130ab521df8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/HelpModuleTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/HelpModuleTest.java @@ -24,9 +24,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import java.io.IOException; import java.net.URL; @@ -45,7 +45,7 @@ public class HelpModuleTest { // Topic // - SHOW TABLES // - SELECT TIME - @Before + @BeforeEach public void setUp() { categories = Lists.newArrayList(); topics = Lists.newArrayList(); @@ -98,83 +98,83 @@ public void setUp() { System.out.println(HelpModuleTest.class.getClassLoader().getResource("")); } - @Ignore + @Disabled public void testNormal() throws IOException, UserException { HelpModule module = new HelpModule(); URL help = getClass().getClassLoader().getResource("data/help"); module.setUp(help.getPath()); HelpTopic topic = module.getTopic("SELECT TIME"); - Assert.assertNotNull(topic); + Assertions.assertNotNull(topic); topic = module.getTopic("select time"); - Assert.assertNotNull(topic); + Assertions.assertNotNull(topic); // Must ordered by alpha. List categories = module.listCategoryByCategory("Admin"); - Assert.assertEquals(2, categories.size()); - Assert.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray())); + Assertions.assertEquals(2, categories.size()); + Assertions.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray())); // topics List topics = module.listTopicByKeyword("SHOW"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); topics = module.listTopicByKeyword("SELECT"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); topics = module.listTopicByCategory("selEct"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); topics = module.listTopicByCategory("show"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); - Assert.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(), + Assertions.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(), Lists.newArrayList("Admin").toArray())); } - @Ignore + @Disabled public void testLoadFromZip() throws IOException, UserException { HelpModule module = new HelpModule(); URL help = getClass().getClassLoader().getResource("test-help-resource.zip"); module.setUpByZip(help.getPath()); HelpTopic topic = module.getTopic("SELECT TIME"); - Assert.assertNotNull(topic); + Assertions.assertNotNull(topic); topic = module.getTopic("select time"); - Assert.assertNotNull(topic); + Assertions.assertNotNull(topic); // Must ordered by alpha. List categories = module.listCategoryByCategory("Admin"); - Assert.assertEquals(2, categories.size()); - Assert.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray())); + Assertions.assertEquals(2, categories.size()); + Assertions.assertTrue(Arrays.equals(categories.toArray(), Lists.newArrayList("Select", "Show").toArray())); // topics List topics = module.listTopicByKeyword("SHOW"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); topics = module.listTopicByKeyword("SELECT"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); topics = module.listTopicByCategory("selEct"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SELECT TIME").toArray())); topics = module.listTopicByCategory("show"); - Assert.assertEquals(1, topics.size()); - Assert.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); + Assertions.assertEquals(1, topics.size()); + Assertions.assertTrue(Arrays.equals(topics.toArray(), Lists.newArrayList("SHOW TABLES").toArray())); - Assert.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(), + Assertions.assertTrue(Arrays.equals(module.listCategoryByName("ADMIN").toArray(), Lists.newArrayList("Admin").toArray())); } // Need first call docs/build_help_resource.sh to build real help resource. // And copy docs/build/help-resource.zip to fe/fe-core/src/test/resources/real-help-resource.zip - @Ignore + @Disabled public void testRealHelpZip() { try { HelpModule.getInstance().setUpModule("real-help-resource.zip"); diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/HelpObjectLoaderTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/HelpObjectLoaderTest.java index 8ed392b9158a0e..955d8979384e35 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/HelpObjectLoaderTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/HelpObjectLoaderTest.java @@ -23,8 +23,8 @@ import org.apache.doris.qe.help.HelpTopic; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URL; @@ -38,28 +38,28 @@ public void testTopicNormal() throws IOException, UserException { URL resource = getClass().getClassLoader().getResource("data/helpTopicNormal.md"); HelpObjectLoader loader = HelpObjectLoader.createTopicLoader(); List helpTopics = loader.loadAll(resource.getFile()); - Assert.assertNotNull(helpTopics); - Assert.assertEquals(2, helpTopics.size()); + Assertions.assertNotNull(helpTopics); + Assertions.assertEquals(2, helpTopics.size()); for (HelpTopic topic : helpTopics) { if (topic.getName().equals("SHOW TABLES")) { - Assert.assertTrue(Arrays.equals(Lists.newArrayList("SHOW", "TABLES").toArray(), + Assertions.assertTrue(Arrays.equals(Lists.newArrayList("SHOW", "TABLES").toArray(), topic.getKeywords().toArray())); - Assert.assertEquals("Administration\n", topic.getCategory()); - Assert.assertEquals("", topic.getUrl()); - Assert.assertEquals("show table in this\n" + Assertions.assertEquals("Administration\n", topic.getCategory()); + Assertions.assertEquals("", topic.getUrl()); + Assertions.assertEquals("show table in this\n" + "SYNTAX: SHOW TABLES\n", topic.getDescription()); - Assert.assertEquals("show tables\n", topic.getExample()); + Assertions.assertEquals("show tables\n", topic.getExample()); } else { // SHOW DATABASES - Assert.assertEquals("SHOW DATABASES", topic.getName()); - Assert.assertTrue(Arrays.equals(Lists.newArrayList("SHOW", "DATABASES").toArray(), + Assertions.assertEquals("SHOW DATABASES", topic.getName()); + Assertions.assertTrue(Arrays.equals(Lists.newArrayList("SHOW", "DATABASES").toArray(), topic.getKeywords().toArray())); - Assert.assertEquals("", topic.getCategory()); - Assert.assertEquals("", topic.getUrl()); - Assert.assertEquals("show table in this\n" + Assertions.assertEquals("", topic.getCategory()); + Assertions.assertEquals("", topic.getUrl()); + Assertions.assertEquals("show table in this\n" + " SYNTAX: SHOW DATABASES\n", topic.getDescription()); - Assert.assertEquals("", topic.getExample()); + Assertions.assertEquals("", topic.getExample()); } } } @@ -70,16 +70,16 @@ public void testCategoryNormal() throws IOException, UserException { HelpObjectLoader loader = HelpObjectLoader.createCategoryLoader(); List helpTopics = loader.loadAll(resource.getFile()); - Assert.assertNotNull(helpTopics); - Assert.assertEquals(2, helpTopics.size()); + Assertions.assertNotNull(helpTopics); + Assertions.assertEquals(2, helpTopics.size()); for (HelpCategory topic : helpTopics) { if (topic.getName().equals("Polygon properties")) { - Assert.assertEquals("", topic.getUrl()); - Assert.assertEquals("Geographic Features\n", topic.getParent()); + Assertions.assertEquals("", topic.getUrl()); + Assertions.assertEquals("Geographic Features\n", topic.getParent()); } else if (topic.getName().equals("Geographic")) { - Assert.assertEquals("", topic.getUrl()); - Assert.assertEquals("", topic.getParent()); + Assertions.assertEquals("", topic.getUrl()); + Assertions.assertEquals("", topic.getParent()); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/InsertStreamTxnExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/InsertStreamTxnExecutorTest.java index fb22b660bcf7c4..b0e75ad0291ceb 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/InsertStreamTxnExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/InsertStreamTxnExecutorTest.java @@ -22,8 +22,8 @@ import org.apache.doris.system.SystemInfoService; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -44,7 +44,7 @@ public void testSelectBackendForTxnLoadUsesCurrentClusterBackends() throws Excep Backend selectedBackend = InsertStreamTxnExecutor.selectBackendForTxnLoad(); - Assert.assertEquals(currentClusterBackend.getId(), selectedBackend.getId()); + Assertions.assertEquals(currentClusterBackend.getId(), selectedBackend.getId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/JournalObservableTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/JournalObservableTest.java index d78b8ece6c5077..8780ef696a9b43 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/JournalObservableTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/JournalObservableTest.java @@ -19,8 +19,8 @@ import com.google.common.collect.Multiset; import com.google.common.collect.TreeMultiset; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; @@ -36,16 +36,16 @@ public void testUpperBound() { // empty { // CHECKSTYLE IGNORE THIS LINE - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), 0, 1L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), 0, 1L)); } // CHECKSTYLE IGNORE THIS LINE // one element { // CHECKSTYLE IGNORE THIS LINE elements.add(observer2); int size = elements.size(); - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 2L)); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 3L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 2L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 3L)); } // CHECKSTYLE IGNORE THIS LINE // same element @@ -62,16 +62,16 @@ public void testUpperBound() { } int size = elements.size(); - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 2L)); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 3L)); - Assert.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 4L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 2L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), size, 3L)); + Assertions.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 4L)); elements.remove(observer41); - Assert.assertEquals(3, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); + Assertions.assertEquals(3, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); elements.remove(observer4); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); elements.remove(observer42); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); } // CHECKSTYLE IGNORE THIS LINE // same element 2 @@ -81,11 +81,11 @@ public void testUpperBound() { elements.add(observer41); int size = elements.size(); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 4L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 4L)); elements.remove(observer41); - Assert.assertEquals(1, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); + Assertions.assertEquals(1, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); elements.remove(observer4); - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), elements.size(), 4L)); } // CHECKSTYLE IGNORE THIS LINE // odd elements @@ -98,13 +98,13 @@ public void testUpperBound() { elements.add(observer6); elements.add(observer6); int size = elements.size(); - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 2L)); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 3L)); - Assert.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 4L)); - Assert.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 5L)); - Assert.assertEquals(6, JournalObservable.upperBound(elements.toArray(), size, 6L)); - Assert.assertEquals(6, JournalObservable.upperBound(elements.toArray(), size, 7L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 2L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 3L)); + Assertions.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 4L)); + Assertions.assertEquals(4, JournalObservable.upperBound(elements.toArray(), size, 5L)); + Assertions.assertEquals(6, JournalObservable.upperBound(elements.toArray(), size, 6L)); + Assertions.assertEquals(6, JournalObservable.upperBound(elements.toArray(), size, 7L)); } // CHECKSTYLE IGNORE THIS LINE // even elements { // CHECKSTYLE IGNORE THIS LINE @@ -117,13 +117,13 @@ public void testUpperBound() { elements.add(observer6); elements.add(observer6); int size = elements.size(); - Assert.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 2L)); - Assert.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 3L)); - Assert.assertEquals(5, JournalObservable.upperBound(elements.toArray(), size, 4L)); - Assert.assertEquals(5, JournalObservable.upperBound(elements.toArray(), size, 5L)); - Assert.assertEquals(7, JournalObservable.upperBound(elements.toArray(), size, 6L)); - Assert.assertEquals(7, JournalObservable.upperBound(elements.toArray(), size, 7L)); + Assertions.assertEquals(0, JournalObservable.upperBound(elements.toArray(), size, 1L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 2L)); + Assertions.assertEquals(2, JournalObservable.upperBound(elements.toArray(), size, 3L)); + Assertions.assertEquals(5, JournalObservable.upperBound(elements.toArray(), size, 4L)); + Assertions.assertEquals(5, JournalObservable.upperBound(elements.toArray(), size, 5L)); + Assertions.assertEquals(7, JournalObservable.upperBound(elements.toArray(), size, 6L)); + Assertions.assertEquals(7, JournalObservable.upperBound(elements.toArray(), size, 7L)); } // CHECKSTYLE IGNORE THIS LINE { // CHECKSTYLE IGNORE THIS LINE CountDownLatch latch = new CountDownLatch(1); diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/LimitUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/LimitUtilsTest.java index 012fbad18a5ddb..9a22b5eea9fd27 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/LimitUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/LimitUtilsTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.Status; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.function.Consumer; @@ -35,25 +35,25 @@ public void testUpperBound() { RowBatch rowBatch = new RowBatch(); rowBatch.setEos(false); // - no limit - Assert.assertFalse(LimitUtils.cancelIfReachLimit(rowBatch, 0, 10, cancelFunc)); - Assert.assertFalse(rowBatch.isEos()); - Assert.assertEquals(0, res); + Assertions.assertFalse(LimitUtils.cancelIfReachLimit(rowBatch, 0, 10, cancelFunc)); + Assertions.assertFalse(rowBatch.isEos()); + Assertions.assertEquals(0, res); // - not reach limit - Assert.assertFalse(LimitUtils.cancelIfReachLimit(rowBatch, 10, 1, cancelFunc)); - Assert.assertFalse(rowBatch.isEos()); - Assert.assertEquals(0, res); + Assertions.assertFalse(LimitUtils.cancelIfReachLimit(rowBatch, 10, 1, cancelFunc)); + Assertions.assertFalse(rowBatch.isEos()); + Assertions.assertEquals(0, res); // - reach limit - Assert.assertTrue(LimitUtils.cancelIfReachLimit(rowBatch, 10, 10, cancelFunc)); - Assert.assertTrue(rowBatch.isEos()); - Assert.assertEquals(666, res); + Assertions.assertTrue(LimitUtils.cancelIfReachLimit(rowBatch, 10, 10, cancelFunc)); + Assertions.assertTrue(rowBatch.isEos()); + Assertions.assertEquals(666, res); // - reach limit res = 0; rowBatch.setEos(false); - Assert.assertTrue(LimitUtils.cancelIfReachLimit(rowBatch, 10, 100, cancelFunc)); - Assert.assertTrue(rowBatch.isEos()); - Assert.assertEquals(666, res); + Assertions.assertTrue(LimitUtils.cancelIfReachLimit(rowBatch, 10, 100, cancelFunc)); + Assertions.assertTrue(rowBatch.isEos()); + Assertions.assertEquals(666, res); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java index b7f125cb06100a..2efd31307a7da3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/MasterOpExecutorBackendSelectionTest.java @@ -27,9 +27,9 @@ import org.apache.doris.thrift.TMasterOpRequest; import org.apache.doris.thrift.TMasterOpResult; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -38,7 +38,7 @@ public class MasterOpExecutorBackendSelectionTest { - @After + @AfterEach public void resetBackendSelectionProvider() { BackendSelectionManager.resetProviderForTest(); } @@ -55,10 +55,10 @@ public void testGroupCommitLoadBackendChecksForwardResultStatusCode() throws Exc try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - LoadException exception = Assert.assertThrows(LoadException.class, + LoadException exception = Assertions.assertThrows(LoadException.class, () -> executor.getGroupCommitLoadBeId(1L, "")); - Assert.assertTrue(exception.getMessage().contains("status code: 1")); + Assertions.assertTrue(exception.getMessage().contains("status code: 1")); } } @@ -81,7 +81,7 @@ public void testGroupCommitLoadBackendDoesNotWaitJournalReplay() throws Exceptio try (MockedStatic mockedEnv = Mockito.mockStatic(Env.class)) { mockedEnv.when(Env::getCurrentEnv).thenReturn(env); - Assert.assertEquals(123L, executor.getGroupCommitLoadBeId(1L, "")); + Assertions.assertEquals(123L, executor.getGroupCommitLoadBeId(1L, "")); Mockito.verify(journalObservable, Mockito.never()).waitOn(Mockito.anyLong(), Mockito.anyInt()); } @@ -101,7 +101,7 @@ public void testGroupCommitLoadBackendRequestAlwaysSignalsErrorResultCapability( executor.getGroupCommitLoadBeId(1L, ""); - Assert.assertTrue(executor.capturedRequest.getGroupCommitInfo().isSupportsSelectionErrorResult()); + Assertions.assertTrue(executor.capturedRequest.getGroupCommitInfo().isSupportsSelectionErrorResult()); } } @@ -144,7 +144,7 @@ public void testForwardResultExposesExternalDmlAuditBackendIds() throws Exceptio executor.installForwardResult(); - Assert.assertEquals(Set.of(10001L, 10002L), executor.getAuditStatisticsBackendIds()); + Assertions.assertEquals(Set.of(10001L, 10002L), executor.getAuditStatisticsBackendIds()); } } @@ -158,9 +158,9 @@ public void testDisabledLoadSelectionDoesNotPopulateForwardedInfo() { MasterOpExecutor.setGroupCommitLoadSelectionHint(info, context); - Assert.assertFalse(info.isSetLoadSelectionPreferredKey()); - Assert.assertFalse(info.isSetLoadSelectionMode()); - Assert.assertEquals(0, policy.getLoadSelectionHintCalls); + Assertions.assertFalse(info.isSetLoadSelectionPreferredKey()); + Assertions.assertFalse(info.isSetLoadSelectionMode()); + Assertions.assertEquals(0, policy.getLoadSelectionHintCalls); } @Test @@ -173,9 +173,9 @@ public void testEnabledLoadSelectionPopulatesForwardedInfo() { MasterOpExecutor.setGroupCommitLoadSelectionHint(info, context); - Assert.assertEquals("key_a", info.getLoadSelectionPreferredKey()); - Assert.assertEquals(BackendSelection.Mode.PREFER.name(), info.getLoadSelectionMode()); - Assert.assertEquals(1, policy.getLoadSelectionHintCalls); + Assertions.assertEquals("key_a", info.getLoadSelectionPreferredKey()); + Assertions.assertEquals(BackendSelection.Mode.PREFER.name(), info.getLoadSelectionMode()); + Assertions.assertEquals(1, policy.getLoadSelectionHintCalls); } private static final class DisabledLoadSelectionPolicy implements BackendSelectionProvider { diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/OlapQueryCacheTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/OlapQueryCacheTest.java index 14c020cdc82c57..194ef9a37a62c4 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/OlapQueryCacheTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/OlapQueryCacheTest.java @@ -76,11 +76,11 @@ import com.google.common.collect.Range; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.mockito.MockedStatic; import org.mockito.Mockito; @@ -110,7 +110,7 @@ public class OlapQueryCacheTest { private MockedStatic mockedEnv; private MockedStatic mockedConnectContext; - @BeforeClass + @BeforeAll public static void start() { MetricRepo.init(); try { @@ -126,7 +126,7 @@ public static void start() { } } - @Before + @BeforeEach public void setUp() throws Exception { state = new QueryState(); scheduler = new ConnectScheduler(10); @@ -207,7 +207,7 @@ public void setUp() throws Exception { db.registerTable(view4); } - @After + @AfterEach public void tearDown() { if (mockedUtil != null) { mockedUtil.close(); @@ -276,7 +276,7 @@ private void setPartitionItem(PartitionInfo partInfo, Partition partition, Colum partInfo.setItem(partition.getId(), false, new RangePartitionItem(rangeP1)); } catch (AnalysisException e) { LOG.warn("Part,an_ex={}", e); - Assert.fail(e.getMessage()); + Assertions.fail(e.getMessage()); } } @@ -456,7 +456,7 @@ private StatementBase parseSqlByNereids(String sql) { stmt = adapter; } catch (Throwable throwable) { LOG.warn("Part,an_ex={}", throwable); - Assert.fail(throwable.getMessage()); + Assertions.fail(throwable.getMessage()); } return stmt; } @@ -477,13 +477,13 @@ public void testCacheNode() throws Exception { Types.PUniqueId key1 = Types.PUniqueId.newBuilder().setHi(1L).setLo(1L).build(); Backend bk = cp.findBackend(key1); - Assert.assertNotNull(bk); - Assert.assertEquals(bk.getId(), 3); + Assertions.assertNotNull(bk); + Assertions.assertEquals(bk.getId(), 3); key1 = key1.toBuilder().setHi(669560558156283345L).build(); bk = cp.findBackend(key1); - Assert.assertNotNull(bk); - Assert.assertEquals(bk.getId(), 1); + Assertions.assertNotNull(bk); + Assertions.assertEquals(bk.getId(), 1); } @Test @@ -492,7 +492,7 @@ public void testCacheModeNone() throws Exception { List scanNodes = Lists.newArrayList(); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(0); - Assert.assertEquals(ca.getCacheMode(), CacheMode.NoNeed); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.NoNeed); } @Test @@ -505,7 +505,7 @@ public void testCacheModeTable() throws Exception { List scanNodes = Lists.newArrayList(createProfileScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(0); - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); } @Test @@ -518,7 +518,7 @@ public void testWithinMinTime() throws Exception { List scanNodes = Lists.newArrayList(createProfileScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579024800000L); // 2020-1-15 02:00:00 - Assert.assertEquals(ca.getCacheMode(), CacheMode.None); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.None); } @Test @@ -527,10 +527,10 @@ public void testParseByte() throws Exception { byte[] buffer = new byte[] {10, 50, 48, 50, 48, 45, 48, 51, 45, 49, 48, 1, 51, 2, 67, 78}; PartitionRange.PartitionKeyType key1 = sb.getKeyFromRow(buffer, 0, Type.DATE); LOG.info("real value key1 {}", key1.realValue()); - Assert.assertEquals(key1.realValue(), 20200310); + Assertions.assertEquals(key1.realValue(), 20200310); PartitionRange.PartitionKeyType key2 = sb.getKeyFromRow(buffer, 1, Type.INT); LOG.info("real value key2 {}", key2.realValue()); - Assert.assertEquals(key2.realValue(), 3); + Assertions.assertEquals(key2.realValue(), 3); } @Test @@ -544,7 +544,7 @@ public void testHitSqlCache() throws Exception { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); } @Test @@ -558,13 +558,13 @@ public void testSqlCacheKey() { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); SqlCache sqlCache = (SqlCache) ca.getCache(); String cacheKey = sqlCache.getSqlWithViewStmt(); - Assert.assertEquals(cacheKey, + Assertions.assertEquals(cacheKey, "SELECT eventdate, COUNT(userid) FROM appevent WHERE eventdate>=\"2020-01-12\" and eventdate<=\"2020-01-14\" GROUP BY eventdate|"); - Assert.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); + Assertions.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); } @Test @@ -578,12 +578,12 @@ public void testSqlCacheKeyWithChineseChar() { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); SqlCache sqlCache = (SqlCache) ca.getCache(); String cacheKey = sqlCache.getSqlWithViewStmt(); Types.PUniqueId sqlKey2 = CacheProxy.getMd5(cacheKey.replace("北京", "上海")); - Assert.assertNotEquals(CacheProxy.getMd5(sqlCache.getSqlWithViewStmt()), sqlKey2); - Assert.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); + Assertions.assertNotEquals(CacheProxy.getMd5(sqlCache.getSqlWithViewStmt()), sqlKey2); + Assertions.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); } @Test @@ -594,14 +594,14 @@ public void testSqlCacheKeyWithViewForNereids() { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); SqlCache sqlCache = (SqlCache) ca.getCache(); String cacheKey = sqlCache.getSqlWithViewStmt(); - Assert.assertEquals(cacheKey, "SELECT * from testDb.view1|SELECT `eventdate` AS `eventdate`, " + Assertions.assertEquals(cacheKey, "SELECT * from testDb.view1|SELECT `eventdate` AS `eventdate`, " + "count(`userid`) AS `__count_1` FROM `testDb`.`appevent` " + "WHERE ((`eventdate` >= '2020-01-12') AND (`eventdate` <= '2020-01-14')) GROUP BY `eventdate`"); - Assert.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); + Assertions.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); } @Test @@ -619,17 +619,17 @@ public void testSqlCacheKeyWithSubSelectViewForNereids() { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); SqlCache sqlCache = (SqlCache) ca.getCache(); String cacheKey = sqlCache.getSqlWithViewStmt(); - Assert.assertEquals(cacheKey, "select origin.eventdate as eventdate, origin.userid as userid\n" + Assertions.assertEquals(cacheKey, "select origin.eventdate as eventdate, origin.userid as userid\n" + "from (\n" + " select view2.eventdate as eventdate, view2.userid as userid \n" + " from testDb.view2 view2 \n" + " where view2.eventdate >=\"2020-01-12\" and view2.eventdate <= \"2020-01-14\"\n" + ") origin|SELECT `eventdate` AS `eventdate`, `userid` AS `userid` FROM `testDb`.`appevent`"); - Assert.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); + Assertions.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); } @Test @@ -640,15 +640,15 @@ public void testSqlCacheKeyWithNestedViewForNereids() { List scanNodes = Lists.newArrayList(createEventScanNode(selectedPartitionIds)); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(1579053661000L); // 2020-1-15 10:01:01 - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); SqlCache sqlCache = (SqlCache) ca.getCache(); String cacheKey = sqlCache.getSqlWithViewStmt(); - Assert.assertEquals(cacheKey, "SELECT * from testDb.view4|SELECT `eventdate` AS `eventdate`, " + Assertions.assertEquals(cacheKey, "SELECT * from testDb.view4|SELECT `eventdate` AS `eventdate`, " + "count(`userid`) AS `__count_1` FROM `testDb`.`view2` WHERE ((`eventdate` >= '2020-01-12') " + "AND (`eventdate` <= '2020-01-14')) GROUP BY `eventdate`|SELECT `eventdate` AS `eventdate`, " + "`userid` AS `userid` FROM `testDb`.`appevent`"); - Assert.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); + Assertions.assertEquals(selectedPartitionIds.size(), sqlCache.getSumOfPartitionNum()); } @Test @@ -669,7 +669,7 @@ public void testCacheLocalViewMultiOperand() { List scanNodes = Lists.newArrayList(scanNode, scanNode, scanNode); CacheAnalyzer ca = new CacheAnalyzer(context, parseStmt, scanNodes); ca.checkCacheModeForNereids(0); - Assert.assertEquals(ca.getCacheMode(), CacheMode.Sql); - Assert.assertEquals(selectedPartitionIds.size() * 3, ((SqlCache) ca.getCache()).getSumOfPartitionNum()); + Assertions.assertEquals(ca.getCacheMode(), CacheMode.Sql); + Assertions.assertEquals(selectedPartitionIds.size() * 3, ((SqlCache) ca.getCache()).getSumOfPartitionNum()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/PointQueryExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/PointQueryExecutorTest.java index aea5a113fc2059..fcf3bc20c6e220 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/PointQueryExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/PointQueryExecutorTest.java @@ -19,8 +19,8 @@ import org.apache.doris.planner.OlapScanNode; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class PointQueryExecutorTest { @@ -29,9 +29,9 @@ public void testCandidateBackendsShuffleDependsOnQuerySelectionOrder() { OlapScanNode scanNode = Mockito.mock(OlapScanNode.class); Mockito.when(scanNode.isScanBackendOrderBySelection()).thenReturn(false); - Assert.assertTrue(PointQueryExecutor.shouldShuffleCandidateBackends(scanNode)); + Assertions.assertTrue(PointQueryExecutor.shouldShuffleCandidateBackends(scanNode)); Mockito.when(scanNode.isScanBackendOrderBySelection()).thenReturn(true); - Assert.assertFalse(PointQueryExecutor.shouldShuffleCandidateBackends(scanNode)); + Assertions.assertFalse(PointQueryExecutor.shouldShuffleCandidateBackends(scanNode)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ProxyProtocolHandlerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ProxyProtocolHandlerTest.java index 533c5ad9b46ae0..42e44c218bf50e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ProxyProtocolHandlerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ProxyProtocolHandlerTest.java @@ -21,8 +21,8 @@ import org.apache.doris.mysql.ProxyProtocolHandler; import org.apache.doris.mysql.ProxyProtocolHandler.ProtocolType; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.ByteBuffer; @@ -87,32 +87,40 @@ public void handleV1ProtocolWithUnknown() throws IOException { Assertions.assertEquals(ProtocolType.PROTOCOL_WITHOUT_IP, result.pType); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithInvalidProtocol() throws IOException { - byte[] data = "PROXY TCP7 xxx\r\n".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "PROXY TCP7 xxx\r\n".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithInvalidData() throws IOException { - byte[] data = "INVALID DATA".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "INVALID DATA".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithIncompleteData() throws IOException { - byte[] data = "PROXY TCP4 192.168.0.1 192.168.0.2 12345".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "PROXY TCP4 192.168.0.1 192.168.0.2 12345".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithExtraData() throws IOException { - byte[] data = "PROXY TCP4 192.168.0.1 192.168.0.2 12345 54321 EXTRA DATA\r\n".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "PROXY TCP4 192.168.0.1 192.168.0.2 12345 54321 EXTRA DATA\r\n".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } @Test @@ -137,24 +145,30 @@ public void handleNotProxyProtocol() throws IOException { Assertions.assertEquals(ProtocolType.NOT_PROXY_PROTOCOL, result.pType); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithInvalidIPv6Data() throws IOException { - byte[] data = "PROXY TCP6 2001:db8:0:1:1:1:1:1 2001:db8:0:1:1:1:1:2 12345 EXTRA DATA\r\n".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "PROXY TCP6 2001:db8:0:1:1:1:1:1 2001:db8:0:1:1:1:1:2 12345 EXTRA DATA\r\n".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } - @Test(expected = IOException.class) + @Test public void handleV1ProtocolWithIncompleteIPv6Data() throws IOException { - byte[] data = "PROXY TCP6 2001:db8:0:1:1:1:1:1 2001:db8:0:1:1:1:1:2 12345".getBytes(); - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = "PROXY TCP6 2001:db8:0:1:1:1:1:1 2001:db8:0:1:1:1:1:2 12345".getBytes(); + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } - @Test(expected = IOException.class) + @Test public void handleV2Protocol() throws IOException { - byte[] data = new byte[] {0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A}; - testChannel = new TestChannel(data); - ProxyProtocolHandler.handle(testChannel); + Assertions.assertThrows(IOException.class, () -> { + byte[] data = new byte[] {0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A}; + testChannel = new TestChannel(data); + ProxyProtocolHandler.handle(testChannel); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/QeProcessorImplTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/QeProcessorImplTest.java index b303be2fd8b965..2a7aa4de5d9c37 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/QeProcessorImplTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/QeProcessorImplTest.java @@ -26,10 +26,10 @@ import org.apache.doris.thrift.TQueryOptions; import org.apache.doris.thrift.TUniqueId; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Field; @@ -42,14 +42,14 @@ public class QeProcessorImplTest { private boolean originalMetricInit; private AutoMappedMetric originalQueryInstanceMetric; - @Before + @BeforeEach public void setUp() throws Exception { clearQeProcessorState(); originalMetricInit = MetricRepo.isInit; originalQueryInstanceMetric = MetricRepo.USER_COUNTER_QUERY_INSTANCE_BEGIN; } - @After + @AfterEach public void tearDown() throws Exception { MetricRepo.isInit = originalMetricInit; MetricRepo.USER_COUNTER_QUERY_INSTANCE_BEGIN = originalQueryInstanceMetric; @@ -67,8 +67,8 @@ public void testRegisterInstancesSkipsMetricBeforeMetricRepoInit() throws Except QE_PROCESSOR.registerInstances(queryId, 3); - Assert.assertEquals(Integer.valueOf(3), QE_PROCESSOR.getInstancesNumPerUser().get(user)); - Assert.assertEquals(Integer.valueOf(3), getQueryToInstancesNum().get(queryId)); + Assertions.assertEquals(Integer.valueOf(3), QE_PROCESSOR.getInstancesNumPerUser().get(user)); + Assertions.assertEquals(Integer.valueOf(3), getQueryToInstancesNum().get(queryId)); } @Test @@ -83,9 +83,9 @@ public void testRegisterInstancesUpdatesMetricAfterMetricRepoInit() throws Excep QE_PROCESSOR.registerInstances(queryId, 2); - Assert.assertEquals(Integer.valueOf(2), QE_PROCESSOR.getInstancesNumPerUser().get(user)); - Assert.assertEquals(Integer.valueOf(2), getQueryToInstancesNum().get(queryId)); - Assert.assertEquals(Long.valueOf(2L), + Assertions.assertEquals(Integer.valueOf(2), QE_PROCESSOR.getInstancesNumPerUser().get(user)); + Assertions.assertEquals(Integer.valueOf(2), getQueryToInstancesNum().get(queryId)); + Assertions.assertEquals(Long.valueOf(2L), MetricRepo.USER_COUNTER_QUERY_INSTANCE_BEGIN.getOrAdd(user).getValue()); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/QueryFinishCallbackRegistryTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/QueryFinishCallbackRegistryTest.java index df9ede51dcbc95..2b4c1f00bfb443 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/QueryFinishCallbackRegistryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/QueryFinishCallbackRegistryTest.java @@ -18,8 +18,8 @@ package org.apache.doris.qe; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -36,7 +36,7 @@ public void testRunAndClearRunsRegisteredCallback() { registry.runAndClear("q1"); - Assert.assertEquals(1, runs.get()); + Assertions.assertEquals(1, runs.get()); } // The generic query-cleanup path drains this registry for every query, @@ -60,7 +60,7 @@ public void testMultipleCallbacksRunInRegistrationOrder() { registry.runAndClear("q1"); - Assert.assertEquals(Lists.newArrayList(1, 2, 3), order); + Assertions.assertEquals(Lists.newArrayList(1, 2, 3), order); } // The early lock-release path can drain a query before its final drain at @@ -74,7 +74,7 @@ public void testRunAndClearIsIdempotent() { registry.runAndClear("q1"); registry.runAndClear("q1"); - Assert.assertEquals(1, runs.get()); + Assertions.assertEquals(1, runs.get()); } // One connector's failing cleanup must not block another's, nor break the @@ -90,7 +90,7 @@ public void testFailingCallbackIsIsolated() { registry.runAndClear("q1"); - Assert.assertEquals(1, runs.get()); + Assertions.assertEquals(1, runs.get()); } // Cleanup is scoped to the finishing query: draining one query must not run @@ -105,10 +105,10 @@ public void testCallbacksAreScopedPerQuery() { registry.runAndClear("q1"); - Assert.assertEquals(1, q1Runs.get()); - Assert.assertEquals(0, q2Runs.get()); + Assertions.assertEquals(1, q1Runs.get()); + Assertions.assertEquals(0, q2Runs.get()); registry.runAndClear("q2"); - Assert.assertEquals(1, q2Runs.get()); + Assertions.assertEquals(1, q2Runs.get()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/QueryStateTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/QueryStateTest.java index 1f83c7c43c2a34..f6b9027e57804e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/QueryStateTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/QueryStateTest.java @@ -21,22 +21,22 @@ import org.apache.doris.mysql.MysqlErrPacket; import org.apache.doris.mysql.MysqlOkPacket; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class QueryStateTest { @Test public void testNormal() { QueryState state = new QueryState(); - Assert.assertTrue(state.toResponsePacket() instanceof MysqlOkPacket); + Assertions.assertTrue(state.toResponsePacket() instanceof MysqlOkPacket); state.setEof(); - Assert.assertTrue(state.toResponsePacket() instanceof MysqlEofPacket); + Assertions.assertTrue(state.toResponsePacket() instanceof MysqlEofPacket); state.setError("abc"); - Assert.assertTrue(state.toResponsePacket() instanceof MysqlErrPacket); - Assert.assertEquals("abc", state.getErrorMessage()); + Assertions.assertTrue(state.toResponsePacket() instanceof MysqlErrPacket); + Assertions.assertEquals("abc", state.getErrorMessage()); state.reset(); - Assert.assertTrue(state.toResponsePacket() instanceof MysqlOkPacket); + Assertions.assertTrue(state.toResponsePacket() instanceof MysqlOkPacket); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ResultReceiverConsumerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ResultReceiverConsumerTest.java index b85830da646b77..923c9fd8c36ee5 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ResultReceiverConsumerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ResultReceiverConsumerTest.java @@ -24,9 +24,8 @@ import com.google.common.collect.Lists; import com.google.common.util.concurrent.FutureCallback; import org.apache.thrift.TException; -import org.junit.Assert; -import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -42,7 +41,7 @@ public void testEmptyReceiversForRemoteResult() throws Exception { System.currentTimeMillis() + 3600); Status status = new Status(); - Assert.assertFalse(consumer.isEos()); + Assertions.assertFalse(consumer.isEos()); Assertions.assertThrows(UserException.class, () -> consumer.getNext(status)); } @@ -87,13 +86,13 @@ public void testEosHandling() throws Exception { for (int i = 0; i < 5; i++) { RowBatch batch = consumer.getNext(status); - Assert.assertFalse(consumer.isEos()); - Assert.assertFalse(batch.isEos()); + Assertions.assertFalse(consumer.isEos()); + Assertions.assertFalse(batch.isEos()); } RowBatch batch = consumer.getNext(status); - Assert.assertTrue(consumer.isEos()); - Assert.assertTrue(batch.isEos()); + Assertions.assertTrue(consumer.isEos()); + Assertions.assertTrue(batch.isEos()); } @Test @@ -125,7 +124,7 @@ public void testGetNextExceptionHandling() throws Exception { Mockito.when(receiver2.getNext(ArgumentMatchers.any(Status.class))).thenThrow(new TException("Network error")); RowBatch batch = consumer.getNext(status); - Assert.assertFalse(batch.isEos()); + Assertions.assertFalse(batch.isEos()); Assertions.assertThrows(TException.class, () -> consumer.getNext(status)); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/RuntimeFilterTypeHelperTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/RuntimeFilterTypeHelperTest.java index c4e3fb59c5b8cb..dde6bdb6d5778d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/RuntimeFilterTypeHelperTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/RuntimeFilterTypeHelperTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.DdlException; import org.apache.doris.thrift.TRuntimeFilterType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -31,113 +31,125 @@ public class RuntimeFilterTypeHelperTest { @Test public void testNormal() throws DdlException { String runtimeFilterType = ""; - Assert.assertEquals(new Long(0L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(0L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "IN"; - Assert.assertEquals(new Long(1L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(1L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "BLOOM_FILTER"; - Assert.assertEquals(new Long(2L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(2L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "MIN_MAX"; - Assert.assertEquals(new Long(4L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(4L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "IN,MIN_MAX"; - Assert.assertEquals(new Long(5L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(5L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "MIN_MAX, BLOOM_FILTER"; - Assert.assertEquals(new Long(6L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(6L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "IN_OR_BLOOM_FILTER"; - Assert.assertEquals(new Long(8L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(8L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); runtimeFilterType = "MIN_MAX,IN_OR_BLOOM_FILTER"; - Assert.assertEquals(new Long(12L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); + Assertions.assertEquals(new Long(12L), RuntimeFilterTypeHelper.encode(runtimeFilterType)); long runtimeFilterTypeValue = 0L; - Assert.assertEquals("", RuntimeFilterTypeHelper.decode(runtimeFilterTypeValue)); + Assertions.assertEquals("", RuntimeFilterTypeHelper.decode(runtimeFilterTypeValue)); runtimeFilterTypeValue = 1L; - Assert.assertEquals("IN", RuntimeFilterTypeHelper.decode(runtimeFilterTypeValue)); + Assertions.assertEquals("IN", RuntimeFilterTypeHelper.decode(runtimeFilterTypeValue)); } - @Test(expected = DdlException.class) + @Test public void testInvalidSqlMode() throws DdlException { - RuntimeFilterTypeHelper.encode("BLOOM,IN"); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.encode("BLOOM,IN"); + Assertions.fail("No exception throws"); + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidDecode() throws DdlException { - RuntimeFilterTypeHelper.decode(32L); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.decode(32L); + Assertions.fail("No exception throws"); + }); } @Test public void testDeprecatedBitmapNumericCompatibility() throws DdlException { - Assert.assertEquals(Long.valueOf(0L), RuntimeFilterTypeHelper.encode("16")); - Assert.assertEquals(Long.valueOf(8L), RuntimeFilterTypeHelper.encode("24")); - Assert.assertEquals(Long.valueOf(12L), RuntimeFilterTypeHelper.encode("28")); + Assertions.assertEquals(Long.valueOf(0L), RuntimeFilterTypeHelper.encode("16")); + Assertions.assertEquals(Long.valueOf(8L), RuntimeFilterTypeHelper.encode("24")); + Assertions.assertEquals(Long.valueOf(12L), RuntimeFilterTypeHelper.encode("28")); - Assert.assertEquals("", RuntimeFilterTypeHelper.decode(16L)); - Assert.assertEquals("IN_OR_BLOOM_FILTER", RuntimeFilterTypeHelper.decode(24L)); - Assert.assertEquals("IN_OR_BLOOM_FILTER,MIN_MAX", RuntimeFilterTypeHelper.decode(28L)); + Assertions.assertEquals("", RuntimeFilterTypeHelper.decode(16L)); + Assertions.assertEquals("IN_OR_BLOOM_FILTER", RuntimeFilterTypeHelper.decode(24L)); + Assertions.assertEquals("IN_OR_BLOOM_FILTER,MIN_MAX", RuntimeFilterTypeHelper.decode(28L)); } @Test public void testDeprecatedBitmapIsNotAllowedForPlanning() { - Assert.assertFalse(RuntimeFilterTypeHelper.getSupportedRuntimeFilterTypes() + Assertions.assertFalse(RuntimeFilterTypeHelper.getSupportedRuntimeFilterTypes() .contains(TRuntimeFilterType.BITMAP)); - Assert.assertFalse(RuntimeFilterTypeHelper.allowedRuntimeFilterType(24L, TRuntimeFilterType.BITMAP)); - Assert.assertTrue(RuntimeFilterTypeHelper.allowedRuntimeFilterType(24L, TRuntimeFilterType.IN_OR_BLOOM)); + Assertions.assertFalse(RuntimeFilterTypeHelper.allowedRuntimeFilterType(24L, TRuntimeFilterType.BITMAP)); + Assertions.assertTrue(RuntimeFilterTypeHelper.allowedRuntimeFilterType(24L, TRuntimeFilterType.IN_OR_BLOOM)); } @Test public void testDeprecatedBitmapSessionRestoreCompatibility() throws Exception { SessionVariable restored = new SessionVariable(); restored.readFromJson("{\"runtime_filter_type\":24}"); - Assert.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue(), restored.getRuntimeFilterType()); - Assert.assertFalse(restored.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); + Assertions.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue(), restored.getRuntimeFilterType()); + Assertions.assertFalse(restored.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); Map sessionVarMap = new HashMap<>(); sessionVarMap.put(SessionVariable.RUNTIME_FILTER_TYPE, "28"); restored.readFromMap(sessionVarMap); - Assert.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue() | TRuntimeFilterType.MIN_MAX.getValue(), + Assertions.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue() | TRuntimeFilterType.MIN_MAX.getValue(), restored.getRuntimeFilterType()); - Assert.assertFalse(restored.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); + Assertions.assertFalse(restored.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); SessionVariable forwarded = new SessionVariable(); Map forwardVariables = new HashMap<>(); forwardVariables.put(SessionVariable.RUNTIME_FILTER_TYPE, "24"); forwarded.setForwardedSessionVariables(forwardVariables); - Assert.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue(), forwarded.getRuntimeFilterType()); - Assert.assertFalse(forwarded.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); + Assertions.assertEquals(TRuntimeFilterType.IN_OR_BLOOM.getValue(), forwarded.getRuntimeFilterType()); + Assertions.assertFalse(forwarded.allowedRuntimeFilterType(TRuntimeFilterType.BITMAP)); restored.setRuntimeFilterType(TRuntimeFilterType.BITMAP.getValue()); - Assert.assertEquals(0, restored.getRuntimeFilterType()); + Assertions.assertEquals(0, restored.getRuntimeFilterType()); } - @Test(expected = DdlException.class) + @Test public void testInvalidSqlMode2() throws DdlException { - RuntimeFilterTypeHelper.encode("BLOOM_FILTER,IN"); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.encode("BLOOM_FILTER,IN"); + Assertions.fail("No exception throws"); + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidSqlMode3() throws DdlException { - RuntimeFilterTypeHelper.encode("BLOOM_FILTER,IN_OR_BLOOM_FILTER"); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.encode("BLOOM_FILTER,IN_OR_BLOOM_FILTER"); + Assertions.fail("No exception throws"); + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidSqlMode4() throws DdlException { - RuntimeFilterTypeHelper.encode("IN,IN_OR_BLOOM_FILTER"); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.encode("IN,IN_OR_BLOOM_FILTER"); + Assertions.fail("No exception throws"); + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidBitmapSqlMode() throws DdlException { - RuntimeFilterTypeHelper.encode("BITMAP_FILTER"); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + RuntimeFilterTypeHelper.encode("BITMAP_FILTER"); + Assertions.fail("No exception throws"); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowExecutorTest.java index 07abc8b159e245..1e286283cef8ac 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowExecutorTest.java @@ -50,14 +50,11 @@ import org.apache.doris.thrift.TStorageType; import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -71,10 +68,7 @@ public class ShowExecutorTest { private MockedStatic mockedEnvStatic; private MockedStatic mockedConnectContextStatic; - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() throws Exception { ctx = new ConnectContext(); ctx.setCommand(MysqlCommand.COM_SLEEP); @@ -150,7 +144,7 @@ public void setUp() throws Exception { mockedConnectContextStatic.when(ConnectContext::get).thenReturn(ctx); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -170,8 +164,8 @@ public void testShowDb() throws AnalysisException { throw new RuntimeException(e); } - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("testDb", resultSet.getString(0)); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("testDb", resultSet.getString(0)); } @Test @@ -184,7 +178,7 @@ public void testShowDbPattern() throws AnalysisException { throw new RuntimeException(e); } - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } @Test @@ -197,8 +191,8 @@ public void testShowDbFromCatalog() throws AnalysisException { throw new RuntimeException(e); } - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("testDb", resultSet.getString(0)); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("testDb", resultSet.getString(0)); } @Test @@ -214,9 +208,9 @@ public void testShowTable() throws Exception { null, false, PlanType.SHOW_TABLES); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("testTbl", resultSet.getString(0)); - Assert.assertFalse(resultSet.next()); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("testTbl", resultSet.getString(0)); + Assertions.assertFalse(resultSet.next()); } @Test @@ -225,7 +219,7 @@ public void testShowViews() throws Exception { null, false, PlanType.SHOW_VIEWS); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } @Test @@ -234,7 +228,7 @@ public void testShowStream() throws Exception { null, false, PlanType.SHOW_STREAMS); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } @Test @@ -243,9 +237,9 @@ public void testShowTableFromCatalog() throws Exception { "internal", false, PlanType.SHOW_TABLES); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("testTbl", resultSet.getString(0)); - Assert.assertFalse(resultSet.next()); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("testTbl", resultSet.getString(0)); + Assertions.assertFalse(resultSet.next()); } @Test @@ -253,9 +247,11 @@ public void testShowTableFromUnknownDatabase() throws Exception { ShowTableCommand command = new ShowTableCommand("emptyDb", null, false, PlanType.SHOW_TABLES); - expectedEx.expect(Exception.class); - expectedEx.expectMessage("Unknown database 'emptyDb'"); - command.doRun(ctx, new StmtExecutor(ctx, "")); + Exception e = Assertions.assertThrows(Exception.class, () -> { + command.doRun(ctx, new StmtExecutor(ctx, "")); + }); + Assertions.assertTrue(e.getMessage().contains("Unknown database 'emptyDb'"), + "unexpected message: " + e.getMessage()); } @Test @@ -264,10 +260,10 @@ public void testShowTablePattern() throws Exception { null, false, "empty%", null, PlanType.SHOW_TABLES); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } - @Ignore + @Disabled @Test public void testDescribe() { SystemInfoService clusterInfo = AccessTestUtil.fetchSystemInfoService(); @@ -281,10 +277,10 @@ public void testDescribe() { ShowResultSet resultSet = null; try { resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } catch (Exception e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } @@ -294,10 +290,10 @@ public void testShowTableVerbose() throws Exception { null, true, PlanType.SHOW_TABLES); ShowResultSet resultSet = command.doRun(ctx, new StmtExecutor(ctx, "")); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("testTbl", resultSet.getString(0)); - Assert.assertEquals("BASE TABLE", resultSet.getString(1)); - Assert.assertFalse(resultSet.next()); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("testTbl", resultSet.getString(0)); + Assertions.assertEquals("BASE TABLE", resultSet.getString(1)); + Assertions.assertFalse(resultSet.next()); } @Test @@ -313,7 +309,7 @@ public void testShowView() throws UserException { throw new RuntimeException(e); } - Assert.assertFalse(resultSet.next()); + Assertions.assertFalse(resultSet.next()); } @Test @@ -321,8 +317,8 @@ public void testShowEngine() throws Exception { ShowStorageEnginesCommand command = new ShowStorageEnginesCommand(); ShowResultSet resultSet = command.doRun(ctx, null); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("Olap engine", resultSet.getString(0)); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("Olap engine", resultSet.getString(0)); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetMetaDataTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetMetaDataTest.java index b743ecf777c51f..4f7200e7f47e80 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetMetaDataTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetMetaDataTest.java @@ -21,29 +21,31 @@ import org.apache.doris.catalog.PrimitiveType; import org.apache.doris.catalog.ScalarType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ShowResultSetMetaDataTest { @Test public void testNormal() { ShowResultSetMetaData metaData = ShowResultSetMetaData.builder().build(); - Assert.assertEquals(0, metaData.getColumnCount()); + Assertions.assertEquals(0, metaData.getColumnCount()); metaData = ShowResultSetMetaData.builder() .addColumn(new Column("col1", ScalarType.createType(PrimitiveType.INT))) .addColumn(new Column("col2", ScalarType.createType(PrimitiveType.INT))) .build(); - Assert.assertEquals(2, metaData.getColumnCount()); - Assert.assertEquals("col1", metaData.getColumn(0).getName()); - Assert.assertEquals("col2", metaData.getColumn(1).getName()); + Assertions.assertEquals(2, metaData.getColumnCount()); + Assertions.assertEquals("col1", metaData.getColumn(0).getName()); + Assertions.assertEquals("col2", metaData.getColumn(1).getName()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testOutBound() { - ShowResultSetMetaData metaData = ShowResultSetMetaData.builder().build(); - metaData.getColumn(1); - Assert.fail("No exception throws."); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + ShowResultSetMetaData metaData = ShowResultSetMetaData.builder().build(); + metaData.getColumn(1); + Assertions.fail("No exception throws."); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetTest.java index c83abc2538e82c..27af88baf036b9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/ShowResultSetTest.java @@ -18,8 +18,8 @@ package org.apache.doris.qe; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -34,35 +34,39 @@ public void testNormal() { rows.add(Lists.newArrayList("col1-0", "col2-0")); rows.add(Lists.newArrayList("123", "456")); ShowResultSet resultSet = new ShowResultSet(metaData, rows); - Assert.assertEquals(rows, resultSet.getResultRows()); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals("col1-0", resultSet.getString(0)); - Assert.assertEquals("col2-0", resultSet.getString(1)); - Assert.assertTrue(resultSet.next()); - Assert.assertEquals(123, resultSet.getInt(0)); - Assert.assertEquals(456, resultSet.getLong(1)); - Assert.assertFalse(resultSet.next()); + Assertions.assertEquals(rows, resultSet.getResultRows()); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals("col1-0", resultSet.getString(0)); + Assertions.assertEquals("col2-0", resultSet.getString(1)); + Assertions.assertTrue(resultSet.next()); + Assertions.assertEquals(123, resultSet.getInt(0)); + Assertions.assertEquals(456, resultSet.getLong(1)); + Assertions.assertFalse(resultSet.next()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testOutOfBound() { - List> rows = Lists.newArrayList(); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { + List> rows = Lists.newArrayList(); - rows.add(Lists.newArrayList("col1-0", "col2-0")); - rows.add(Lists.newArrayList("123", "456")); - ShowResultSet resultSet = new ShowResultSet(metaData, rows); - resultSet.getString(0); - Assert.fail("No exception throws."); + rows.add(Lists.newArrayList("col1-0", "col2-0")); + rows.add(Lists.newArrayList("123", "456")); + ShowResultSet resultSet = new ShowResultSet(metaData, rows); + resultSet.getString(0); + Assertions.fail("No exception throws."); + }); } - @Test(expected = NumberFormatException.class) + @Test public void testBadNumber() { - List> rows = Lists.newArrayList(); + Assertions.assertThrows(NumberFormatException.class, () -> { + List> rows = Lists.newArrayList(); - rows.add(Lists.newArrayList(" 123", "456")); - ShowResultSet resultSet = new ShowResultSet(metaData, rows); - resultSet.next(); - resultSet.getInt(0); - Assert.fail("No exception throws."); + rows.add(Lists.newArrayList(" 123", "456")); + ShowResultSet resultSet = new ShowResultSet(metaData, rows); + resultSet.next(); + resultSet.getInt(0); + Assertions.fail("No exception throws."); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/SimpleSchedulerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/SimpleSchedulerTest.java index f33508ca21d091..d848052fd9b656 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/SimpleSchedulerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/SimpleSchedulerTest.java @@ -30,7 +30,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -96,13 +96,13 @@ public void run() { long start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { TNetworkAddress address = SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref); - Assert.assertNotNull(address); + Assertions.assertNotNull(address); if (!foundCandidate && address.getHostname().equals(be2.getHost())) { foundCandidate = true; } } System.out.println("cost: " + (System.currentTimeMillis() - start)); - Assert.assertTrue(foundCandidate); + Assertions.assertTrue(foundCandidate); } catch (Exception e) { throw new RuntimeException(e); } @@ -117,11 +117,11 @@ public void run() { Set resBackends = Sets.newHashSet(); for (int i = 0; i < 1000; i++) { TNetworkAddress address = SimpleScheduler.getHost(backends, ref); - Assert.assertNotNull(address); + Assertions.assertNotNull(address); resBackends.add(address.hostname); } System.out.println("cost: " + (System.currentTimeMillis() - start)); - Assert.assertTrue(resBackends.size() >= 4); + Assertions.assertTrue(resBackends.size() >= 4); } catch (Exception e) { throw new RuntimeException(e); } @@ -150,11 +150,11 @@ public void run() { t1.join(); t2.join(); - Assert.assertFalse(SimpleScheduler.isAvailable(be1)); + Assertions.assertFalse(SimpleScheduler.isAvailable(be1)); be1.setAlive(true); // Sleep 5s so that UpdateBlacklistThread will remove be1 from blacklist Thread.sleep(1000 * 5L); - Assert.assertTrue(SimpleScheduler.isAvailable(be1)); + Assertions.assertTrue(SimpleScheduler.isAvailable(be1)); } @Test @@ -173,7 +173,7 @@ public void testGetHostAbnormal() throws UserException, InterruptedException { try { SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { System.out.println(e.getMessage()); } @@ -211,7 +211,7 @@ public void testGetHostAbnormal() throws UserException, InterruptedException { try { SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { System.out.println(e.getMessage()); } @@ -222,6 +222,6 @@ public void testGetHostAbnormal() throws UserException, InterruptedException { be4.setAlive(true); be5.setAlive(true); Thread.sleep((Config.heartbeat_interval_second + 5) * 1000); - Assert.assertNotNull(SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref)); + Assertions.assertNotNull(SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/SqlModeHelperTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/SqlModeHelperTest.java index 96b9713844772f..229a4096a50193 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/SqlModeHelperTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/SqlModeHelperTest.java @@ -19,40 +19,44 @@ import org.apache.doris.common.DdlException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SqlModeHelperTest { @Test public void testNormal() throws DdlException { String sqlMode = "PIPES_AS_CONCAT"; - Assert.assertEquals(new Long(2L), SqlModeHelper.encode(sqlMode)); + Assertions.assertEquals(new Long(2L), SqlModeHelper.encode(sqlMode)); sqlMode = ""; - Assert.assertEquals(new Long(0L), SqlModeHelper.encode(sqlMode)); + Assertions.assertEquals(new Long(0L), SqlModeHelper.encode(sqlMode)); sqlMode = "0,1, PIPES_AS_CONCAT"; - Assert.assertEquals(new Long(3L), SqlModeHelper.encode(sqlMode)); + Assertions.assertEquals(new Long(3L), SqlModeHelper.encode(sqlMode)); long sqlModeValue = 2L; - Assert.assertEquals("PIPES_AS_CONCAT", SqlModeHelper.decode(sqlModeValue)); + Assertions.assertEquals("PIPES_AS_CONCAT", SqlModeHelper.decode(sqlModeValue)); sqlModeValue = 0L; - Assert.assertEquals("", SqlModeHelper.decode(sqlModeValue)); + Assertions.assertEquals("", SqlModeHelper.decode(sqlModeValue)); } - @Test(expected = DdlException.class) + @Test public void testInvalidSqlMode() throws DdlException { - String sqlMode = "PIPES_AS_CONCAT, WRONG_MODE"; - SqlModeHelper.encode(sqlMode); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + String sqlMode = "PIPES_AS_CONCAT, WRONG_MODE"; + SqlModeHelper.encode(sqlMode); + Assertions.fail("No exception throws"); + }); } - @Test(expected = DdlException.class) + @Test public void testInvalidDecode() throws DdlException { - long sqlMode = SqlModeHelper.MODE_LAST; - SqlModeHelper.decode(sqlMode); - Assert.fail("No exception throws"); + Assertions.assertThrows(DdlException.class, () -> { + long sqlMode = SqlModeHelper.MODE_LAST; + SqlModeHelper.decode(sqlMode); + Assertions.fail("No exception throws"); + }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorInternalQueryTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorInternalQueryTest.java index ee2b87d1abf6f6..e592b465aa821d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorInternalQueryTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorInternalQueryTest.java @@ -26,8 +26,8 @@ import org.apache.doris.resource.workloadschedpolicy.WorkloadRuntimeStatusMgr; import org.apache.doris.thrift.TQueryOptions; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; import org.mockito.Mockito; @@ -48,7 +48,7 @@ public void testSetSqlHash() { // do nothing } } - Assert.assertEquals("a8ec30e5ad0820f8c5bd16a82a4491ca", executor.getContext().getSqlHash()); + Assertions.assertEquals("a8ec30e5ad0820f8c5bd16a82a4491ca", executor.getContext().getSqlHash()); } @Test @@ -64,17 +64,14 @@ public void testExecuteInternalQuerySetsErrorStateOnFailure() { Mockito.doThrow(new RuntimeException("mock plan failure")) .when(mock).plan(Mockito.any(StatementBase.class), Mockito.any(TQueryOptions.class)); })) { - Assert.assertThrows(RuntimeException.class, executor::executeInternalQuery); + Assertions.assertThrows(RuntimeException.class, executor::executeInternalQuery); } - Assert.assertEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType()); - Assert.assertEquals(ErrorCode.ERR_INTERNAL_ERROR, ctx.getState().getErrorCode()); - Assert.assertNotNull(ctx.getState().getErrorMessage()); - Assert.assertTrue("error message should mention root cause, got: " + ctx.getState().getErrorMessage(), - ctx.getState().getErrorMessage().contains("mock plan failure")); - Assert.assertTrue("internal query should be flagged as internal in audit state", - ctx.getState().isInternal()); - Assert.assertTrue("internal query should be flagged as query in audit state", - ctx.getState().isQuery()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, ctx.getState().getStateType()); + Assertions.assertEquals(ErrorCode.ERR_INTERNAL_ERROR, ctx.getState().getErrorCode()); + Assertions.assertNotNull(ctx.getState().getErrorMessage()); + Assertions.assertTrue(ctx.getState().getErrorMessage().contains("mock plan failure"), "error message should mention root cause, got: " + ctx.getState().getErrorMessage()); + Assertions.assertTrue(ctx.getState().isInternal(), "internal query should be flagged as internal in audit state"); + Assertions.assertTrue(ctx.getState().isQuery(), "internal query should be flagged as query in audit state"); } @Test @@ -94,7 +91,7 @@ public void testExecuteInternalQuerySubmitsErrorAuditEventOnFailure() { Mockito.doThrow(new RuntimeException("mock plan failure")) .when(mock).plan(Mockito.any(StatementBase.class), Mockito.any(TQueryOptions.class)); })) { - Assert.assertThrows(RuntimeException.class, executor::executeInternalQuery); + Assertions.assertThrows(RuntimeException.class, executor::executeInternalQuery); } Mockito.verify(workloadRuntimeStatusMgr).submitFinishQueryToAudit(auditEventCaptor.capture()); @@ -103,16 +100,15 @@ public void testExecuteInternalQuerySubmitsErrorAuditEventOnFailure() { } AuditEvent auditEvent = auditEventCaptor.getValue(); - Assert.assertEquals(AuditEvent.EventType.AFTER_QUERY, auditEvent.type); - Assert.assertEquals("ERR", auditEvent.state); - Assert.assertEquals(ErrorCode.ERR_INTERNAL_ERROR.getCode(), auditEvent.errorCode); - Assert.assertNotNull(auditEvent.errorMessage); - Assert.assertTrue("error message should mention root cause, got: " + auditEvent.errorMessage, - auditEvent.errorMessage.contains("mock plan failure")); - Assert.assertTrue("audit event should be marked as internal", auditEvent.isInternal); - Assert.assertTrue("audit event should be marked as query", auditEvent.isQuery); - Assert.assertTrue("audit event should be marked as nereids", auditEvent.isNereids); - Assert.assertEquals("select * from table1", auditEvent.stmt); - Assert.assertEquals("a8ec30e5ad0820f8c5bd16a82a4491ca", auditEvent.sqlHash); + Assertions.assertEquals(AuditEvent.EventType.AFTER_QUERY, auditEvent.type); + Assertions.assertEquals("ERR", auditEvent.state); + Assertions.assertEquals(ErrorCode.ERR_INTERNAL_ERROR.getCode(), auditEvent.errorCode); + Assertions.assertNotNull(auditEvent.errorMessage); + Assertions.assertTrue(auditEvent.errorMessage.contains("mock plan failure"), "error message should mention root cause, got: " + auditEvent.errorMessage); + Assertions.assertTrue(auditEvent.isInternal, "audit event should be marked as internal"); + Assertions.assertTrue(auditEvent.isQuery, "audit event should be marked as query"); + Assertions.assertTrue(auditEvent.isNereids, "audit event should be marked as nereids"); + Assertions.assertEquals("select * from table1", auditEvent.stmt); + Assertions.assertEquals("a8ec30e5ad0820f8c5bd16a82a4491ca", auditEvent.sqlHash); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java index eb70a206b3a6d4..756fb451589104 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java @@ -37,7 +37,6 @@ import org.apache.doris.utframe.TestWithFeService; import com.google.common.collect.Lists; -import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -75,7 +74,7 @@ public void testShow() throws Exception { public void testShowNull() throws Exception { StmtExecutor stmtExecutor = new StmtExecutor(connectContext, ""); stmtExecutor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } // Arrow Flight SQL keeps a query's coordinator alive across GetFlightInfo -> DoGet (see #62259); @@ -97,47 +96,47 @@ public void testFinalizeArrowFlightQueryUnregistersQueryEvenIfCoordCloseThrows() // Simulate the in-flight query whose results DoGet is still pulling. QeProcessorImpl.INSTANCE.registerQuery(queryId, new QeProcessorImpl.QueryInfo(coord)); - Assert.assertNotNull(QeProcessorImpl.INSTANCE.getCoordinator(queryId)); + Assertions.assertNotNull(QeProcessorImpl.INSTANCE.getCoordinator(queryId)); try { stmtExecutor.finalizeArrowFlightQuery(); - Assert.fail("expected coord.close() failure to propagate after the query is unregistered"); + Assertions.fail("expected coord.close() failure to propagate after the query is unregistered"); } catch (RuntimeException e) { - Assert.assertEquals("coord close failed", e.getMessage()); + Assertions.assertEquals("coord close failed", e.getMessage()); } // The coordinator close was attempted (releases SplitSource + query queue slot) ... Mockito.verify(coord).close(); // ... and despite it failing, the query registration was still released (no leak). - Assert.assertNull(QeProcessorImpl.INSTANCE.getCoordinator(queryId)); + Assertions.assertNull(QeProcessorImpl.INSTANCE.getCoordinator(queryId)); } @Test public void testKill() throws Exception { StmtExecutor stmtExecutor = new StmtExecutor(connectContext, ""); stmtExecutor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } @Test public void testKillOtherFail() throws Exception { StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "kill 1000"); stmtExecutor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); } @Test public void testKillNoCtx() throws Exception { StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "kill 1"); stmtExecutor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); } @Test public void testSet() throws Exception { StmtExecutor stmtExecutor = new StmtExecutor(connectContext, ""); stmtExecutor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } @Test @@ -149,35 +148,35 @@ public void testDdlFail() throws Exception { + " + \" \\\"catalog\\\" = \\\"kafka\\\"\\n\"\n" + " + \");"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); } @Test public void testUse() throws Exception { StmtExecutor executor = new StmtExecutor(connectContext, "use testDb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } @Test public void testUseFail() throws Exception { StmtExecutor executor = new StmtExecutor(connectContext, "use nondb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); } @Test public void testUseWithCatalog() throws Exception { StmtExecutor executor = new StmtExecutor(connectContext, "use internal.testDb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } @Test public void testUseWithCatalogFail() throws Exception { StmtExecutor executor = new StmtExecutor(connectContext, "use internal.nondb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.ERR, connectContext.getState().getStateType()); } @Test @@ -196,7 +195,7 @@ public void testBlockSqlAst() throws Exception { } catch (Exception ignore) { // do nothing ignore.printStackTrace(); - Assert.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); + Assertions.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); } Config.block_sql_ast_names = "AlterStmt, CreateFileCommand"; @@ -208,7 +207,7 @@ public void testBlockSqlAst() throws Exception { executor.execute(); } catch (Exception ignore) { ignore.printStackTrace(); - Assert.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); + Assertions.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); } Config.block_sql_ast_names = "CreateFunctionStmt, CreateFileCommand"; @@ -223,18 +222,18 @@ public void testBlockSqlAst() throws Exception { executor.execute(); } catch (Exception ignore) { ignore.printStackTrace(); - Assert.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); + Assertions.assertTrue(ignore.getMessage().contains("SQL is blocked with AST name: CreateFileCommand")); } executor = new StmtExecutor(connectContext, "use testDb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); Config.block_sql_ast_names = ""; StmtExecutor.initBlockSqlAstNames(); executor = new StmtExecutor(connectContext, "use testDb"); executor.execute(); - Assert.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); + Assertions.assertEquals(QueryState.MysqlStateType.OK, connectContext.getState().getStateType()); } @Test diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/cache/CacheManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/cache/CacheManagerTest.java index 1289463797f82a..9c3053c59210d8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/cache/CacheManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/cache/CacheManagerTest.java @@ -33,9 +33,9 @@ import org.apache.doris.rpc.RpcException; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; @@ -43,7 +43,7 @@ public class CacheManagerTest { - @BeforeClass + @BeforeAll public static void setUpClass() { MetricRepo.init(); } @@ -76,11 +76,11 @@ public void testBuildCacheTableForOlapScanNodeBypassesCacheWhenPartitionDropped( // inconsistent, so building the cache table must fail and the cache is bypassed. // Assert on the controlled message (not just RuntimeException) so a regression to the // old bare NullPointerException path is caught rather than silently satisfying the test. - RuntimeException ex = Assert.assertThrows(RuntimeException.class, + RuntimeException ex = Assertions.assertThrows(RuntimeException.class, () -> analyzer.buildCacheTableForOlapScanNode(node)); - Assert.assertFalse(ex instanceof NullPointerException); - Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("Partition 2")); - Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("dropped")); + Assertions.assertFalse(ex instanceof NullPointerException); + Assertions.assertTrue(ex.getMessage().contains("Partition 2"), ex.getMessage()); + Assertions.assertTrue(ex.getMessage().contains("dropped"), ex.getMessage()); // partition3, ordered after the dropped partition2, must never be visited. Mockito.verify(olapTable, Mockito.never()).getPartition(3L); @@ -112,11 +112,11 @@ public void testBuildCacheTableForOlapScanNodeBypassesCacheWhenCloudBatchLookupN Mockito.doThrow(new NullPointerException("simulated cloud batch lookup NPE on dropped partition")) .when(olapTable).getVersionInBatchForCloudMode(Mockito.anyCollection()); - RuntimeException ex = Assert.assertThrows(RuntimeException.class, + RuntimeException ex = Assertions.assertThrows(RuntimeException.class, () -> analyzer.buildCacheTableForOlapScanNode(node)); - Assert.assertFalse(ex instanceof NullPointerException); - Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("Partition 2")); - Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("dropped")); + Assertions.assertFalse(ex instanceof NullPointerException); + Assertions.assertTrue(ex.getMessage().contains("Partition 2"), ex.getMessage()); + Assertions.assertTrue(ex.getMessage().contains("dropped"), ex.getMessage()); } @Test @@ -150,7 +150,7 @@ public void testCheckCacheModeForNereidsFallsBackToNoneWhenPartitionDropped() th analyzer.checkCacheModeForNereids(0); - Assert.assertEquals(CacheAnalyzer.CacheMode.None, analyzer.getCacheMode()); + Assertions.assertEquals(CacheAnalyzer.CacheMode.None, analyzer.getCacheMode()); } @Test @@ -186,18 +186,18 @@ public void testBuildCacheTableForOlapScanNodeWhenVersionBatchFailed() throws Ex .when(olapTable).getVersionInBatchForCloudMode(Mockito.anyCollection()); CacheAnalyzer.CacheTable cacheTable = analyzer.buildCacheTableForOlapScanNode(node); - Assert.assertEquals(2L, cacheTable.partitionNum); - Assert.assertSame(olapTable, cacheTable.table); - Assert.assertEquals(20L, cacheTable.latestPartitionId); - Assert.assertEquals(4000L, cacheTable.latestPartitionTime); - Assert.assertEquals(200L, cacheTable.latestPartitionVersion); + Assertions.assertEquals(2L, cacheTable.partitionNum); + Assertions.assertSame(olapTable, cacheTable.table); + Assertions.assertEquals(20L, cacheTable.latestPartitionId); + Assertions.assertEquals(4000L, cacheTable.latestPartitionTime); + Assertions.assertEquals(200L, cacheTable.latestPartitionVersion); List> scanTables = analyzer.getScanTables(); - Assert.assertEquals(1, scanTables.size()); + Assertions.assertEquals(1, scanTables.size()); Pair pair = scanTables.get(0); - Assert.assertSame(olapTable, pair.second); - Assert.assertEquals("internal.testDb.test_tbl2", pair.first.getFullTableName().toString()); - Assert.assertEquals(selectedPartitionIds, pair.first.getScanPartitions()); + Assertions.assertSame(olapTable, pair.second); + Assertions.assertEquals("internal.testDb.test_tbl2", pair.first.getFullTableName().toString()); + Assertions.assertEquals(selectedPartitionIds, pair.first.getScanPartitions()); } @Test @@ -232,18 +232,18 @@ public void testBuildCacheTableForOlapScanNodeWithOlderAndEqualVersionTime() thr Mockito.when(partition300.getCachedVisibleVersion()).thenReturn(3000L); CacheAnalyzer.CacheTable cacheTable = analyzer.buildCacheTableForOlapScanNode(node); - Assert.assertEquals(3L, cacheTable.partitionNum); - Assert.assertSame(olapTable, cacheTable.table); + Assertions.assertEquals(3L, cacheTable.partitionNum); + Assertions.assertSame(olapTable, cacheTable.table); // partition100 (5000L) is visited first, then partition300 (also 5000L) overrides because of >=. - Assert.assertEquals(300L, cacheTable.latestPartitionId); - Assert.assertEquals(5000L, cacheTable.latestPartitionTime); - Assert.assertEquals(3000L, cacheTable.latestPartitionVersion); + Assertions.assertEquals(300L, cacheTable.latestPartitionId); + Assertions.assertEquals(5000L, cacheTable.latestPartitionTime); + Assertions.assertEquals(3000L, cacheTable.latestPartitionVersion); List> scanTables = analyzer.getScanTables(); - Assert.assertEquals(1, scanTables.size()); + Assertions.assertEquals(1, scanTables.size()); Pair pair = scanTables.get(0); - Assert.assertSame(olapTable, pair.second); - Assert.assertEquals("internal.testDb.test_tbl3", pair.first.getFullTableName().toString()); - Assert.assertEquals(selectedPartitionIds, pair.first.getScanPartitions()); + Assertions.assertSame(olapTable, pair.second); + Assertions.assertEquals("internal.testDb.test_tbl3", pair.first.getFullTableName().toString()); + Assertions.assertEquals(selectedPartitionIds, pair.first.getScanPartitions()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/cache/PluginTableCacheAnalyzerTest.java b/fe/fe-core/src/test/java/org/apache/doris/qe/cache/PluginTableCacheAnalyzerTest.java index 97a02f347c9042..f1392d7a9cd36d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/qe/cache/PluginTableCacheAnalyzerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/qe/cache/PluginTableCacheAnalyzerTest.java @@ -29,7 +29,7 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.qe.SessionVariable; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -78,7 +78,7 @@ public void testRecognizePluginTableByCapability() { PluginDrivenMvccExternalTable table = Mockito.mock(PluginDrivenMvccExternalTable.class); PluginDrivenScanNode node = mockPluginScanNode(table, 3L); boolean recognized = Deencapsulation.invoke(analyzer, "isExternalCacheableScanNode", node); - Assert.assertTrue("a PluginDrivenMvccExternalTable scan must be cacheable", recognized); + Assertions.assertTrue(recognized, "a PluginDrivenMvccExternalTable scan must be cacheable"); } /** @@ -91,8 +91,7 @@ public void testRejectTvfBackedNode() { FunctionGenTable tvfTable = Mockito.mock(FunctionGenTable.class); PluginDrivenScanNode node = mockPluginScanNode(tvfTable, 0L); boolean recognized = Deencapsulation.invoke(analyzer, "isExternalCacheableScanNode", node); - Assert.assertFalse("a jdbc-query TVF (FunctionGenTable) has no token and must not be cacheable", - recognized); + Assertions.assertFalse(recognized, "a jdbc-query TVF (FunctionGenTable) has no token and must not be cacheable"); } /** A scan node with no tuple descriptor is defensively excluded (no NPE). */ @@ -101,7 +100,7 @@ public void testRejectNullTupleDesc() { PluginDrivenScanNode node = Mockito.mock(PluginDrivenScanNode.class); Mockito.when(node.getTupleDesc()).thenReturn(null); boolean recognized = Deencapsulation.invoke(analyzer, "isExternalCacheableScanNode", node); - Assert.assertFalse(recognized); + Assertions.assertFalse(recognized); } /** @@ -126,9 +125,9 @@ public void testTokenSourcedFromConnectorFreshness() { CacheAnalyzer.CacheTable cacheTable = Deencapsulation.invoke(analyzer, "buildCacheTableForExternalScanNode", node); - Assert.assertSame(table, cacheTable.table); - Assert.assertEquals(token, cacheTable.latestPartitionTime); - Assert.assertEquals(5L, cacheTable.partitionNum); + Assertions.assertSame(table, cacheTable.table); + Assertions.assertEquals(token, cacheTable.latestPartitionTime); + Assertions.assertEquals(5L, cacheTable.partitionNum); } /** @@ -157,8 +156,7 @@ public void testGateValueSourcedFromWallClockAccessor() { CacheAnalyzer.CacheTable cacheTable = Deencapsulation.invoke(analyzer, "buildCacheTableForExternalScanNode", node); - Assert.assertEquals("BE PCache version key stays the raw token", token, cacheTable.latestPartitionTime); - Assert.assertEquals("the quiet-window gate value is the wall-clock millis", wallClockMillis, - cacheTable.latestPartitionUpdateMillis); + Assertions.assertEquals(token, cacheTable.latestPartitionTime, "BE PCache version key stays the raw token"); + Assertions.assertEquals(wallClockMillis, cacheTable.latestPartitionUpdateMillis, "the quiet-window gate value is the wall-clock millis"); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/ComputeGroupTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/ComputeGroupTest.java index e1def2644b993d..939ad2f1c10b35 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/ComputeGroupTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/ComputeGroupTest.java @@ -53,11 +53,11 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +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.mockito.MockedStatic; import org.mockito.Mockito; @@ -78,13 +78,13 @@ public class ComputeGroupTest { private MockedStatic mockedEnvStatic; private Env originalEnv; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { FeConstants.runningUnitTest = true; connectContext = UtFrameUtils.createDefaultCtx(); } - @Before + @BeforeEach public void setUp() throws MetaNotFoundException { auth = new Auth(); env = Mockito.mock(Env.class); @@ -115,7 +115,7 @@ public void setUp() throws MetaNotFoundException { connectContext.setEnv(env); } - @After + @AfterEach public void tearDown() { if (originalEnv != null) { connectContext.setEnv(originalEnv); @@ -144,7 +144,7 @@ public void testGetSetResourceTagFromAuth() throws Exception { { String invalidUser = RandomIdentifierGenerator.generateRandomIdentifier(8); ComputeGroup cg1 = auth.getComputeGroup(invalidUser); - Assert.assertTrue(cg1 == ComputeGroup.INVALID_COMPUTE_GROUP); + Assertions.assertTrue(cg1 == ComputeGroup.INVALID_COMPUTE_GROUP); } // 2 get a non-admin user without resource tag { @@ -157,54 +157,54 @@ public void testGetSetResourceTagFromAuth() throws Exception { auth.createUser(createUserCommand.getInfo()); ComputeGroup cg = auth.getComputeGroup(nonAdminUserStr); - Assert.assertTrue(cg instanceof MergedComputeGroup); - Assert.assertTrue(((MergedComputeGroup) cg).getName().contains(Tag.VALUE_DEFAULT_TAG)); + Assertions.assertTrue(cg instanceof MergedComputeGroup); + Assertions.assertTrue(((MergedComputeGroup) cg).getName().contains(Tag.VALUE_DEFAULT_TAG)); // 2.1 get a non-admin user with resource tag String setPropStr = "set property for '" + nonAdminUserStr + "' 'resource_tags.location' = 'test_rg1';"; ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr)); ComputeGroup cg2 = auth.getComputeGroup(nonAdminUserStr); - Assert.assertTrue(cg2 instanceof MergedComputeGroup); - Assert.assertTrue(((MergedComputeGroup) cg2).getName().contains("test_rg1")); + Assertions.assertTrue(cg2 instanceof MergedComputeGroup); + Assertions.assertTrue(((MergedComputeGroup) cg2).getName().contains("test_rg1")); // 2.2 get a non-admin user with multi-resource tag String setPropStr2 = "set property for '" + nonAdminUserStr + "' 'resource_tags.location' = 'test_rg1,test_rg2';"; ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr2)); ComputeGroup cg3 = auth.getComputeGroup(nonAdminUserStr); - Assert.assertTrue(cg3 instanceof MergedComputeGroup); + Assertions.assertTrue(cg3 instanceof MergedComputeGroup); String cgName3 = ((MergedComputeGroup) cg3).getName(); - Assert.assertTrue(cgName3.contains("test_rg1")); - Assert.assertTrue(cgName3.contains("test_rg2")); + Assertions.assertTrue(cgName3.contains("test_rg1")); + Assertions.assertTrue(cgName3.contains("test_rg2")); // 2.3 get a non-admin user with empty tag String setPropStr3 = "set property for '" + nonAdminUserStr + "' 'resource_tags.location' = '';"; ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr3)); ComputeGroup cg4 = auth.getComputeGroup(nonAdminUserStr); - Assert.assertTrue(cg4 instanceof MergedComputeGroup); + Assertions.assertTrue(cg4 instanceof MergedComputeGroup); String cgName4 = ((MergedComputeGroup) cg4).getName(); - Assert.assertTrue(cgName4.contains("default")); + Assertions.assertTrue(cgName4.contains("default")); } // 4 get an admin user without resource tag { ComputeGroup cg1 = auth.getComputeGroup("root"); - Assert.assertTrue(cg1 instanceof AllBackendComputeGroup); + Assertions.assertTrue(cg1 instanceof AllBackendComputeGroup); // 4.1 get an admin user with a resource tag String setPropStr = "set property for 'root' 'resource_tags.location' = 'test_rg2';"; ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr)); ComputeGroup cg2 = auth.getComputeGroup("root"); - Assert.assertTrue(cg2 instanceof MergedComputeGroup); - Assert.assertTrue(((MergedComputeGroup) cg2).getName().contains("test_rg2")); + Assertions.assertTrue(cg2 instanceof MergedComputeGroup); + Assertions.assertTrue(((MergedComputeGroup) cg2).getName().contains("test_rg2")); // 4.2 get an admin user with an empty resource tag String setPropStr2 = "set property for 'root' 'resource_tags.location' = '';"; ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr2)); ComputeGroup cg3 = auth.getComputeGroup("root"); - Assert.assertTrue(cg3 instanceof AllBackendComputeGroup); + Assertions.assertTrue(cg3 instanceof AllBackendComputeGroup); } } @@ -215,20 +215,20 @@ public void testComputeGroup() { try { ComputeGroup.INVALID_COMPUTE_GROUP.getBackendList(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("invalid compute group can not be used")); + Assertions.assertTrue(e.getMessage().contains("invalid compute group can not be used")); } try { ComputeGroup.INVALID_COMPUTE_GROUP.containsBackend(""); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("invalid compute group can not be used")); + Assertions.assertTrue(e.getMessage().contains("invalid compute group can not be used")); } String invalidCgToString = ComputeGroup.INVALID_COMPUTE_GROUP.toString(); String expectedCgString = String.format("%s id=%s, name=%s", ComputeGroup.INVALID_COMPUTE_GROUP.getClass().getSimpleName(), ComputeGroup.INVALID_COMPUTE_GROUP_NAME, ComputeGroup.INVALID_COMPUTE_GROUP_NAME); - Assert.assertTrue(expectedCgString.equals(invalidCgToString)); + Assertions.assertTrue(expectedCgString.equals(invalidCgToString)); } // test Compute group @@ -236,12 +236,12 @@ public void testComputeGroup() { String cgId = "test_cg_id"; String cgName = "test_cg_1"; ComputeGroup cg1 = new ComputeGroup(cgId, cgName, null); - Assert.assertTrue(cgId.equals(cg1.getId())); - Assert.assertTrue(cgName.equals(cg1.getName())); + Assertions.assertTrue(cgId.equals(cg1.getId())); + Assertions.assertTrue(cgName.equals(cg1.getName())); String cg1ToString = String.format("%s id=%s, name=%s", ComputeGroup.class.getSimpleName(), cgId, cgName); - Assert.assertTrue(cg1ToString.equals(cg1.toString())); - Assert.assertTrue(cg1.containsBackend(cgName)); - Assert.assertFalse(cg1.containsBackend("123")); + Assertions.assertTrue(cg1ToString.equals(cg1.toString())); + Assertions.assertTrue(cg1.containsBackend(cgName)); + Assertions.assertFalse(cg1.containsBackend("123")); } // test Cloud Compute group @@ -249,13 +249,13 @@ public void testComputeGroup() { String cgId = "test_cloud_cg_id"; String cgName = "test_cloud_cg_name"; ComputeGroup cg1 = new CloudComputeGroup(cgId, cgName, null); - Assert.assertTrue(cgId.equals(cg1.getId())); - Assert.assertTrue(cgName.equals(cg1.getName())); + Assertions.assertTrue(cgId.equals(cg1.getId())); + Assertions.assertTrue(cgName.equals(cg1.getName())); String cg1ToString = String.format("%s id=%s, name=%s", CloudComputeGroup.class.getSimpleName(), cgId, cgName); - Assert.assertTrue(cg1ToString.equals(cg1.toString())); - Assert.assertTrue(cg1.containsBackend(cgName)); - Assert.assertFalse(cg1.containsBackend("123")); + Assertions.assertTrue(cg1ToString.equals(cg1.toString())); + Assertions.assertTrue(cg1.containsBackend(cgName)); + Assertions.assertFalse(cg1.containsBackend("123")); } // test MergedComputeGroup @@ -267,16 +267,16 @@ public void testComputeGroup() { mergedEmptyName, emptyTags, null); String mergedCgToString = String.format("%s name=%s ", MergedComputeGroup.class.getSimpleName(), ""); - Assert.assertTrue(mergedCgToString.equals(emptyMergedCg.toString())); - Assert.assertFalse(emptyMergedCg.containsBackend(beTag)); + Assertions.assertTrue(mergedCgToString.equals(emptyMergedCg.toString())); + Assertions.assertFalse(emptyMergedCg.containsBackend(beTag)); Set tags = Sets.newHashSet(); tags.add(beTag); String mergedName = String.join(",", tags); ComputeGroup notEmptyMergedCg = new MergedComputeGroup(mergedName, tags, null); String mergedCgToString2 = String.format("%s name=%s ", MergedComputeGroup.class.getSimpleName(), mergedName); - Assert.assertTrue(mergedCgToString2.equals(notEmptyMergedCg.toString())); - Assert.assertTrue(notEmptyMergedCg.containsBackend(beTag)); + Assertions.assertTrue(mergedCgToString2.equals(notEmptyMergedCg.toString())); + Assertions.assertTrue(notEmptyMergedCg.containsBackend(beTag)); } // test AllBackendComputeGroup @@ -285,16 +285,16 @@ public void testComputeGroup() { try { allBeCg.getName(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("AllBackendComputeGroup not implements getName")); + Assertions.assertTrue(e.getMessage().contains("AllBackendComputeGroup not implements getName")); } try { allBeCg.getId(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("AllBackendComputeGroup not implements getId")); + Assertions.assertTrue(e.getMessage().contains("AllBackendComputeGroup not implements getId")); } - Assert.assertTrue(allBeCg.getClass().getSimpleName().equals(allBeCg.toString())); + Assertions.assertTrue(allBeCg.getClass().getSimpleName().equals(allBeCg.toString())); } // test equals @@ -312,55 +312,55 @@ public void testComputeGroup() { ComputeGroup cg3 = new ComputeGroup(cgId1, cgName1, null); - Assert.assertFalse(cg1.equals(cg2)); - Assert.assertFalse(cg2.equals(cg1)); + Assertions.assertFalse(cg1.equals(cg2)); + Assertions.assertFalse(cg2.equals(cg1)); - Assert.assertFalse(cg1.equals(cg3)); - Assert.assertFalse(cg3.equals(cg1)); + Assertions.assertFalse(cg1.equals(cg3)); + Assertions.assertFalse(cg3.equals(cg1)); - Assert.assertFalse(cg1.equals(cg11)); - Assert.assertFalse(cg11.equals(cg1)); + Assertions.assertFalse(cg1.equals(cg11)); + Assertions.assertFalse(cg11.equals(cg1)); - Assert.assertFalse(cg1.equals(null)); + Assertions.assertFalse(cg1.equals(null)); CloudComputeGroup cloudCg1 = new CloudComputeGroup(cgId1, cgName1, null); CloudComputeGroup cloudCg2 = new CloudComputeGroup(cgId2, cgName2, null); - Assert.assertFalse(cloudCg1.equals(cloudCg2)); - Assert.assertFalse(cloudCg2.equals(cloudCg1)); + Assertions.assertFalse(cloudCg1.equals(cloudCg2)); + Assertions.assertFalse(cloudCg2.equals(cloudCg1)); AllBackendComputeGroup allBecg1 = new AllBackendComputeGroup(null); AllBackendComputeGroup allBecg2 = new AllBackendComputeGroup(null); - Assert.assertFalse(allBecg1.equals(allBecg2)); - Assert.assertFalse(allBecg2.equals(allBecg1)); + Assertions.assertFalse(allBecg1.equals(allBecg2)); + Assertions.assertFalse(allBecg2.equals(allBecg1)); MergedComputeGroup mergedCg1 = new MergedComputeGroup("", null, null); MergedComputeGroup mergedCg2 = new MergedComputeGroup("", null, null); - Assert.assertFalse(mergedCg1.equals(mergedCg2)); - Assert.assertFalse(mergedCg2.equals(mergedCg1)); + Assertions.assertFalse(mergedCg1.equals(mergedCg2)); + Assertions.assertFalse(mergedCg2.equals(mergedCg1)); // ComputeGroup vs others - Assert.assertTrue(cg1.equals(cg1)); - Assert.assertFalse(cg1.equals(cloudCg1)); - Assert.assertFalse(cg1.equals(allBecg1)); - Assert.assertFalse(cg1.equals(mergedCg1)); + Assertions.assertTrue(cg1.equals(cg1)); + Assertions.assertFalse(cg1.equals(cloudCg1)); + Assertions.assertFalse(cg1.equals(allBecg1)); + Assertions.assertFalse(cg1.equals(mergedCg1)); // CloudComputeGroup vs others - Assert.assertTrue(cloudCg1.equals(cloudCg1)); - Assert.assertFalse(cloudCg1.equals(cg1)); - Assert.assertFalse(cloudCg1.equals(allBecg1)); - Assert.assertFalse(cloudCg1.equals(mergedCg1)); + Assertions.assertTrue(cloudCg1.equals(cloudCg1)); + Assertions.assertFalse(cloudCg1.equals(cg1)); + Assertions.assertFalse(cloudCg1.equals(allBecg1)); + Assertions.assertFalse(cloudCg1.equals(mergedCg1)); // AllBackendComputeGroup vs others - Assert.assertTrue(allBecg1.equals(allBecg1)); - Assert.assertFalse(allBecg1.equals(cg1)); - Assert.assertFalse(allBecg1.equals(cloudCg1)); - Assert.assertFalse(allBecg1.equals(mergedCg1)); + Assertions.assertTrue(allBecg1.equals(allBecg1)); + Assertions.assertFalse(allBecg1.equals(cg1)); + Assertions.assertFalse(allBecg1.equals(cloudCg1)); + Assertions.assertFalse(allBecg1.equals(mergedCg1)); // MergedComputeGroup vs others - Assert.assertTrue(mergedCg1.equals(mergedCg1)); - Assert.assertFalse(mergedCg1.equals(cg1)); - Assert.assertFalse(mergedCg1.equals(allBecg1)); - Assert.assertFalse(mergedCg1.equals(cloudCg1)); + Assertions.assertTrue(mergedCg1.equals(mergedCg1)); + Assertions.assertFalse(mergedCg1.equals(cg1)); + Assertions.assertFalse(mergedCg1.equals(allBecg1)); + Assertions.assertFalse(mergedCg1.equals(cloudCg1)); } } @@ -406,21 +406,21 @@ public void testComputeGroupMgr() throws Exception { } ComputeGroup cg1 = cgmgr.getComputeGroupByName(beTag1.value); - Assert.assertTrue(cg1.getBackendList().size() == 2); + Assertions.assertTrue(cg1.getBackendList().size() == 2); ComputeGroup cg2 = cgmgr.getComputeGroupByName("abc"); - Assert.assertTrue(cg2.getBackendList().size() == 0); + Assertions.assertTrue(cg2.getBackendList().size() == 0); Set tagSet1 = Sets.newHashSet(beTag1, beTag2); - Assert.assertTrue(cgmgr.getComputeGroup(tagSet1).getBackendList().size() == 4); + Assertions.assertTrue(cgmgr.getComputeGroup(tagSet1).getBackendList().size() == 4); Tag beTag4 = Tag.create(Tag.TYPE_LOCATION, "abc"); Set tagset2 = Sets.newHashSet(beTag4); - Assert.assertTrue(cgmgr.getComputeGroup(tagset2).getBackendList().size() == 0); + Assertions.assertTrue(cgmgr.getComputeGroup(tagset2).getBackendList().size() == 0); Set emptyTagSet = Sets.newHashSet(); - Assert.assertTrue(cgmgr.getComputeGroup(emptyTagSet).getBackendList().size() == 0); + Assertions.assertTrue(cgmgr.getComputeGroup(emptyTagSet).getBackendList().size() == 0); - Assert.assertTrue(cgmgr.getAllBackendComputeGroup().getBackendList().size() == 5); + Assertions.assertTrue(cgmgr.getAllBackendComputeGroup().getBackendList().size() == 5); } @@ -457,8 +457,8 @@ public void testConnectContextToFederationBackendPolicy() throws UserException, ConnectContext.remove(); FederationBackendPolicy fbPolicy = new FederationBackendPolicy(); fbPolicy.init(beSelPolicy); - Assert.assertTrue(fbPolicy.getBackends().size() == 1); - Assert.assertTrue(fbPolicy.getBackends().contains(defaultBe)); + Assertions.assertTrue(fbPolicy.getBackends().size() == 1); + Assertions.assertTrue(fbPolicy.getBackends().contains(defaultBe)); } // 2 get compute group from connect ctx @@ -469,8 +469,8 @@ public void testConnectContextToFederationBackendPolicy() throws UserException, context.setComputeGroup(cgmgr.getComputeGroupByName(beTag1.value)); FederationBackendPolicy fbPolicy = new FederationBackendPolicy(); fbPolicy.init(beSelPolicy); - Assert.assertTrue(fbPolicy.getBackends().size() == 1); - Assert.assertTrue(fbPolicy.getBackends().contains(tag1Be)); + Assertions.assertTrue(fbPolicy.getBackends().size() == 1); + Assertions.assertTrue(fbPolicy.getBackends().contains(tag1Be)); } // 3 test set invalid compute group @@ -483,7 +483,7 @@ public void testConnectContextToFederationBackendPolicy() throws UserException, try { fbPolicy.init(beSelPolicy); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains(ComputeGroup.INVALID_COMPUTE_GROUP_ERR_MSG)); + Assertions.assertTrue(e.getMessage().contains(ComputeGroup.INVALID_COMPUTE_GROUP_ERR_MSG)); } } @@ -495,8 +495,8 @@ public void testConnectContextToFederationBackendPolicy() throws UserException, ExceptionChecker.expectThrowsNoException(() -> setProperty(setPropStr)); FederationBackendPolicy fbPolicy = new FederationBackendPolicy(); fbPolicy.init(beSelPolicy); - Assert.assertTrue(fbPolicy.getBackends().size() == 1); - Assert.assertTrue(fbPolicy.getBackends().contains(tag1Be)); + Assertions.assertTrue(fbPolicy.getBackends().size() == 1); + Assertions.assertTrue(fbPolicy.getBackends().contains(tag1Be)); } } @@ -512,7 +512,7 @@ public void testBrokerLoadToConnectContext() throws UserException, IOException { BrokerLoadJob brokerLoadJob = new BrokerLoadJob(1, null, null, null, emptyUser); brokerLoadJob.setComputeGroup(); - Assert.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); + Assertions.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); } // test invalid user @@ -523,7 +523,7 @@ public void testBrokerLoadToConnectContext() throws UserException, IOException { BrokerLoadJob brokerLoadJob = new BrokerLoadJob(1, null, null, null, emptyUser); brokerLoadJob.setComputeGroup(); - Assert.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); + Assertions.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); } // test get cg from user property @@ -546,8 +546,8 @@ public void testBrokerLoadToConnectContext() throws UserException, IOException { new BrokerLoadJob(1, null, null, null, nonAdminUser); brokerLoadJob.setComputeGroup(); ComputeGroup cg = ConnectContext.get().getComputeGroupSafely(); - Assert.assertTrue(cg instanceof MergedComputeGroup); - Assert.assertTrue(((MergedComputeGroup) cg).getName().contains(tagName)); + Assertions.assertTrue(cg instanceof MergedComputeGroup); + Assertions.assertTrue(((MergedComputeGroup) cg).getName().contains(tagName)); } } @@ -564,7 +564,7 @@ public void testRoutineLoadToConnectContext() throws Exception { ConnectContext ctx = UtFrameUtils.createDefaultCtx(); RoutineLoadJob job = new KafkaRoutineLoadJob(); job.setComputeGroup(); - Assert.assertTrue(ctx.getComputeGroupSafely() instanceof AllBackendComputeGroup); + Assertions.assertTrue(ctx.getComputeGroupSafely() instanceof AllBackendComputeGroup); } @@ -573,7 +573,7 @@ public void testRoutineLoadToConnectContext() throws Exception { ConnectContext.get().setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("xxxx", "%")); RoutineLoadJob job = new KafkaRoutineLoadJob(); job.setComputeGroup(); - Assert.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); + Assertions.assertTrue(ConnectContext.get().getComputeGroupSafely() instanceof AllBackendComputeGroup); } // 3 get a valid compute group @@ -584,8 +584,8 @@ public void testRoutineLoadToConnectContext() throws Exception { RoutineLoadJob job = new KafkaRoutineLoadJob(); job.setComputeGroup(); ComputeGroup cg = ConnectContext.get().getComputeGroupSafely(); - Assert.assertTrue(cg instanceof MergedComputeGroup); - Assert.assertTrue(((MergedComputeGroup) cg).getName().contains("tag_rg_1")); + Assertions.assertTrue(cg instanceof MergedComputeGroup); + Assertions.assertTrue(((MergedComputeGroup) cg).getName().contains("tag_rg_1")); } // 4 get a null job @@ -594,7 +594,7 @@ public void testRoutineLoadToConnectContext() throws Exception { try { routineLoadManager.getAvailableBackendIdsForUt(1); } catch (LoadException e) { - Assert.assertTrue(e.getMessage().contains("does not exist")); + Assertions.assertTrue(e.getMessage().contains("does not exist")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/TagSerializationTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/TagSerializationTest.java index a72c4d2d38e8ee..36eda044a495ad 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/TagSerializationTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/TagSerializationTest.java @@ -20,9 +20,9 @@ import org.apache.doris.common.AnalysisException; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -40,7 +40,7 @@ public class TagSerializationTest { private static String fileName = "./TagSerializationTest"; - @After + @AfterEach public void tearDown() { File file = new File(fileName); file.delete(); @@ -62,6 +62,6 @@ public void testSerializeTag() throws IOException, AnalysisException { DataInputStream in = new DataInputStream(new FileInputStream(file)); Tag readTag = Tag.read(in); - Assert.assertEquals(tag, readTag); + Assertions.assertEquals(tag, readTag); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/TagTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/TagTest.java index eda0eea55db56c..73d0bcd44d9ea6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/TagTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/TagTest.java @@ -20,21 +20,25 @@ import org.apache.doris.common.AnalysisException; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; public class TagTest { - @Test(expected = AnalysisException.class) + @Test public void testTagName1() throws AnalysisException { - Tag.create("location", "_tag1"); + Assertions.assertThrows(AnalysisException.class, () -> { + Tag.create("location", "_tag1"); + }); } - @Test(expected = AnalysisException.class) + @Test public void testTagName2() throws AnalysisException { - Tag.create("location", "asdlajwdjdawhkjldjawlkdjawldjlkwasdasdsadasdd"); + Assertions.assertThrows(AnalysisException.class, () -> { + Tag.create("location", "asdlajwdjdawhkjldjawlkdjawldjlkwasdasdsadasdd"); + }); } @Test @@ -47,7 +51,7 @@ public void testTagName3() throws AnalysisException { @Test public void testTagName4() throws AnalysisException { Tag tag = Tag.create("location", "zone1"); - Assert.assertEquals("{\"location\" : \"zone1\"}", tag.toString()); + Assertions.assertEquals("{\"location\" : \"zone1\"}", tag.toString()); } @Test @@ -58,12 +62,14 @@ public void testTagSet1() throws AnalysisException { TagSet.create(map); } - @Test(expected = AnalysisException.class) + @Test public void testTagSet2() throws AnalysisException { - Map map = Maps.newHashMap(); - map.put("location", "zone1, zone2"); - map.put("type", "tag1, _tag2"); - TagSet.create(map); + Assertions.assertThrows(AnalysisException.class, () -> { + Map map = Maps.newHashMap(); + map.put("location", "zone1, zone2"); + map.put("type", "tag1, _tag2"); + TagSet.create(map); + }); } @Test @@ -73,26 +79,26 @@ public void testTagSet3() throws AnalysisException { map.put("type", "backend"); map.put("function", "store,computation"); TagSet tagSet = TagSet.create(map); - Assert.assertTrue(tagSet.containsTag(Tag.create("location", "zone1"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("location", "zone2"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("type", "backend"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "store"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "computation"))); - Assert.assertFalse(tagSet.containsTag(Tag.create("function", "load"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("location", "zone1"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("location", "zone2"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("type", "backend"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "store"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "computation"))); + Assertions.assertFalse(tagSet.containsTag(Tag.create("function", "load"))); // test union Map map2 = Maps.newHashMap(); map2.put("function", "load"); TagSet tagSet2 = TagSet.create(map2); tagSet.union(tagSet2); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "store"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "computation"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "load"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "store"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "computation"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "load"))); // test substitute merge tagSet.substituteMerge(tagSet2); - Assert.assertFalse(tagSet.containsTag(Tag.create("function", "store"))); - Assert.assertFalse(tagSet.containsTag(Tag.create("function", "computation"))); - Assert.assertTrue(tagSet.containsTag(Tag.create("function", "load"))); + Assertions.assertFalse(tagSet.containsTag(Tag.create("function", "store"))); + Assertions.assertFalse(tagSet.containsTag(Tag.create("function", "computation"))); + Assertions.assertTrue(tagSet.containsTag(Tag.create("function", "load"))); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/WorkloadSchedTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/WorkloadSchedTest.java index 11c00eca234161..11239d218dec21 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/WorkloadSchedTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/WorkloadSchedTest.java @@ -25,8 +25,8 @@ import org.apache.doris.resource.workloadschedpolicy.WorkloadQueryInfo; import org.apache.doris.resource.workloadschedpolicy.WorkloadSchedPolicy; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; @@ -51,11 +51,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "101"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 1.2 >= @@ -72,11 +72,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "10"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 1.3 = @@ -93,11 +93,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "10"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 1.4 < @@ -114,11 +114,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "99"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 1.5 <= @@ -135,11 +135,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "101"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 2 string compare @@ -156,11 +156,11 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.USERNAME, "root"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match queryInfo.metricMap.put(WorkloadMetricType.USERNAME, "abc"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } // 3 mixed condition @@ -181,15 +181,15 @@ public void testPolicyCondition() { queryInfo.metricMap.put(WorkloadMetricType.QUERY_TIME, "100"); // match - Assert.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertTrue(workloadSchedPolicy1.isMatch(queryInfo)); // not match 1 queryInfo.metricMap.remove(WorkloadMetricType.USERNAME); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); // not match 2 queryInfo.metricMap.put(WorkloadMetricType.USERNAME, "abc"); - Assert.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); + Assertions.assertFalse(workloadSchedPolicy1.isMatch(queryInfo)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupMgrTest.java index 30b16aaabfe2b3..e2ce8927b3c4ab 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupMgrTest.java @@ -33,10 +33,10 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -61,7 +61,7 @@ public class WorkloadGroupMgrTest { private AtomicLong id = new AtomicLong(10); - @Before + @BeforeEach public void setUp() throws DdlException { mockedEnv = Mockito.mockStatic(Env.class); mockedEnv.when(Env::getCurrentEnv).thenReturn(env); @@ -75,7 +75,7 @@ public void setUp() throws DdlException { Mockito.when(auth.isWorkloadGroupInUse(ArgumentMatchers.anyString())).thenReturn(Pair.of(false, "")); } - @After + @AfterEach public void tearDown() { if (mockedEnv != null) { mockedEnv.close(); @@ -103,15 +103,15 @@ public void testCreateWorkloadGroup() throws DdlException { WorkloadGroupKey key1 = WorkloadGroupKey.get(cg1, wgName1); Map nameToRG = workloadGroupMgr.getNameToWorkloadGroup(); - Assert.assertEquals(1, nameToRG.size()); - Assert.assertTrue(nameToRG.containsKey(key1)); + Assertions.assertEquals(1, nameToRG.size()); + Assertions.assertTrue(nameToRG.containsKey(key1)); WorkloadGroup group1 = nameToRG.get(key1); - Assert.assertEquals(key1.getWorkloadGroupName(), group1.getName()); - Assert.assertEquals(key1.getComputeGroup(), group1.getComputeGroup()); + Assertions.assertEquals(key1.getWorkloadGroupName(), group1.getName()); + Assertions.assertEquals(key1.getComputeGroup(), group1.getComputeGroup()); Map idToRG = workloadGroupMgr.getIdToWorkloadGroup(); - Assert.assertEquals(1, idToRG.size()); - Assert.assertTrue(idToRG.containsKey(group1.getId())); + Assertions.assertEquals(1, idToRG.size()); + Assertions.assertTrue(idToRG.containsKey(group1.getId())); // 2 create workload group 2 long wgId2 = 2; @@ -126,13 +126,13 @@ public void testCreateWorkloadGroup() throws DdlException { WorkloadGroupKey key2 = WorkloadGroupKey.get(cg2, wgName2); nameToRG = workloadGroupMgr.getNameToWorkloadGroup(); - Assert.assertEquals(2, nameToRG.size()); - Assert.assertTrue(nameToRG.containsKey(key2)); + Assertions.assertEquals(2, nameToRG.size()); + Assertions.assertTrue(nameToRG.containsKey(key2)); WorkloadGroup group2 = nameToRG.get(key2); idToRG = workloadGroupMgr.getIdToWorkloadGroup(); - Assert.assertEquals(2, idToRG.size()); - Assert.assertTrue(idToRG.containsKey(group2.getId())); - Assert.assertTrue(key2.getComputeGroup().equals(wg2.getComputeGroup())); + Assertions.assertEquals(2, idToRG.size()); + Assertions.assertTrue(idToRG.containsKey(group2.getId())); + Assertions.assertTrue(key2.getComputeGroup().equals(wg2.getComputeGroup())); // 3 test memory limit exceeds, it will success Map properties3 = Maps.newHashMap(); @@ -152,9 +152,9 @@ public void testCreateWorkloadGroup() throws DdlException { propertiesErrorMincpu.put(WorkloadGroup.COMPUTE_GROUP, cg1); propertiesErrorMincpu.put(WorkloadGroup.MAX_MEMORY_PERCENT, "1%"); workloadGroupMgr.createWorkloadGroup(cg1, new WorkloadGroup(11, "wg_err_mincpu", propertiesErrorMincpu), false); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } // test sum of min memory percent > 100, it will fail @@ -165,9 +165,9 @@ public void testCreateWorkloadGroup() throws DdlException { propertiesErrorMinmem.put(WorkloadGroup.COMPUTE_GROUP, cg1); propertiesErrorMinmem.put(WorkloadGroup.MAX_MEMORY_PERCENT, "1%"); workloadGroupMgr.createWorkloadGroup(cg1, new WorkloadGroup(11, "wg_err_minmem", propertiesErrorMinmem), false); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } // 4 test create duplicate workload group error. @@ -175,9 +175,9 @@ public void testCreateWorkloadGroup() throws DdlException { try { // create wg1 in cg1, it should fail workloadGroupMgr.createWorkloadGroup(cg1, new WorkloadGroup(4, wgName1, properties1), false); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("already has workload group")); + Assertions.assertTrue(e.getMessage().contains("already has workload group")); } Map properties4 = Maps.newHashMap(); properties4.put(WorkloadGroup.MIN_CPU_PERCENT, "10"); @@ -194,9 +194,9 @@ public void testCreateWorkloadGroup() throws DdlException { propertiesMinCpu.put(WorkloadGroup.COMPUTE_GROUP, cg1); // create wg1 in cg1, it should fail workloadGroupMgr.createWorkloadGroup(cg1, new WorkloadGroup(11, "test_min_cpu", propertiesMinCpu), false); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } // test workload group's min memory percent > max memory percent @@ -207,9 +207,9 @@ public void testCreateWorkloadGroup() throws DdlException { propertiesMinMemory.put(WorkloadGroup.COMPUTE_GROUP, cg1); // create wg1 in cg1, it should fail workloadGroupMgr.createWorkloadGroup(cg1, new WorkloadGroup(11, "test_min_memory", propertiesMinMemory), false); - Assert.fail(); + Assertions.fail(); } catch (DdlException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } } @@ -244,17 +244,17 @@ public void testGetWorkloadGroup() throws UserException { .stream() .map(e -> e.toThrift()) .collect(Collectors.toList()); - Assert.assertTrue(ret.get(0).getId() == 100); + Assertions.assertTrue(ret.get(0).getId() == 100); ctx.setComputeGroup(new ComputeGroup(cgName2, cgName2, null)); - Assert.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).get(0).getId() == 101); + Assertions.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).get(0).getId() == 101); // 1.2 get from user prop // 1.3 get from session ctx.getSessionVariable().setWorkloadGroup(wgName2); - Assert.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).size() == 1); - Assert.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).get(0).getId() == wgId2); + Assertions.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).size() == 1); + Assertions.assertTrue(workloadGroupMgr.getWorkloadGroup(ctx).get(0).getId() == wgId2); // 1.4 get multi workload group Set cgSet = Sets.newHashSet(); @@ -276,9 +276,9 @@ public void testGetWorkloadGroup() throws UserException { idSet.add(tpip.getId()); } - Assert.assertTrue(idSet.size() == 2); - Assert.assertTrue(idSet.contains(wgId2)); - Assert.assertTrue(idSet.contains(wgId3)); + Assertions.assertTrue(idSet.size() == 2); + Assertions.assertTrue(idSet.contains(wgId2)); + Assertions.assertTrue(idSet.contains(wgId3)); // 1.5 test get failed ctx.getSessionVariable().setWorkloadGroup("abc"); @@ -286,9 +286,9 @@ public void testGetWorkloadGroup() throws UserException { workloadGroupMgr.getWorkloadGroup(ctx) .stream() .map(e -> e.toThrift()).collect(Collectors.toList()); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("Can not find workload group")); + Assertions.assertTrue(e.getMessage().contains("Can not find workload group")); } } @@ -303,14 +303,14 @@ public void testAlterWorkloadGroup() throws UserException { try { workloadGroupMgr.alterWorkloadGroup(new ComputeGroup("", "", null), "", p0); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("should contain at least one property")); + Assertions.assertTrue(e.getMessage().contains("should contain at least one property")); } p0.put(WorkloadGroup.MIN_CPU_PERCENT, "10"); try { workloadGroupMgr.alterWorkloadGroup(new ComputeGroup("", "", null), "abc", p0); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("Can not find workload group")); + Assertions.assertTrue(e.getMessage().contains("Can not find workload group")); } long wgId1 = 1; @@ -320,7 +320,7 @@ public void testAlterWorkloadGroup() throws UserException { prop1.put(WorkloadGroup.COMPUTE_GROUP, cgName1); prop1.put(WorkloadGroup.MIN_CPU_PERCENT, "10"); workloadGroupMgr.createWorkloadGroup(cgName1, new WorkloadGroup(wgId1, wgName1, prop1), false); - Assert.assertTrue(Long.valueOf( + Assertions.assertTrue(Long.valueOf( workloadGroupMgr.getNameToWorkloadGroup().get(WorkloadGroupKey.get(cgName1, wgName1)).getProperties() .get(WorkloadGroup.MIN_CPU_PERCENT)) == 10); @@ -331,15 +331,15 @@ public void testAlterWorkloadGroup() throws UserException { prop2.put(WorkloadGroup.MIN_CPU_PERCENT, "20"); try { workloadGroupMgr.alterWorkloadGroup(new ComputeGroup(cgName2, cgName2, null), wgName2, prop2); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("Can not find workload group")); + Assertions.assertTrue(e.getMessage().contains("Can not find workload group")); } // test alter success workloadGroupMgr.alterWorkloadGroup(new ComputeGroup(cgName1, cgName1, null), wgName1, prop2); WorkloadGroup wg = workloadGroupMgr.getNameToWorkloadGroup().get(WorkloadGroupKey.get(cgName1, wgName1)); - Assert.assertTrue(Long.valueOf(wg.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT)) == 20); + Assertions.assertTrue(Long.valueOf(wg.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT)) == 20); } // before: @@ -389,9 +389,9 @@ public void testBindWorkloadGroupToCg() throws DdlException { WorkloadGroup wg4 = new WorkloadGroup(wgId4, wgName4, prop4); wgMgr.createWorkloadGroup(cg1, wg4, false); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 4); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 4); - Assert.assertTrue(wgMgr.getOldWorkloadGroup().size() == 3); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 4); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 4); + Assertions.assertTrue(wgMgr.getOldWorkloadGroup().size() == 3); String cg2 = "cg2"; Set cgSet = Sets.newHashSet(); @@ -402,33 +402,33 @@ public void testBindWorkloadGroupToCg() throws DdlException { wgMgr.bindWorkloadGroupToComputeGroup(cgSet, oldWg); } - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 6); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 6); - Assert.assertTrue(wgMgr.getOldWorkloadGroup().size() == 0); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId1) == null); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId2) == null); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId3) == null); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId4).equals(wg4)); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 6); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 6); + Assertions.assertTrue(wgMgr.getOldWorkloadGroup().size() == 0); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId1) == null); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId2) == null); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId3) == null); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().get(wgId4).equals(wg4)); for (String cgName : cgSet) { WorkloadGroup wg11 = wgMgr.getNameToWorkloadGroup().get(WorkloadGroupKey.get(cgName, wgName1)); WorkloadGroup wg22 = wgMgr.getNameToWorkloadGroup().get(WorkloadGroupKey.get(cgName, wgName2)); WorkloadGroup wg33 = wgMgr.getNameToWorkloadGroup().get(WorkloadGroupKey.get(cgName, wgName3)); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg11.getId())); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg22.getId())); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg33.getId())); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg11.getId())); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg22.getId())); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().containsKey(wg33.getId())); - Assert.assertTrue(wg11.getComputeGroup().equals(cgName)); - Assert.assertTrue(wg22.getComputeGroup().equals(cgName)); - Assert.assertTrue(wg33.getComputeGroup().equals(cgName)); + Assertions.assertTrue(wg11.getComputeGroup().equals(cgName)); + Assertions.assertTrue(wg22.getComputeGroup().equals(cgName)); + Assertions.assertTrue(wg33.getComputeGroup().equals(cgName)); - Assert.assertTrue(wg11.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); - Assert.assertTrue(wg22.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); + Assertions.assertTrue(wg11.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); + Assertions.assertTrue(wg22.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); if (cg1.equals(cgName)) { - Assert.assertTrue(wg33.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("15")); + Assertions.assertTrue(wg33.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("15")); } else { - Assert.assertTrue(wg33.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); + Assertions.assertTrue(wg33.getProperties().get(WorkloadGroup.MIN_CPU_PERCENT).equals("12")); } } @@ -531,9 +531,9 @@ public void testMultiTagAlterWorkloadGroup() throws UserException { try { workloadGroupMgr.alterWorkloadGroup(new ComputeGroup(cg1, cg1, null), "wg1", properties); } catch (DdlException e) { - Assert.assertTrue(e.getMessage().contains("current sum val:110")); - Assert.assertTrue(e.getMessage().contains("cg1")); - Assert.assertFalse(e.getMessage().contains("cg2")); + Assertions.assertTrue(e.getMessage().contains("current sum val:110")); + Assertions.assertTrue(e.getMessage().contains("cg1")); + Assertions.assertFalse(e.getMessage().contains("cg2")); } } @@ -549,16 +549,16 @@ public void testMultiTagAlterWorkloadGroup() throws UserException { @Test public void testReplayWorkloadGroup() { WorkloadGroupMgr wgMgr = new WorkloadGroupMgr(); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 0); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 0); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 0); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 0); // 1 test replay create WorkloadGroup wg1 = new WorkloadGroup(1, "wg1", Maps.newHashMap()); wgMgr.replayCreateWorkloadGroup(wg1); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 1); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 1); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg1.getWorkloadGroupKey()) + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 1); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 1); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg1.getWorkloadGroupKey()) .equals(wgMgr.getIdToWorkloadGroup().get(wg1.getId()))); // 2 test replay alter @@ -566,17 +566,17 @@ public void testReplayWorkloadGroup() { pop2.put("MIN_CPU_PERCENT", "2345"); WorkloadGroup wg2 = new WorkloadGroup(1, "wg1", pop2); wgMgr.replayAlterWorkloadGroup(wg2); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg2.getWorkloadGroupKey()) + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg2.getWorkloadGroupKey()) .equals(wgMgr.getIdToWorkloadGroup().get(wg2.getId()))); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg2.getWorkloadGroupKey()).getProperties().get("MIN_CPU_PERCENT") + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().get(wg2.getWorkloadGroupKey()).getProperties().get("MIN_CPU_PERCENT") .equals("2345")); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 1); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 1); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 1); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 1); // 3 test replay drop DropWorkloadGroupOperationLog dropLog = new DropWorkloadGroupOperationLog(1); wgMgr.replayDropWorkloadGroup(dropLog); - Assert.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 0); - Assert.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 0); + Assertions.assertTrue(wgMgr.getNameToWorkloadGroup().size() == 0); + Assertions.assertTrue(wgMgr.getIdToWorkloadGroup().size() == 0); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupTest.java index 9e66fc4ec0cf52..d69e13b7c123ea 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadgroup/WorkloadGroupTest.java @@ -22,8 +22,8 @@ import org.apache.doris.thrift.TWgSlotMemoryPolicy; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -39,19 +39,21 @@ public void testCreateNormal() throws DdlException { properties1.put(WorkloadGroup.COMPUTE_GROUP, "default"); String name1 = "g1"; WorkloadGroup group1 = WorkloadGroup.create(name1, properties1); - Assert.assertEquals(name1, group1.getName()); - Assert.assertTrue(group1.getProperties().containsKey(WorkloadGroup.MIN_CPU_PERCENT)); - Assert.assertTrue(group1.getMaxMemoryPercent() == 30); + Assertions.assertEquals(name1, group1.getName()); + Assertions.assertTrue(group1.getProperties().containsKey(WorkloadGroup.MIN_CPU_PERCENT)); + Assertions.assertTrue(group1.getMaxMemoryPercent() == 30); } - @Test(expected = DdlException.class) + @Test public void testNotSupportProperty() throws DdlException { - Map properties1 = Maps.newHashMap(); - properties1.put(WorkloadGroup.MIN_CPU_PERCENT, "10"); - properties1.put(WorkloadGroup.MAX_MEMORY_PERCENT, "30%"); - properties1.put("share", "10"); - String name1 = "g1"; - WorkloadGroup.create(name1, properties1); + Assertions.assertThrows(DdlException.class, () -> { + Map properties1 = Maps.newHashMap(); + properties1.put(WorkloadGroup.MIN_CPU_PERCENT, "10"); + properties1.put(WorkloadGroup.MAX_MEMORY_PERCENT, "30%"); + properties1.put("share", "10"); + String name1 = "g1"; + WorkloadGroup.create(name1, properties1); + }); } @Test @@ -67,27 +69,27 @@ public void testGetProcNodeData() throws DdlException { BaseProcResult result = new BaseProcResult(); group1.getProcNodeData(result); List> rows = result.getRows(); - Assert.assertEquals(1, rows.size()); + Assertions.assertEquals(1, rows.size()); // TODO check proc data with system table } @Test public void testPolicyToString() { TWgSlotMemoryPolicy p1 = WorkloadGroup.findSlotPolicyValueByString("fixed"); - Assert.assertEquals(p1, TWgSlotMemoryPolicy.FIXED); + Assertions.assertEquals(p1, TWgSlotMemoryPolicy.FIXED); TWgSlotMemoryPolicy p2 = WorkloadGroup.findSlotPolicyValueByString("dynamic"); - Assert.assertEquals(p2, TWgSlotMemoryPolicy.DYNAMIC); + Assertions.assertEquals(p2, TWgSlotMemoryPolicy.DYNAMIC); TWgSlotMemoryPolicy p3 = WorkloadGroup.findSlotPolicyValueByString("none"); - Assert.assertEquals(p3, TWgSlotMemoryPolicy.NONE); + Assertions.assertEquals(p3, TWgSlotMemoryPolicy.NONE); TWgSlotMemoryPolicy p4 = WorkloadGroup.findSlotPolicyValueByString("none"); - Assert.assertEquals(p4, TWgSlotMemoryPolicy.NONE); + Assertions.assertEquals(p4, TWgSlotMemoryPolicy.NONE); boolean hasException = false; try { WorkloadGroup.findSlotPolicyValueByString("disableDa"); } catch (RuntimeException e) { hasException = true; } - Assert.assertEquals(hasException, true); + Assertions.assertEquals(hasException, true); } @Test @@ -96,40 +98,40 @@ public void testWorkloadGroupKey() { WorkloadGroupKey eqKey1 = WorkloadGroupKey.get("cg1", "wg1"); WorkloadGroupKey eqKey2 = WorkloadGroupKey.get("cg1", "wg1"); WorkloadGroupKey eqKey3 = WorkloadGroupKey.get("cg1", "wg2"); - Assert.assertTrue(eqKey1.equals(eqKey1)); - Assert.assertTrue(eqKey1.equals(eqKey2)); - Assert.assertTrue(eqKey2.equals(eqKey1)); - Assert.assertTrue(eqKey1.hashCode() == eqKey2.hashCode()); + Assertions.assertTrue(eqKey1.equals(eqKey1)); + Assertions.assertTrue(eqKey1.equals(eqKey2)); + Assertions.assertTrue(eqKey2.equals(eqKey1)); + Assertions.assertTrue(eqKey1.hashCode() == eqKey2.hashCode()); - Assert.assertFalse(eqKey3.equals(eqKey1)); - Assert.assertFalse(eqKey1.equals(eqKey3)); - Assert.assertTrue(eqKey1.hashCode() != eqKey3.hashCode()); + Assertions.assertFalse(eqKey3.equals(eqKey1)); + Assertions.assertFalse(eqKey1.equals(eqKey3)); + Assertions.assertTrue(eqKey1.hashCode() != eqKey3.hashCode()); WorkloadGroupKey eqKey4 = WorkloadGroupKey.get("cg2", "wg2"); - Assert.assertFalse(eqKey4.equals(eqKey3)); - Assert.assertFalse(eqKey3.equals(eqKey4)); - Assert.assertFalse(eqKey4.hashCode() == eqKey3.hashCode()); + Assertions.assertFalse(eqKey4.equals(eqKey3)); + Assertions.assertFalse(eqKey3.equals(eqKey4)); + Assertions.assertFalse(eqKey4.hashCode() == eqKey3.hashCode()); // test wg name exception try { WorkloadGroupKey.get("cg1", ""); - Assert.fail(); + Assertions.fail(); } catch (IllegalStateException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } // test null equal - Assert.assertTrue(!eqKey1.equals(null)); + Assertions.assertTrue(!eqKey1.equals(null)); WorkloadGroupKey nullkey2 = WorkloadGroupKey.get(null, "wg1"); WorkloadGroupKey nullkey3 = WorkloadGroupKey.get("", "wg1"); - Assert.assertTrue(nullkey2.equals(nullkey3)); - Assert.assertTrue(nullkey3.equals(nullkey2)); + Assertions.assertTrue(nullkey2.equals(nullkey3)); + Assertions.assertTrue(nullkey3.equals(nullkey2)); - Assert.assertFalse(nullkey2.equals(eqKey1)); - Assert.assertFalse(eqKey1.equals(nullkey2)); + Assertions.assertFalse(nullkey2.equals(eqKey1)); + Assertions.assertFalse(eqKey1.equals(nullkey2)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadRuntimeStatusMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadRuntimeStatusMgrTest.java index 6b58bf996a3e09..4e41a0578e73dd 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadRuntimeStatusMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadRuntimeStatusMgrTest.java @@ -27,9 +27,9 @@ import org.apache.doris.thrift.TReportWorkloadRuntimeStatusParams; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -46,7 +46,7 @@ public class WorkloadRuntimeStatusMgrTest { private WorkloadRuntimeStatusMgr mgr; - @Before + @BeforeEach public void setUp() { mgr = new WorkloadRuntimeStatusMgr(); } @@ -65,12 +65,12 @@ public void testSingleBeProgressMerge() { mgr.updateBeQueryStats(params); Map merged = getMergedSnapshot(); - Assert.assertEquals(1, merged.size()); + Assertions.assertEquals(1, merged.size()); TQueryStatistics result = merged.get("q1"); - Assert.assertNotNull(result); - Assert.assertEquals(10, result.getTotalTasksNum()); - Assert.assertEquals(3, result.getFinishedTasksNum()); + Assertions.assertNotNull(result); + Assertions.assertEquals(10, result.getTotalTasksNum()); + Assertions.assertEquals(3, result.getFinishedTasksNum()); } // ---- Merge: multiple BEs, same query (summing across BEs) ---- @@ -84,11 +84,11 @@ public void testMultiBeSummingAcrossQuery() { mgr.updateBeQueryStats(buildParams(10002L, "q1", buildStats(8, 5))); Map merged = getMergedSnapshot(); - Assert.assertEquals(1, merged.size()); + Assertions.assertEquals(1, merged.size()); TQueryStatistics result = merged.get("q1"); - Assert.assertEquals(18, result.getTotalTasksNum()); - Assert.assertEquals(8, result.getFinishedTasksNum()); + Assertions.assertEquals(18, result.getTotalTasksNum()); + Assertions.assertEquals(8, result.getFinishedTasksNum()); } // ---- Merge: multiple BEs, multiple queries remain independent ---- @@ -99,12 +99,12 @@ public void testMultiQueryIndependence() { mgr.updateBeQueryStats(buildParams(10001L, "q2", buildStats(20, 15))); Map merged = getMergedSnapshot(); - Assert.assertEquals(2, merged.size()); + Assertions.assertEquals(2, merged.size()); - Assert.assertEquals(10, merged.get("q1").getTotalTasksNum()); - Assert.assertEquals(2, merged.get("q1").getFinishedTasksNum()); - Assert.assertEquals(20, merged.get("q2").getTotalTasksNum()); - Assert.assertEquals(15, merged.get("q2").getFinishedTasksNum()); + Assertions.assertEquals(10, merged.get("q1").getTotalTasksNum()); + Assertions.assertEquals(2, merged.get("q1").getFinishedTasksNum()); + Assertions.assertEquals(20, merged.get("q2").getTotalTasksNum()); + Assertions.assertEquals(15, merged.get("q2").getFinishedTasksNum()); } // ---- isSet flag: unset fields should not override previous values ---- @@ -126,8 +126,8 @@ public void testIsSetPreservesPreviousValues() { TQueryStatistics result = merged.get("q1"); // BE2 didn't set total/finished, so original values from BE1 should be preserved - Assert.assertEquals(10, result.getTotalTasksNum()); - Assert.assertEquals(3, result.getFinishedTasksNum()); + Assertions.assertEquals(10, result.getTotalTasksNum()); + Assertions.assertEquals(3, result.getFinishedTasksNum()); } // ---- Zero-reporting BE should not interfere ---- @@ -143,8 +143,8 @@ public void testBeWithZeroProgress() { TQueryStatistics result = merged.get("q1"); // total=10, finished=4 (from BE1); BE2's (0,0) is additive → still (10,4) - Assert.assertEquals(10, result.getTotalTasksNum()); - Assert.assertEquals(4, result.getFinishedTasksNum()); + Assertions.assertEquals(10, result.getTotalTasksNum()); + Assertions.assertEquals(4, result.getFinishedTasksNum()); } // ---- getQueryStatistics returns per-BE map ---- @@ -155,11 +155,11 @@ public void testGetQueryStatisticsPerBe() { mgr.updateBeQueryStats(buildParams(10002L, "q1", buildStats(3, 1))); Map perBe = mgr.getQueryStatistics("q1"); - Assert.assertEquals(2, perBe.size()); - Assert.assertTrue(perBe.containsKey(10001L)); - Assert.assertTrue(perBe.containsKey(10002L)); - Assert.assertEquals(5, perBe.get(10001L).getStatistics().getTotalTasksNum()); - Assert.assertEquals(3, perBe.get(10002L).getStatistics().getTotalTasksNum()); + Assertions.assertEquals(2, perBe.size()); + Assertions.assertTrue(perBe.containsKey(10001L)); + Assertions.assertTrue(perBe.containsKey(10002L)); + Assertions.assertEquals(5, perBe.get(10001L).getStatistics().getTotalTasksNum()); + Assertions.assertEquals(3, perBe.get(10002L).getStatistics().getTotalTasksNum()); } // ---- Non-existent query returns empty map ---- @@ -167,7 +167,7 @@ public void testGetQueryStatisticsPerBe() { @Test public void testGetQueryStatisticsNonExistent() { Map perBe = mgr.getQueryStatistics("non-existent-query"); - Assert.assertTrue(perBe.isEmpty()); + Assertions.assertTrue(perBe.isEmpty()); } // ---- updateBeQueryStats with missing fields ---- @@ -177,7 +177,7 @@ public void testUpdateBeQueryStatsMissingBackendId() { TReportWorkloadRuntimeStatusParams params = new TReportWorkloadRuntimeStatusParams(); // backend_id not set, updateBeQueryStats should log a warning and return early mgr.updateBeQueryStats(params); - Assert.assertTrue(getMergedSnapshot().isEmpty()); + Assertions.assertTrue(getMergedSnapshot().isEmpty()); } // ---- updateBeQueryStats with missing query stats map ---- @@ -188,7 +188,7 @@ public void testUpdateBeQueryStatsMissingQueryStatsMap() { params.setBackendId(10001L); // query_statistics_result_map not set → should return early mgr.updateBeQueryStats(params); - Assert.assertTrue(getMergedSnapshot().isEmpty()); + Assertions.assertTrue(getMergedSnapshot().isEmpty()); } // ---- isSet flag: verifying Thrift setter behavior inline ---- @@ -201,20 +201,18 @@ public void testThriftIsSetFlagRequired() { TQueryStatistics viaSetter = new TQueryStatistics(); viaSetter.setTotalTasksNum(5); - Assert.assertTrue("setTotalTasksNum via setter must set __isset flag", - viaSetter.isSetTotalTasksNum()); + Assertions.assertTrue(viaSetter.isSetTotalTasksNum(), "setTotalTasksNum via setter must set __isset flag"); TQueryStatistics viaField = new TQueryStatistics(); viaField.total_tasks_num = 5; // direct field assignment - Assert.assertFalse("direct field assignment must NOT set __isset flag", - viaField.isSetTotalTasksNum()); + Assertions.assertFalse(viaField.isSetTotalTasksNum(), "direct field assignment must NOT set __isset flag"); // Same for finished_tasks_num viaSetter.setFinishedTasksNum(3); - Assert.assertTrue(viaSetter.isSetFinishedTasksNum()); + Assertions.assertTrue(viaSetter.isSetFinishedTasksNum()); viaField.finished_tasks_num = 3; - Assert.assertFalse(viaField.isSetFinishedTasksNum()); + Assertions.assertFalse(viaField.isSetFinishedTasksNum()); } // ---- Merge without any progress fields ---- @@ -231,8 +229,8 @@ public void testMergeWithoutProgressFields() { TQueryStatistics result = merged.get("q1"); // Fields should still be 0 and isSet should be false - Assert.assertEquals(0, result.getTotalTasksNum()); - Assert.assertEquals(0, result.getFinishedTasksNum()); + Assertions.assertEquals(0, result.getTotalTasksNum()); + Assertions.assertEquals(0, result.getFinishedTasksNum()); } // ---- Merge: three BEs combined ---- @@ -244,25 +242,25 @@ public void testThreeBeMergeProgress() { mgr.updateBeQueryStats(buildParams(10003L, "q1", buildStats(5, 0))); Map merged = getMergedSnapshot(); - Assert.assertEquals(1, merged.size()); + Assertions.assertEquals(1, merged.size()); TQueryStatistics result = merged.get("q1"); // total = 4 + 3 + 5 = 12, finished = 1 + 3 + 0 = 4 - Assert.assertEquals(12, result.getTotalTasksNum()); - Assert.assertEquals(4, result.getFinishedTasksNum()); + Assertions.assertEquals(12, result.getTotalTasksNum()); + Assertions.assertEquals(4, result.getFinishedTasksNum()); } @Test public void testSnapshotReadRequiresRebuild() { mgr.updateBeQueryStats(buildParams(10001L, "q1", buildStats(6, 2))); // Newly reported data is not visible to sync readers before snapshot rebuild. - Assert.assertTrue(mgr.getQueryStatisticsMap().isEmpty()); + Assertions.assertTrue(mgr.getQueryStatisticsMap().isEmpty()); // Rebuild snapshot and verify the new data becomes visible. Map merged = getMergedSnapshot(); - Assert.assertEquals(1, merged.size()); - Assert.assertEquals(6, merged.get("q1").getTotalTasksNum()); - Assert.assertEquals(2, merged.get("q1").getFinishedTasksNum()); + Assertions.assertEquals(1, merged.size()); + Assertions.assertEquals(6, merged.get("q1").getTotalTasksNum()); + Assertions.assertEquals(2, merged.get("q1").getFinishedTasksNum()); } @Test @@ -279,12 +277,12 @@ public void testExternalDmlAuditWaitsForEveryBackendFinalSnapshot() { mgr.updateBeQueryStats(buildParams(10002L, "q1", buildStats(20, 4), false)); List events = Deencapsulation.invoke(mgr, "getQueryNeedAudit"); - Assert.assertTrue("external DML audit must wait for every participating BE", events.isEmpty()); + Assertions.assertTrue(events.isEmpty(), "external DML audit must wait for every participating BE"); mgr.updateBeQueryStats(buildParams(10002L, "q1", buildStats(20, 4), true)); events = Deencapsulation.invoke(mgr, "getQueryNeedAudit"); - Assert.assertEquals(1, events.size()); - Assert.assertSame(event, events.get(0)); + Assertions.assertEquals(1, events.size()); + Assertions.assertSame(event, events.get(0)); } finally { Config.query_audit_log_timeout_ms = originalAuditTimeout; } @@ -302,8 +300,8 @@ public void testExternalDmlAuditUsesBoundedFallback() { event.pushToAuditLogQueueTime = System.currentTimeMillis() - 40; List events = Deencapsulation.invoke(mgr, "getQueryNeedAudit"); - Assert.assertEquals(1, events.size()); - Assert.assertSame(event, events.get(0)); + Assertions.assertEquals(1, events.size()); + Assertions.assertSame(event, events.get(0)); } finally { Config.query_audit_log_timeout_ms = originalAuditTimeout; Config.be_report_query_statistics_timeout_ms = originalReportTimeout; @@ -339,12 +337,12 @@ public void testExternalDmlAuditUsesFinalCumulativeStatistics() { } Mockito.verify(processor).handleAuditEvent(event); - Assert.assertEquals(100, event.scanRows); - Assert.assertEquals(110, event.scanBytes); - Assert.assertEquals(120, event.scanBytesFromLocalStorage); - Assert.assertEquals(130, event.scanBytesFromRemoteStorage); - Assert.assertEquals(20, event.cpuTimeMs); - Assert.assertEquals(30, event.peakMemoryBytes); + Assertions.assertEquals(100, event.scanRows); + Assertions.assertEquals(110, event.scanBytes); + Assertions.assertEquals(120, event.scanBytesFromLocalStorage); + Assertions.assertEquals(130, event.scanBytesFromRemoteStorage); + Assertions.assertEquals(20, event.cpuTimeMs); + Assertions.assertEquals(30, event.peakMemoryBytes); } finally { Config.query_audit_log_timeout_ms = originalAuditTimeout; } @@ -360,8 +358,8 @@ public void testRegularAuditKeepsExistingTimeoutBehavior() { event.pushToAuditLogQueueTime = System.currentTimeMillis() - 20; List events = Deencapsulation.invoke(mgr, "getQueryNeedAudit"); - Assert.assertEquals(1, events.size()); - Assert.assertSame(event, events.get(0)); + Assertions.assertEquals(1, events.size()); + Assertions.assertSame(event, events.get(0)); } finally { Config.query_audit_log_timeout_ms = originalAuditTimeout; } @@ -381,8 +379,8 @@ public void testAuditScanDoesNotAssumeWallClockInsertionOrder() { List events = Deencapsulation.invoke(mgr, "getQueryNeedAudit"); - Assert.assertEquals(1, events.size()); - Assert.assertSame(dueEvent, events.get(0)); + Assertions.assertEquals(1, events.size()); + Assertions.assertSame(dueEvent, events.get(0)); } finally { Config.query_audit_log_timeout_ms = originalAuditTimeout; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadSchedPolicyMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadSchedPolicyMgrTest.java index 7d68d77f276ba7..aa6693bc70ae7f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadSchedPolicyMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/resource/workloadschedpolicy/WorkloadSchedPolicyMgrTest.java @@ -23,10 +23,10 @@ import org.apache.doris.persist.EditLog; import org.apache.doris.thrift.TWorkloadMetricType; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -47,7 +47,7 @@ public class WorkloadSchedPolicyMgrTest { private String originCloudUniqueId; private WorkloadSchedPolicyMgr mgr; - @Before + @BeforeEach public void setUp() { originDeployMode = Config.deploy_mode; originCloudUniqueId = Config.cloud_unique_id; @@ -60,7 +60,7 @@ public void setUp() { Mockito.when(env.getEditLog()).thenReturn(editLog); } - @After + @AfterEach public void tearDown() { Config.deploy_mode = originDeployMode; Config.cloud_unique_id = originCloudUniqueId; @@ -88,7 +88,7 @@ public void testCheckPolicyCondition() { mgr.createWorkloadSchedPolicy("policy_mixed_be", false, conditionMetas, actionMetas, null); } catch (UserException e) { - Assert.fail("Should not throw exception for mixed USERNAME and BE metrics: " + e.getMessage()); + Assertions.fail("Should not throw exception for mixed USERNAME and BE metrics: " + e.getMessage()); } // Case 2: USERNAME (Shared) + BE Action -> OK @@ -101,7 +101,7 @@ public void testCheckPolicyCondition() { mgr.createWorkloadSchedPolicy("policy_username_be_action", false, conditionMetas, actionMetas, null); } catch (UserException e) { - Assert.fail("Should not throw exception for USERNAME + BE Action: " + e.getMessage()); + Assertions.fail("Should not throw exception for USERNAME + BE Action: " + e.getMessage()); } } @@ -109,9 +109,9 @@ public void testCheckPolicyCondition() { public void testSetSessionVariableActionIsRejected() { try { new WorkloadActionMeta("set_session_variable", "workload_group=normal"); - Assert.fail("Should throw exception for removed set_session_variable action"); + Assertions.fail("Should throw exception for removed set_session_variable action"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("invalid action type set_session_variable")); + Assertions.assertTrue(e.getMessage().contains("invalid action type set_session_variable")); } } @@ -129,7 +129,7 @@ public void testCheckProperties() throws UserException { props.put("enabled", "true"); mgr.createWorkloadSchedPolicy("policy_prop_valid", false, conditionMetas, actionMetas, props); } catch (UserException e) { - Assert.fail("Should not throw exception for valid properties: " + e.getMessage()); + Assertions.fail("Should not throw exception for valid properties: " + e.getMessage()); } // Test invalid priority. @@ -137,9 +137,9 @@ public void testCheckProperties() throws UserException { Map props = new HashMap<>(); props.put("priority", "101"); mgr.createWorkloadSchedPolicy("policy_prop_invalid_prio", false, conditionMetas, actionMetas, props); - Assert.fail("Should throw exception for invalid priority"); + Assertions.fail("Should throw exception for invalid priority"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("policy's priority can only between 0 ~ 100")); + Assertions.assertTrue(e.getMessage().contains("policy's priority can only between 0 ~ 100")); } // Test invalid enabled. @@ -147,9 +147,9 @@ public void testCheckProperties() throws UserException { Map props = new HashMap<>(); props.put("enabled", "yes"); mgr.createWorkloadSchedPolicy("policy_prop_invalid_enabled", false, conditionMetas, actionMetas, props); - Assert.fail("Should throw exception for invalid enabled"); + Assertions.fail("Should throw exception for invalid enabled"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("invalid enabled property value")); + Assertions.assertTrue(e.getMessage().contains("invalid enabled property value")); } } @@ -163,9 +163,9 @@ public void testUsernameConditionRejectsBlankValue() throws UserException { try { conditionMetas.add(new WorkloadConditionMeta("username", "=", "")); mgr.createWorkloadSchedPolicy("policy_empty_username", false, conditionMetas, actionMetas, null); - Assert.fail("Should throw exception for empty username"); + Assertions.fail("Should throw exception for empty username"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("username can not be empty")); + Assertions.assertTrue(e.getMessage().contains("username can not be empty")); } conditionMetas.clear(); @@ -174,39 +174,36 @@ public void testUsernameConditionRejectsBlankValue() throws UserException { try { conditionMetas.add(new WorkloadConditionMeta("username", "=", " ")); mgr.createWorkloadSchedPolicy("policy_blank_username", false, conditionMetas, actionMetas, null); - Assert.fail("Should throw exception for blank username"); + Assertions.fail("Should throw exception for blank username"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("username can not be empty")); + Assertions.assertTrue(e.getMessage().contains("username can not be empty")); } } @Test public void testCloudModeRejectsUnqualifiedWorkloadGroup() { Config.cloud_unique_id = "ut_cloud"; - Assert.assertTrue(Config.isCloudMode()); + Assertions.assertTrue(Config.isCloudMode()); try { mgr.checkProperties(propsWith("superset"), new ArrayList<>()); - Assert.fail("expected UserException for unqualified workload_group in cloud mode"); + Assertions.fail("expected UserException for unqualified workload_group in cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention .; got: " + e.getMessage(), - e.getMessage().contains(".")); - Assert.assertTrue("message should mention cloud mode; got: " + e.getMessage(), - e.getMessage().contains("cloud mode")); + Assertions.assertTrue(e.getMessage().contains("."), "message should mention .; got: " + e.getMessage()); + Assertions.assertTrue(e.getMessage().contains("cloud mode"), "message should mention cloud mode; got: " + e.getMessage()); } } @Test public void testCloudModeRejectsTooManyDotsInWorkloadGroup() { Config.cloud_unique_id = "ut_cloud"; - Assert.assertTrue(Config.isCloudMode()); + Assertions.assertTrue(Config.isCloudMode()); try { mgr.checkProperties(propsWith("etl.superset.extra"), new ArrayList<>()); - Assert.fail("expected UserException for over-qualified workload_group in cloud mode"); + Assertions.fail("expected UserException for over-qualified workload_group in cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention .; got: " + e.getMessage(), - e.getMessage().contains(".")); + Assertions.assertTrue(e.getMessage().contains("."), "message should mention .; got: " + e.getMessage()); } } @@ -217,23 +214,21 @@ public void testNonCloudModeRejectsTooManyDotsInWorkloadGroup() { // any lookup. Config.deploy_mode = "share_nothing"; Config.cloud_unique_id = ""; - Assert.assertFalse(Config.isCloudMode()); + Assertions.assertFalse(Config.isCloudMode()); try { mgr.checkProperties(propsWith("etl.superset.extra"), new ArrayList<>()); - Assert.fail("expected UserException for over-qualified workload_group in non-cloud mode"); + Assertions.fail("expected UserException for over-qualified workload_group in non-cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention the allowed forms; got: " + e.getMessage(), - e.getMessage().contains("")); - Assert.assertTrue("message should mention non-cloud mode; got: " + e.getMessage(), - e.getMessage().contains("non-cloud mode")); + Assertions.assertTrue(e.getMessage().contains(""), "message should mention the allowed forms; got: " + e.getMessage()); + Assertions.assertTrue(e.getMessage().contains("non-cloud mode"), "message should mention non-cloud mode; got: " + e.getMessage()); } } @Test public void testEmptyOrMissingWorkloadGroupPropertyIsAccepted() throws Exception { Config.cloud_unique_id = "ut_cloud"; - Assert.assertTrue(Config.isCloudMode()); + Assertions.assertTrue(Config.isCloudMode()); // Absent property is OK: the workload_group binding is simply not set. mgr.checkProperties(new HashMap<>(), new ArrayList<>()); @@ -245,32 +240,30 @@ public void testEmptyOrMissingWorkloadGroupPropertyIsAccepted() throws Exception @Test public void testCloudModeRejectsTrailingDotInWorkloadGroup() { Config.cloud_unique_id = "ut_cloud"; - Assert.assertTrue(Config.isCloudMode()); + Assertions.assertTrue(Config.isCloudMode()); // "etl." splits to ["etl", ""] under split(".", -1); the empty workload-group // segment must be rejected before reaching the compute-group lookup. try { mgr.checkProperties(propsWith("etl."), new ArrayList<>()); - Assert.fail("expected UserException for trailing-dot workload_group in cloud mode"); + Assertions.fail("expected UserException for trailing-dot workload_group in cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention .; got: " + e.getMessage(), - e.getMessage().contains(".")); + Assertions.assertTrue(e.getMessage().contains("."), "message should mention .; got: " + e.getMessage()); } } @Test public void testCloudModeRejectsLeadingDotInWorkloadGroup() { Config.cloud_unique_id = "ut_cloud"; - Assert.assertTrue(Config.isCloudMode()); + Assertions.assertTrue(Config.isCloudMode()); // ".superset" splits to ["", "superset"]; the empty compute-group segment must // be rejected rather than falling through with an empty cg name. try { mgr.checkProperties(propsWith(".superset"), new ArrayList<>()); - Assert.fail("expected UserException for leading-dot workload_group in cloud mode"); + Assertions.fail("expected UserException for leading-dot workload_group in cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention .; got: " + e.getMessage(), - e.getMessage().contains(".")); + Assertions.assertTrue(e.getMessage().contains("."), "message should mention .; got: " + e.getMessage()); } } @@ -278,19 +271,17 @@ public void testCloudModeRejectsLeadingDotInWorkloadGroup() { public void testNonCloudModeRejectsTrailingDotInWorkloadGroup() { Config.deploy_mode = "share_nothing"; Config.cloud_unique_id = ""; - Assert.assertFalse(Config.isCloudMode()); + Assertions.assertFalse(Config.isCloudMode()); // "wg." splits to ["wg", ""]; previously split("\\.") would drop the trailing // empty segment and let this pass. With split(..., -1) the empty workload-group // component is detected and rejected before lookup. try { mgr.checkProperties(propsWith("wg."), new ArrayList<>()); - Assert.fail("expected UserException for trailing-dot workload_group in non-cloud mode"); + Assertions.fail("expected UserException for trailing-dot workload_group in non-cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention the allowed forms; got: " + e.getMessage(), - e.getMessage().contains("")); - Assert.assertTrue("message should mention non-cloud mode; got: " + e.getMessage(), - e.getMessage().contains("non-cloud mode")); + Assertions.assertTrue(e.getMessage().contains(""), "message should mention the allowed forms; got: " + e.getMessage()); + Assertions.assertTrue(e.getMessage().contains("non-cloud mode"), "message should mention non-cloud mode; got: " + e.getMessage()); } } @@ -298,18 +289,16 @@ public void testNonCloudModeRejectsTrailingDotInWorkloadGroup() { public void testNonCloudModeRejectsLeadingDotInWorkloadGroup() { Config.deploy_mode = "share_nothing"; Config.cloud_unique_id = ""; - Assert.assertFalse(Config.isCloudMode()); + Assertions.assertFalse(Config.isCloudMode()); // ".wg" splits to ["", "wg"]; the empty resource-group component must be // rejected rather than falling through with an empty cg name. try { mgr.checkProperties(propsWith(".wg"), new ArrayList<>()); - Assert.fail("expected UserException for leading-dot workload_group in non-cloud mode"); + Assertions.fail("expected UserException for leading-dot workload_group in non-cloud mode"); } catch (UserException e) { - Assert.assertTrue("message should mention the allowed forms; got: " + e.getMessage(), - e.getMessage().contains("")); - Assert.assertTrue("message should mention non-cloud mode; got: " + e.getMessage(), - e.getMessage().contains("non-cloud mode")); + Assertions.assertTrue(e.getMessage().contains(""), "message should mention the allowed forms; got: " + e.getMessage()); + Assertions.assertTrue(e.getMessage().contains("non-cloud mode"), "message should mention non-cloud mode; got: " + e.getMessage()); } } @@ -323,9 +312,9 @@ public void testRemoteScanBytesMetricCanCreateBePolicy() throws UserException { mgr.createWorkloadSchedPolicy("policy_remote_scan_bytes", false, conditionMetas, actionMetas, null); - Assert.assertTrue(WorkloadSchedPolicyMgr.BE_METRIC_SET.contains( + Assertions.assertTrue(WorkloadSchedPolicyMgr.BE_METRIC_SET.contains( WorkloadMetricType.BE_SCAN_BYTES_FROM_REMOTE_STORAGE)); - Assert.assertEquals(TWorkloadMetricType.BE_SCAN_BYTES_FROM_REMOTE_STORAGE, + Assertions.assertEquals(TWorkloadMetricType.BE_SCAN_BYTES_FROM_REMOTE_STORAGE, WorkloadSchedPolicyMgr.METRIC_MAP.get(WorkloadMetricType.BE_SCAN_BYTES_FROM_REMOTE_STORAGE)); } @@ -335,9 +324,9 @@ public void testRemoteScanBytesMetricRejectsNegativeValue() throws UserException // Reject negative thresholds for the remote scan bytes breaker. WorkloadCondition.createWorkloadCondition( new WorkloadConditionMeta("be_scan_bytes_from_remote_storage", ">", "-1")); - Assert.fail("Should throw exception for negative remote scan bytes value"); + Assertions.fail("Should throw exception for negative remote scan bytes value"); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("remote scan bytes")); + Assertions.assertTrue(e.getMessage().contains("remote scan bytes")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceClientTest.java b/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceClientTest.java index 8a16137f7713b7..21e90e77642b70 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceClientTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceClientTest.java @@ -26,10 +26,10 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.grpc.ManagedChannel; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.concurrent.ExecutorService; @@ -45,7 +45,7 @@ public class BackendServiceClientTest { private int originalGrpcMaxMessageSize; private long originalRemoteFragmentExecTimeout; - @Before + @BeforeEach public void setUp() { // Create executor for tests executor = Executors.newCachedThreadPool(); @@ -61,7 +61,7 @@ public void setUp() { Config.remote_fragment_exec_timeout_ms = 5000; } - @After + @AfterEach public void tearDown() { // Restore original config Config.grpc_keep_alive_second = originalGrpcKeepAliveSeconds; @@ -89,15 +89,15 @@ public void testClientUsesResolvedIp() { BackendServiceClient client = new BackendServiceClient(address, resolvedIp, executor); // Verify client was created - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify the address is stored TNetworkAddress storedAddress = Deencapsulation.getField(client, "address"); - Assert.assertEquals(address, storedAddress); + Assertions.assertEquals(address, storedAddress); // Verify the channel was created (non-null) ManagedChannel channel = Deencapsulation.getField(client, "channel"); - Assert.assertNotNull(channel); + Assertions.assertNotNull(channel); // Note: We cannot easily verify that the channel uses the IP instead of hostname // without inspecting the channel's internal state, which is implementation-dependent. @@ -122,11 +122,11 @@ public void testClientFallsBackToHostnameWhenIpIsEmpty() { BackendServiceClient client = new BackendServiceClient(address, emptyIp, executor); // Verify client was created - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify channel was created ManagedChannel channel = Deencapsulation.getField(client, "channel"); - Assert.assertNotNull(channel); + Assertions.assertNotNull(channel); // Cleanup client.shutdown(); @@ -147,11 +147,11 @@ public void testClientFallsBackToHostnameWhenIpIsNull() { BackendServiceClient client = new BackendServiceClient(address, nullIp, executor); // Verify client was created - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify channel was created ManagedChannel channel = Deencapsulation.getField(client, "channel"); - Assert.assertNotNull(channel); + Assertions.assertNotNull(channel); // Cleanup client.shutdown(); @@ -174,8 +174,7 @@ public void testIsNormalState() { // Verify client is in normal state initially // (IDLE or CONNECTING state is considered normal) - Assert.assertTrue("Client should be in normal state after creation", - client.isNormalState()); + Assertions.assertTrue(client.isNormalState(), "Client should be in normal state after creation"); // Cleanup client.shutdown(); @@ -200,7 +199,7 @@ public void testShutdown() throws InterruptedException { // Verify channel is not shutdown initially ManagedChannel channel = Deencapsulation.getField(client, "channel"); - Assert.assertFalse("Channel should not be shutdown initially", channel.isShutdown()); + Assertions.assertFalse(channel.isShutdown(), "Channel should not be shutdown initially"); // Shutdown client client.shutdown(); @@ -209,8 +208,7 @@ public void testShutdown() throws InterruptedException { Thread.sleep(100); // Verify channel is shutdown or terminated - Assert.assertTrue("Channel should be shutdown or terminated", - channel.isShutdown() || channel.isTerminated()); + Assertions.assertTrue(channel.isShutdown() || channel.isTerminated(), "Channel should be shutdown or terminated"); } /** @@ -224,10 +222,10 @@ public void testMultipleClients() { BackendServiceClient client1 = new BackendServiceClient(address1, "127.0.0.1", executor); BackendServiceClient client2 = new BackendServiceClient(address2, "127.0.0.1", executor); - Assert.assertNotNull(client1); - Assert.assertNotNull(client2); - Assert.assertTrue(client1.isNormalState()); - Assert.assertTrue(client2.isNormalState()); + Assertions.assertNotNull(client1); + Assertions.assertNotNull(client2); + Assertions.assertTrue(client1.isNormalState()); + Assertions.assertTrue(client2.isNormalState()); // Cleanup client1.shutdown(); @@ -254,7 +252,7 @@ public void testSyncTabletMeta() { ListenableFuture actualFuture = client.syncTabletMeta(request); - Assert.assertSame(expectedFuture, actualFuture); + Assertions.assertSame(expectedFuture, actualFuture); Mockito.verify(stub).syncTabletMeta(request); client.shutdown(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceProxyTest.java b/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceProxyTest.java index 427ff4570341f4..58f2261b452b5f 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceProxyTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/rpc/BackendServiceProxyTest.java @@ -26,10 +26,10 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -49,7 +49,7 @@ public class BackendServiceProxyTest { private boolean originalFqdnMode; private int originalProxyNum; - @Before + @BeforeEach public void setUp() { // Save original config values originalFqdnMode = Config.enable_fqdn_mode; @@ -74,7 +74,7 @@ public void setUp() { proxy = new BackendServiceProxy(); } - @After + @AfterEach public void tearDown() { // Restore original config Config.enable_fqdn_mode = originalFqdnMode; @@ -105,15 +105,15 @@ public void testGetProxyWithValidIp() throws Exception { BackendServiceClient client = Deencapsulation.invoke(proxy, "getProxy", address); // Verify client was created - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify DNS cache was called Mockito.verify(mockDnsCache, Mockito.times(1)).get(hostname); // Verify the client is stored in serviceMap Map serviceMap = Deencapsulation.getField(proxy, "serviceMap"); - Assert.assertEquals(1, serviceMap.size()); - Assert.assertTrue(serviceMap.containsKey(address)); + Assertions.assertEquals(1, serviceMap.size()); + Assertions.assertTrue(serviceMap.containsKey(address)); } /** @@ -133,13 +133,11 @@ public void testGetProxyWithDnsResolutionFailure() { // Should throw UnknownHostException try { Deencapsulation.invoke(proxy, "getProxy", address); - Assert.fail("Expected UnknownHostException to be thrown"); + Assertions.fail("Expected UnknownHostException to be thrown"); } catch (Exception e) { - Assert.assertTrue("Expected UnknownHostException", e instanceof UnknownHostException); - Assert.assertTrue("Exception message should contain hostname", - e.getMessage().contains(hostname)); - Assert.assertTrue("Exception message should mention DNS cache", - e.getMessage().contains("DNS cache returned empty IP address")); + Assertions.assertTrue(e instanceof UnknownHostException, "Expected UnknownHostException"); + Assertions.assertTrue(e.getMessage().contains(hostname), "Exception message should contain hostname"); + Assertions.assertTrue(e.getMessage().contains("DNS cache returned empty IP address"), "Exception message should mention DNS cache"); } // Verify DNS cache was called @@ -166,7 +164,7 @@ public void testGetProxyWithDnsFailureAndFqdnModeDisabled() throws Exception { BackendServiceClient client = Deencapsulation.invoke(proxy, "getProxy", address); // Verify client was created - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify DNS cache was called Mockito.verify(mockDnsCache, Mockito.times(1)).get(hostname); @@ -188,24 +186,24 @@ public void testGetProxyWithIpChange() throws Exception { // First call - create client with old IP Mockito.when(mockDnsCache.get(hostname)).thenReturn(oldIp); BackendServiceClient client1 = Deencapsulation.invoke(proxy, "getProxy", address); - Assert.assertNotNull(client1); + Assertions.assertNotNull(client1); // Verify serviceMap contains the client Map serviceMap = Deencapsulation.getField(proxy, "serviceMap"); - Assert.assertEquals(1, serviceMap.size()); + Assertions.assertEquals(1, serviceMap.size()); // Second call - IP changed Mockito.when(mockDnsCache.get(hostname)).thenReturn(newIp); BackendServiceClient client2 = Deencapsulation.invoke(proxy, "getProxy", address); // Verify a new client was created - Assert.assertNotNull(client2); + Assertions.assertNotNull(client2); // Verify DNS cache was called twice Mockito.verify(mockDnsCache, Mockito.times(2)).get(hostname); // Verify serviceMap still has one entry but with new client - Assert.assertEquals(1, serviceMap.size()); + Assertions.assertEquals(1, serviceMap.size()); // Note: We cannot easily verify client1.shutdown() was called because // the client is created as a real object, not a mock. In a real test @@ -229,13 +227,13 @@ public void testGetProxyReusesClientWithSameIp() throws Exception { // First call BackendServiceClient client1 = Deencapsulation.invoke(proxy, "getProxy", address); - Assert.assertNotNull(client1); + Assertions.assertNotNull(client1); // Second call with same IP BackendServiceClient client2 = Deencapsulation.invoke(proxy, "getProxy", address); // Should reuse the same client - Assert.assertSame("Client should be reused when IP hasn't changed", client1, client2); + Assertions.assertSame(client1, client2, "Client should be reused when IP hasn't changed"); // DNS cache should be called twice (once per getProxy call) Mockito.verify(mockDnsCache, Mockito.times(2)).get(hostname); @@ -257,17 +255,17 @@ public void testRemoveProxy() throws Exception { // Create client BackendServiceClient client = Deencapsulation.invoke(proxy, "getProxy", address); - Assert.assertNotNull(client); + Assertions.assertNotNull(client); // Verify serviceMap contains the client Map serviceMap = Deencapsulation.getField(proxy, "serviceMap"); - Assert.assertEquals(1, serviceMap.size()); + Assertions.assertEquals(1, serviceMap.size()); // Remove proxy proxy.removeProxy(address); // Verify serviceMap is now empty - Assert.assertEquals(0, serviceMap.size()); + Assertions.assertEquals(0, serviceMap.size()); // Note: In a real test, you would verify client.shutdown() was called // This would require mocking the client creation process @@ -295,14 +293,14 @@ public void testMultipleBackends() throws Exception { BackendServiceClient client1 = Deencapsulation.invoke(proxy, "getProxy", address1); BackendServiceClient client2 = Deencapsulation.invoke(proxy, "getProxy", address2); - Assert.assertNotNull(client1); - Assert.assertNotNull(client2); + Assertions.assertNotNull(client1); + Assertions.assertNotNull(client2); // Verify serviceMap contains both clients Map serviceMap = Deencapsulation.getField(proxy, "serviceMap"); - Assert.assertEquals(2, serviceMap.size()); - Assert.assertTrue(serviceMap.containsKey(address1)); - Assert.assertTrue(serviceMap.containsKey(address2)); + Assertions.assertEquals(2, serviceMap.size()); + Assertions.assertTrue(serviceMap.containsKey(address1)); + Assertions.assertTrue(serviceMap.containsKey(address2)); } @Test @@ -330,7 +328,7 @@ public void testSyncTabletMeta() throws Exception { ListenableFuture actualFuture = proxy.syncTabletMeta(address, request); - Assert.assertSame(expectedFuture, actualFuture); + Assertions.assertSame(expectedFuture, actualFuture); Mockito.verify(client).syncTabletMeta(request); } @@ -343,8 +341,8 @@ public void testSyncTabletMetaThrowsRpcException() { .build(); Mockito.when(mockDnsCache.get(hostname)).thenReturn(""); - RpcException exception = Assert.assertThrows(RpcException.class, () -> proxy.syncTabletMeta(address, request)); - Assert.assertTrue(exception.getMessage().contains(hostname)); + RpcException exception = Assertions.assertThrows(RpcException.class, () -> proxy.syncTabletMeta(address, request)); + Assertions.assertTrue(exception.getMessage().contains(hostname)); } private Object newBackendServiceClientExtIp(String realIp, BackendServiceClient client) throws Exception { diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/ExecuteEnvTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/ExecuteEnvTest.java index 3c2370dd888576..07d317ee69b26f 100755 --- a/fe/fe-core/src/test/java/org/apache/doris/service/ExecuteEnvTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/ExecuteEnvTest.java @@ -17,8 +17,8 @@ package org.apache.doris.service; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; @@ -44,7 +44,7 @@ public void testGetInstance() { } } for (int i = 1; i < threadMaxNum; i++) { - Assert.assertEquals(oids[i - 1], oids[i]); + Assertions.assertEquals(oids[i - 1], oids[i]); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendOptionsTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendOptionsTest.java index 7a46084477c538..dcb332d00379c7 100755 --- a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendOptionsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendOptionsTest.java @@ -20,10 +20,10 @@ import org.apache.doris.common.AnalysisException; import com.google.common.net.InetAddresses; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -32,14 +32,14 @@ public class FrontendOptionsTest { private MockedStatic mockedInetAddresses; - @Before + @BeforeEach public void setUp() throws NoSuchMethodException, SecurityException, AnalysisException { mockedInetAddresses = Mockito.mockStatic(InetAddresses.class, Mockito.CALLS_REAL_METHODS); mockedInetAddresses.when(() -> InetAddresses.toAddrString(Mockito.nullable(InetAddress.class))) .thenReturn("2408:400a:5a:ea00:2fb5:112e:39dd:9bba%eth0"); } - @After + @AfterEach public void tearDown() { if (mockedInetAddresses != null) { mockedInetAddresses.close(); @@ -49,6 +49,6 @@ public void tearDown() { @Test public void testGetIpByLocalAddr() { String ip = FrontendOptions.getIpByLocalAddr(null); - Assert.assertEquals("2408:400a:5a:ea00:2fb5:112e:39dd:9bba", ip); + Assertions.assertEquals("2408:400a:5a:ea00:2fb5:112e:39dd:9bba", ip); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplBackendSelectionTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplBackendSelectionTest.java index 8dfdb6aab6acb4..544082e8358f8e 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplBackendSelectionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplBackendSelectionTest.java @@ -28,9 +28,9 @@ import org.apache.doris.thrift.TMasterOpResult; import org.apache.logging.log4j.Level; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -38,7 +38,7 @@ public class FrontendServiceImplBackendSelectionTest { - @After + @AfterEach public void resetBackendSelectionProvider() { BackendSelectionManager.resetProviderForTest(); } @@ -50,8 +50,8 @@ public void testUnsetForwardedGroupCommitSelectionDoesNotResolveDecision() { BackendSelectionManager.setProviderForTest(policy); - Assert.assertNull(FrontendServiceImpl.forwardedGroupCommitLoadSelectionHint(info)); - Assert.assertEquals(0, policy.forwardedLoadSelectionHintCalls); + Assertions.assertNull(FrontendServiceImpl.forwardedGroupCommitLoadSelectionHint(info)); + Assertions.assertEquals(0, policy.forwardedLoadSelectionHintCalls); } @Test @@ -63,10 +63,10 @@ public void testForwardedGroupCommitSelectionUsesSetFields() { BackendSelectionManager.setProviderForTest(policy); - Assert.assertSame(policy.decision, FrontendServiceImpl.forwardedGroupCommitLoadSelectionHint(info)); - Assert.assertEquals(1, policy.forwardedLoadSelectionHintCalls); - Assert.assertEquals("key_a", policy.preferredKey); - Assert.assertEquals(BackendSelection.Mode.PREFER.name(), policy.mode); + Assertions.assertSame(policy.decision, FrontendServiceImpl.forwardedGroupCommitLoadSelectionHint(info)); + Assertions.assertEquals(1, policy.forwardedLoadSelectionHintCalls); + Assertions.assertEquals("key_a", policy.preferredKey); + Assertions.assertEquals(BackendSelection.Mode.PREFER.name(), policy.mode); } @Test @@ -88,9 +88,9 @@ public void testGroupCommitLoadBackendSelectionFailureLogsWarn() throws Exceptio TMasterOpResult result = invokeHandleGroupCommitLoadBeId(service, info); - Assert.assertEquals(1, result.getStatusCode()); - Assert.assertTrue(result.getErrMessage().contains("no backend")); - Assert.assertTrue(appender.contains(Level.WARN, + Assertions.assertEquals(1, result.getStatusCode()); + Assertions.assertTrue(result.getErrMessage().contains("no backend")); + Assertions.assertTrue(appender.contains(Level.WARN, "failed to select backend for forwarded group commit load, tableId=10, cluster=cluster_a")); } } @@ -112,10 +112,10 @@ public void testGroupCommitLoadBackendSelectionFailureThrowsForOldFollower() thr try { invokeHandleGroupCommitLoadBeId(service, info); - Assert.fail("expected TException for a follower without supportsSelectionErrorResult"); + Assertions.fail("expected TException for a follower without supportsSelectionErrorResult"); } catch (java.lang.reflect.InvocationTargetException e) { - Assert.assertTrue(e.getCause() instanceof org.apache.thrift.TException); - Assert.assertTrue(e.getCause().getMessage().contains("no backend")); + Assertions.assertTrue(e.getCause() instanceof org.apache.thrift.TException); + Assertions.assertTrue(e.getCause().getMessage().contains("no backend")); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplCloudTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplCloudTest.java index a5a28080315ca9..ef0cd3e7be47d1 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplCloudTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/FrontendServiceImplCloudTest.java @@ -25,8 +25,8 @@ import org.apache.doris.thrift.TGetTabletReplicaInfosResult; import org.apache.doris.thrift.TStatusCode; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -68,9 +68,8 @@ public void testGetTabletReplicaInfosNullJobReturnsCancelledWithoutNpe() { + "warm-up job has been removed from CacheHotspotManager", e); } - Assert.assertNotNull("result.status must be set", result.getStatus()); - Assert.assertEquals("BE must be told to cancel its stale warm-up job entry", - TStatusCode.CANCELLED, result.getStatus().getStatusCode()); + Assertions.assertNotNull(result.getStatus(), "result.status must be set"); + Assertions.assertEquals(TStatusCode.CANCELLED, result.getStatus().getStatusCode(), "BE must be told to cancel its stale warm-up job entry"); } finally { Config.cloud_unique_id = originalCloudUniqueId; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/DorisFlightSqlProducerTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/DorisFlightSqlProducerTest.java index eede12688517be..1879766fecd47a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/DorisFlightSqlProducerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/DorisFlightSqlProducerTest.java @@ -31,10 +31,10 @@ import org.apache.arrow.flight.Result; import org.apache.arrow.flight.sql.impl.FlightSql.ActionCreatePreparedStatementRequest; import org.apache.arrow.flight.sql.impl.FlightSql.CommandStatementQuery; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; import org.mockito.Mockito; @@ -46,7 +46,7 @@ public class DorisFlightSqlProducerTest { private boolean prevRunningUnitTest; - @Before + @BeforeEach public void setUp() { // FlightSqlConnectContext.init() only reaches Env when this is false; keep it true so the // context can be built without a running FE. @@ -54,7 +54,7 @@ public void setUp() { FeConstants.runningUnitTest = true; } - @After + @AfterEach public void tearDown() { FeConstants.runningUnitTest = prevRunningUnitTest; } @@ -79,7 +79,7 @@ public void createPreparedStatementDoesNotLeakChannelAllocator() throws Exceptio // so allocator bookkeeping is exercised for real instead of mocked away. FlightSqlConnectContext connectContext = new FlightSqlConnectContext("test-peer-identity"); FlightSqlChannel channel = connectContext.getFlightSqlChannel(); - Assert.assertEquals("channel allocator should start empty", 0L, channel.getAllocatedMemory()); + Assertions.assertEquals(0L, channel.getAllocatedMemory(), "channel allocator should start empty"); FlightSessionsManager sessionsManager = new FlightSessionsManager() { @Override @@ -131,17 +131,15 @@ public void onCompleted() { ActionCreatePreparedStatementRequest request = ActionCreatePreparedStatementRequest.newBuilder() .setQuery("select * from t where id = " + i).build(); producer.createPreparedStatement(request, callContext, listener); - Assert.assertTrue("createPreparedStatement #" + i + " did not finish in time", - finished.await(30, TimeUnit.SECONDS)); + Assertions.assertTrue(finished.await(30, TimeUnit.SECONDS), "createPreparedStatement #" + i + " did not finish in time"); } // Guard against a false pass: if a prepare failed before reaching the allocation, no buffer // would be leaked and the memory assertion below could not detect a regression. - Assert.assertEquals("no createPreparedStatement call should fail", 0, errors.get()); + Assertions.assertEquals(0, errors.get(), "no createPreparedStatement call should fail"); // Every temporary VectorSchemaRoot must have been closed, so the channel's Arrow allocator // is back to zero. Reverting the fix leaves `rounds` ResultMeta buffers allocated here. - Assert.assertEquals("createPreparedStatement leaked off-heap memory in the channel allocator", - 0L, channel.getAllocatedMemory()); + Assertions.assertEquals(0L, channel.getAllocatedMemory(), "createPreparedStatement leaked off-heap memory in the channel allocator"); } finally { producer.close(); } @@ -189,7 +187,7 @@ public void testGetFlightInfoFinalizesDeferredExecutorWhenSchemaFetchFails() thr try { producer.getFlightInfoStatement(request, callContext, descriptor); - Assert.fail("expected the schema fetch failure to propagate as a CallStatus"); + Assertions.fail("expected the schema fetch failure to propagate as a CallStatus"); } catch (Throwable expected) { // GetFlightInfo is expected to fail; the point of the test is what happens to the // deferred coordinator, not the thrown status itself. diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/auth2/FlightRemoteIpServerStreamTracerTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/auth2/FlightRemoteIpServerStreamTracerTest.java index 250cd9f26ecb06..76ded9f63017f6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/auth2/FlightRemoteIpServerStreamTracerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/auth2/FlightRemoteIpServerStreamTracerTest.java @@ -22,8 +22,8 @@ import io.grpc.Grpc; import io.grpc.MethodDescriptor; import io.grpc.ServerStreamTracer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.net.SocketAddress; @@ -38,7 +38,7 @@ public void testGetRemoteIpFromServerCallAttributes() { try { tracer.serverCallStarted(new TestServerCallInfo(new InetSocketAddress("10.26.20.3", 12345))); - Assert.assertEquals("10.26.20.3", FlightRemoteIpServerStreamTracer.getRemoteIp()); + Assertions.assertEquals("10.26.20.3", FlightRemoteIpServerStreamTracer.getRemoteIp()); } finally { context.detach(previous); } @@ -52,7 +52,7 @@ public void testFallbackRemoteIpWithoutServerCallAttributes() { try { tracer.serverCallStarted(new TestServerCallInfo(null)); - Assert.assertEquals("0.0.0.0", FlightRemoteIpServerStreamTracer.getRemoteIp()); + Assertions.assertEquals("0.0.0.0", FlightRemoteIpServerStreamTracer.getRemoteIp()); } finally { context.detach(previous); } @@ -60,7 +60,7 @@ public void testFallbackRemoteIpWithoutServerCallAttributes() { @Test public void testFallbackRemoteIpWithoutFlightContext() { - Assert.assertEquals("0.0.0.0", FlightRemoteIpServerStreamTracer.getRemoteIp()); + Assertions.assertEquals("0.0.0.0", FlightRemoteIpServerStreamTracer.getRemoteIp()); } private static class TestServerCallInfo extends ServerStreamTracer.ServerCallInfo { diff --git a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/sessions/FlightSqlConnectPoolMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/sessions/FlightSqlConnectPoolMgrTest.java index 0513221569d9e7..d18de94becce76 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/sessions/FlightSqlConnectPoolMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/service/arrowflight/sessions/FlightSqlConnectPoolMgrTest.java @@ -20,8 +20,8 @@ import org.apache.doris.qe.ConnectContext; import org.apache.doris.service.arrowflight.results.FlightSqlChannel; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class FlightSqlConnectPoolMgrTest { @@ -64,6 +64,6 @@ public void testUnregisterRegisteredConnectionFinalizesDeferredExecutors() { Mockito.verify(channel).close(); Mockito.verify(ctx).closeFlightSqlDeferredExecutors(); - Assert.assertNull(poolMgr.getConnectionMap().get(7)); + Assertions.assertNull(poolMgr.getConnectionMap().get(7)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/statistics/HistogramTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/statistics/HistogramTaskTest.java index d0d2e309cc8699..301e9e2d9b8390 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/statistics/HistogramTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/statistics/HistogramTaskTest.java @@ -32,10 +32,10 @@ import org.apache.doris.statistics.util.StatisticsUtil; import org.apache.doris.utframe.TestWithFeService; -import org.junit.FixMethodOrder; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -44,7 +44,7 @@ import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; -@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodOrderer.MethodName.class) public class HistogramTaskTest extends TestWithFeService { @Override diff --git a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/Hll128Test.java b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/Hll128Test.java index d692b90ce3171b..595b2fcb384dc9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/Hll128Test.java +++ b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/Hll128Test.java @@ -20,8 +20,8 @@ import org.apache.doris.common.io.Hll; import org.apache.commons.codec.binary.StringUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -31,16 +31,16 @@ public class Hll128Test { public void basicTest() { // test empty Hll128 emptyHll = new Hll128(); - Assert.assertEquals(Hll128.HLL_DATA_EMPTY, emptyHll.getType()); - Assert.assertEquals(0, emptyHll.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EMPTY, emptyHll.getType()); + Assertions.assertEquals(0, emptyHll.estimateCardinality()); // test explicit Hll128 explicitHll = new Hll128(); for (int i = 0; i < Hll.HLL_EXPLICIT_INT64_NUM; i++) { explicitHll.update(i); } - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicitHll.getType()); - Assert.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM, explicitHll.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicitHll.getType()); + Assertions.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM, explicitHll.estimateCardinality()); // test full Hll128 fullHll = new Hll128(); @@ -48,9 +48,9 @@ public void basicTest() { byte[] v = StringUtils.getBytesUtf8(String.valueOf(i)); fullHll.update(Hll.hash64(v, v.length, Hll.SEED)); } - Assert.assertEquals(Hll.HLL_DATA_FULL, fullHll.getType()); - Assert.assertEquals(33141, fullHll.estimateCardinality()); - Assert.assertTrue(fullHll.estimateCardinality() > Short.MAX_VALUE * (1 - 0.1) + Assertions.assertEquals(Hll.HLL_DATA_FULL, fullHll.getType()); + Assertions.assertEquals(33141, fullHll.estimateCardinality()); + Assertions.assertTrue(fullHll.estimateCardinality() > Short.MAX_VALUE * (1 - 0.1) && fullHll.estimateCardinality() < Short.MAX_VALUE * (1 + 0.1)); } @@ -60,8 +60,8 @@ public void testFromHll() throws IOException { // test empty Hll emptyHll = new Hll(); Hll128 hll128 = Hll128.fromHll(emptyHll); - Assert.assertEquals(Hll128.HLL_DATA_EMPTY, hll128.getType()); - Assert.assertEquals(0, hll128.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EMPTY, hll128.getType()); + Assertions.assertEquals(0, hll128.estimateCardinality()); // test explicit Hll explicitHll = new Hll(); @@ -69,8 +69,8 @@ public void testFromHll() throws IOException { explicitHll.updateWithHash(i); } hll128 = Hll128.fromHll(explicitHll); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, hll128.getType()); - Assert.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM, hll128.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, hll128.getType()); + Assertions.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM, hll128.estimateCardinality()); // test full Hll fullHll = new Hll(); @@ -78,8 +78,8 @@ public void testFromHll() throws IOException { fullHll.updateWithHash(i); } hll128 = Hll128.fromHll(fullHll); - Assert.assertEquals(Hll128.HLL_DATA_FULL, hll128.getType()); - Assert.assertTrue(hll128.estimateCardinality() > 9000 && hll128.estimateCardinality() < 11000); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, hll128.getType()); + Assertions.assertTrue(hll128.estimateCardinality() > 9000 && hll128.estimateCardinality() < 11000); } @Test @@ -88,8 +88,8 @@ public void testMerge() throws IOException { Hll128 empty1 = new Hll128(); Hll128 empty2 = new Hll128(); empty1.merge(empty2); - Assert.assertEquals(Hll128.HLL_DATA_EMPTY, empty1.getType()); - Assert.assertEquals(0, empty1.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EMPTY, empty1.getType()); + Assertions.assertEquals(0, empty1.estimateCardinality()); // test empty merge explicit Hll128 empty = new Hll128(); @@ -99,8 +99,8 @@ public void testMerge() throws IOException { explicit.update(Hll.hash64(v, v.length, Hll.SEED)); } empty.merge(explicit); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, empty.getType()); - Assert.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM - 1, empty.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, empty.getType()); + Assertions.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM - 1, empty.estimateCardinality()); // test empty merge full empty = new Hll128(); @@ -110,8 +110,8 @@ public void testMerge() throws IOException { full.update(Hll.hash64(v, v.length, Hll.SEED)); } empty.merge(full); - Assert.assertEquals(Hll128.HLL_DATA_FULL, empty.getType()); - Assert.assertTrue(empty.estimateCardinality() > 9000 && empty.estimateCardinality() < 11000); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, empty.getType()); + Assertions.assertTrue(empty.estimateCardinality() > 9000 && empty.estimateCardinality() < 11000); // test explicit merge empty empty = new Hll128(); @@ -121,8 +121,8 @@ public void testMerge() throws IOException { explicit.update(Hll.hash64(v, v.length, Hll.SEED)); } explicit.merge(empty); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit.getType()); - Assert.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM - 1, explicit.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit.getType()); + Assertions.assertEquals(Hll.HLL_EXPLICIT_INT64_NUM - 1, explicit.estimateCardinality()); // test explicit merge explicit Hll128 explicit1 = new Hll128(); @@ -136,20 +136,20 @@ public void testMerge() throws IOException { explicit2.update(Hll.hash64(v, v.length, Hll.SEED)); } explicit1.merge(explicit2); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit1.getType()); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit2.getType()); - Assert.assertEquals(30, explicit1.estimateCardinality()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit1.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit2.getType()); + Assertions.assertEquals(30, explicit1.estimateCardinality()); explicit2 = new Hll128(); for (int i = 10001; i < 10000 + Hll.HLL_EXPLICIT_INT64_NUM; i++) { byte[] v = StringUtils.getBytesUtf8(String.valueOf(i)); explicit2.update(Hll.hash64(v, v.length, Hll.SEED)); } - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit1.getType()); - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit2.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit1.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit2.getType()); explicit1.merge(explicit2); - Assert.assertEquals(Hll128.HLL_DATA_FULL, explicit1.getType()); - Assert.assertTrue(explicit1.estimateCardinality() > 170 && explicit1.estimateCardinality() < 210); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, explicit1.getType()); + Assertions.assertTrue(explicit1.estimateCardinality() > 170 && explicit1.estimateCardinality() < 210); // Test explicit merge full explicit = new Hll128(); @@ -162,10 +162,10 @@ public void testMerge() throws IOException { byte[] v = StringUtils.getBytesUtf8(String.valueOf(i)); full.update(Hll.hash64(v, v.length, Hll.SEED)); } - Assert.assertEquals(Hll128.HLL_DATA_FULL, full.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, full.getType()); explicit.merge(full); - Assert.assertEquals(Hll128.HLL_DATA_FULL, explicit.getType()); - Assert.assertTrue(explicit.estimateCardinality() > 9000 && explicit.estimateCardinality() < 11000); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, explicit.getType()); + Assertions.assertTrue(explicit.estimateCardinality() > 9000 && explicit.estimateCardinality() < 11000); // Test full merge explicit explicit = new Hll128(); @@ -178,10 +178,10 @@ public void testMerge() throws IOException { byte[] v = StringUtils.getBytesUtf8(String.valueOf(i)); full.update(Hll.hash64(v, v.length, Hll.SEED)); } - Assert.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_EXPLICIT, explicit.getType()); full.merge(explicit); - Assert.assertEquals(Hll128.HLL_DATA_FULL, full.getType()); - Assert.assertTrue(full.estimateCardinality() > 9000 && full.estimateCardinality() < 11000); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, full.getType()); + Assertions.assertTrue(full.estimateCardinality() > 9000 && full.estimateCardinality() < 11000); // Test full merge full Hll128 full1 = new Hll128(); @@ -194,11 +194,11 @@ public void testMerge() throws IOException { byte[] v = StringUtils.getBytesUtf8(String.valueOf(i)); full2.update(Hll.hash64(v, v.length, Hll.SEED)); } - Assert.assertEquals(Hll128.HLL_DATA_FULL, full1.getType()); - Assert.assertEquals(Hll128.HLL_DATA_FULL, full2.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, full1.getType()); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, full2.getType()); full1.merge(full2); - Assert.assertEquals(Hll128.HLL_DATA_FULL, full1.getType()); - Assert.assertTrue(full1.estimateCardinality() > 13500 && full1.estimateCardinality() < 16500); + Assertions.assertEquals(Hll128.HLL_DATA_FULL, full1.getType()); + Assertions.assertTrue(full1.estimateCardinality() > 13500 && full1.estimateCardinality() < 16500); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalQueryBufferTest.java b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalQueryBufferTest.java index 3e27acca6baa37..89a776e8106dba 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalQueryBufferTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalQueryBufferTest.java @@ -17,16 +17,16 @@ package org.apache.doris.statistics.util; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; public class InternalQueryBufferTest { private InternalQueryBuffer internalQueryBuffer; - @Before + @BeforeEach public void setUp() throws Exception { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put((byte) 6); @@ -47,74 +47,74 @@ public void setUp() throws Exception { @Test public void testData() { byte[] result = internalQueryBuffer.data(); - Assert.assertEquals(1024, result.length); + Assertions.assertEquals(1024, result.length); } @Test public void testLength() { int result = internalQueryBuffer.length(); - Assert.assertEquals(1024, result); + Assertions.assertEquals(1024, result); } @Test public void testPosition() { int result = internalQueryBuffer.position(); // (1 + 6) + (1 + 3) + (1 + 3) + (1 + 7) - Assert.assertEquals(23, result); + Assertions.assertEquals(23, result); } @Test public void testReadBytesWithLength() { internalQueryBuffer.clear(); byte[] result1 = internalQueryBuffer.readBytesWithLength(); - Assert.assertArrayEquals("field1".getBytes(), result1); + Assertions.assertArrayEquals("field1".getBytes(), result1); byte[] result2 = internalQueryBuffer.readBytesWithLength(); - Assert.assertArrayEquals("123".getBytes(), result2); + Assertions.assertArrayEquals("123".getBytes(), result2); byte[] result3 = internalQueryBuffer.readBytesWithLength(); - Assert.assertArrayEquals("0.1".getBytes(), result3); + Assertions.assertArrayEquals("0.1".getBytes(), result3); } @Test public void testReadStringWithLength() { internalQueryBuffer.clear(); String result1 = internalQueryBuffer.readStringWithLength(); - Assert.assertEquals("field1", result1); + Assertions.assertEquals("field1", result1); String result2 = internalQueryBuffer.readStringWithLength(); - Assert.assertEquals("123", result2); + Assertions.assertEquals("123", result2); String result3 = internalQueryBuffer.readStringWithLength(); - Assert.assertEquals("0.1", result3); + Assertions.assertEquals("0.1", result3); } @Test public void testReadStringWithLengthByCharset() throws Exception { internalQueryBuffer.clear(); String result1 = internalQueryBuffer.readStringWithLength("UTF-8"); - Assert.assertEquals("field1", result1); + Assertions.assertEquals("field1", result1); String result2 = internalQueryBuffer.readStringWithLength("UTF-8"); - Assert.assertEquals("123", result2); + Assertions.assertEquals("123", result2); String result3 = internalQueryBuffer.readStringWithLength("UTF-8"); - Assert.assertEquals("0.1", result3); + Assertions.assertEquals("0.1", result3); } @Test public void testReadIntAndFloatAndDouble() { internalQueryBuffer.clear(); String result1 = internalQueryBuffer.readStringWithLength(); - Assert.assertEquals("field1", result1); + Assertions.assertEquals("field1", result1); int result2 = internalQueryBuffer.readInt(); - Assert.assertEquals(123, result2); + Assertions.assertEquals(123, result2); float result3 = internalQueryBuffer.readFloat(); - Assert.assertEquals(0.1, result3, 0.0001); + Assertions.assertEquals(0.1, result3, 0.0001); double result4 = internalQueryBuffer.readDouble(); - Assert.assertEquals(18.2322, result4, 0.0001); + Assertions.assertEquals(18.2322, result4, 0.0001); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalSqlTemplateTest.java b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalSqlTemplateTest.java index 5e7fa281dcb088..02a1f0905ab2a7 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalSqlTemplateTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/statistics/util/InternalSqlTemplateTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.InvalidFormatException; import org.apache.doris.statistics.util.InternalSqlTemplate.QueryType; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -43,7 +43,7 @@ public void testProcessTemplate() throws InvalidFormatException { String result = InternalSqlTemplate.processTemplate(template, params); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -55,7 +55,7 @@ public void testProcessTemplate_ThrowsInvalidFormatException() { params.put("table", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.processTemplate(template, params)); } @@ -73,7 +73,7 @@ public void testBuildStatsMinMaxNdvValueSql() throws Exception { String result = InternalSqlTemplate.buildStatsMinMaxNdvValueSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -91,7 +91,7 @@ public void testBuildStatsMinMaxNdvValueSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsMinMaxNdvValueSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -101,7 +101,7 @@ public void testBuildStatsMinMaxNdvValueSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsMinMaxNdvValueSql(params, QueryType.FULL)); } @@ -120,7 +120,7 @@ public void testBuildStatsPartitionMinMaxNdvValueSql() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionMinMaxNdvValueSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -139,7 +139,7 @@ public void testBuildStatsPartitionMinMaxNdvValueSqlBySample() throws Exception String result = InternalSqlTemplate.buildStatsPartitionMinMaxNdvValueSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -149,7 +149,7 @@ public void testBuildStatsPartitionMinMaxNdvValueSql_ThrowsInvalidFormatExceptio params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsPartitionMinMaxNdvValueSql(params, QueryType.FULL)); } @@ -165,7 +165,7 @@ public void testBuildStatsRowCountSql() throws Exception { String result = InternalSqlTemplate.buildStatsRowCountSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -181,7 +181,7 @@ public void testBuildStatsRowCountSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsRowCountSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -191,7 +191,7 @@ public void testBuildStatsRowCountSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsRowCountSql(params, QueryType.FULL)); } @@ -208,7 +208,7 @@ public void testBuildStatsPartitionRowCountSql() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionRowCountSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -226,7 +226,7 @@ public void testBuildStatsPartitionRowCountSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionRowCountSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -236,7 +236,7 @@ public void testBuildStatsPartitionRowCountSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsPartitionRowCountSql(params, QueryType.FULL)); } @@ -254,7 +254,7 @@ public void testBuildStatsMaxAvgSizeSql() throws Exception { String result = InternalSqlTemplate.buildStatsMaxAvgSizeSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -272,7 +272,7 @@ public void testBuildStatsMaxAvgSizeSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsMaxAvgSizeSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -282,7 +282,7 @@ public void testBuildStatsMaxAvgSizeSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsMaxAvgSizeSql(params, QueryType.FULL)); } @@ -301,7 +301,7 @@ public void testBuildStatsPartitionMaxAvgSizeSql() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionMaxAvgSizeSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -320,7 +320,7 @@ public void testBuildStatsPartitionMaxAvgSizeSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionMaxAvgSizeSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -330,7 +330,7 @@ public void testBuildStatsPartitionMaxAvgSizeSql_ThrowsInvalidFormatException() params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsPartitionMaxAvgSizeSql(params, QueryType.FULL)); } @@ -347,7 +347,7 @@ public void testBuildStatsNumNullsSql() throws Exception { String result = InternalSqlTemplate.buildStatsNumNullsSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -365,7 +365,7 @@ public void testBuildStatsNumNullsSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsNumNullsSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -375,7 +375,7 @@ public void testBuildStatsNumNullsSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsNumNullsSql(params, QueryType.FULL)); } @@ -394,7 +394,7 @@ public void testBuildStatsPartitionNumNullsSql() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionNumNullsSql(params, QueryType.FULL); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -413,7 +413,7 @@ public void testBuildStatsPartitionNumNullsSqlBySample() throws Exception { String result = InternalSqlTemplate.buildStatsPartitionNumNullsSql(params, QueryType.SAMPLE); // Verify the results - Assert.assertEquals(expectSQL, result); + Assertions.assertEquals(expectSQL, result); } @Test @@ -423,7 +423,7 @@ public void testBuildStatsPartitionNumNullsSql_ThrowsInvalidFormatException() { params.put("xxx", "table0"); // Run the test - Assert.assertThrows(InvalidFormatException.class, + Assertions.assertThrows(InvalidFormatException.class, () -> InternalSqlTemplate.buildStatsPartitionNumNullsSql(params, QueryType.FULL)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/system/HeartbeatMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/system/HeartbeatMgrTest.java index 8e9120ba276b4b..91b21bca6f04c8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/system/HeartbeatMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/system/HeartbeatMgrTest.java @@ -38,10 +38,10 @@ import org.apache.doris.thrift.TNetworkAddress; import org.apache.doris.thrift.TPaloBrokerService; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -53,7 +53,7 @@ public class HeartbeatMgrTest { private Env env = Mockito.mock(Env.class); private MockedStatic mockedEnvStatic; - @Before + @BeforeEach public void setUp() { mockedEnvStatic = Mockito.mockStatic(Env.class); mockedEnvStatic.when(Env::getCurrentEnv).thenReturn(env); @@ -61,7 +61,7 @@ public void setUp() { Mockito.when(env.isReady()).thenReturn(true); } - @After + @AfterEach public void tearDown() { if (mockedEnvStatic != null) { mockedEnvStatic.close(); @@ -101,27 +101,27 @@ public void testFrontendHbHandler() throws Exception { FrontendHeartbeatHandler handler = new FrontendHeartbeatHandler(fe, 12345, "abcd"); HeartbeatResponse response = handler.call(); - Assert.assertTrue(response instanceof FrontendHbResponse); + Assertions.assertTrue(response instanceof FrontendHbResponse); FrontendHbResponse hbResponse = (FrontendHbResponse) response; - Assert.assertEquals(191224, hbResponse.getReplayedJournalId()); - Assert.assertEquals(9131, hbResponse.getQueryPort()); - Assert.assertEquals(9121, hbResponse.getRpcPort()); - Assert.assertEquals(9141, hbResponse.getArrowFlightSqlPort()); - Assert.assertEquals(HbStatus.OK, hbResponse.getStatus()); - Assert.assertEquals("test", hbResponse.getVersion()); + Assertions.assertEquals(191224, hbResponse.getReplayedJournalId()); + Assertions.assertEquals(9131, hbResponse.getQueryPort()); + Assertions.assertEquals(9121, hbResponse.getRpcPort()); + Assertions.assertEquals(9141, hbResponse.getArrowFlightSqlPort()); + Assertions.assertEquals(HbStatus.OK, hbResponse.getStatus()); + Assertions.assertEquals("test", hbResponse.getVersion()); Frontend fe2 = new Frontend(FrontendNodeType.FOLLOWER, "test2", "192.168.1.2", 9010); handler = new FrontendHeartbeatHandler(fe2, 12345, "abcde"); response = handler.call(); - Assert.assertTrue(response instanceof FrontendHbResponse); + Assertions.assertTrue(response instanceof FrontendHbResponse); hbResponse = (FrontendHbResponse) response; - Assert.assertEquals(0, hbResponse.getReplayedJournalId()); - Assert.assertEquals(0, hbResponse.getQueryPort()); - Assert.assertEquals(0, hbResponse.getRpcPort()); - Assert.assertEquals(0, hbResponse.getArrowFlightSqlPort()); - Assert.assertEquals(HbStatus.BAD, hbResponse.getStatus()); - Assert.assertEquals("not ready", hbResponse.getMsg()); + Assertions.assertEquals(0, hbResponse.getReplayedJournalId()); + Assertions.assertEquals(0, hbResponse.getQueryPort()); + Assertions.assertEquals(0, hbResponse.getRpcPort()); + Assertions.assertEquals(0, hbResponse.getArrowFlightSqlPort()); + Assertions.assertEquals(HbStatus.BAD, hbResponse.getStatus()); + Assertions.assertEquals("not ready", hbResponse.getMsg()); } finally { ClientPool.frontendHeartbeatPool = originalPool; } @@ -146,13 +146,13 @@ public void testSetMasterHttpPort() throws Exception { mgr.setMaster(1, "token", 1L); AtomicReference masterInfo = (AtomicReference) masterInfoField.get(null); - Assert.assertEquals(8030, masterInfo.get().getHttpPort()); + Assertions.assertEquals(8030, masterInfo.get().getHttpPort()); // enable_https=true: must send https_port to BEs so small_file_mgr can connect Config.enable_https = true; mgr.setMaster(1, "token", 1L); masterInfo = (AtomicReference) masterInfoField.get(null); - Assert.assertEquals(8050, masterInfo.get().getHttpPort()); + Assertions.assertEquals(8050, masterInfo.get().getHttpPort()); } finally { Config.http_port = originalHttpPort; Config.https_port = originalHttpsPort; @@ -180,9 +180,9 @@ public void testBrokerHbHandler() throws Exception { BrokerHeartbeatHandler handler = new BrokerHeartbeatHandler("hdfs", broker, "abc"); HeartbeatResponse response = handler.call(); - Assert.assertTrue(response instanceof BrokerHbResponse); + Assertions.assertTrue(response instanceof BrokerHbResponse); BrokerHbResponse hbResponse = (BrokerHbResponse) response; - Assert.assertEquals(HbStatus.OK, hbResponse.getStatus()); + Assertions.assertEquals(HbStatus.OK, hbResponse.getStatus()); } finally { ClientPool.brokerPool = originalPool; } diff --git a/fe/fe-core/src/test/java/org/apache/doris/system/SystemInfoServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/system/SystemInfoServiceTest.java index f79a5a7020f9a9..045c6c60fcefd3 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/system/SystemInfoServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/system/SystemInfoServiceTest.java @@ -33,9 +33,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -53,7 +53,7 @@ public class SystemInfoServiceTest { private SystemInfoService infoService; - @Before + @BeforeEach public void setUp() { infoService = new SystemInfoService(); } @@ -70,23 +70,23 @@ public void testGetHostAndPort() { String ipv6Error = "fe80::5054:ff:fec9:dee0:9050"; try { HostInfo hostAndPort = SystemInfoService.getHostAndPort(ipv4); - Assert.assertEquals("192.168.1.2", hostAndPort.getHost()); - Assert.assertEquals(9050, hostAndPort.getPort()); + Assertions.assertEquals("192.168.1.2", hostAndPort.getHost()); + Assertions.assertEquals(9050, hostAndPort.getPort()); } catch (AnalysisException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } try { HostInfo hostAndPort = SystemInfoService.getHostAndPort(ipv6); - Assert.assertEquals("fe80::5054:ff:fec9:dee0", hostAndPort.getHost()); - Assert.assertEquals(9050, hostAndPort.getPort()); + Assertions.assertEquals("fe80::5054:ff:fec9:dee0", hostAndPort.getHost()); + Assertions.assertEquals(9050, hostAndPort.getPort()); } catch (AnalysisException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } try { SystemInfoService.getHostAndPort(ipv6Error); - Assert.fail(); + Assertions.fail(); } catch (AnalysisException e) { e.printStackTrace(); } @@ -113,18 +113,18 @@ public void testBackendHbResponseSerialization() throws IOException { dos.flush(); } catch (IOException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // Read objects from file try (DataInputStream dis = new DataInputStream(new FileInputStream(file1))) { BackendHbResponse readResponse = (BackendHbResponse) HeartbeatResponse.read(dis); // Before meta version 121, nodeRole will not be read, so readResponse is not equal to writeResponse - Assert.assertTrue(readResponse.toString().equals(writeResponse.toString())); - Assert.assertTrue(Tag.VALUE_COMPUTATION.equals(readResponse.getNodeRole())); + Assertions.assertTrue(readResponse.toString().equals(writeResponse.toString())); + Assertions.assertTrue(Tag.VALUE_COMPUTATION.equals(readResponse.getNodeRole())); } catch (IOException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } finally { @@ -137,17 +137,17 @@ public void testSelectBackendIdsByPolicy() throws Exception { Config.disable_backend_black_list = true; // 1. no backend BeSelectionPolicy policy = new BeSelectionPolicy.Builder().needLoadAvailable().build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 1).size()); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 4).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 4).size()); // 2. add one backend but not alive addBackend(10001, "192.168.1.1", 9050); Backend be1 = infoService.getBackend(10001); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 1).size()); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 0).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy, 0).size()); // policy with no condition BeSelectionPolicy policy2 = new BeSelectionPolicy.Builder().build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy2, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy2, 1).size()); // 3. add more backends addBackend(10002, "192.168.1.2", 9050); @@ -164,15 +164,15 @@ public void testSelectBackendIdsByPolicy() throws Exception { // b1 and be5 is dead, be2,3,4 is alive BeSelectionPolicy policy3 = new BeSelectionPolicy.Builder().needScheduleAvailable().build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy3, 1).size()); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy3, 1).contains(10001L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy3, 1).contains(10005L)); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy3, 2).size()); - Assert.assertEquals(3, infoService.selectBackendIdsByPolicy(policy3, 3).size()); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10002L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10003L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10004L)); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy3, 4).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy3, 1).size()); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy3, 1).contains(10001L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy3, 1).contains(10005L)); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy3, 2).size()); + Assertions.assertEquals(3, infoService.selectBackendIdsByPolicy(policy3, 3).size()); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10002L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10003L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy3, 3).contains(10004L)); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy3, 4).size()); // 4. set be status be2.setLoadDisabled(true); @@ -180,26 +180,26 @@ public void testSelectBackendIdsByPolicy() throws Exception { be4.setDecommissioned(true); // now, only b3,b4 is loadable, only be2,b4 is queryable, only be2,3 is schedulable BeSelectionPolicy policy4 = new BeSelectionPolicy.Builder().needScheduleAvailable().build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy4, 1).size()); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10001L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10004L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10005L)); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy4, 2).size()); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy4, 2).contains(10002L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy4, 2).contains(10003L)); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy4, 3).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy4, 1).size()); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10001L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10004L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy4, 1).contains(10005L)); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy4, 2).size()); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy4, 2).contains(10002L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy4, 2).contains(10003L)); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy4, 3).size()); BeSelectionPolicy policy5 = new BeSelectionPolicy.Builder().needLoadAvailable().build(); - Assert.assertTrue(policy5.toString().contains("nonDecommissioned=true")); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy5, 1).size()); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10001L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10002L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10005L)); - Assert.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10004L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10003L)); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy5, 2).size()); + Assertions.assertTrue(policy5.toString().contains("nonDecommissioned=true")); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy5, 1).size()); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10001L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10002L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10005L)); + Assertions.assertFalse(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10004L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy5, 1).contains(10003L)); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy5, 2).size()); be3.setDecommissioning(true); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy5, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy5, 1).size()); be3.setDecommissioning(false); // 5. set tags @@ -213,7 +213,7 @@ public void testSelectBackendIdsByPolicy() throws Exception { be4.setDecommissioned(false); be5.setAlive(true); BeSelectionPolicy policy6 = new BeSelectionPolicy.Builder().needQueryAvailable().build(); - Assert.assertEquals(5, infoService.selectBackendIdsByPolicy(policy6, 5).size()); + Assertions.assertEquals(5, infoService.selectBackendIdsByPolicy(policy6, 5).size()); Tag taga = Tag.create(Tag.TYPE_LOCATION, "taga"); Tag tagb = Tag.create(Tag.TYPE_LOCATION, "tagb"); @@ -225,22 +225,22 @@ public void testSelectBackendIdsByPolicy() throws Exception { BeSelectionPolicy policy7 = new BeSelectionPolicy.Builder().needQueryAvailable().addTags(Sets.newHashSet(taga)) .build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy7, 1).size()); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy7, 2).size()); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy7, 2).contains(10001L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy7, 2).contains(10002L)); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy7, 3).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy7, 1).size()); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy7, 2).size()); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy7, 2).contains(10001L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy7, 2).contains(10002L)); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy7, 3).size()); BeSelectionPolicy policy8 = new BeSelectionPolicy.Builder().needQueryAvailable().addTags(Sets.newHashSet(tagb)) .build(); - Assert.assertEquals(3, infoService.selectBackendIdsByPolicy(policy8, 3).size()); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10003L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10004L)); - Assert.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10005L)); + Assertions.assertEquals(3, infoService.selectBackendIdsByPolicy(policy8, 3).size()); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10003L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10004L)); + Assertions.assertTrue(infoService.selectBackendIdsByPolicy(policy8, 3).contains(10005L)); BeSelectionPolicy policy9 = new BeSelectionPolicy.Builder().needQueryAvailable() .addTags(Sets.newHashSet(taga, tagb)).build(); - Assert.assertEquals(5, infoService.selectBackendIdsByPolicy(policy9, 5).size()); + Assertions.assertEquals(5, infoService.selectBackendIdsByPolicy(policy9, 5).size()); // 6. check storage medium addDisk(be1, "path1", TStorageMedium.HDD, 200 * 1024 * 1024L, 1 * 1024 * 1024L); @@ -251,25 +251,25 @@ public void testSelectBackendIdsByPolicy() throws Exception { BeSelectionPolicy policy10 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga, tagb)) .setStorageMedium(TStorageMedium.SSD).build(); - Assert.assertEquals(4, infoService.selectBackendIdsByPolicy(policy10, 4).size()); - Assert.assertEquals(3, infoService.selectBackendIdsByPolicy(policy10, 3).size()); + Assertions.assertEquals(4, infoService.selectBackendIdsByPolicy(policy10, 4).size()); + Assertions.assertEquals(3, infoService.selectBackendIdsByPolicy(policy10, 3).size()); // check return as many as possible - Assert.assertEquals(4, infoService.selectBackendIdsByPolicy(policy10, -1).size()); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy10, 5).size()); + Assertions.assertEquals(4, infoService.selectBackendIdsByPolicy(policy10, -1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy10, 5).size()); BeSelectionPolicy policy11 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(tagb)).setStorageMedium(TStorageMedium.HDD) .build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy11, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy11, 1).size()); // 7. check disk usage BeSelectionPolicy policy12 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)).setStorageMedium(TStorageMedium.HDD) .build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy12, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy12, 1).size()); BeSelectionPolicy policy13 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).needCheckDiskUsage().build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy13, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy13, 1).size()); // 8. check same host addBackend(10006, "192.168.1.1", 9051); @@ -280,10 +280,10 @@ public void testSelectBackendIdsByPolicy() throws Exception { addDisk(be6, "path1", TStorageMedium.HDD, 200 * 1024 * 1024L, 100 * 1024 * 1024L); BeSelectionPolicy policy14 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy14, 2).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy14, 2).size()); BeSelectionPolicy policy15 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).allowOnSameHost().build(); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy15, 2).size()); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy15, 2).size()); } @Test @@ -297,19 +297,19 @@ public void testComputeNodeBackendSelect() throws Exception { addDisk(be1, "path1", TStorageMedium.HDD, 200 * 1024 * 1024L, 100 * 1024 * 1024L); BeSelectionPolicy policy01 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy01, 1).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy01, 1).size()); BeSelectionPolicy policy02 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).preferComputeNode(true).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy02, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy02, 1).size()); BeSelectionPolicy policy03 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).preferComputeNode(true).assignExpectBeNum(0).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy03, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy03, 1).size()); BeSelectionPolicy policy04 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).preferComputeNode(true).assignExpectBeNum(1).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy04, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy04, 1).size()); // one compute node and two mix node addBackend(20002, "192.168.2.2", 9051); @@ -326,15 +326,15 @@ public void testComputeNodeBackendSelect() throws Exception { BeSelectionPolicy policy05 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).build(); - Assert.assertEquals(0, infoService.selectBackendIdsByPolicy(policy05, 3).size()); + Assertions.assertEquals(0, infoService.selectBackendIdsByPolicy(policy05, 3).size()); BeSelectionPolicy policy06 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).preferComputeNode(true).assignExpectBeNum(2).build(); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy06, 2).size()); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy06, 2).size()); BeSelectionPolicy policy07 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .setStorageMedium(TStorageMedium.HDD).preferComputeNode(true).assignExpectBeNum(3).build(); - Assert.assertEquals(3, infoService.selectBackendIdsByPolicy(policy07, 3).size()); + Assertions.assertEquals(3, infoService.selectBackendIdsByPolicy(policy07, 3).size()); } @Test @@ -360,23 +360,23 @@ public void testPreferLocationsSelect() throws Exception { List preferLocations = new ArrayList<>(); preferLocations.add("192.168.1.2"); BeSelectionPolicy policy1 = new BeSelectionPolicy.Builder().addPreLocations(preferLocations).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy1, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy1, 1).size()); preferLocations.add("192.168.1.3"); BeSelectionPolicy policy2 = new BeSelectionPolicy.Builder().addPreLocations(preferLocations).build(); - Assert.assertEquals(2, infoService.selectBackendIdsByPolicy(policy2, 2).size()); + Assertions.assertEquals(2, infoService.selectBackendIdsByPolicy(policy2, 2).size()); // only one preferLocations preferLocations.clear(); preferLocations.add("192.168.1.4"); BeSelectionPolicy policy3 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .addPreLocations(preferLocations).preferComputeNode(true).assignExpectBeNum(3).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy3, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy3, 1).size()); preferLocations.add("192.168.1.5"); BeSelectionPolicy policy4 = new BeSelectionPolicy.Builder().addTags(Sets.newHashSet(taga)) .addPreLocations(preferLocations).preferComputeNode(true).assignExpectBeNum(1).build(); - Assert.assertEquals(1, infoService.selectBackendIdsByPolicy(policy4, 1).size()); + Assertions.assertEquals(1, infoService.selectBackendIdsByPolicy(policy4, 1).size()); } @Test @@ -415,7 +415,7 @@ public void testSelectBackendIdsForReplicaCreation() throws Exception { Pair>, TStorageMedium> ret = infoService.selectBackendIdsForReplicaCreation(replicaAlloc, Maps.newHashMap(), TStorageMedium.HDD, false, false); Map> res = ret.first; - Assert.assertEquals(3, res.get(Tag.DEFAULT_BACKEND_TAG).size()); + Assertions.assertEquals(3, res.get(Tag.DEFAULT_BACKEND_TAG).size()); for (Long beId : res.get(Tag.DEFAULT_BACKEND_TAG)) { beCounterMap.put(beId, beCounterMap.getOrDefault(beId, 0) + 1); } @@ -423,13 +423,13 @@ public void testSelectBackendIdsForReplicaCreation() throws Exception { Set expectBackendIds = infoService.getMixBackends().stream() .filter(Backend::isAlive).map(Backend::getId) .collect(Collectors.toSet()); - Assert.assertEquals(expectBackendIds, beCounterMap.keySet().stream().collect(Collectors.toSet())); + Assertions.assertEquals(expectBackendIds, beCounterMap.keySet().stream().collect(Collectors.toSet())); List list = Lists.newArrayList(beCounterMap.values()); Collections.sort(list); int max = list.get(list.size() - 1); int diff = max - list.get(0); // The max replica num and min replica num's diff is less than 30%. - Assert.assertTrue((diff * 1.0 / max) < 0.3); + Assertions.assertTrue((diff * 1.0 / max) < 0.3); } private void addDisk(Backend be, String path, TStorageMedium medium, long totalB, long availB) { @@ -452,7 +452,7 @@ private void setComputeNode(Backend be, Tag tag) { public void testGetMinPipelineExecutorSize() { // Test case 1: No backends int result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(1, result); + Assertions.assertEquals(1, result); // Test case 2: Single backend with pipeline executor size = 8 addBackend(20001, "192.168.2.1", 9050); @@ -461,7 +461,7 @@ public void testGetMinPipelineExecutorSize() { be1.setAlive(true); result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(8, result); + Assertions.assertEquals(8, result); // Test case 3: Multiple backends with different pipeline executor sizes addBackend(20002, "192.168.2.2", 9050); @@ -475,7 +475,7 @@ public void testGetMinPipelineExecutorSize() { be3.setAlive(true); result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(4, result); + Assertions.assertEquals(4, result); // Test case 4: Backends with zero and negative pipeline executor sizes (should // be ignored) @@ -490,7 +490,7 @@ public void testGetMinPipelineExecutorSize() { be5.setAlive(true); result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(4, result); // Still should be 4 from be2 + Assertions.assertEquals(4, result); // Still should be 4 from be2 // Test case 5: All backends have zero or negative pipeline executor sizes be1.setPipelineExecutorSize(0); @@ -498,7 +498,7 @@ public void testGetMinPipelineExecutorSize() { be3.setPipelineExecutorSize(0); result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(1, result); // Should return default value 1 + Assertions.assertEquals(1, result); // Should return default value 1 // Test case 6: Mix of positive and non-positive values be1.setPipelineExecutorSize(16); @@ -506,7 +506,7 @@ public void testGetMinPipelineExecutorSize() { be3.setPipelineExecutorSize(6); // This should be the minimum result = infoService.getMinPipelineExecutorSize(""); - Assert.assertEquals(6, result); + Assertions.assertEquals(6, result); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunctionTest.java b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunctionTest.java index 09eb838f759353..17f683fbd7b313 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunctionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/CdcStreamTableValuedFunctionTest.java @@ -27,8 +27,8 @@ import org.apache.doris.job.util.StreamingJobUtils; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -45,8 +45,8 @@ public class CdcStreamTableValuedFunctionTest { public void testDeleteSignIsExcludedByDefault() throws Exception { List columns = getTableColumns(baseProperties()); - Assert.assertEquals(1, columns.size()); - Assert.assertEquals("id", columns.get(0).getName()); + Assertions.assertEquals(1, columns.size()); + Assertions.assertEquals("id", columns.get(0).getName()); } @Test @@ -56,11 +56,11 @@ public void testDeleteSignIsIncludedWhenEnabled() throws Exception { List columns = getTableColumns(properties); - Assert.assertEquals(2, columns.size()); + Assertions.assertEquals(2, columns.size()); Column deleteSign = columns.get(1); - Assert.assertEquals(Column.DELETE_SIGN, deleteSign.getName()); - Assert.assertEquals(PrimitiveType.TINYINT, deleteSign.getType().getPrimitiveType()); - Assert.assertFalse(deleteSign.isAllowNull()); + Assertions.assertEquals(Column.DELETE_SIGN, deleteSign.getName()); + Assertions.assertEquals(PrimitiveType.TINYINT, deleteSign.getType().getPrimitiveType()); + Assertions.assertFalse(deleteSign.isAllowNull()); } @Test @@ -68,10 +68,10 @@ public void testInvalidIncludeDeleteSignIsRejected() { Map properties = baseProperties(); properties.put(CdcStreamTableValuedFunction.INCLUDE_DELETE_SIGN, "invalid"); - AnalysisException exception = Assert.assertThrows(AnalysisException.class, + AnalysisException exception = Assertions.assertThrows(AnalysisException.class, () -> new CdcStreamTableValuedFunction(properties)); - Assert.assertTrue(exception.getMessage().contains("include_delete_sign")); + Assertions.assertTrue(exception.getMessage().contains("include_delete_sign")); } @Test @@ -80,7 +80,7 @@ public void testMysqlJdbcUrlIsNormalizedInPayload() throws Exception { FetchRecordRequest request = OBJECT_MAPPER.readValue( function.getBackendConnectProperties().get("http.payload"), FetchRecordRequest.class); - Assert.assertEquals("jdbc:mysql://localhost:3306/test_db?yearIsDateType=false" + Assertions.assertEquals("jdbc:mysql://localhost:3306/test_db?yearIsDateType=false" + "&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8", request.getConfig().get(DataSourceConfigKeys.JDBC_URL)); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/ExternalFileTableValuedFunctionTest.java b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/ExternalFileTableValuedFunctionTest.java index 34df496439589c..4330905561864a 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/ExternalFileTableValuedFunctionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/ExternalFileTableValuedFunctionTest.java @@ -26,8 +26,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.List; @@ -45,8 +45,8 @@ public void testHiveParquetTimeZoneIsCanonicalizedAndRemovedFromStoragePropertie Map storageProperties = tvf.parseCommonProperties(properties); - Assert.assertEquals("+08:00", tvf.getHiveParquetTimeZone()); - Assert.assertFalse(storageProperties.containsKey(FileFormatConstants.PROP_HIVE_PARQUET_TIME_ZONE)); + Assertions.assertEquals("+08:00", tvf.getHiveParquetTimeZone()); + Assertions.assertFalse(storageProperties.containsKey(FileFormatConstants.PROP_HIVE_PARQUET_TIME_ZONE)); } @Test @@ -57,10 +57,10 @@ public void testHiveParquetTimeZoneRejectsAmbiguousShortAlias() { properties.put(FileFormatConstants.PROP_FORMAT, FileFormatConstants.FORMAT_PARQUET); properties.put(FileFormatConstants.PROP_HIVE_PARQUET_TIME_ZONE, "CST"); - AnalysisException exception = Assert.assertThrows( + AnalysisException exception = Assertions.assertThrows( AnalysisException.class, () -> tvf.parseCommonProperties(properties)); - Assert.assertTrue(exception.getMessage().contains("short timezone aliases are not supported")); + Assertions.assertTrue(exception.getMessage().contains("short timezone aliases are not supported")); } @Test @@ -73,10 +73,10 @@ public void testCsvSchemaParse() { List csvSchema = Lists.newArrayList(); try { FileFormatUtils.parseCsvSchema(csvSchema, properties.get(FileFormatConstants.PROP_CSV_SCHEMA)); - Assert.fail(); + Assertions.fail(); } catch (AnalysisException e) { e.printStackTrace(); - Assert.assertTrue(e.getMessage().contains("unsupported column type: bool")); + Assertions.assertTrue(e.getMessage().contains("unsupported column type: bool")); } csvSchema.clear(); @@ -85,65 +85,65 @@ public void testCsvSchemaParse() { + "k8:string;k9:date;k10:datetime;k11:decimal(10, 2);k12:decimal( 38,10); k13:datetime(5)"); try { FileFormatUtils.parseCsvSchema(csvSchema, properties.get(FileFormatConstants.PROP_CSV_SCHEMA)); - Assert.assertEquals(13, csvSchema.size()); + Assertions.assertEquals(13, csvSchema.size()); Column decimalCol = csvSchema.get(10); - Assert.assertEquals(10, decimalCol.getPrecision()); - Assert.assertEquals(2, decimalCol.getScale()); + Assertions.assertEquals(10, decimalCol.getPrecision()); + Assertions.assertEquals(2, decimalCol.getScale()); decimalCol = csvSchema.get(11); - Assert.assertEquals(38, decimalCol.getPrecision()); - Assert.assertEquals(10, decimalCol.getScale()); + Assertions.assertEquals(38, decimalCol.getPrecision()); + Assertions.assertEquals(10, decimalCol.getScale()); Column datetimeCol = csvSchema.get(12); - Assert.assertEquals(5, datetimeCol.getScale()); + Assertions.assertEquals(5, datetimeCol.getScale()); for (int i = 0; i < csvSchema.size(); i++) { Column col = csvSchema.get(i); switch (col.getName()) { case "k1": - Assert.assertEquals(PrimitiveType.INT, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.INT, col.getType().getPrimitiveType()); break; case "k2": - Assert.assertEquals(PrimitiveType.BIGINT, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.BIGINT, col.getType().getPrimitiveType()); break; case "k3": - Assert.assertEquals(PrimitiveType.FLOAT, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.FLOAT, col.getType().getPrimitiveType()); break; case "k4": - Assert.assertEquals(PrimitiveType.DOUBLE, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DOUBLE, col.getType().getPrimitiveType()); break; case "k5": - Assert.assertEquals(PrimitiveType.SMALLINT, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.SMALLINT, col.getType().getPrimitiveType()); break; case "k6": - Assert.assertEquals(PrimitiveType.TINYINT, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.TINYINT, col.getType().getPrimitiveType()); break; case "k7": - Assert.assertEquals(PrimitiveType.BOOLEAN, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.BOOLEAN, col.getType().getPrimitiveType()); break; case "k8": - Assert.assertEquals(PrimitiveType.STRING, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.STRING, col.getType().getPrimitiveType()); break; case "k9": - Assert.assertEquals(PrimitiveType.DATEV2, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DATEV2, col.getType().getPrimitiveType()); break; case "k10": - Assert.assertEquals(PrimitiveType.DATETIMEV2, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DATETIMEV2, col.getType().getPrimitiveType()); break; case "k11": - Assert.assertEquals(PrimitiveType.DECIMAL64, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DECIMAL64, col.getType().getPrimitiveType()); break; case "k12": - Assert.assertEquals(PrimitiveType.DECIMAL128, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DECIMAL128, col.getType().getPrimitiveType()); break; case "k13": - Assert.assertEquals(PrimitiveType.DATETIMEV2, col.getType().getPrimitiveType()); + Assertions.assertEquals(PrimitiveType.DATETIMEV2, col.getType().getPrimitiveType()); break; default: - Assert.fail("unknown column name: " + col.getName()); + Assertions.fail("unknown column name: " + col.getName()); } } } catch (AnalysisException e) { e.printStackTrace(); - Assert.fail(); + Assertions.fail(); } } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/FrontendsTableValuedFunctionTest.java b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/FrontendsTableValuedFunctionTest.java index 7d430d4a2cf0ce..8c1a019da540b9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/FrontendsTableValuedFunctionTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/FrontendsTableValuedFunctionTest.java @@ -26,9 +26,9 @@ import org.apache.doris.system.SystemInfoService.HostInfo; import org.apache.doris.thrift.TMetaScanRange; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -46,7 +46,7 @@ public class FrontendsTableValuedFunctionTest { private MockedStatic mockedEnvStatic; private MockedStatic mockedCtxStatic; - @After + @AfterEach public void tearDown() { if (mockedCtxStatic != null) { mockedCtxStatic.close(); @@ -77,7 +77,7 @@ public void testGetMetaScanRangeUseCurrentConnectedFe() throws Exception { mockContext("self-fe-host", "connected-fe-host"); FrontendsTableValuedFunction tvf = new FrontendsTableValuedFunction(new HashMap<>()); TMetaScanRange range = tvf.getMetaScanRange(Collections.emptyList()); - Assert.assertEquals("connected-fe-host", range.getFrontendsParams().getCurrentConnectedFeHost()); + Assertions.assertEquals("connected-fe-host", range.getFrontendsParams().getCurrentConnectedFeHost()); } @Test @@ -85,6 +85,6 @@ public void testGetMetaScanRangeFallbackToSelfNode() throws Exception { mockContext("self-fe-host", ""); FrontendsTableValuedFunction tvf = new FrontendsTableValuedFunction(new HashMap<>()); TMetaScanRange range = tvf.getMetaScanRange(Collections.emptyList()); - Assert.assertEquals("self-fe-host", range.getFrontendsParams().getCurrentConnectedFeHost()); + Assertions.assertEquals("self-fe-host", range.getFrontendsParams().getCurrentConnectedFeHost()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/HFUtilsTest.java b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/HFUtilsTest.java index 8d18b021af0fbc..236ed0330792aa 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tablefunction/HFUtilsTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tablefunction/HFUtilsTest.java @@ -20,8 +20,8 @@ import org.apache.doris.common.AnalysisException; import org.apache.doris.tablefunction.HFUtils.ParsedHFUrl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; @@ -33,56 +33,56 @@ public void testValidHfUrlParsing() throws AnalysisException { String url1 = "hf://datasets/lhoestq/demo1/default/train/0000.parquet"; ParsedHFUrl parsed1 = HFUtils.parseHfUrl(url1); - Assert.assertEquals("datasets", parsed1.getRepoType()); - Assert.assertEquals("lhoestq/demo1", parsed1.getRepository()); - Assert.assertEquals("main", parsed1.getRevision()); - Assert.assertEquals("/default/train/0000.parquet", parsed1.getPath()); - Assert.assertEquals("https://huggingface.co", parsed1.getEndpoint()); + Assertions.assertEquals("datasets", parsed1.getRepoType()); + Assertions.assertEquals("lhoestq/demo1", parsed1.getRepository()); + Assertions.assertEquals("main", parsed1.getRevision()); + Assertions.assertEquals("/default/train/0000.parquet", parsed1.getPath()); + Assertions.assertEquals("https://huggingface.co", parsed1.getEndpoint()); // Test URL with revision String url2 = "hf://datasets/username/dataset@v1.0/path/to/file.csv"; ParsedHFUrl parsed2 = HFUtils.parseHfUrl(url2); - Assert.assertEquals("datasets", parsed2.getRepoType()); - Assert.assertEquals("username/dataset", parsed2.getRepository()); - Assert.assertEquals("v1.0", parsed2.getRevision()); - Assert.assertEquals("/path/to/file.csv", parsed2.getPath()); + Assertions.assertEquals("datasets", parsed2.getRepoType()); + Assertions.assertEquals("username/dataset", parsed2.getRepository()); + Assertions.assertEquals("v1.0", parsed2.getRevision()); + Assertions.assertEquals("/path/to/file.csv", parsed2.getPath()); // Test spaces URL String url3 = "hf://spaces/gradio/calculator/app.py"; ParsedHFUrl parsed3 = HFUtils.parseHfUrl(url3); - Assert.assertEquals("spaces", parsed3.getRepoType()); - Assert.assertEquals("gradio/calculator", parsed3.getRepository()); - Assert.assertEquals("main", parsed3.getRevision()); - Assert.assertEquals("/app.py", parsed3.getPath()); + Assertions.assertEquals("spaces", parsed3.getRepoType()); + Assertions.assertEquals("gradio/calculator", parsed3.getRepository()); + Assertions.assertEquals("main", parsed3.getRevision()); + Assertions.assertEquals("/app.py", parsed3.getPath()); // Test URL with empty path String url4 = "hf://datasets/user/repo/"; ParsedHFUrl parsed4 = HFUtils.parseHfUrl(url4); - Assert.assertEquals("datasets", parsed4.getRepoType()); - Assert.assertEquals("user/repo", parsed4.getRepository()); - Assert.assertEquals("main", parsed4.getRevision()); - Assert.assertEquals("/", parsed4.getPath()); + Assertions.assertEquals("datasets", parsed4.getRepoType()); + Assertions.assertEquals("user/repo", parsed4.getRepository()); + Assertions.assertEquals("main", parsed4.getRevision()); + Assertions.assertEquals("/", parsed4.getPath()); // Test URL with HuggingFace web interface format (/blob/main/) String url5 = "hf://datasets/fka/awesome-chatgpt-prompts/blob/main/prompts.csv"; ParsedHFUrl parsed5 = HFUtils.parseHfUrl(url5); - Assert.assertEquals("datasets", parsed5.getRepoType()); - Assert.assertEquals("fka/awesome-chatgpt-prompts", parsed5.getRepository()); - Assert.assertEquals("main", parsed5.getRevision()); - Assert.assertEquals("/prompts.csv", parsed5.getPath()); + Assertions.assertEquals("datasets", parsed5.getRepoType()); + Assertions.assertEquals("fka/awesome-chatgpt-prompts", parsed5.getRepository()); + Assertions.assertEquals("main", parsed5.getRevision()); + Assertions.assertEquals("/prompts.csv", parsed5.getPath()); // Test URL with HuggingFace web interface format (/tree/v1.0/) String url6 = "hf://datasets/user/dataset/tree/v1.0/data/file.txt"; ParsedHFUrl parsed6 = HFUtils.parseHfUrl(url6); - Assert.assertEquals("datasets", parsed6.getRepoType()); - Assert.assertEquals("user/dataset", parsed6.getRepository()); - Assert.assertEquals("v1.0", parsed6.getRevision()); - Assert.assertEquals("/data/file.txt", parsed6.getPath()); + Assertions.assertEquals("datasets", parsed6.getRepoType()); + Assertions.assertEquals("user/dataset", parsed6.getRepository()); + Assertions.assertEquals("v1.0", parsed6.getRevision()); + Assertions.assertEquals("/data/file.txt", parsed6.getPath()); } @Test @@ -91,25 +91,25 @@ public void testHttpUrlConversion() throws AnalysisException { String hfUrl1 = "hf://datasets/lhoestq/demo1/default/train/0000.parquet"; String httpUrl1 = HFUtils.convertHfUrlToHttpUrl(hfUrl1); String expected1 = "https://huggingface.co/datasets/lhoestq/demo1/resolve/main/default/train/0000.parquet"; - Assert.assertEquals(expected1, httpUrl1); + Assertions.assertEquals(expected1, httpUrl1); // Test conversion with revision String hfUrl2 = "hf://datasets/username/dataset@v1.0/path/to/file.csv"; String httpUrl2 = HFUtils.convertHfUrlToHttpUrl(hfUrl2); String expected2 = "https://huggingface.co/datasets/username/dataset/resolve/v1.0/path/to/file.csv"; - Assert.assertEquals(expected2, httpUrl2); + Assertions.assertEquals(expected2, httpUrl2); // Test spaces conversion String hfUrl3 = "hf://spaces/gradio/calculator/app.py"; String httpUrl3 = HFUtils.convertHfUrlToHttpUrl(hfUrl3); String expected3 = "https://huggingface.co/spaces/gradio/calculator/resolve/main/app.py"; - Assert.assertEquals(expected3, httpUrl3); + Assertions.assertEquals(expected3, httpUrl3); // Test HuggingFace web interface format conversion String hfUrl4 = "hf://datasets/fka/awesome-chatgpt-prompts/blob/main/prompts.csv"; String httpUrl4 = HFUtils.convertHfUrlToHttpUrl(hfUrl4); String expected4 = "https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/prompts.csv"; - Assert.assertEquals(expected4, httpUrl4); + Assertions.assertEquals(expected4, httpUrl4); } @Test @@ -120,42 +120,42 @@ public void testTreeApiUrlGeneration() throws AnalysisException { // Test without limit String treeUrl1 = HFUtils.buildTreeApiUrl(parsed, 0); String expected1 = "https://huggingface.co/api/datasets/lhoestq/demo1/tree/main/default/train"; - Assert.assertEquals(expected1, treeUrl1); + Assertions.assertEquals(expected1, treeUrl1); // Test with limit String treeUrl2 = HFUtils.buildTreeApiUrl(parsed, 100); String expected2 = "https://huggingface.co/api/datasets/lhoestq/demo1/tree/main/default/train?limit=100"; - Assert.assertEquals(expected2, treeUrl2); + Assertions.assertEquals(expected2, treeUrl2); } @Test public void testRepositoryInfo() throws AnalysisException { String hfUrl1 = "hf://datasets/lhoestq/demo1/default/train/0000.parquet"; String repoInfo1 = HFUtils.getRepositoryInfo(hfUrl1); - Assert.assertEquals("datasets/lhoestq/demo1@main", repoInfo1); + Assertions.assertEquals("datasets/lhoestq/demo1@main", repoInfo1); String hfUrl2 = "hf://datasets/username/dataset@v1.0/path/to/file.csv"; String repoInfo2 = HFUtils.getRepositoryInfo(hfUrl2); - Assert.assertEquals("datasets/username/dataset@v1.0", repoInfo2); + Assertions.assertEquals("datasets/username/dataset@v1.0", repoInfo2); } @Test public void testValidHfUrlValidation() { // Valid URLs - Assert.assertTrue(HFUtils.isValidHfUrl("hf://datasets/user/repo/file.txt")); - Assert.assertTrue(HFUtils.isValidHfUrl("hf://spaces/user/space/app.py")); - Assert.assertTrue(HFUtils.isValidHfUrl("hf://datasets/user/repo@v1.0/file.txt")); + Assertions.assertTrue(HFUtils.isValidHfUrl("hf://datasets/user/repo/file.txt")); + Assertions.assertTrue(HFUtils.isValidHfUrl("hf://spaces/user/space/app.py")); + Assertions.assertTrue(HFUtils.isValidHfUrl("hf://datasets/user/repo@v1.0/file.txt")); // Invalid URLs - Assert.assertFalse(HFUtils.isValidHfUrl(null)); - Assert.assertFalse(HFUtils.isValidHfUrl("")); - Assert.assertFalse(HFUtils.isValidHfUrl("http://example.com")); - Assert.assertFalse(HFUtils.isValidHfUrl("hf://")); - Assert.assertFalse(HFUtils.isValidHfUrl("hf://datasets")); - Assert.assertFalse(HFUtils.isValidHfUrl("hf://datasets/")); - Assert.assertFalse(HFUtils.isValidHfUrl("hf://datasets/user")); - Assert.assertFalse(HFUtils.isValidHfUrl("hf://datasets/user/repo")); // Missing path - Assert.assertFalse(HFUtils.isValidHfUrl("hf://invalid/user/repo/file.txt")); + Assertions.assertFalse(HFUtils.isValidHfUrl(null)); + Assertions.assertFalse(HFUtils.isValidHfUrl("")); + Assertions.assertFalse(HFUtils.isValidHfUrl("http://example.com")); + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://")); + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://datasets")); + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://datasets/")); + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://datasets/user")); + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://datasets/user/repo")); // Missing path + Assertions.assertFalse(HFUtils.isValidHfUrl("hf://invalid/user/repo/file.txt")); } @Test @@ -163,56 +163,56 @@ public void testInvalidUrlExceptions() { // Test null/empty URL try { HFUtils.parseHfUrl(null); - Assert.fail("Should throw AnalysisException for null URL"); + Assertions.fail("Should throw AnalysisException for null URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } try { HFUtils.parseHfUrl(""); - Assert.fail("Should throw AnalysisException for empty URL"); + Assertions.fail("Should throw AnalysisException for empty URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } // Test non-hf URL try { HFUtils.parseHfUrl("http://example.com"); - Assert.fail("Should throw AnalysisException for non-hf URL"); + Assertions.fail("Should throw AnalysisException for non-hf URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("must start with 'hf://'")); + Assertions.assertTrue(e.getMessage().contains("must start with 'hf://'")); } // Test incomplete URL try { HFUtils.parseHfUrl("hf://datasets"); - Assert.fail("Should throw AnalysisException for incomplete URL"); + Assertions.fail("Should throw AnalysisException for incomplete URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); + Assertions.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); } // Test invalid repository type try { HFUtils.parseHfUrl("hf://models/user/model/file.txt"); - Assert.fail("Should throw AnalysisException for unsupported repo type"); + Assertions.fail("Should throw AnalysisException for unsupported repo type"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("only supports 'datasets' and 'spaces'")); + Assertions.assertTrue(e.getMessage().contains("only supports 'datasets' and 'spaces'")); } // Test empty username try { HFUtils.parseHfUrl("hf://datasets//repo/file.txt"); - Assert.fail("Should throw AnalysisException for empty username"); + Assertions.fail("Should throw AnalysisException for empty username"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); + Assertions.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); } // Test empty revision try { HFUtils.parseHfUrl("hf://datasets/user/repo@/file.txt"); - Assert.fail("Should throw AnalysisException for empty revision"); + Assertions.fail("Should throw AnalysisException for empty revision"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); + Assertions.assertTrue(e.getMessage().contains("Failed to parse HuggingFace URL")); } } @@ -221,25 +221,25 @@ public void testConvertHfUrlToHttpUrlExceptions() { // Test null URL try { HFUtils.convertHfUrlToHttpUrl(null); - Assert.fail("Should throw AnalysisException for null URL"); + Assertions.fail("Should throw AnalysisException for null URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } // Test empty URL try { HFUtils.convertHfUrlToHttpUrl(""); - Assert.fail("Should throw AnalysisException for empty URL"); + Assertions.fail("Should throw AnalysisException for empty URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } // Test invalid URL try { HFUtils.convertHfUrlToHttpUrl("http://example.com"); - Assert.fail("Should throw AnalysisException for invalid URL"); + Assertions.fail("Should throw AnalysisException for invalid URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("must start with 'hf://'")); + Assertions.assertTrue(e.getMessage().contains("must start with 'hf://'")); } } @@ -249,80 +249,80 @@ public void testEdgeCases() throws AnalysisException { String hfUrl1 = "hf://datasets/user/repo/path with spaces/file-name_123.parquet"; String httpUrl1 = HFUtils.convertHfUrlToHttpUrl(hfUrl1); String expected1 = "https://huggingface.co/datasets/user/repo/resolve/main/path with spaces/file-name_123.parquet"; - Assert.assertEquals(expected1, httpUrl1); + Assertions.assertEquals(expected1, httpUrl1); // Test URL with multiple slashes in path String hfUrl2 = "hf://datasets/user/repo/path/to/deep/nested/file.txt"; String httpUrl2 = HFUtils.convertHfUrlToHttpUrl(hfUrl2); String expected2 = "https://huggingface.co/datasets/user/repo/resolve/main/path/to/deep/nested/file.txt"; - Assert.assertEquals(expected2, httpUrl2); + Assertions.assertEquals(expected2, httpUrl2); // Test URL with revision containing special characters String hfUrl3 = "hf://datasets/user/repo@feature-branch-v1.0/file.txt"; String httpUrl3 = HFUtils.convertHfUrlToHttpUrl(hfUrl3); String expected3 = "https://huggingface.co/datasets/user/repo/resolve/feature-branch-v1.0/file.txt"; - Assert.assertEquals(expected3, httpUrl3); + Assertions.assertEquals(expected3, httpUrl3); } @Test public void testGlobFunctionality() throws AnalysisException { // Test wildcard detection - Assert.assertTrue(HFUtils.containsWildcards("/path/*.parquet")); - Assert.assertTrue(HFUtils.containsWildcards("/path/**/train/*.csv")); - Assert.assertTrue(HFUtils.containsWildcards("/path/file_[abc].txt")); - Assert.assertTrue(HFUtils.containsWildcards("/path/file_{1,2,3}.txt")); - Assert.assertFalse(HFUtils.containsWildcards("/path/file.txt")); - Assert.assertFalse(HFUtils.containsWildcards("")); - Assert.assertFalse(HFUtils.containsWildcards(null)); + Assertions.assertTrue(HFUtils.containsWildcards("/path/*.parquet")); + Assertions.assertTrue(HFUtils.containsWildcards("/path/**/train/*.csv")); + Assertions.assertTrue(HFUtils.containsWildcards("/path/file_[abc].txt")); + Assertions.assertTrue(HFUtils.containsWildcards("/path/file_{1,2,3}.txt")); + Assertions.assertFalse(HFUtils.containsWildcards("/path/file.txt")); + Assertions.assertFalse(HFUtils.containsWildcards("")); + Assertions.assertFalse(HFUtils.containsWildcards(null)); // Test longest prefix extraction - Assert.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/*.parquet")); - Assert.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/**/train/*.csv")); - Assert.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/file_[abc].txt")); - Assert.assertEquals("/path/to/deep", HFUtils.getLongestPrefixWithoutWildcards("/path/to/deep/*.txt")); - Assert.assertEquals("/path/file.txt", HFUtils.getLongestPrefixWithoutWildcards("/path/file.txt")); - Assert.assertEquals("", HFUtils.getLongestPrefixWithoutWildcards("*.txt")); + Assertions.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/*.parquet")); + Assertions.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/**/train/*.csv")); + Assertions.assertEquals("/path", HFUtils.getLongestPrefixWithoutWildcards("/path/file_[abc].txt")); + Assertions.assertEquals("/path/to/deep", HFUtils.getLongestPrefixWithoutWildcards("/path/to/deep/*.txt")); + Assertions.assertEquals("/path/file.txt", HFUtils.getLongestPrefixWithoutWildcards("/path/file.txt")); + Assertions.assertEquals("", HFUtils.getLongestPrefixWithoutWildcards("*.txt")); // Test glob URL validation - Assert.assertTrue(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/*.parquet")); - Assert.assertTrue(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/**/train/*.csv")); - Assert.assertFalse(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/file.txt")); - Assert.assertFalse(HFUtils.isValidGlobUrl("http://example.com/*.txt")); - Assert.assertFalse(HFUtils.isValidGlobUrl(null)); + Assertions.assertTrue(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/*.parquet")); + Assertions.assertTrue(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/**/train/*.csv")); + Assertions.assertFalse(HFUtils.isValidGlobUrl("hf://datasets/user/repo/path/file.txt")); + Assertions.assertFalse(HFUtils.isValidGlobUrl("http://example.com/*.txt")); + Assertions.assertFalse(HFUtils.isValidGlobUrl(null)); } @Test public void testGlobPatternMatching() { // Test basic pattern matching - Assert.assertTrue(HFUtils.matchGlobPattern("file.txt", "*.txt")); - Assert.assertTrue(HFUtils.matchGlobPattern("file.parquet", "*.parquet")); - Assert.assertTrue(HFUtils.matchGlobPattern("file_a.txt", "file_[abc].txt")); - Assert.assertFalse(HFUtils.matchGlobPattern("file_d.txt", "file_[abc].txt")); - Assert.assertFalse(HFUtils.matchGlobPattern("file.csv", "*.txt")); + Assertions.assertTrue(HFUtils.matchGlobPattern("file.txt", "*.txt")); + Assertions.assertTrue(HFUtils.matchGlobPattern("file.parquet", "*.parquet")); + Assertions.assertTrue(HFUtils.matchGlobPattern("file_a.txt", "file_[abc].txt")); + Assertions.assertFalse(HFUtils.matchGlobPattern("file_d.txt", "file_[abc].txt")); + Assertions.assertFalse(HFUtils.matchGlobPattern("file.csv", "*.txt")); // Test edge cases - Assert.assertFalse(HFUtils.matchGlobPattern(null, "*.txt")); - Assert.assertFalse(HFUtils.matchGlobPattern("file.txt", null)); - Assert.assertFalse(HFUtils.matchGlobPattern("", "*.txt")); + Assertions.assertFalse(HFUtils.matchGlobPattern(null, "*.txt")); + Assertions.assertFalse(HFUtils.matchGlobPattern("file.txt", null)); + Assertions.assertFalse(HFUtils.matchGlobPattern("", "*.txt")); } @Test public void testPathSplitting() { List components1 = HFUtils.splitPath("/path/to/file.txt"); - Assert.assertEquals(3, components1.size()); - Assert.assertEquals("path", components1.get(0)); - Assert.assertEquals("to", components1.get(1)); - Assert.assertEquals("file.txt", components1.get(2)); + Assertions.assertEquals(3, components1.size()); + Assertions.assertEquals("path", components1.get(0)); + Assertions.assertEquals("to", components1.get(1)); + Assertions.assertEquals("file.txt", components1.get(2)); List components2 = HFUtils.splitPath("path/to/file.txt"); - Assert.assertEquals(3, components2.size()); - Assert.assertEquals("path", components2.get(0)); + Assertions.assertEquals(3, components2.size()); + Assertions.assertEquals("path", components2.get(0)); List components3 = HFUtils.splitPath(""); - Assert.assertEquals(0, components3.size()); + Assertions.assertEquals(0, components3.size()); List components4 = HFUtils.splitPath(null); - Assert.assertEquals(0, components4.size()); + Assertions.assertEquals(0, components4.size()); } @Test @@ -330,24 +330,24 @@ public void testAdvancedPatternMatching() { // Test ** recursive matching List pathComponents1 = HFUtils.splitPath("path/to/deep/file.txt"); List patternComponents1 = HFUtils.splitPath("path/**/file.txt"); - Assert.assertTrue(HFUtils.matchPathComponents(pathComponents1, patternComponents1)); + Assertions.assertTrue(HFUtils.matchPathComponents(pathComponents1, patternComponents1)); List pathComponents2 = HFUtils.splitPath("path/file.txt"); List patternComponents2 = HFUtils.splitPath("path/**/file.txt"); - Assert.assertTrue(HFUtils.matchPathComponents(pathComponents2, patternComponents2)); + Assertions.assertTrue(HFUtils.matchPathComponents(pathComponents2, patternComponents2)); List pathComponents3 = HFUtils.splitPath("different/file.txt"); List patternComponents3 = HFUtils.splitPath("path/**/file.txt"); - Assert.assertFalse(HFUtils.matchPathComponents(pathComponents3, patternComponents3)); + Assertions.assertFalse(HFUtils.matchPathComponents(pathComponents3, patternComponents3)); // Test single * matching List pathComponents4 = HFUtils.splitPath("path/train/file.txt"); List patternComponents4 = HFUtils.splitPath("path/*/file.txt"); - Assert.assertTrue(HFUtils.matchPathComponents(pathComponents4, patternComponents4)); + Assertions.assertTrue(HFUtils.matchPathComponents(pathComponents4, patternComponents4)); List pathComponents5 = HFUtils.splitPath("path/to/deep/file.txt"); List patternComponents5 = HFUtils.splitPath("path/*/file.txt"); - Assert.assertFalse(HFUtils.matchPathComponents(pathComponents5, patternComponents5)); + Assertions.assertFalse(HFUtils.matchPathComponents(pathComponents5, patternComponents5)); } @Test @@ -355,15 +355,15 @@ public void testGlobExpansion() throws AnalysisException { // Test non-glob URL (should return single result) String nonGlobUrl = "hf://datasets/user/repo/path/file.txt"; List result1 = HFUtils.expandGlob(nonGlobUrl); - Assert.assertEquals(1, result1.size()); - Assert.assertEquals("https://huggingface.co/datasets/user/repo/resolve/main/path/file.txt", result1.get(0)); + Assertions.assertEquals(1, result1.size()); + Assertions.assertEquals("https://huggingface.co/datasets/user/repo/resolve/main/path/file.txt", result1.get(0)); // Test glob URL validation String globUrl1 = "hf://datasets/user/repo/path/*.parquet"; - Assert.assertTrue(HFUtils.isValidGlobUrl(globUrl1)); + Assertions.assertTrue(HFUtils.isValidGlobUrl(globUrl1)); String globUrl2 = "hf://datasets/user/repo/path/*.csv"; - Assert.assertTrue(HFUtils.isValidGlobUrl(globUrl2)); + Assertions.assertTrue(HFUtils.isValidGlobUrl(globUrl2)); // Note: Real glob expansion tests would require actual HuggingFace API calls // The actual expansion will fail without real API access, but URL parsing works @@ -374,42 +374,42 @@ public void testGlobExpansionExceptions() throws AnalysisException { // Test null URL try { HFUtils.expandGlob(null); - Assert.fail("Should throw AnalysisException for null URL"); + Assertions.fail("Should throw AnalysisException for null URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } // Test empty URL try { HFUtils.expandGlob(""); - Assert.fail("Should throw AnalysisException for empty URL"); + Assertions.fail("Should throw AnalysisException for empty URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("cannot be null or empty")); + Assertions.assertTrue(e.getMessage().contains("cannot be null or empty")); } // Test invalid URL try { HFUtils.expandGlob("http://example.com/*.txt"); - Assert.fail("Should throw AnalysisException for invalid URL"); + Assertions.fail("Should throw AnalysisException for invalid URL"); } catch (AnalysisException e) { - Assert.assertTrue(e.getMessage().contains("must start with 'hf://'")); + Assertions.assertTrue(e.getMessage().contains("must start with 'hf://'")); } List res = HFUtils.expandGlob("hf://datasets/fka/awesome-chatgpt-prompts/blob/main/prompts.csv"); - Assert.assertEquals(1, res.size()); - Assert.assertEquals("https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/prompts.csv", + Assertions.assertEquals(1, res.size()); + Assertions.assertEquals("https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/prompts.csv", res.get(0)); ParsedHFUrl parsed = HFUtils.parseHfUrl("hf://datasets/fka/awesome-chatgpt-prompts/blob/main/prompts.csv"); - Assert.assertEquals("/prompts.csv", parsed.getPath()); + Assertions.assertEquals("/prompts.csv", parsed.getPath()); res = HFUtils.expandGlob("hf://datasets/fka/awesome-chatgpt-prompts/blob/main/*"); - Assert.assertEquals(3, res.size()); - Assert.assertTrue(res.contains( + Assertions.assertEquals(3, res.size()); + Assertions.assertTrue(res.contains( "https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/prompts.csv")); - Assert.assertTrue(res.contains( + Assertions.assertTrue(res.contains( "https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/.gitattributes")); - Assert.assertTrue(res.contains( + Assertions.assertTrue(res.contains( "https://huggingface.co/datasets/fka/awesome-chatgpt-prompts/resolve/main/README.md")); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/task/AgentTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/task/AgentTaskTest.java index e6b3ee74451cc0..ed4365feee6477 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/task/AgentTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/task/AgentTaskTest.java @@ -42,9 +42,9 @@ import org.apache.doris.thrift.TTaskType; import com.google.common.collect.Range; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.Arrays; @@ -98,7 +98,7 @@ public class AgentTaskTest { private AgentTask cancelDeleteTask; private AgentTask storageMediaMigrationTask; - @Before + @BeforeEach public void setUp() throws AnalysisException { MetricRepo.init(); agentBatchTask = new AgentBatchTask(); @@ -143,20 +143,20 @@ public void setUp() throws AnalysisException { public void addTaskTest() { // add null agentBatchTask.addTask(null); - Assert.assertEquals(0, agentBatchTask.getTaskNum()); + Assertions.assertEquals(0, agentBatchTask.getTaskNum()); // normal agentBatchTask.addTask(createReplicaTask); - Assert.assertEquals(1, agentBatchTask.getTaskNum()); + Assertions.assertEquals(1, agentBatchTask.getTaskNum()); List allTasks = agentBatchTask.getAllTasks(); - Assert.assertEquals(1, allTasks.size()); + Assertions.assertEquals(1, allTasks.size()); for (AgentTask agentTask : allTasks) { if (agentTask instanceof CreateReplicaTask) { - Assert.assertEquals(createReplicaTask, agentTask); + Assertions.assertEquals(createReplicaTask, agentTask); } else { - Assert.fail(); + Assertions.fail(); } } } @@ -170,9 +170,9 @@ public void toThriftTest() throws Exception { // create TAgentTaskRequest request = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createReplicaTask); - Assert.assertEquals(TTaskType.CREATE, request.getTaskType()); - Assert.assertEquals(createReplicaTask.getSignature(), request.getSignature()); - Assert.assertNotNull(request.getCreateTabletReq()); + Assertions.assertEquals(TTaskType.CREATE, request.getTaskType()); + Assertions.assertEquals(createReplicaTask.getSignature(), request.getSignature()); + Assertions.assertNotNull(request.getCreateTabletReq()); // create with row binlog tablet BinlogConfig binlogConfig = BinlogTestUtils.newTestRowBinlogConfig(true, false); @@ -185,8 +185,8 @@ public void toThriftTest() throws Exception { createWithRowBinlog.setTabletRole(TTabletRole.TABLET_ROLE_ROW_BINLOG); TAgentTaskRequest requestWithRowBinlog = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithRowBinlog); - Assert.assertNotNull(requestWithRowBinlog.getCreateTabletReq()); - Assert.assertEquals(TTabletRole.TABLET_ROLE_ROW_BINLOG, + Assertions.assertNotNull(requestWithRowBinlog.getCreateTabletReq()); + Assertions.assertEquals(TTabletRole.TABLET_ROLE_ROW_BINLOG, requestWithRowBinlog.getCreateTabletReq().getTabletRole()); List bfIndexes = Arrays.asList(new Index(1L, "bf_k1", Arrays.asList("k1"), @@ -199,17 +199,17 @@ public void toThriftTest() throws Exception { TEncryptionAlgorithm.PLAINTEXT, storageDictPageSize, new HashMap<>(), 5); TAgentTaskRequest requestWithBfIndex = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithBfIndex); - Assert.assertNotNull(requestWithBfIndex.getCreateTabletReq()); - Assert.assertTrue(requestWithBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertNotNull(requestWithBfIndex.getCreateTabletReq()); + Assertions.assertTrue(requestWithBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).isIsBloomFilterColumn()); - Assert.assertFalse(requestWithBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertFalse(requestWithBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(1).isSetIsBloomFilterColumn()); // bfColumns is null, so table-level FPP is not set for BfIndex-only tables. // Each BfIndex carries its own FPP in its properties. - Assert.assertFalse(requestWithBfIndex.getCreateTabletReq().getTabletSchema().isSetBloomFilterFpp()); - Assert.assertTrue(requestWithBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertFalse(requestWithBfIndex.getCreateTabletReq().getTabletSchema().isSetBloomFilterFpp()); + Assertions.assertTrue(requestWithBfIndex.getCreateTabletReq().getTabletSchema() .getIndexes().get(0).getProperties().containsKey("bloom_filter_fpp")); - Assert.assertEquals("0.02", requestWithBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertEquals("0.02", requestWithBfIndex.getCreateTabletReq().getTabletSchema() .getIndexes().get(0).getProperties().get("bloom_filter_fpp")); Set bfColumns = new HashSet<>(); @@ -222,10 +222,10 @@ public void toThriftTest() throws Exception { TEncryptionAlgorithm.PLAINTEXT, storageDictPageSize, new HashMap<>(), 5); TAgentTaskRequest requestWithBfColumns = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithBfColumns); - Assert.assertNotNull(requestWithBfColumns.getCreateTabletReq()); - Assert.assertTrue(requestWithBfColumns.getCreateTabletReq().getTabletSchema() + Assertions.assertNotNull(requestWithBfColumns.getCreateTabletReq()); + Assertions.assertTrue(requestWithBfColumns.getCreateTabletReq().getTabletSchema() .getColumns().get(0).isIsBloomFilterColumn()); - Assert.assertEquals(0.02, + Assertions.assertEquals(0.02, requestWithBfColumns.getCreateTabletReq().getTabletSchema().getBloomFilterFpp(), 0); List shadowColumns = Arrays.asList( @@ -240,9 +240,9 @@ public void toThriftTest() throws Exception { TEncryptionAlgorithm.PLAINTEXT, storageDictPageSize, new HashMap<>(), 5); TAgentTaskRequest requestWithShadowBfIndex = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithShadowBfIndex); - Assert.assertEquals("k1", requestWithShadowBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertEquals("k1", requestWithShadowBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).getColumnName()); - Assert.assertTrue(requestWithShadowBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertTrue(requestWithShadowBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).isIsBloomFilterColumn()); AgentTask createWithFoldedBfIndex = new CreateReplicaTask(backendId1, dbId, tableId, partitionId, @@ -255,14 +255,14 @@ public void toThriftTest() throws Exception { TEncryptionAlgorithm.PLAINTEXT, storageDictPageSize, new HashMap<>(), 5); TAgentTaskRequest requestWithFoldedBfIndex = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithFoldedBfIndex); - Assert.assertEquals("k1", requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertEquals("k1", requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).getColumnName()); - Assert.assertTrue(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertTrue(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).isIsBloomFilterColumn()); // bfColumns is null, so table-level FPP is not set. BfIndexes carry their own FPP. - Assert.assertFalse(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema().isSetBloomFilterFpp()); - Assert.assertTrue(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema().isSetIndexes()); - Assert.assertEquals("0.03", requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertFalse(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema().isSetBloomFilterFpp()); + Assertions.assertTrue(requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema().isSetIndexes()); + Assertions.assertEquals("0.03", requestWithFoldedBfIndex.getCreateTabletReq().getTabletSchema() .getIndexes().get(0).getProperties().get("bloom_filter_fpp")); Set emptyBfColumns = new HashSet<>(); @@ -277,60 +277,60 @@ public void toThriftTest() throws Exception { TAgentTaskRequest requestWithEmptyBfColumnsAndBfIndex = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, createWithEmptyBfColumnsAndBfIndex); - Assert.assertTrue(requestWithEmptyBfColumnsAndBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertTrue(requestWithEmptyBfColumnsAndBfIndex.getCreateTabletReq().getTabletSchema() .getColumns().get(0).isIsBloomFilterColumn()); - Assert.assertFalse(requestWithEmptyBfColumnsAndBfIndex.getCreateTabletReq().getTabletSchema() + Assertions.assertFalse(requestWithEmptyBfColumnsAndBfIndex.getCreateTabletReq().getTabletSchema() .isSetBloomFilterFpp()); // drop TAgentTaskRequest request2 = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, dropTask); - Assert.assertEquals(TTaskType.DROP, request2.getTaskType()); - Assert.assertEquals(dropTask.getSignature(), request2.getSignature()); - Assert.assertNotNull(request2.getDropTabletReq()); + Assertions.assertEquals(TTaskType.DROP, request2.getTaskType()); + Assertions.assertEquals(dropTask.getSignature(), request2.getSignature()); + Assertions.assertNotNull(request2.getDropTabletReq()); // clone TAgentTaskRequest request4 = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, cloneTask); - Assert.assertEquals(TTaskType.CLONE, request4.getTaskType()); - Assert.assertEquals(cloneTask.getSignature(), request4.getSignature()); - Assert.assertNotNull(request4.getCloneReq()); + Assertions.assertEquals(TTaskType.CLONE, request4.getTaskType()); + Assertions.assertEquals(cloneTask.getSignature(), request4.getSignature()); + Assertions.assertNotNull(request4.getCloneReq()); // storageMediaMigrationTask TAgentTaskRequest request7 = (TAgentTaskRequest) toAgentTaskRequest.invoke(agentBatchTask, storageMediaMigrationTask); - Assert.assertEquals(TTaskType.STORAGE_MEDIUM_MIGRATE, request7.getTaskType()); - Assert.assertEquals(storageMediaMigrationTask.getSignature(), request7.getSignature()); - Assert.assertNotNull(request7.getStorageMediumMigrateReq()); - Assert.assertTrue(request7.getStorageMediumMigrateReq().isSetDataDir()); - Assert.assertEquals(request7.getStorageMediumMigrateReq().getDataDir(), "/home/a"); + Assertions.assertEquals(TTaskType.STORAGE_MEDIUM_MIGRATE, request7.getTaskType()); + Assertions.assertEquals(storageMediaMigrationTask.getSignature(), request7.getSignature()); + Assertions.assertNotNull(request7.getStorageMediumMigrateReq()); + Assertions.assertTrue(request7.getStorageMediumMigrateReq().isSetDataDir()); + Assertions.assertEquals(request7.getStorageMediumMigrateReq().getDataDir(), "/home/a"); } @Test public void agentTaskQueueTest() { AgentTaskQueue.clearAllTasks(); - Assert.assertEquals(0, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(0, AgentTaskQueue.getTaskNum()); // add AgentTaskQueue.addTask(createReplicaTask); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); - Assert.assertFalse(AgentTaskQueue.addTask(createReplicaTask)); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertFalse(AgentTaskQueue.addTask(createReplicaTask)); // get AgentTask task = AgentTaskQueue.getTask(backendId1, TTaskType.CREATE, createReplicaTask.getSignature()); - Assert.assertEquals(createReplicaTask, task); + Assertions.assertEquals(createReplicaTask, task); Map> runningTasks = new HashMap>(); List diffTasks = AgentTaskQueue.getDiffTasks(backendId1, runningTasks); - Assert.assertEquals(1, diffTasks.size()); + Assertions.assertEquals(1, diffTasks.size()); Set set = new HashSet(); set.add(createReplicaTask.getSignature()); runningTasks.put(TTaskType.CREATE, set); diffTasks = AgentTaskQueue.getDiffTasks(backendId1, runningTasks); - Assert.assertEquals(0, diffTasks.size()); + Assertions.assertEquals(0, diffTasks.size()); // remove AgentTaskQueue.removeTask(backendId1, TTaskType.CREATE, createReplicaTask.getSignature()); - Assert.assertEquals(0, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(0, AgentTaskQueue.getTaskNum()); } @Test @@ -338,20 +338,20 @@ public void failedAgentTaskTest() { AgentTaskQueue.clearAllTasks(); AgentTaskQueue.addTask(dropTask); - Assert.assertEquals(0, dropTask.getFailedTimes()); + Assertions.assertEquals(0, dropTask.getFailedTimes()); dropTask.failed(); - Assert.assertEquals(1, dropTask.getFailedTimes()); + Assertions.assertEquals(1, dropTask.getFailedTimes()); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum()); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, false)); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum(-1, TTaskType.DROP, false)); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, true)); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum()); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, false)); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum(-1, TTaskType.DROP, false)); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, true)); dropTask.failed(); DropReplicaTask dropTask2 = new DropReplicaTask(backendId2, tabletId1, replicaId1, schemaHash1, false); AgentTaskQueue.addTask(dropTask2); dropTask2.failed(); - Assert.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, true)); - Assert.assertEquals(2, AgentTaskQueue.getTaskNum(-1, TTaskType.DROP, true)); + Assertions.assertEquals(1, AgentTaskQueue.getTaskNum(backendId1, TTaskType.DROP, true)); + Assertions.assertEquals(2, AgentTaskQueue.getTaskNum(-1, TTaskType.DROP, true)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/task/MasterTaskExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/task/MasterTaskExecutorTest.java index ae88afe2e59b64..ad42815ddf5493 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/task/MasterTaskExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/task/MasterTaskExecutorTest.java @@ -17,10 +17,10 @@ package org.apache.doris.task; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,13 +31,13 @@ public class MasterTaskExecutorTest { private MasterTaskExecutor executor; - @Before + @BeforeEach public void setUp() { executor = new MasterTaskExecutor("master_task_executor_test", THREAD_NUM, false); executor.start(); } - @After + @AfterEach public void tearDown() { if (executor != null) { executor.close(); @@ -48,23 +48,23 @@ public void tearDown() { public void testSubmit() { // submit task MasterTask task1 = new TestMasterTask(1L); - Assert.assertTrue(executor.submit(task1)); - Assert.assertEquals(1, executor.getTaskNum()); + Assertions.assertTrue(executor.submit(task1)); + Assertions.assertEquals(1, executor.getTaskNum()); // submit same running task error - Assert.assertFalse(executor.submit(task1)); - Assert.assertEquals(1, executor.getTaskNum()); + Assertions.assertFalse(executor.submit(task1)); + Assertions.assertEquals(1, executor.getTaskNum()); // submit another task MasterTask task2 = new TestMasterTask(2L); - Assert.assertTrue(executor.submit(task2)); - Assert.assertEquals(2, executor.getTaskNum()); + Assertions.assertTrue(executor.submit(task2)); + Assertions.assertEquals(2, executor.getTaskNum()); // wait for tasks run to end try { // checker thread interval is 1s // sleep 3s Thread.sleep(SLEEP_MS * 300); - Assert.assertEquals(0, executor.getTaskNum()); + Assertions.assertEquals(0, executor.getTaskNum()); } catch (InterruptedException e) { LOG.error("error", e); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/task/PriorityMasterTaskExecutorTest.java b/fe/fe-core/src/test/java/org/apache/doris/task/PriorityMasterTaskExecutorTest.java index 29d97e7cf8e535..5dbc3fb003b0b0 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/task/PriorityMasterTaskExecutorTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/task/PriorityMasterTaskExecutorTest.java @@ -18,10 +18,10 @@ package org.apache.doris.task; import com.google.common.collect.Lists; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +40,7 @@ public class PriorityMasterTaskExecutorTest { private PriorityMasterTaskExecutor executor; - @Before + @BeforeEach public void setUp() { Comparator comparator = Comparator.comparing(TestMasterTask::getPriority) .thenComparingLong(TestMasterTask::getSignature); @@ -49,7 +49,7 @@ public void setUp() { executor.start(); } - @After + @AfterEach public void tearDown() { if (executor != null) { executor.close(); @@ -62,10 +62,10 @@ public void testSubmit() { MasterTask errorTask = new ErrorMasterTask(); try { executor.submit(errorTask); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e instanceof RejectedExecutionException); - Assert.assertTrue(("Task must be an instance of [" + TestMasterTask.class.getName() + "]").equals(e.getMessage())); + Assertions.assertTrue(e instanceof RejectedExecutionException); + Assertions.assertTrue(("Task must be an instance of [" + TestMasterTask.class.getName() + "]").equals(e.getMessage())); } @@ -73,12 +73,12 @@ public void testSubmit() { CountDownLatch finishLatch = new CountDownLatch(5); // submit task MasterTask task1 = new TestMasterTask(1L, 0, startLatch, finishLatch); - Assert.assertTrue(executor.submit(task1)); - Assert.assertEquals(1, executor.getTaskNum()); + Assertions.assertTrue(executor.submit(task1)); + Assertions.assertEquals(1, executor.getTaskNum()); // submit same running task error - Assert.assertFalse(executor.submit(task1)); - Assert.assertEquals(1, executor.getTaskNum()); + Assertions.assertFalse(executor.submit(task1)); + Assertions.assertEquals(1, executor.getTaskNum()); // submit some task with priority MasterTask task5 = new TestMasterTask(5L, 1, startLatch, finishLatch); @@ -101,17 +101,17 @@ public void testSubmit() { finishLatch.await(); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); - Assert.fail(); + Assertions.fail(); } // compare priority value first, the lower the higher priority // then compare signature value, the lower the higher priority - Assert.assertTrue(runningOrderList.size() == 5); - Assert.assertTrue(runningOrderList.get(0) == task1); - Assert.assertTrue(runningOrderList.get(1) == task3); - Assert.assertTrue(runningOrderList.get(2) == task4); - Assert.assertTrue(runningOrderList.get(3) == task2); - Assert.assertTrue(runningOrderList.get(4) == task5); + Assertions.assertTrue(runningOrderList.size() == 5); + Assertions.assertTrue(runningOrderList.get(0) == task1); + Assertions.assertTrue(runningOrderList.get(1) == task3); + Assertions.assertTrue(runningOrderList.get(2) == task4); + Assertions.assertTrue(runningOrderList.get(3) == task2); + Assertions.assertTrue(runningOrderList.get(4) == task5); } private class ErrorMasterTask extends MasterTask { diff --git a/fe/fe-core/src/test/java/org/apache/doris/task/PublishVersionTaskTest.java b/fe/fe-core/src/test/java/org/apache/doris/task/PublishVersionTaskTest.java index df6c9e3cc5732a..ca54dbaab35fc9 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/task/PublishVersionTaskTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/task/PublishVersionTaskTest.java @@ -18,8 +18,8 @@ package org.apache.doris.task; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; @@ -45,11 +45,10 @@ private PublishVersionTask newTask() { @Test public void testDefaultSuccTabletsIsNotNull() { PublishVersionTask task = newTask(); - Assert.assertNotNull("succTablets must be non-null right after construction", - task.getSuccTablets()); - Assert.assertTrue("succTablets must start empty", task.getSuccTablets().isEmpty()); + Assertions.assertNotNull(task.getSuccTablets(), "succTablets must be non-null right after construction"); + Assertions.assertTrue(task.getSuccTablets().isEmpty(), "succTablets must start empty"); // Should not NPE. - Assert.assertFalse(task.getSuccTablets().containsKey(1L)); + Assertions.assertFalse(task.getSuccTablets().containsKey(1L)); } /** setSuccTablets(null) must coerce to an empty map, not store null. */ @@ -57,9 +56,9 @@ public void testDefaultSuccTabletsIsNotNull() { public void testSetSuccTabletsNullCoercesToEmptyMap() { PublishVersionTask task = newTask(); task.setSuccTablets(null); - Assert.assertNotNull(task.getSuccTablets()); - Assert.assertTrue(task.getSuccTablets().isEmpty()); - Assert.assertFalse(task.getSuccTablets().containsKey(123L)); + Assertions.assertNotNull(task.getSuccTablets()); + Assertions.assertTrue(task.getSuccTablets().isEmpty()); + Assertions.assertFalse(task.getSuccTablets().containsKey(123L)); } /** A populated map must be returned as-is by the getter. */ @@ -68,8 +67,8 @@ public void testSetSuccTabletsKeepsValues() { PublishVersionTask task = newTask(); Map populated = ImmutableMap.of(1L, 100L, 2L, 200L); task.setSuccTablets(populated); - Assert.assertEquals(populated, task.getSuccTablets()); - Assert.assertTrue(task.getSuccTablets().containsKey(1L)); + Assertions.assertEquals(populated, task.getSuccTablets()); + Assertions.assertTrue(task.getSuccTablets().containsKey(1L)); } /** @@ -85,9 +84,9 @@ public void testForceFinishWithoutSetSuccTabletsDoesNotNpe() { task.setFinished(true); // No setSuccTablets call — this is the AgentTaskCleanupDaemon code path. Map succ = task.getSuccTablets(); - Assert.assertNotNull("getSuccTablets() must not return null even when force-finished", succ); - Assert.assertTrue(task.isFinished()); - Assert.assertFalse(succ.containsKey(42L)); + Assertions.assertNotNull(succ, "getSuccTablets() must not return null even when force-finished"); + Assertions.assertTrue(task.isFinished()); + Assertions.assertFalse(succ.containsKey(42L)); } /** @@ -101,9 +100,9 @@ public void testFinishPublishVersionPathWithNullSuccTablets() { task.setSuccTablets(null); // emulates request.isSetSuccTablets() == false task.setFinished(true); // matches MasterImpl ordering Map succ = task.getSuccTablets(); - Assert.assertNotNull(succ); - Assert.assertEquals(Collections.emptyMap(), succ); + Assertions.assertNotNull(succ); + Assertions.assertEquals(Collections.emptyMap(), succ); // The exact line that crashed pre-fix at DatabaseTransactionMgr.java:1478. - Assert.assertFalse(succ.containsKey(7L)); + Assertions.assertFalse(succ.containsKey(7L)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/AutoPartitionCacheManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/AutoPartitionCacheManagerTest.java index b1c9d54bd869db..06b668d9f27c5d 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/AutoPartitionCacheManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/AutoPartitionCacheManagerTest.java @@ -19,8 +19,8 @@ import org.apache.doris.thrift.TTabletLocation; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -35,22 +35,22 @@ public void testGetOrSetAutoPartitionInfoReturnsCachedLoadTabletIdx() { firstTablets.add(new TTabletLocation(10001L, Arrays.asList(1L))); long storedLoadTabletIdx = cacheManager.getOrSetAutoPartitionInfo( 10L, 20L, firstTablets, 3); - Assert.assertEquals(3, storedLoadTabletIdx); + Assertions.assertEquals(3, storedLoadTabletIdx); List secondTablets = new ArrayList<>(); secondTablets.add(new TTabletLocation(20001L, Arrays.asList(2L))); long cachedLoadTabletIdx = cacheManager.getOrSetAutoPartitionInfo( 10L, 20L, secondTablets, 5); - Assert.assertEquals(3, cachedLoadTabletIdx); - Assert.assertEquals(1, secondTablets.size()); - Assert.assertEquals(10001L, secondTablets.get(0).getTabletId()); + Assertions.assertEquals(3, cachedLoadTabletIdx); + Assertions.assertEquals(1, secondTablets.size()); + Assertions.assertEquals(10001L, secondTablets.get(0).getTabletId()); List cachedTablets = new ArrayList<>(); AtomicLong readLoadTabletIdx = new AtomicLong(-1); - Assert.assertTrue(cacheManager.getAutoPartitionInfo( + Assertions.assertTrue(cacheManager.getAutoPartitionInfo( 10L, 20L, cachedTablets, readLoadTabletIdx)); - Assert.assertEquals(3, readLoadTabletIdx.get()); - Assert.assertEquals(1, cachedTablets.size()); - Assert.assertEquals(10001L, cachedTablets.get(0).getTabletId()); + Assertions.assertEquals(3, readLoadTabletIdx.get()); + Assertions.assertEquals(1, cachedTablets.size()); + Assertions.assertEquals(10001L, cachedTablets.get(0).getTabletId()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/CheckReplicaContinuousVersionSuccTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/CheckReplicaContinuousVersionSuccTest.java index 6e34d3173d7d59..3f65b97bff6a01 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/CheckReplicaContinuousVersionSuccTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/CheckReplicaContinuousVersionSuccTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Field; @@ -58,8 +58,7 @@ private PublishVersionTask newFinishedTaskWithNullSuccTablets() throws Exception Field f = PublishVersionTask.class.getDeclaredField("succTablets"); f.setAccessible(true); f.set(task, null); - Assert.assertNull("precondition: succTablets must be null for this test", - task.getSuccTablets()); + Assertions.assertNull(task.getSuccTablets(), "precondition: succTablets must be null for this test"); return task; } @@ -86,7 +85,7 @@ private void invokeCheck(Set errorReplicaIds, tabletSuccReplicas, tabletWriteFailedReplicas, tabletVersionFailedReplicas); } catch (InvocationTargetException ite) { if (ite.getCause() instanceof NullPointerException) { - Assert.fail("checkReplicaContinuousVersionSucc threw NPE on null succTablets: " + Assertions.fail("checkReplicaContinuousVersionSucc threw NPE on null succTablets: " + ite.getCause()); } throw ite; @@ -116,10 +115,9 @@ public void testNoNpeWhenSuccTabletsIsNull() throws Exception { tabletVersionFailedReplicas, task, replica, /*minReplicaVersion*/100L, /*maxReplicaVersion*/101L); - Assert.assertTrue("replica should be classified as write-failed when succTablets is null", - tabletWriteFailedReplicas.contains(replica)); - Assert.assertTrue(tabletSuccReplicas.isEmpty()); - Assert.assertTrue(tabletVersionFailedReplicas.isEmpty()); + Assertions.assertTrue(tabletWriteFailedReplicas.contains(replica), "replica should be classified as write-failed when succTablets is null"); + Assertions.assertTrue(tabletSuccReplicas.isEmpty()); + Assertions.assertTrue(tabletVersionFailedReplicas.isEmpty()); } /** @@ -148,10 +146,8 @@ public void testHappyPathWhenSuccTabletsContainsTabletId() throws Exception { tabletVersionFailedReplicas, task, replica, /*minReplicaVersion*/100L, /*maxReplicaVersion*/100L); - Assert.assertFalse("happy path must clear the replica from errorReplicaIds", - errorReplicaIds.contains(REPLICA_ID)); - Assert.assertTrue("happy path must add the replica to tabletSuccReplicas", - tabletSuccReplicas.contains(replica)); + Assertions.assertFalse(errorReplicaIds.contains(REPLICA_ID), "happy path must clear the replica from errorReplicaIds"); + Assertions.assertTrue(tabletSuccReplicas.contains(replica), "happy path must add the replica to tabletSuccReplicas"); } /** @@ -172,6 +168,6 @@ public void testNoNpeWhenTaskIsNull() throws Exception { invokeCheck(errorReplicaIds, tabletSuccReplicas, tabletWriteFailedReplicas, tabletVersionFailedReplicas, /*task*/null, replica, 100L, 101L); - Assert.assertTrue(tabletWriteFailedReplicas.contains(replica)); + Assertions.assertTrue(tabletWriteFailedReplicas.contains(replica)); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/CommitDataSerializerTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/CommitDataSerializerTest.java index da2f9767847984..3068a4a802c343 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/CommitDataSerializerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/CommitDataSerializerTest.java @@ -27,8 +27,8 @@ import org.apache.thrift.TDeserializer; import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TBinaryProtocol; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -81,7 +81,7 @@ private static void assertBinaryRoundTrip(TBase original, TBase targ throws Exception { byte[] bytes = new TSerializer(new TBinaryProtocol.Factory()).serialize(original); new TDeserializer(new TBinaryProtocol.Factory()).deserialize(target, bytes); - Assert.assertEquals(original, target); + Assertions.assertEquals(original, target); } /** @@ -129,11 +129,11 @@ public void addCommitData(byte[] commitFragment) { CommitDataSerializer.feed(collector, input); - Assert.assertEquals(input.size(), payloads.size()); + Assertions.assertEquals(input.size(), payloads.size()); for (int i = 0; i < input.size(); i++) { TIcebergCommitData roundTripped = new TIcebergCommitData(); new TDeserializer(new TBinaryProtocol.Factory()).deserialize(roundTripped, payloads.get(i)); - Assert.assertEquals(input.get(i), roundTripped); + Assertions.assertEquals(input.get(i), roundTripped); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/DatabaseTransactionMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/DatabaseTransactionMgrTest.java index bc85c2134bf1fe..ea0e2b90f3f869 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/DatabaseTransactionMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/DatabaseTransactionMgrTest.java @@ -50,12 +50,10 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.lang.reflect.Field; @@ -71,9 +69,6 @@ public class DatabaseTransactionMgrTest { private static final Logger LOG = LogManager.getLogger(DatabaseTransactionMgrTest.class); private List allBackends = GlobalTransactionMgrTest.allBackends; - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - private static FakeEditLog fakeEditLog; private static FakeEnv fakeEnv; private static FakeTransactionIDGenerator fakeTransactionIDGenerator; @@ -123,7 +118,7 @@ public static void setTransactionFinishPublish(TransactionState transactionState } } - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, UserException { fakeEditLog = new FakeEditLog(); @@ -144,7 +139,7 @@ public void setUp() throws InstantiationException, IllegalAccessException, Illeg LabelToTxnId = addTransactionToTransactionMgr(); } - @After + @AfterEach public void tearDown() { if (fakeEnv != null) { fakeEnv.close(); @@ -217,30 +212,30 @@ public Map addTransactionToTransactionMgr() throws UserException { @Test public void testNormal() throws UserException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); - Assert.assertEquals(4, masterDbTransMgr.getTransactionNum()); - Assert.assertEquals(3, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(1, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(4, masterDbTransMgr.getTransactionNum()); + Assertions.assertEquals(3, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(1, masterDbTransMgr.getFinishedTxnNums()); DatabaseTransactionMgr slaveDbTransMgr = slaveTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); - Assert.assertEquals(1, slaveDbTransMgr.getTransactionNum()); - Assert.assertEquals(1, slaveDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(1, slaveDbTransMgr.getTransactionNum()); + Assertions.assertEquals(1, slaveDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel2).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel3).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel4).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel2).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel3).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel4).size()); Long txnId1 = masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1).iterator().next(); - Assert.assertEquals(txnId1, LabelToTxnId.get(CatalogTestUtil.testTxnLabel1)); + Assertions.assertEquals(txnId1, LabelToTxnId.get(CatalogTestUtil.testTxnLabel1)); TransactionState transactionState1 = masterDbTransMgr.getTransactionState( LabelToTxnId.get(CatalogTestUtil.testTxnLabel1)); - Assert.assertEquals(txnId1.longValue(), transactionState1.getTransactionId()); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState1.getTransactionStatus()); + Assertions.assertEquals(txnId1.longValue(), transactionState1.getTransactionId()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState1.getTransactionStatus()); Long txnId2 = masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel2).iterator().next(); - Assert.assertEquals(txnId2, LabelToTxnId.get(CatalogTestUtil.testTxnLabel2)); + Assertions.assertEquals(txnId2, LabelToTxnId.get(CatalogTestUtil.testTxnLabel2)); TransactionState transactionState2 = masterDbTransMgr.getTransactionState(txnId2); - Assert.assertEquals(txnId2.longValue(), transactionState2.getTransactionId()); - Assert.assertEquals(TransactionStatus.PREPARE, transactionState2.getTransactionStatus()); + Assertions.assertEquals(txnId2.longValue(), transactionState2.getTransactionId()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState2.getTransactionStatus()); } @Test @@ -277,9 +272,9 @@ public void testResourceGroupSuccessQuorum() throws UserException { try { masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { - Assert.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); + Assertions.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); } transactionId = masterTransMgr.beginTransaction(CatalogTestUtil.testDbId1, @@ -291,9 +286,9 @@ public void testResourceGroupSuccessQuorum() throws UserException { try { masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { - Assert.assertTrue(e.getMessage().contains("resource group success quorum failed for group2")); + Assertions.assertTrue(e.getMessage().contains("resource group success quorum failed for group2")); } backend2.setTagMap(ImmutableMap.of(Tag.TYPE_LOCATION, "group2")); @@ -318,7 +313,7 @@ public void testResourceGroupSuccessQuorum() throws UserException { transactionSource, LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.assertTrue(appender.contains(Level.WARN, "Invalid resource_group_load_success_quorum item")); + Assertions.assertTrue(appender.contains(Level.WARN, "Invalid resource_group_load_success_quorum item")); } try (TestLogAppender appender = TestLogAppender.attach(DatabaseTransactionMgr.class, Level.WARN)) { transactionId = masterTransMgr.beginTransaction(CatalogTestUtil.testDbId1, @@ -326,7 +321,7 @@ public void testResourceGroupSuccessQuorum() throws UserException { transactionSource, LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.assertFalse(appender.contains(Level.WARN, "Invalid resource_group_load_success_quorum item")); + Assertions.assertFalse(appender.contains(Level.WARN, "Invalid resource_group_load_success_quorum item")); } } finally { @@ -376,9 +371,9 @@ public void testResourceGroupSuccessQuorumDoesNotShrinkAfterReplicaBecomesUnavai try { masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { - Assert.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); + Assertions.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); } backend2.setAlive(true); @@ -389,9 +384,9 @@ public void testResourceGroupSuccessQuorumDoesNotShrinkAfterReplicaBecomesUnavai try { masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), transactionId, commitInfos, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { - Assert.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); + Assertions.assertTrue(e.getMessage().contains("resource group success quorum failed for group1")); } } finally { Config.resource_group_load_success_quorum = originalResourceGroupSuccQuorum; @@ -440,10 +435,10 @@ public void testResourceGroupSuccessQuorumIgnoresExtraReplicaBeyondAllocation() tablet.addReplica(extraReplica); try { - Assert.assertEquals(3, table.getPartitionInfo() + Assertions.assertEquals(3, table.getPartitionInfo() .getReplicaAllocation(CatalogTestUtil.testPartitionId1).getTotalReplicaNum()); - Assert.assertEquals(4, tablet.getReplicas().size()); - Assert.assertEquals(Replica.ReplicaState.NORMAL, + Assertions.assertEquals(4, tablet.getReplicas().size()); + Assertions.assertEquals(Replica.ReplicaState.NORMAL, tablet.getReplicaByBackendId(extraBackendId).getState()); Config.resource_group_load_success_quorum = new String[] {"group1:2"}; @@ -473,15 +468,15 @@ public void testAbortTransaction() throws UserException { long txnId2 = LabelToTxnId.get(CatalogTestUtil.testTxnLabel2); masterDbTransMgr.abortTransaction(txnId2, "test abort transaction", null); - Assert.assertEquals(2, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(2, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(4, masterDbTransMgr.getTransactionNum()); + Assertions.assertEquals(2, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(2, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(4, masterDbTransMgr.getTransactionNum()); long txnId3 = LabelToTxnId.get(CatalogTestUtil.testTxnLabel3); masterDbTransMgr.abortTransaction(txnId3, "test abort transaction", null); - Assert.assertEquals(1, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(3, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(4, masterDbTransMgr.getTransactionNum()); + Assertions.assertEquals(1, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(3, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(4, masterDbTransMgr.getTransactionNum()); } @Test @@ -489,18 +484,20 @@ public void testAbortTransactionWithNotFoundException() throws UserException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); long txnId1 = LabelToTxnId.get(CatalogTestUtil.testTxnLabel1); - expectedEx.expect(UserException.class); - expectedEx.expectMessage("transaction not found"); - masterDbTransMgr.abortTransaction(txnId1, "test abort transaction", null); + UserException e = Assertions.assertThrows(UserException.class, () -> { + masterDbTransMgr.abortTransaction(txnId1, "test abort transaction", null); + }); + Assertions.assertTrue(e.getMessage().contains("transaction not found"), + "unexpected message: " + e.getMessage()); } @Test public void testGetTransactionIdByCoordinateBe() throws UserException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); List> transactionInfoList = masterDbTransMgr.getPrepareTransactionIdByCoordinateBe(0, "be1", 10); - Assert.assertEquals(3, transactionInfoList.size()); - Assert.assertEquals(CatalogTestUtil.testDbId1, transactionInfoList.get(0).first.longValue()); - Assert.assertEquals(TransactionStatus.PREPARE, + Assertions.assertEquals(3, transactionInfoList.size()); + Assertions.assertEquals(CatalogTestUtil.testDbId1, transactionInfoList.get(0).first.longValue()); + Assertions.assertEquals(TransactionStatus.PREPARE, masterDbTransMgr.getTransactionState(transactionInfoList.get(0).second).getTransactionStatus()); } @@ -509,23 +506,23 @@ public void testGetSingleTranInfo() throws AnalysisException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); long txnId = LabelToTxnId.get(CatalogTestUtil.testTxnLabel1); List> singleTranInfos = masterDbTransMgr.getSingleTranInfo(CatalogTestUtil.testDbId1, txnId); - Assert.assertEquals(1, singleTranInfos.size()); + Assertions.assertEquals(1, singleTranInfos.size()); List txnInfo = singleTranInfos.get(0); - Assert.assertEquals("1000", txnInfo.get(0)); - Assert.assertEquals(CatalogTestUtil.testTxnLabel1, txnInfo.get(1)); - Assert.assertEquals("FE: localfe", txnInfo.get(2)); - Assert.assertEquals("VISIBLE", txnInfo.get(3)); - Assert.assertEquals("FRONTEND", txnInfo.get(4)); + Assertions.assertEquals("1000", txnInfo.get(0)); + Assertions.assertEquals(CatalogTestUtil.testTxnLabel1, txnInfo.get(1)); + Assertions.assertEquals("FE: localfe", txnInfo.get(2)); + Assertions.assertEquals("VISIBLE", txnInfo.get(3)); + Assertions.assertEquals("FRONTEND", txnInfo.get(4)); long currentTime = System.currentTimeMillis(); - Assert.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(5))); - Assert.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(6))); - Assert.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(7))); - Assert.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(8))); - Assert.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(9))); - Assert.assertEquals("", txnInfo.get(10)); - Assert.assertEquals("0", txnInfo.get(11)); - Assert.assertEquals("-1", txnInfo.get(12)); - Assert.assertEquals(String.valueOf(Config.stream_load_default_timeout_second * 1000), txnInfo.get(13)); + Assertions.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(5))); + Assertions.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(6))); + Assertions.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(7))); + Assertions.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(8))); + Assertions.assertTrue(currentTime > TimeUtils.timeStringToLong(txnInfo.get(9))); + Assertions.assertEquals("", txnInfo.get(10)); + Assertions.assertEquals("0", txnInfo.get(11)); + Assertions.assertEquals("-1", txnInfo.get(12)); + Assertions.assertEquals(String.valueOf(Config.stream_load_default_timeout_second * 1000), txnInfo.get(13)); } @Test @@ -534,9 +531,9 @@ public void testRemoveExpiredTxns() throws AnalysisException { Config.label_keep_max_second = -1; long currentMillis = System.currentTimeMillis(); masterDbTransMgr.removeUselessTxns(currentMillis); - Assert.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(3, masterDbTransMgr.getTransactionNum()); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); + Assertions.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(3, masterDbTransMgr.getTransactionNum()); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); } @Test @@ -544,9 +541,9 @@ public void testRemoveOverLimitTxns() throws AnalysisException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); Config.label_num_threshold = 0; masterDbTransMgr.removeUselessTxns(System.currentTimeMillis()); - Assert.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(3, masterDbTransMgr.getTransactionNum()); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); + Assertions.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(3, masterDbTransMgr.getTransactionNum()); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); } @Test @@ -554,11 +551,11 @@ public void testGetTableTransInfo() throws AnalysisException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); Long txnId = LabelToTxnId.get(CatalogTestUtil.testTxnLabel1); List> tableTransInfos = masterDbTransMgr.getTableTransInfo(txnId); - Assert.assertEquals(1, tableTransInfos.size()); + Assertions.assertEquals(1, tableTransInfos.size()); List tableTransInfo = tableTransInfos.get(0); - Assert.assertEquals(2, tableTransInfo.size()); - Assert.assertEquals(2L, tableTransInfo.get(0)); - Assert.assertEquals("3", tableTransInfo.get(1)); + Assertions.assertEquals(2, tableTransInfo.size()); + Assertions.assertEquals(2L, tableTransInfo.get(0)); + Assertions.assertEquals("3", tableTransInfo.get(1)); } @Test @@ -567,11 +564,11 @@ public void testGetPartitionTransInfo() throws AnalysisException { Long txnId = LabelToTxnId.get(CatalogTestUtil.testTxnLabel1); List> partitionTransInfos = masterDbTransMgr.getPartitionTransInfo(txnId, CatalogTestUtil.testTableId1); - Assert.assertEquals(1, partitionTransInfos.size()); + Assertions.assertEquals(1, partitionTransInfos.size()); List partitionTransInfo = partitionTransInfos.get(0); - Assert.assertEquals(2, partitionTransInfo.size()); - Assert.assertEquals(3L, partitionTransInfo.get(0)); - Assert.assertEquals(13L, partitionTransInfo.get(1)); + Assertions.assertEquals(2, partitionTransInfo.size()); + Assertions.assertEquals(3L, partitionTransInfo.get(0)); + Assertions.assertEquals(13L, partitionTransInfo.get(1)); } @Test @@ -580,10 +577,10 @@ public void testDeleteTransaction() throws AnalysisException { long txnId = LabelToTxnId.get(CatalogTestUtil.testTxnLabel1); TransactionState transactionState = masterDbTransMgr.getTransactionState(txnId); masterDbTransMgr.replayDeleteTransaction(transactionState); - Assert.assertEquals(3, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(3, masterDbTransMgr.getTransactionNum()); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); + Assertions.assertEquals(3, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(3, masterDbTransMgr.getTransactionNum()); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); } @Test @@ -591,17 +588,17 @@ public void testSubTransaction() throws UserException { addSubTransaction(); DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr( CatalogTestUtil.testDbId1); - Assert.assertEquals(4 + 4, masterDbTransMgr.getTransactionNum()); - Assert.assertEquals(3 + 2, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(1 + 2, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(4 + 4, masterDbTransMgr.getTransactionNum()); + Assertions.assertEquals(3 + 2, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(1 + 2, masterDbTransMgr.getFinishedTxnNums()); // LoadJobSourceType.INSERT_STREAMING does not write edit log when begin txn DatabaseTransactionMgr slaveDbTransMgr = slaveTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1); - Assert.assertEquals(1, slaveDbTransMgr.getTransactionNum()); + Assertions.assertEquals(1, slaveDbTransMgr.getTransactionNum()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel5).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel7).size()); - Assert.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel8).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel5).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel7).size()); + Assertions.assertEquals(1, masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel8).size()); // test get transaction state by subTxnId TransactionState transactionState6 = masterDbTransMgr.getTransactionState( @@ -610,7 +607,7 @@ public void testSubTransaction() throws UserException { long subTransactionId3 = transactionState6.getSubTxnIds().get(2); TransactionState subTransactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, subTransactionId3); - Assert.assertEquals(null, subTransactionState); // finished txn will remove sub txn map + Assertions.assertEquals(null, subTransactionState); // finished txn will remove sub txn map // test show transaction state command /*List> singleTranInfos = masterDbTransMgr.getSingleTranInfo(CatalogTestUtil.testDbId1, subTransactionId3); @@ -621,49 +618,49 @@ public void testSubTransaction() throws UserException { // test get table transaction info: table_id to partition_id map List> tableTransInfos = masterDbTransMgr.getTableTransInfo(transactionId6); LOG.info("tableTransInfos: {}", tableTransInfos); - Assert.assertEquals(3, tableTransInfos.size()); + Assertions.assertEquals(3, tableTransInfos.size()); List tableTransInfo0 = tableTransInfos.get(0); - Assert.assertEquals(2, tableTransInfo0.size()); - Assert.assertEquals(2L, tableTransInfo0.get(0)); - Assert.assertEquals("3", tableTransInfo0.get(1)); + Assertions.assertEquals(2, tableTransInfo0.size()); + Assertions.assertEquals(2L, tableTransInfo0.get(0)); + Assertions.assertEquals("3", tableTransInfo0.get(1)); List tableTransInfo1 = tableTransInfos.get(1); - Assert.assertEquals(2, tableTransInfo1.size()); - Assert.assertEquals(15L, tableTransInfo1.get(0)); - Assert.assertEquals("16", tableTransInfo1.get(1)); + Assertions.assertEquals(2, tableTransInfo1.size()); + Assertions.assertEquals(15L, tableTransInfo1.get(0)); + Assertions.assertEquals("16", tableTransInfo1.get(1)); List tableTransInfo2 = tableTransInfos.get(2); - Assert.assertEquals(2, tableTransInfo2.size()); - Assert.assertEquals(2L, tableTransInfo2.get(0)); - Assert.assertEquals("3", tableTransInfo2.get(1)); + Assertions.assertEquals(2, tableTransInfo2.size()); + Assertions.assertEquals(2L, tableTransInfo2.get(0)); + Assertions.assertEquals("3", tableTransInfo2.get(1)); // test get partition transaction info List> partitionTransInfos1 = masterDbTransMgr.getPartitionTransInfo(transactionId6, CatalogTestUtil.testTableId1); LOG.info("partitionTransInfos for table1: {}", partitionTransInfos1); - Assert.assertEquals(2, partitionTransInfos1.size()); + Assertions.assertEquals(2, partitionTransInfos1.size()); List partitionTransInfo0 = partitionTransInfos1.get(0); - Assert.assertEquals(2, partitionTransInfo0.size()); - Assert.assertEquals(3L, partitionTransInfo0.get(0)); - Assert.assertEquals(14L, partitionTransInfo0.get(1)); + Assertions.assertEquals(2, partitionTransInfo0.size()); + Assertions.assertEquals(3L, partitionTransInfo0.get(0)); + Assertions.assertEquals(14L, partitionTransInfo0.get(1)); List partitionTransInfo1 = partitionTransInfos1.get(1); - Assert.assertEquals(2, partitionTransInfo1.size()); - Assert.assertEquals(3L, partitionTransInfo1.get(0)); - Assert.assertEquals(15L, partitionTransInfo1.get(1)); + Assertions.assertEquals(2, partitionTransInfo1.size()); + Assertions.assertEquals(3L, partitionTransInfo1.get(0)); + Assertions.assertEquals(15L, partitionTransInfo1.get(1)); List> partitionTransInfos2 = masterDbTransMgr.getPartitionTransInfo(transactionId6, CatalogTestUtil.testTableId2); LOG.info("partitionTransInfos for table2: {}", partitionTransInfos2); - Assert.assertEquals(1, partitionTransInfos2.size()); + Assertions.assertEquals(1, partitionTransInfos2.size()); List partitionTransInfo3 = partitionTransInfos2.get(0); - Assert.assertEquals(2, partitionTransInfo3.size()); - Assert.assertEquals(16L, partitionTransInfo3.get(0)); - Assert.assertEquals(13L, partitionTransInfo3.get(1)); + Assertions.assertEquals(2, partitionTransInfo3.size()); + Assertions.assertEquals(16L, partitionTransInfo3.get(0)); + Assertions.assertEquals(13L, partitionTransInfo3.get(1)); // test delete transaction masterDbTransMgr.replayDeleteTransaction(transactionState6); - Assert.assertEquals(4 + 3, masterDbTransMgr.getTransactionNum()); - Assert.assertEquals(3 + 2, masterDbTransMgr.getRunningTxnNums()); - Assert.assertEquals(1 + 1, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6)); - Assert.assertNull(masterDbTransMgr.getTransactionState(subTransactionId3)); + Assertions.assertEquals(4 + 3, masterDbTransMgr.getTransactionNum()); + Assertions.assertEquals(3 + 2, masterDbTransMgr.getRunningTxnNums()); + Assertions.assertEquals(1 + 1, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6)); + Assertions.assertNull(masterDbTransMgr.getTransactionState(subTransactionId3)); } @Test @@ -674,10 +671,10 @@ public void testRemoveExpiredTxnsWithSubTxn() throws UserException { Config.streaming_label_keep_max_second = -1; long currentMillis = System.currentTimeMillis(); masterDbTransMgr.removeUselessTxns(currentMillis); - Assert.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); - Assert.assertEquals(3 + 2, masterDbTransMgr.getTransactionNum()); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); - Assert.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6)); + Assertions.assertEquals(0, masterDbTransMgr.getFinishedTxnNums()); + Assertions.assertEquals(3 + 2, masterDbTransMgr.getTransactionNum()); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel1)); + Assertions.assertNull(masterDbTransMgr.unprotectedGetTxnIdsByLabel(CatalogTestUtil.testTxnLabel6)); } @Test @@ -695,7 +692,7 @@ public void testRemoveOverLimitTxnsWithSubTxn() throws UserException { private Pair> beginTransactionWithSubTxn(String label, List tableIds) throws UserException { - Assert.assertTrue(tableIds.size() > 0); + Assertions.assertTrue(tableIds.size() > 0); long transactionId = masterTransMgr.beginTransaction(CatalogTestUtil.testDbId1, Lists.newArrayList(tableIds.get(0)), label, transactionSource, LoadJobSourceType.INSERT_STREAMING, @@ -714,7 +711,7 @@ private Pair> beginTransactionWithSubTxn(String lab // get transaction state by subTransactionId TransactionState subTransactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, subTransactionId); - Assert.assertEquals(subTransactionState, transactionState); + Assertions.assertEquals(subTransactionState, transactionState); } return Pair.of(transactionState, subTxnIds); } @@ -799,7 +796,7 @@ private void addSubTransaction() throws UserException { transactionState6.getTransactionId(), GlobalTransactionMgrTest.generateSubTransactionStates(masterTransMgr, transactionState6, subTransactionInfos), 300000); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState6.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState6.getTransactionStatus()); // finish transaction DatabaseTransactionMgrTest.setTransactionFinishPublish(transactionState6, allBackends, keyToSuccessTablets); @@ -807,7 +804,7 @@ private void addSubTransaction() throws UserException { Map> backendPartitions = Maps.newHashMap(); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState6.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState6.getTransactionStatus()); } // txn with label7 @@ -817,7 +814,7 @@ private void addSubTransaction() throws UserException { // abort transaction masterTransMgr.abortTransaction(CatalogTestUtil.testDbId1, transactionState7.getTransactionId(), "user rollback"); - Assert.assertEquals(TransactionStatus.ABORTED, transactionState7.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.ABORTED, transactionState7.getTransactionStatus()); // txn with label8 Pair> txnInfo8 = beginTransactionWithSubTxn(CatalogTestUtil.testTxnLabel8, @@ -836,7 +833,7 @@ private void addSubTransaction() throws UserException { transactionState8.getTransactionId(), GlobalTransactionMgrTest.generateSubTransactionStates(masterTransMgr, transactionState8, subTransactionInfos), 300000); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState8.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState8.getTransactionStatus()); } LabelToTxnId.put(CatalogTestUtil.testTxnLabel5, transactionState5.getTransactionId()); @@ -883,11 +880,11 @@ public void testCommitTransactionSetsCommitTSOWhenEnableTso() throws Exception { txnId, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(txnId); - Assert.assertNotNull(transactionState); - Assert.assertEquals(expectedCommitTSO, transactionState.getCommitTSO()); + Assertions.assertNotNull(transactionState); + Assertions.assertEquals(expectedCommitTSO, transactionState.getCommitTSO()); TableCommitInfo tableCommitInfo = transactionState.getIdToTableCommitInfos().get(CatalogTestUtil.testTableId1); - Assert.assertNotNull(tableCommitInfo); - Assert.assertEquals(expectedCommitTSO, tableCommitInfo.getCommitTSO()); + Assertions.assertNotNull(tableCommitInfo); + Assertions.assertEquals(expectedCommitTSO, tableCommitInfo.getCommitTSO()); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -920,11 +917,11 @@ public void testCommitTransactionCommitTSORemainsMinusOneWhenTableDisableTso() t txnId, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(txnId); - Assert.assertNotNull(transactionState); - Assert.assertEquals(-1L, transactionState.getCommitTSO()); + Assertions.assertNotNull(transactionState); + Assertions.assertEquals(-1L, transactionState.getCommitTSO()); TableCommitInfo tableCommitInfo = transactionState.getIdToTableCommitInfos().get(CatalogTestUtil.testTableId1); - Assert.assertNotNull(tableCommitInfo); - Assert.assertEquals(-1L, tableCommitInfo.getCommitTSO()); + Assertions.assertNotNull(tableCommitInfo); + Assertions.assertEquals(-1L, tableCommitInfo.getCommitTSO()); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -956,9 +953,9 @@ public void testCommitTransactionFailsWhenGetTSOInvalid() throws Exception { try { masterTransMgr.commitTransactionWithoutLock(CatalogTestUtil.testDbId1, Lists.newArrayList(table), txnId, transTablets, null); - Assert.fail(); + Assertions.fail(); } catch (UserException e) { - Assert.assertTrue(e.getMessage().contains("failed to get TSO")); + Assertions.assertTrue(e.getMessage().contains("failed to get TSO")); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/GlobalTransactionMgrTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/GlobalTransactionMgrTest.java index 2f818857c9374d..b76370ea5e4365 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/GlobalTransactionMgrTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/GlobalTransactionMgrTest.java @@ -63,10 +63,10 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -94,7 +94,7 @@ public class GlobalTransactionMgrTest { protected static List allBackends = Lists.newArrayList(CatalogTestUtil.testBackendId1, CatalogTestUtil.testBackendId2, CatalogTestUtil.testBackendId3); - @Before + @BeforeEach public void setUp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { fakeEditLog = new FakeEditLog(); @@ -113,7 +113,7 @@ public void setUp() throws InstantiationException, IllegalAccessException, Illeg slaveTransMgr.setEditLog(slaveEnv.getEditLog()); } - @After + @AfterEach public void tearDown() { if (fakeEditLog != null) { fakeEditLog.close(); @@ -135,11 +135,11 @@ public void testBeginTransaction() throws LabelAlreadyUsedException, AnalysisExc transactionSource, LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); TransactionState transactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, transactionId); - Assert.assertNotNull(transactionState); - Assert.assertEquals(transactionId, transactionState.getTransactionId()); - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); - Assert.assertEquals(CatalogTestUtil.testDbId1, transactionState.getDbId()); - Assert.assertEquals(transactionSource.toString(), transactionState.getCoordinator().toString()); + Assertions.assertNotNull(transactionState); + Assertions.assertEquals(transactionId, transactionState.getTransactionId()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(CatalogTestUtil.testDbId1, transactionState.getDbId()); + Assertions.assertEquals(transactionSource.toString(), transactionState.getCoordinator().toString()); } @Test @@ -160,20 +160,20 @@ public void testBeginTransactionWithSameLabel() throws LabelAlreadyUsedException e.printStackTrace(); } TransactionState transactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, transactionId); - Assert.assertNotNull(transactionState); - Assert.assertEquals(transactionId, transactionState.getTransactionId()); - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); - Assert.assertEquals(CatalogTestUtil.testDbId1, transactionState.getDbId()); - Assert.assertEquals(transactionSource.toString(), transactionState.getCoordinator().toString()); + Assertions.assertNotNull(transactionState); + Assertions.assertEquals(transactionId, transactionState.getTransactionId()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(CatalogTestUtil.testDbId1, transactionState.getDbId()); + Assertions.assertEquals(transactionSource.toString(), transactionState.getCoordinator().toString()); try { transactionId = masterTransMgr.beginTransaction(CatalogTestUtil.testDbId1, Lists.newArrayList(CatalogTestUtil.testTableId1), CatalogTestUtil.testTxnLabel1, transactionSource, LoadJobSourceType.FRONTEND, Config.stream_load_default_timeout_second); - Assert.fail(); + Assertions.fail(); } catch (Exception e) { - Assert.assertTrue(e.getMessage(), e instanceof LabelAlreadyUsedException); + Assertions.assertTrue(e instanceof LabelAlreadyUsedException, e.getMessage()); } } @@ -192,7 +192,7 @@ public void testCommitTransaction() throws UserException { CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(transactionId); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check replica version checkVersion(testTable1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion + 2, @@ -200,7 +200,7 @@ public void testCommitTransaction() throws UserException { // slave replay new state and compare catalog FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // commit with only two replicas @@ -235,7 +235,7 @@ public void testCommitTransactionWithOneFailed() throws UserException { TransactionState transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // txn2 @@ -253,11 +253,11 @@ public void testCommitTransactionWithOneFailed() throws UserException { try { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId2, transTablets, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { TransactionState transactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, transactionId2); // check status is prepare, because the commit failed - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); } // check replica version checkVersion(testTable1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, @@ -265,7 +265,7 @@ public void testCommitTransactionWithOneFailed() throws UserException { CatalogTestUtil.testStartVersion + 2, CatalogTestUtil.testStartVersion); // the transaction not committed, so that catalog should be equal - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // txn3: commit the second transaction with 1,2,3 success @@ -275,7 +275,7 @@ public void testCommitTransactionWithOneFailed() throws UserException { CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId2, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(transactionId2); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition visible and next version; check replica version checkVersion(testTable1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, @@ -296,7 +296,7 @@ public void testCommitTransactionWithOneFailed() throws UserException { transactionState = fakeEditLog.getTransaction(transactionId2); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } } @@ -355,9 +355,9 @@ public void testCommitRoutineLoadTransaction() 1L, Lists.newArrayList(testTable1), 1L, transTablets, txnCommitAttachment); RoutineLoadStatistic jobStatistic = Deencapsulation.getField(routineLoadJob, "jobStatistic"); - Assert.assertEquals(Long.valueOf(101), Deencapsulation.getField(jobStatistic, "currentTotalRows")); - Assert.assertEquals(Long.valueOf(1), Deencapsulation.getField(jobStatistic, "currentErrorRows")); - Assert.assertEquals(Long.valueOf(101L), ((KafkaProgress) routineLoadJob.getProgress()).getOffsetByPartition(1)); + Assertions.assertEquals(Long.valueOf(101), Deencapsulation.getField(jobStatistic, "currentTotalRows")); + Assertions.assertEquals(Long.valueOf(1), Deencapsulation.getField(jobStatistic, "currentErrorRows")); + Assertions.assertEquals(Long.valueOf(101L), ((KafkaProgress) routineLoadJob.getProgress()).getOffsetByPartition(1)); // todo(ml): change to assert queue // Assert.assertEquals(1, routineLoadManager.getNeedScheduleTasksQueue().size()); // Assert.assertNotEquals("label", routineLoadManager.getNeedScheduleTasksQueue().peek().getId()); @@ -420,13 +420,13 @@ public void testCommitRoutineLoadTransactionWithErrorMax() // current total rows and error rows will be reset after job pause, so here they should be 0. RoutineLoadStatistic jobStatistic = Deencapsulation.getField(routineLoadJob, "jobStatistic"); - Assert.assertEquals(Long.valueOf(0), Deencapsulation.getField(jobStatistic, "currentTotalRows")); - Assert.assertEquals(Long.valueOf(0), Deencapsulation.getField(jobStatistic, "currentErrorRows")); - Assert.assertEquals(Long.valueOf(111L), + Assertions.assertEquals(Long.valueOf(0), Deencapsulation.getField(jobStatistic, "currentTotalRows")); + Assertions.assertEquals(Long.valueOf(0), Deencapsulation.getField(jobStatistic, "currentErrorRows")); + Assertions.assertEquals(Long.valueOf(111L), ((KafkaProgress) routineLoadJob.getProgress()).getOffsetByPartition(1)); // todo(ml): change to assert queue // Assert.assertEquals(0, routineLoadManager.getNeedScheduleTasksQueue().size()); - Assert.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); + Assertions.assertEquals(RoutineLoadJob.JobState.PAUSED, routineLoadJob.getState()); } @Test @@ -441,7 +441,7 @@ public void testFinishTransaction() throws UserException { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(transactionId); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); checkTableVersion(testTable1, 1, 2); slaveTransMgr.replayUpsertTransactionState(transactionState); // finish transaction @@ -455,33 +455,33 @@ public void testFinishTransaction() throws UserException { masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); transactionState = fakeEditLog.getTransaction(transactionId); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); // check partition version Partition testPartition = masterEnv.getInternalCatalog().getDbOrMetaException(CatalogTestUtil.testDbId1) .getTableOrMetaException(CatalogTestUtil.testTableId1).getPartition(CatalogTestUtil.testPartition1); - Assert.assertEquals(CatalogTestUtil.testStartVersion + 1, testPartition.getVisibleVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion + 2, testPartition.getNextVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 1, testPartition.getVisibleVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 2, testPartition.getNextVersion()); // check replica version Tablet tablet = testPartition.getIndex(CatalogTestUtil.testIndexId1).getTablet(CatalogTestUtil.testTabletId1); for (Replica replica : tablet.getReplicas()) { if (replica.getId() == CatalogTestUtil.testReplicaId1) { - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica.getVersion()); } else { - Assert.assertEquals(CatalogTestUtil.testStartVersion + 1, replica.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 1, replica.getVersion()); } } - Assert.assertEquals(ImmutableMap.of(testPartition.getId(), CatalogTestUtil.testStartVersion + 1), + Assertions.assertEquals(ImmutableMap.of(testPartition.getId(), CatalogTestUtil.testStartVersion + 1), partitionVisibleVersions); Set partitionIds = Sets.newHashSet(testPartition.getId()); - Assert.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId1)); - Assert.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId2)); - Assert.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId3)); + Assertions.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId1)); + Assertions.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId2)); + Assertions.assertEquals(partitionIds, backendPartitions.get(CatalogTestUtil.testBackendId3)); checkTableVersion(testTable1, 2, 3); // slave replay new state and compare catalog slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } @Test @@ -513,7 +513,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { TransactionState transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); // master finish the transaction failed FakeEnv.setEnv(masterEnv); @@ -527,9 +527,9 @@ public void testFinishTransactionWithOneFailed() throws UserException { keyToSuccessTablets); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); - Assert.assertTrue(partitionVisibleVersions.isEmpty()); - Assert.assertTrue(backendPartitions.isEmpty()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertTrue(partitionVisibleVersions.isEmpty()); + Assertions.assertTrue(backendPartitions.isEmpty()); // because after calling `finishTransaction`, the txn state is COMMITTED, not VISIBLE, // so all replicas' version are not changed. checkReplicaVersion(replica1, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion, -1); @@ -544,7 +544,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { .get(CatalogTestUtil.testBackendId2).get(0).setSuccTablets(backend2SuccTablets); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); checkReplicaVersion(replica1, CatalogTestUtil.testStartVersion + 1, CatalogTestUtil.testStartVersion + 1, -1); checkReplicaVersion(replica2, CatalogTestUtil.testStartVersion + 1, CatalogTestUtil.testStartVersion + 1, @@ -556,7 +556,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // commit another transaction with 1,3 success @@ -573,12 +573,12 @@ public void testFinishTransactionWithOneFailed() throws UserException { try { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId2, transTablets, null); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { TransactionState transactionState = masterTransMgr.getTransactionState(CatalogTestUtil.testDbId1, transactionId2); // check status is prepare, because the commit failed - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); } } @@ -589,7 +589,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { CatalogTestUtil.testDbId1, Lists.newArrayList(testTable1), transactionId2, transTablets, null); TransactionState transactionState = fakeEditLog.getTransaction(transactionId2); // check status is commit - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkPartitionVersion(testPartition, CatalogTestUtil.testStartVersion + 1, CatalogTestUtil.testStartVersion + 3); @@ -598,7 +598,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { transactionState = fakeEditLog.getTransaction(transactionId2); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); // master finish the transaction2 Map> keyToSuccessTablets = new HashMap<>(); @@ -609,7 +609,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { DatabaseTransactionMgrTest.setTransactionFinishPublish(transactionState, allBackends, keyToSuccessTablets); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId2, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); checkReplicaVersion(replica1, CatalogTestUtil.testStartVersion + 2, CatalogTestUtil.testStartVersion + 2, -1); checkReplicaVersion(replica2, CatalogTestUtil.testStartVersion + 2, CatalogTestUtil.testStartVersion + 2, @@ -623,7 +623,7 @@ public void testFinishTransactionWithOneFailed() throws UserException { transactionState = fakeEditLog.getTransaction(transactionId2); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } } @@ -634,11 +634,11 @@ public void testTransactionWithSubTxn() throws UserException { Lists.newArrayList(CatalogTestUtil.testTableId1), CatalogTestUtil.testTxnLabel1, transactionSource, LoadJobSourceType.INSERT_STREAMING, Config.stream_load_default_timeout_second); // LoadJobSourceType.INSERT_STREAMING does not write edit log - Assert.assertNull(fakeEditLog.getTransaction(transactionId)); + Assertions.assertNull(fakeEditLog.getTransaction(transactionId)); // check transaction status in memory TransactionState transactionState = masterTransMgr.getDatabaseTransactionMgr(CatalogTestUtil.testDbId1) .getTransactionState(transactionId); - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); } // all replica committed success @@ -666,7 +666,7 @@ public void testCommitTransactionWithSubTxn() throws UserException { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion + 3, @@ -677,7 +677,7 @@ public void testCommitTransactionWithSubTxn() throws UserException { // slave replay new state and compare catalog FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } /** @@ -737,7 +737,7 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, @@ -754,7 +754,7 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // txn2 long transactionId; @@ -779,10 +779,10 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); - Assert.fail(); + Assertions.fail(); } catch (TabletQuorumFailedException e) { // check status is prepare - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); } // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, @@ -797,7 +797,7 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { checkReplicaVersion(replica13, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion + 1); // the transaction not committed, so that catalog should be equal - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } // txn3 if (true) { @@ -816,7 +816,7 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { masterTransMgr.commitTransactionWithoutLock( CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, @@ -848,15 +848,15 @@ public void testCommitTransactionWithSubTxnAndOneFailed() throws UserException { Tablet tablet = testPartition.getIndex(CatalogTestUtil.testIndexId2) .getTablet(CatalogTestUtil.testTabletId2); for (Replica replica : tablet.getReplicas()) { - Assert.assertEquals(-1, replica.getLastFailedVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica.getLastSuccessVersion()); + Assertions.assertEquals(-1, replica.getLastFailedVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica.getLastSuccessVersion()); } } transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } } @@ -898,7 +898,7 @@ public void testCommitTransactionWithSubTxnAndReplicaFailed() throws UserExcepti subTransactionStates, 300000); } catch (TabletQuorumFailedException e) { // check status is prepare, because the commit failed - Assert.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.PREPARE, transactionState.getTransactionStatus()); } } @@ -935,7 +935,7 @@ public void testFinishTransactionWithSubTransaction() throws UserException { CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion + 3, @@ -946,7 +946,7 @@ public void testFinishTransactionWithSubTransaction() throws UserException { // slave replay new state and compare catalog FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); checkTableVersion(table1, 1, 2); checkTableVersion(table2, 1, 2); @@ -964,21 +964,21 @@ public void testFinishTransactionWithSubTransaction() throws UserException { Map> backendPartitions = Maps.newHashMap(); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); // check table1 partition version Partition testPartition = masterEnv.getInternalCatalog().getDbOrMetaException(CatalogTestUtil.testDbId1) .getTableOrMetaException(CatalogTestUtil.testTableId1).getPartition(CatalogTestUtil.testPartition1); - Assert.assertEquals(CatalogTestUtil.testStartVersion + 2, testPartition.getVisibleVersion()); - Assert.assertEquals(CatalogTestUtil.testStartVersion + 3, testPartition.getNextVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 2, testPartition.getVisibleVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 3, testPartition.getNextVersion()); // check table1 replica version, table1 has 3 replicas Tablet tablet = testPartition.getIndex(CatalogTestUtil.testIndexId1).getTablet(CatalogTestUtil.testTabletId1); for (Replica replica : tablet.getReplicas()) { if (replica.getId() == CatalogTestUtil.testReplicaId1) { // TODO replica version is [CatalogTestUtil.testStartVersion + 1] is an improvement - Assert.assertEquals(CatalogTestUtil.testStartVersion, replica.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion, replica.getVersion()); } else { - Assert.assertEquals(CatalogTestUtil.testStartVersion + 2, replica.getVersion()); + Assertions.assertEquals(CatalogTestUtil.testStartVersion + 2, replica.getVersion()); } } // check table2 version, table2 has 1 replicas @@ -990,7 +990,7 @@ public void testFinishTransactionWithSubTransaction() throws UserException { // slave replay new state and compare catalog slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } /** @@ -1039,7 +1039,7 @@ public void testFinishTransactionWithSubTransactionAndOneFailed() throws UserExc CatalogTestUtil.testDbId1, Lists.newArrayList(table1, table2), transactionId, subTransactionStates, 300000); // check status is committed - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // check partition version checkVersion(table1, CatalogTestUtil.testPartition1, CatalogTestUtil.testIndexId1, CatalogTestUtil.testTabletId1, CatalogTestUtil.testStartVersion, @@ -1057,7 +1057,7 @@ public void testFinishTransactionWithSubTransactionAndOneFailed() throws UserExc transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); // master finish the transaction failed FakeEnv.setEnv(masterEnv); @@ -1077,7 +1077,7 @@ public void testFinishTransactionWithSubTransactionAndOneFailed() throws UserExc Map> backendPartitions = Maps.newHashMap(); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.COMMITTED, transactionState.getTransactionStatus()); // because after calling `finishTransaction`, the txn state is COMMITTED, not VISIBLE, // so all replicas' version are not changed. checkReplicaVersion(replica11, CatalogTestUtil.testStartVersion, CatalogTestUtil.testStartVersion, -1); @@ -1093,12 +1093,12 @@ public void testFinishTransactionWithSubTransactionAndOneFailed() throws UserExc .get(CatalogTestUtil.testBackendId2).stream() .filter(t -> t.getTransactionId() == subTransactionStates.get(0).getSubTransactionId()) .collect(Collectors.toList()); - Assert.assertEquals(1, publishVersionTasks.size()); + Assertions.assertEquals(1, publishVersionTasks.size()); PublishVersionTask publishVersionTask = publishVersionTasks.get(0); publishVersionTask.setSuccTablets(ImmutableMap.of(CatalogTestUtil.testTabletId1, 100L)); masterTransMgr.finishTransaction(CatalogTestUtil.testDbId1, transactionId, partitionVisibleVersions, backendPartitions); - Assert.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); + Assertions.assertEquals(TransactionStatus.VISIBLE, transactionState.getTransactionStatus()); checkReplicaVersion(replica11, CatalogTestUtil.testStartVersion + 2, CatalogTestUtil.testStartVersion + 2, -1); checkReplicaVersion(replica12, CatalogTestUtil.testStartVersion + 2, CatalogTestUtil.testStartVersion + 2, @@ -1114,7 +1114,7 @@ public void testFinishTransactionWithSubTransactionAndOneFailed() throws UserExc transactionState = fakeEditLog.getTransaction(transactionId); FakeEnv.setEnv(slaveEnv); slaveTransMgr.replayUpsertTransactionState(transactionState); - Assert.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); + Assertions.assertTrue(CatalogTestUtil.compareCatalog(masterEnv, slaveEnv)); } } @@ -1190,15 +1190,15 @@ private void checkTableVersion(OlapTable olapTable, long visibleVersion, long ne } LOG.info("table={}, visibleVersion={}, nextVersion={}", olapTable.getName(), version, olapTable.getNextVersion()); - Assert.assertEquals(visibleVersion, version); - Assert.assertEquals(nextVersion, olapTable.getNextVersion()); + Assertions.assertEquals(visibleVersion, version); + Assertions.assertEquals(nextVersion, olapTable.getNextVersion()); } private void checkPartitionVersion(Partition partition, long visibleVersion, long nextVersion) { LOG.info("partition={}, visibleVersion={}, nextVersion={}, committedVersion={}", partition.getName(), partition.getVisibleVersion(), partition.getNextVersion(), partition.getCommittedVersion()); - Assert.assertEquals(visibleVersion, partition.getVisibleVersion()); - Assert.assertEquals(nextVersion, partition.getNextVersion()); + Assertions.assertEquals(visibleVersion, partition.getVisibleVersion()); + Assertions.assertEquals(nextVersion, partition.getNextVersion()); } // check partition visible and next version; check replica version @@ -1214,7 +1214,7 @@ private void checkVersion(Table table, String partitionName, long indexId, long + "last_success_version={}, last_failed_version={}", table.getName(), partition.getName(), indexId, tabletId, replica.getId(), replica.getVersion(), replica.getLastSuccessVersion(), replica.getLastFailedVersion()); - Assert.assertEquals(replicaVersion, replica.getVersion()); + Assertions.assertEquals(replicaVersion, replica.getVersion()); } } @@ -1232,8 +1232,8 @@ private void checkReplicaVersion(long dbId, long tableId, String partitionName, } private void checkReplicaVersion(Replica replica, long version, long lastSuccessVersion, long lastFailedVersion) { - Assert.assertEquals(version, replica.getVersion()); - Assert.assertEquals(lastSuccessVersion, replica.getLastSuccessVersion()); - Assert.assertEquals(lastFailedVersion, replica.getLastFailedVersion()); + Assertions.assertEquals(version, replica.getVersion()); + Assertions.assertEquals(lastSuccessVersion, replica.getLastSuccessVersion()); + Assertions.assertEquals(lastFailedVersion, replica.getLastFailedVersion()); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/PluginDrivenTransactionManagerTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/PluginDrivenTransactionManagerTest.java index c8016e7e42e7b5..e9b2b5b6f39a18 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/PluginDrivenTransactionManagerTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/PluginDrivenTransactionManagerTest.java @@ -22,8 +22,8 @@ import org.apache.doris.connector.spi.handle.ConnectorTransaction; import org.apache.doris.connector.spi.handle.WriteBlockAllocatingConnectorTransaction; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -116,8 +116,8 @@ public void addCommitDataIsDelegatedToConnectorTransaction() throws UserExceptio byte[] fragment = {1, 2, 3}; manager.getTransaction(txnId).addCommitData(fragment); - Assert.assertEquals(1, connectorTx.commitFragments.size()); - Assert.assertSame(fragment, connectorTx.commitFragments.get(0)); + Assertions.assertEquals(1, connectorTx.commitFragments.size()); + Assertions.assertSame(fragment, connectorTx.commitFragments.get(0)); } @Test @@ -128,7 +128,7 @@ public void writeBlockCapableConnectorYieldsWriteBlockTransaction() throws UserE long txnId = manager.begin(connectorTx); // The narrow capability is exposed as a TYPE (instanceof gate), not a supports*() runtime flag. - Assert.assertTrue(manager.getTransaction(txnId) instanceof WriteBlockAllocatingTransaction); + Assertions.assertTrue(manager.getTransaction(txnId) instanceof WriteBlockAllocatingTransaction); } @Test @@ -138,7 +138,7 @@ public void plainConnectorIsNotAWriteBlockTransaction() throws UserException { // A connector without the narrow capability must NOT wrap into a WriteBlockAllocatingTransaction, // so the write-block RPC handler's instanceof gate rejects it. - Assert.assertFalse(manager.getTransaction(txnId) instanceof WriteBlockAllocatingTransaction); + Assertions.assertFalse(manager.getTransaction(txnId) instanceof WriteBlockAllocatingTransaction); } @Test @@ -150,12 +150,12 @@ public void allocateWriteBlockRangeIsDelegated() throws UserException { long txnId = manager.begin(connectorTx); Transaction txn = manager.getTransaction(txnId); - Assert.assertTrue(txn instanceof WriteBlockAllocatingTransaction); + Assertions.assertTrue(txn instanceof WriteBlockAllocatingTransaction); long start = ((WriteBlockAllocatingTransaction) txn).allocateWriteBlockRange("write-session-x", 5L); - Assert.assertEquals(100L, start); - Assert.assertEquals("write-session-x", connectorTx.lastWriteSessionId); - Assert.assertEquals(5L, connectorTx.lastCount); + Assertions.assertEquals(100L, start); + Assertions.assertEquals("write-session-x", connectorTx.lastWriteSessionId); + Assertions.assertEquals(5L, connectorTx.lastCount); } @Test @@ -165,7 +165,7 @@ public void getUpdateCntIsDelegated() throws UserException { connectorTx.updateCnt = 42L; long txnId = manager.begin(connectorTx); - Assert.assertEquals(42L, manager.getTransaction(txnId).getUpdateCnt()); + Assertions.assertEquals(42L, manager.getTransaction(txnId).getUpdateCnt()); } @Test @@ -178,8 +178,8 @@ public void legacyMarkerKeepsInertWriteDefaults() throws UserException { // no-op, the update count is zero, and it does not carry the write-block capability (so the RPC // handler's instanceof gate rejects it). txn.addCommitData(new byte[] {9}); - Assert.assertEquals(0L, txn.getUpdateCnt()); - Assert.assertFalse(txn instanceof WriteBlockAllocatingTransaction); + Assertions.assertEquals(0L, txn.getUpdateCnt()); + Assertions.assertFalse(txn instanceof WriteBlockAllocatingTransaction); } // ──────────── global registration (P4-T06a W-d / gap G3) ──────────── @@ -199,8 +199,8 @@ public void beginRegistersConnectorTransactionInGlobalRegistry() throws UserExce try { Transaction registered = Env.getCurrentEnv().getGlobalExternalTransactionInfoMgr().getTxnById(txnId); - Assert.assertSame("global registry must hold the same wrapped transaction the " - + "manager hands out", manager.getTransaction(txnId), registered); + Assertions.assertSame(manager.getTransaction(txnId), registered, "global registry must hold the same wrapped transaction the " + + "manager hands out"); } finally { // do not leak the id into the shared global registry manager.commit(txnId); @@ -236,7 +236,7 @@ public void commitStillDeregistersWhenConnectorCommitThrows() { try { manager.commit(txnId); - Assert.fail("commit must propagate the connector failure"); + Assertions.fail("commit must propagate the connector failure"); } catch (Exception expected) { // the connector's commit failure propagates to the caller } @@ -249,7 +249,7 @@ public void commitStillDeregistersWhenConnectorCommitThrows() { private static void assertNotRegistered(long txnId) { try { Env.getCurrentEnv().getGlobalExternalTransactionInfoMgr().getTxnById(txnId); - Assert.fail("txn " + txnId + " should have been deregistered from the global registry"); + Assertions.fail("txn " + txnId + " should have been deregistered from the global registry"); } catch (RuntimeException expected) { // getTxnById throws "Can't find txn for " once the entry is gone } diff --git a/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java b/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java index f6b72d84af8ac5..4bd5cec17bdfd8 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java @@ -36,9 +36,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.DataInputStream; import java.io.DataOutputStream; @@ -55,7 +55,7 @@ public class TransactionStateTest { private static String fileName2 = "./TransactionStateTest2"; private static String fileName3 = "./TransactionStateTest3"; - @After + @AfterEach public void tearDown() { new File(fileName).delete(); new File(fileName2).delete(); @@ -92,7 +92,7 @@ public void testSerDe() throws IOException { new TxnCoordinator(TxnSourceType.BE, 0, "127.0.0.1", System.currentTimeMillis()), 50000L, 60 * 1000L); testSerDe(fileName, transactionState, readTransactionState -> { - Assert.assertEquals(transactionState.getCoordinator().ip, readTransactionState.getCoordinator().ip); + Assertions.assertEquals(transactionState.getCoordinator().ip, readTransactionState.getCoordinator().ip); }); } @@ -118,18 +118,18 @@ public void testSerDeForBatchLoad() throws IOException { TransactionStatus.COMMITTED, "", 100, 50000L, loadJobFinalOperation, 100, 200, 300, 400); // check testSerDe(fileName2, transactionState, readTransactionState -> { - Assert.assertEquals(TransactionState.LoadJobSourceType.BATCH_LOAD_JOB, + Assertions.assertEquals(TransactionState.LoadJobSourceType.BATCH_LOAD_JOB, readTransactionState.getTxnCommitAttachment().sourceType); - Assert.assertTrue(readTransactionState.getTxnCommitAttachment() instanceof LoadJobFinalOperation); + Assertions.assertTrue(readTransactionState.getTxnCommitAttachment() instanceof LoadJobFinalOperation); LoadJobFinalOperation readLoadJobFinalOperation = (LoadJobFinalOperation) (readTransactionState.getTxnCommitAttachment()); - Assert.assertEquals(loadJobFinalOperation.getId(), readLoadJobFinalOperation.getId()); + Assertions.assertEquals(loadJobFinalOperation.getId(), readLoadJobFinalOperation.getId()); EtlStatus readLoadingStatus = readLoadJobFinalOperation.getLoadingStatus(); - Assert.assertEquals(TEtlState.FINISHED, readLoadingStatus.getState()); - Assert.assertEquals(etlStatus.getTrackingUrl(), readLoadingStatus.getTrackingUrl()); + Assertions.assertEquals(TEtlState.FINISHED, readLoadingStatus.getState()); + Assertions.assertEquals(etlStatus.getTrackingUrl(), readLoadingStatus.getTrackingUrl()); FailMsg readFailMsg = readLoadJobFinalOperation.getFailMsg(); - Assert.assertEquals(failMsg.getCancelType(), readFailMsg.getCancelType()); - Assert.assertEquals(failMsg.getMsg(), readFailMsg.getMsg()); + Assertions.assertEquals(failMsg.getCancelType(), readFailMsg.getCancelType()); + Assertions.assertEquals(failMsg.getMsg(), readFailMsg.getMsg()); }); } @@ -152,15 +152,15 @@ public void testSerDeForRoutineLoad() throws IOException { attachment, 100, 200, 300, 400); // check testSerDe(fileName3, transactionState, readTransactionState -> { - Assert.assertEquals(TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK, + Assertions.assertEquals(TransactionState.LoadJobSourceType.ROUTINE_LOAD_TASK, readTransactionState.getTxnCommitAttachment().sourceType); - Assert.assertTrue(readTransactionState.getTxnCommitAttachment() instanceof RLTaskTxnCommitAttachment); + Assertions.assertTrue(readTransactionState.getTxnCommitAttachment() instanceof RLTaskTxnCommitAttachment); RLTaskTxnCommitAttachment readRLTaskTxnCommitAttachment = (RLTaskTxnCommitAttachment) (readTransactionState.getTxnCommitAttachment()); - Assert.assertTrue(readRLTaskTxnCommitAttachment.getProgress() instanceof KafkaProgress); + Assertions.assertTrue(readRLTaskTxnCommitAttachment.getProgress() instanceof KafkaProgress); KafkaProgress readKafkaProgress = (KafkaProgress) (readRLTaskTxnCommitAttachment.getProgress()); - Assert.assertEquals(1, readKafkaProgress.getOffsetByPartition().size()); - Assert.assertEquals(100L, (long) readKafkaProgress.getOffsetByPartition().getOrDefault(1, -1L)); + Assertions.assertEquals(1, readKafkaProgress.getOffsetByPartition().size()); + Assertions.assertEquals(100L, (long) readKafkaProgress.getOffsetByPartition().getOrDefault(1, -1L)); }); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tso/TSOServiceTest.java b/fe/fe-core/src/test/java/org/apache/doris/tso/TSOServiceTest.java index 30a27bfc4f6031..a591bc9f3592dc 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tso/TSOServiceTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tso/TSOServiceTest.java @@ -26,10 +26,10 @@ import org.apache.doris.metric.MetricRepo; import org.apache.doris.persist.EditLog; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -56,7 +56,7 @@ public class TSOServiceTest { private boolean originalEnableFeatureBinlog; private long originalClockBackwardThresholdMs; - @Before + @BeforeEach public void setUp() { mockedEnv = Mockito.mockStatic(Env.class); @@ -78,7 +78,7 @@ public void setUp() { tsoService = new TSOService(); } - @After + @AfterEach public void tearDown() { mockedEnv.close(); Config.tso_max_get_retry_count = originalMaxGetTSORetryCount; @@ -91,7 +91,7 @@ public void tearDown() { @Test public void testConstructor() { TSOService service = new TSOService(); - Assert.assertNotNull(service); + Assertions.assertNotNull(service); } @Test @@ -99,7 +99,7 @@ public void testGetCurrentTSO() { TSOService service = new TSOService(); long currentTSO = service.getCurrentTSO(); // Should be 0 since not initialized - Assert.assertEquals(0L, currentTSO); + Assertions.assertEquals(0L, currentTSO); } @Test @@ -111,9 +111,9 @@ public void testGetTSOThrowsWhenEnvNotReady() { Mockito.when(env.isReady()).thenReturn(false); try { tsoService.getTSO(); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("Failed to get TSO")); + Assertions.assertTrue(e.getMessage().contains("Failed to get TSO")); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; @@ -129,9 +129,9 @@ public void testGetTSOThrowsWhenNotCalibrated() throws Exception { Mockito.when(env.isMaster()).thenReturn(true); try { tsoService.getTSO(); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("not calibrated")); + Assertions.assertTrue(e.getMessage().contains("not calibrated")); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; @@ -149,12 +149,12 @@ public void testGetTSOThrowsOnLogicalOverflow() throws Exception { setGlobalTimestamp(tsoService, 100L, TSOTimestamp.MAX_LOGICAL_COUNTER); try { tsoService.getTSO(); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("Failed to get TSO")); - Assert.assertNotNull(e.getCause()); - Assert.assertTrue(e.getCause().getMessage().contains("logical counter overflow")); - Assert.assertEquals(TSOTimestamp.MAX_LOGICAL_COUNTER, getGlobalLogicalCounter(tsoService)); + Assertions.assertTrue(e.getMessage().contains("Failed to get TSO")); + Assertions.assertNotNull(e.getCause()); + Assertions.assertTrue(e.getCause().getMessage().contains("logical counter overflow")); + Assertions.assertEquals(TSOTimestamp.MAX_LOGICAL_COUNTER, getGlobalLogicalCounter(tsoService)); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; @@ -171,7 +171,7 @@ public void testGetTSOAcceptsLogicalCounterUpperBound() throws Exception { Mockito.when(env.isMaster()).thenReturn(true); setGlobalTimestamp(tsoService, 100L, TSOTimestamp.MAX_LOGICAL_COUNTER - 1); long tso = tsoService.getTSO(); - Assert.assertEquals(TSOTimestamp.composeTimestamp(100L, TSOTimestamp.MAX_LOGICAL_COUNTER), tso); + Assertions.assertEquals(TSOTimestamp.composeTimestamp(100L, TSOTimestamp.MAX_LOGICAL_COUNTER), tso); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -184,12 +184,12 @@ public void testRunAfterCatalogReadySetsIntervalTo50WhenDisabled() { setInitializedFlag(tsoService, true); Config.enable_feature_binlog = false; tsoService.runAfterCatalogReady(); - Assert.assertEquals(1L, tsoService.getInterval()); + Assertions.assertEquals(1L, tsoService.getInterval()); try { tsoService.getTSO(); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("feature is disabled")); + Assertions.assertTrue(e.getMessage().contains("feature is disabled")); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; @@ -205,7 +205,7 @@ public void testRunAfterCatalogReadyDoesNotResetFatalClockBackwardFlagWhenDisabl tsoService.runAfterCatalogReady(); - Assert.assertTrue(getFatalClockBackwardReportedFlag(tsoService)); + Assertions.assertTrue(getFatalClockBackwardReportedFlag(tsoService)); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -221,7 +221,7 @@ public void testRunAfterCatalogReadyUsesAtLeastOneRetryWhenConfigNonPositive() { Mockito.when(env.isMaster()).thenReturn(true); mockPersistReady(); tsoService.runAfterCatalogReady(); - Assert.assertTrue(tsoService.getTSO() > 0); + Assertions.assertTrue(tsoService.getTSO() > 0); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -252,7 +252,7 @@ public void testRunAfterCatalogReadyUpdateFailureDoesNotTouchMetricWhenNotInit() public void testReplayWindowEndTSOUpdatesServiceState() { long windowEnd = 12345L; tsoService.replayWindowEndTSO(new TSOTimestamp(windowEnd, 0L)); - Assert.assertEquals(windowEnd, tsoService.getWindowEndTSO()); + Assertions.assertEquals(windowEnd, tsoService.getWindowEndTSO()); } @Test @@ -264,12 +264,12 @@ public void testSaveTSOPersistsWindowEndWhenBinlogEnabled() throws IOException { tsoService.replayWindowEndTSO(new TSOTimestamp(windowEnd, 0L)); byte[] bytes = saveTSOBytes(tsoService); - Assert.assertTrue(bytes.length > 0); + Assertions.assertTrue(bytes.length > 0); TSOService recoveredService = new TSOService(); long checksum = recoveredService.loadTSO(new DataInputStream(new ByteArrayInputStream(bytes)), 0L); - Assert.assertEquals(windowEnd, checksum); - Assert.assertEquals(windowEnd, recoveredService.getWindowEndTSO()); + Assertions.assertEquals(windowEnd, checksum); + Assertions.assertEquals(windowEnd, recoveredService.getWindowEndTSO()); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -287,8 +287,8 @@ public void testSaveTSOSkipsWhenWindowEndIsZero() throws IOException { checksum = tsoService.saveTSO(dos, 7L); dos.flush(); } - Assert.assertEquals(7L, checksum); - Assert.assertEquals(0, out.size()); + Assertions.assertEquals(7L, checksum); + Assertions.assertEquals(0, out.size()); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -328,9 +328,9 @@ public void testWriteTimestampToBdbJeThrowsWhenEnabledAndEnvNotReady() throws Ex Mockito.when(env.isReady()).thenReturn(false); try { invokeWriteTimestampToBdbJe(tsoService, 123L); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("Env is not ready")); + Assertions.assertTrue(e.getMessage().contains("Env is not ready")); } } @@ -345,21 +345,21 @@ public void testCalibrateTimestampThrowsWhenPersistWriteFailsAndKeepNotInitializ try { invokeCalibrateTimestamp(tsoService); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("EditLog is null")); + Assertions.assertTrue(e.getMessage().contains("EditLog is null")); } TSOService.TSOStatusSnapshot statusSnapshot = tsoService.getStatusSnapshot(); - Assert.assertFalse(statusSnapshot.isInitialized()); - Assert.assertTrue(statusSnapshot.getCurrentTso() > 0L); - Assert.assertEquals(0L, statusSnapshot.getWindowEndPhysicalTime()); + Assertions.assertFalse(statusSnapshot.isInitialized()); + Assertions.assertTrue(statusSnapshot.getCurrentTso() > 0L); + Assertions.assertEquals(0L, statusSnapshot.getWindowEndPhysicalTime()); try { tsoService.getTSO(); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("not calibrated")); + Assertions.assertTrue(e.getMessage().contains("not calibrated")); } } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; @@ -375,9 +375,9 @@ public void testCalibrateTimestampThrowsWhenClockBackwardExceedsThreshold() thro now + Config.tso_clock_backward_startup_threshold_ms + 60_000, 0L)); try { invokeCalibrateTimestamp(tsoService); - Assert.fail(); + Assertions.fail(); } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("clock backward too much")); + Assertions.assertTrue(e.getMessage().contains("clock backward too much")); } } @@ -390,7 +390,7 @@ public void testCalibrateTimestampResetsFatalClockBackwardReportedOnSuccess() th invokeCalibrateTimestamp(tsoService); - Assert.assertFalse(getFatalClockBackwardReportedFlag(tsoService)); + Assertions.assertFalse(getFatalClockBackwardReportedFlag(tsoService)); } @Test @@ -398,7 +398,7 @@ public void testRunAfterCatalogReadySkipsWhenBinlogDisabled() throws Exception { Config.enable_feature_binlog = false; setInitializedFlag(tsoService, true); tsoService.runAfterCatalogReady(); - Assert.assertEquals(0L, tsoService.getCurrentTSO()); + Assertions.assertEquals(0L, tsoService.getCurrentTSO()); } @Test @@ -410,8 +410,8 @@ public void testUpdateTimestampReturnsEarlyWhenNotCalibrated() throws Exception invokeUpdateTimestamp(tsoService); - Assert.assertEquals(0L, tsoService.getCurrentTSO()); - Assert.assertEquals(initialWindowEnd, tsoService.getWindowEndTSO()); + Assertions.assertEquals(0L, tsoService.getCurrentTSO()); + Assertions.assertEquals(initialWindowEnd, tsoService.getWindowEndTSO()); } @Test @@ -423,14 +423,14 @@ public void testGenerateTSOReturnsZeroWhenDisabledOrNotInitialized() throws Exce Config.enable_feature_binlog = true; setInitializedFlag(tsoService, false); Pair pairWhenNotInitialized = invokeGenerateTSO(tsoService); - Assert.assertEquals(0L, (long) pairWhenNotInitialized.first); - Assert.assertEquals(0L, (long) pairWhenNotInitialized.second); + Assertions.assertEquals(0L, (long) pairWhenNotInitialized.first); + Assertions.assertEquals(0L, (long) pairWhenNotInitialized.second); Config.enable_feature_binlog = false; setInitializedFlag(tsoService, true); Pair pairWhenDisabled = invokeGenerateTSO(tsoService); - Assert.assertEquals(0L, (long) pairWhenDisabled.first); - Assert.assertEquals(0L, (long) pairWhenDisabled.second); + Assertions.assertEquals(0L, (long) pairWhenDisabled.first); + Assertions.assertEquals(0L, (long) pairWhenDisabled.second); } finally { Config.enable_feature_binlog = originalEnableFeatureBinlog; } @@ -535,7 +535,7 @@ private static byte[] saveTSOBytes(TSOService service) throws IOException { try (CountingDataOutputStream dos = new CountingDataOutputStream(out, 0)) { long checksum = service.saveTSO(dos, 0L); dos.flush(); - Assert.assertEquals(service.getWindowEndTSO(), checksum); + Assertions.assertEquals(service.getWindowEndTSO(), checksum); } return out.toByteArray(); } diff --git a/fe/fe-core/src/test/java/org/apache/doris/tso/TSOTimestampTest.java b/fe/fe-core/src/test/java/org/apache/doris/tso/TSOTimestampTest.java index 5d351ddba70b99..2db906f08f3843 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/tso/TSOTimestampTest.java +++ b/fe/fe-core/src/test/java/org/apache/doris/tso/TSOTimestampTest.java @@ -17,8 +17,8 @@ package org.apache.doris.tso; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -34,15 +34,15 @@ public class TSOTimestampTest { public void testConstructor() { // Test default constructor TSOTimestamp timestamp = new TSOTimestamp(); - Assert.assertEquals(0L, timestamp.getPhysicalTimestamp()); - Assert.assertEquals(0L, timestamp.getLogicalCounter()); + Assertions.assertEquals(0L, timestamp.getPhysicalTimestamp()); + Assertions.assertEquals(0L, timestamp.getLogicalCounter()); // Test constructor with parameters long physicalTime = 1625097600000L; long logicalCounter = 123L; timestamp = new TSOTimestamp(physicalTime, logicalCounter); - Assert.assertEquals(physicalTime, timestamp.getPhysicalTimestamp()); - Assert.assertEquals(logicalCounter, timestamp.getLogicalCounter()); + Assertions.assertEquals(physicalTime, timestamp.getPhysicalTimestamp()); + Assertions.assertEquals(logicalCounter, timestamp.getLogicalCounter()); } @Test @@ -54,8 +54,8 @@ public void testComposeAndExtractTimestamp() { long composed = timestamp.composeTimestamp(); // Verify extraction works correctly - Assert.assertEquals(physicalTime, TSOTimestamp.extractPhysicalTime(composed)); - Assert.assertEquals(logicalCounter, TSOTimestamp.extractLogicalCounter(composed)); + Assertions.assertEquals(physicalTime, TSOTimestamp.extractPhysicalTime(composed)); + Assertions.assertEquals(logicalCounter, TSOTimestamp.extractLogicalCounter(composed)); } @Test @@ -68,8 +68,8 @@ public void testBitWidthLimitations() { long composed = timestamp.composeTimestamp(); // Values should be masked to fit in their respective bit widths - Assert.assertEquals(largePhysicalTime & ((1L << 46) - 1), TSOTimestamp.extractPhysicalTime(composed)); - Assert.assertEquals(largeLogicalCounter & ((1L << 18) - 1), TSOTimestamp.extractLogicalCounter(composed)); + Assertions.assertEquals(largePhysicalTime & ((1L << 46) - 1), TSOTimestamp.extractPhysicalTime(composed)); + Assertions.assertEquals(largeLogicalCounter & ((1L << 18) - 1), TSOTimestamp.extractLogicalCounter(composed)); } @Test @@ -82,30 +82,38 @@ public void testSetterAndGetters() { timestamp.setPhysicalTimestamp(physicalTime); timestamp.setLogicalCounter(logicalCounter); - Assert.assertEquals(physicalTime, timestamp.getPhysicalTimestamp()); - Assert.assertEquals(logicalCounter, timestamp.getLogicalCounter()); + Assertions.assertEquals(physicalTime, timestamp.getPhysicalTimestamp()); + Assertions.assertEquals(logicalCounter, timestamp.getLogicalCounter()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstructorRejectNegativePhysicalTimestamp() { - new TSOTimestamp(-1L, 0L); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + new TSOTimestamp(-1L, 0L); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testConstructorRejectNegativeLogicalCounter() { - new TSOTimestamp(0L, -1L); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + new TSOTimestamp(0L, -1L); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetterRejectNegativePhysicalTimestamp() { - TSOTimestamp timestamp = new TSOTimestamp(); - timestamp.setPhysicalTimestamp(-1L); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + TSOTimestamp timestamp = new TSOTimestamp(); + timestamp.setPhysicalTimestamp(-1L); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testSetterRejectNegativeLogicalCounter() { - TSOTimestamp timestamp = new TSOTimestamp(); - timestamp.setLogicalCounter(-1L); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + TSOTimestamp timestamp = new TSOTimestamp(); + timestamp.setLogicalCounter(-1L); + }); } @Test @@ -115,8 +123,8 @@ public void testDecomposeIsConsistentWithExtract() { long tso = TSOTimestamp.composeTimestamp(physicalTime, logicalCounter); TSOTimestamp decomposed = TSOTimestamp.decompose(tso); - Assert.assertEquals(TSOTimestamp.extractPhysicalTime(tso), decomposed.getPhysicalTimestamp()); - Assert.assertEquals(TSOTimestamp.extractLogicalCounter(tso), decomposed.getLogicalCounter()); + Assertions.assertEquals(TSOTimestamp.extractPhysicalTime(tso), decomposed.getPhysicalTimestamp()); + Assertions.assertEquals(TSOTimestamp.extractLogicalCounter(tso), decomposed.getLogicalCounter()); } @Test @@ -131,9 +139,9 @@ public void testWritableRoundTrip() throws Exception { DataInputStream dis = new DataInputStream(bis); TSOTimestamp restored = TSOTimestamp.read(dis); - Assert.assertEquals(timestamp, restored); - Assert.assertEquals(timestamp.hashCode(), restored.hashCode()); - Assert.assertEquals(0, timestamp.compareTo(restored)); + Assertions.assertEquals(timestamp, restored); + Assertions.assertEquals(timestamp.hashCode(), restored.hashCode()); + Assertions.assertEquals(0, timestamp.compareTo(restored)); } @Test @@ -141,14 +149,14 @@ public void testCompareToOrdersByPhysicalThenLogical() { TSOTimestamp a = new TSOTimestamp(100L, 2L); TSOTimestamp b = new TSOTimestamp(100L, 3L); TSOTimestamp c = new TSOTimestamp(101L, 0L); - Assert.assertTrue(a.compareTo(b) < 0); - Assert.assertTrue(b.compareTo(c) < 0); - Assert.assertTrue(a.compareTo(c) < 0); + Assertions.assertTrue(a.compareTo(b) < 0); + Assertions.assertTrue(b.compareTo(c) < 0); + Assertions.assertTrue(a.compareTo(c) < 0); } @Test public void testMaxLogicalCounter() { // Test the maximum logical counter value - Assert.assertEquals((1L << 18) - 1, TSOTimestamp.MAX_LOGICAL_COUNTER); + Assertions.assertEquals((1L << 18) - 1, TSOTimestamp.MAX_LOGICAL_COUNTER); } } diff --git a/fe/fe-core/src/test/java/org/apache/doris/utframe/DorisAssert.java b/fe/fe-core/src/test/java/org/apache/doris/utframe/DorisAssert.java index aa78b67614c36b..be0f67cde38415 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/utframe/DorisAssert.java +++ b/fe/fe-core/src/test/java/org/apache/doris/utframe/DorisAssert.java @@ -37,7 +37,7 @@ import org.apache.doris.qe.StmtExecutor; import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import java.io.IOException; import java.util.Map; @@ -165,7 +165,7 @@ private void checkAlterJob() throws InterruptedException { Thread.sleep(100); } System.out.println("alter job " + alterJobV2.getDbId() + " is done. state: " + alterJobV2.getJobState()); - Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); + Assertions.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } } @@ -184,15 +184,15 @@ public QueryAssert(ConnectContext connectContext, String sql) { } public void explainContains(String... keywords) throws Exception { - Assert.assertTrue(explainQuery(), Stream.of(keywords).allMatch(explainQuery()::contains)); + Assertions.assertTrue(Stream.of(keywords).allMatch(explainQuery()::contains), explainQuery()); } public void explainContains(String keywords, int count) throws Exception { - Assert.assertEquals(StringUtils.countMatches(explainQuery(), keywords), count); + Assertions.assertEquals(StringUtils.countMatches(explainQuery(), keywords), count); } public void explainWithout(String s) throws Exception { - Assert.assertFalse(explainQuery().contains(s)); + Assertions.assertFalse(explainQuery().contains(s)); } public String explainQuery() throws Exception { diff --git a/fe/fe-core/src/test/java/org/apache/doris/utframe/TestWithFeService.java b/fe/fe-core/src/test/java/org/apache/doris/utframe/TestWithFeService.java index da9e9aea08bb77..0692cc81f2a1d6 100644 --- a/fe/fe-core/src/test/java/org/apache/doris/utframe/TestWithFeService.java +++ b/fe/fe-core/src/test/java/org/apache/doris/utframe/TestWithFeService.java @@ -132,7 +132,7 @@ * thus we could wrap common logic in this base class. It's easier to use. * Note: * Unit-test method in derived classes must use the JUnit5 {@link org.junit.jupiter.api.Test} - * annotation, rather than the old JUnit4 {@link org.junit.Test} or others. + * annotation. JUnit 4 is banned by checkstyle and is not on this classpath. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class TestWithFeService { diff --git a/fe/fe-core/test_datasource_properties b/fe/fe-core/test_datasource_properties new file mode 100644 index 00000000000000..194af3c950bf1d Binary files /dev/null and b/fe/fe-core/test_datasource_properties differ diff --git a/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/AuthenticationTest.java b/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/AuthenticationTest.java index b859282c227bd1..37253978942fea 100644 --- a/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/AuthenticationTest.java +++ b/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/AuthenticationTest.java @@ -19,8 +19,8 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class AuthenticationTest { @@ -29,18 +29,18 @@ public void testAuthConf() { Configuration conf = new Configuration(); AuthenticationConfig conf1 = AuthenticationConfig.getKerberosConfig(conf); - Assert.assertEquals(SimpleAuthenticationConfig.class, conf1.getClass()); + Assertions.assertEquals(SimpleAuthenticationConfig.class, conf1.getClass()); conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); AuthenticationConfig conf2 = AuthenticationConfig.getKerberosConfig(conf); - Assert.assertEquals(SimpleAuthenticationConfig.class, conf2.getClass()); + Assertions.assertEquals(SimpleAuthenticationConfig.class, conf2.getClass()); conf.set(AuthenticationConfig.HADOOP_KERBEROS_PRINCIPAL, "principal"); conf.set(AuthenticationConfig.HADOOP_KERBEROS_KEYTAB, "keytab"); AuthenticationConfig conf3 = AuthenticationConfig.getKerberosConfig(conf); - Assert.assertEquals(KerberosAuthenticationConfig.class, conf3.getClass()); + Assertions.assertEquals(KerberosAuthenticationConfig.class, conf3.getClass()); } @Test @@ -49,12 +49,12 @@ public void testDoAsPreservesCheckedExceptionMessage() { conf.set(AuthenticationConfig.HADOOP_USER_NAME, "hms-user"); HadoopAuthenticator authenticator = HadoopAuthenticator.getHadoopAuthenticator(conf); - RuntimeException error = Assert.assertThrows(RuntimeException.class, + RuntimeException error = Assertions.assertThrows(RuntimeException.class, () -> authenticator.doAs(() -> { throw new Exception("Database db is not empty."); })); - Assert.assertEquals("Database db is not empty.", error.getMessage()); - Assert.assertEquals(Exception.class, error.getCause().getClass()); + Assertions.assertEquals("Database db is not empty.", error.getMessage()); + Assertions.assertEquals(Exception.class, error.getCause().getClass()); } } diff --git a/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/KerberosTicketUtilsTest.java b/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/KerberosTicketUtilsTest.java index 1d06ed56ccbfc1..b778ecc35c3eb4 100644 --- a/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/KerberosTicketUtilsTest.java +++ b/fe/fe-kerberos/src/test/java/org/apache/doris/kerberos/KerberosTicketUtilsTest.java @@ -17,8 +17,8 @@ package org.apache.doris.kerberos; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Date; @@ -56,13 +56,13 @@ private static KerberosTicket ticket(String serverPrincipal, long startMs, long public void testGetRefreshTimeIs80PercentOfLifetime() { KerberosTicket tgt = ticket("krbtgt/" + REALM + "@" + REALM, 1000L, 11000L); // 1000 + (long)((11000 - 1000) * 0.8f) = 1000 + 8000 = 9000 - Assert.assertEquals(9000L, KerberosTicketUtils.getRefreshTime(tgt)); + Assertions.assertEquals(9000L, KerberosTicketUtils.getRefreshTime(tgt)); } @Test public void testGetRefreshTimeZeroLifetime() { KerberosTicket tgt = ticket("krbtgt/" + REALM + "@" + REALM, 5000L, 5000L); - Assert.assertEquals(5000L, KerberosTicketUtils.getRefreshTime(tgt)); + Assertions.assertEquals(5000L, KerberosTicketUtils.getRefreshTime(tgt)); } // getTicketGrantingTicket returns the credential whose server is krbtgt/REALM@REALM. @@ -77,7 +77,7 @@ public void testGetTicketGrantingTicketPicksTgtAmongCredentials() { Collections.singleton(new KerberosPrincipal("client@" + REALM)), Collections.emptySet(), privateCreds); - Assert.assertSame(tgt, KerberosTicketUtils.getTicketGrantingTicket(subject)); + Assertions.assertSame(tgt, KerberosTicketUtils.getTicketGrantingTicket(subject)); } @Test @@ -88,7 +88,7 @@ public void testGetTicketGrantingTicketThrowsWhenNoTgt() { Collections.emptySet(), Collections.singleton(serviceTicket)); try { KerberosTicketUtils.getTicketGrantingTicket(subject); - Assert.fail("expected IllegalArgumentException when no TGT is present"); + Assertions.fail("expected IllegalArgumentException when no TGT is present"); } catch (IllegalArgumentException expected) { // expected } diff --git a/fe/hive-udf/src/test/java/org/apache/doris/BitmapUDFTest.java b/fe/hive-udf/src/test/java/org/apache/doris/BitmapUDFTest.java index fba084a9260777..8a7a10b2d59282 100644 --- a/fe/hive-udf/src/test/java/org/apache/doris/BitmapUDFTest.java +++ b/fe/hive-udf/src/test/java/org/apache/doris/BitmapUDFTest.java @@ -28,9 +28,9 @@ import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaConstantBinaryObjectInspector; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -43,7 +43,7 @@ public class BitmapUDFTest { private BinaryObjectInspector inputOI0 = new JavaConstantBinaryObjectInspector(new byte[0]); private BinaryObjectInspector inputOI1 = new JavaConstantBinaryObjectInspector(new byte[0]); - @Before + @BeforeEach public void initData() throws IOException { BitmapValue bitmapValue0 = new BitmapValue(); BitmapValue bitmapValue1 = new BitmapValue(); @@ -68,8 +68,8 @@ public void bitmapAndTest() throws Exception { Object evaluate = bitmapAndUDF.evaluate(args); BitmapValue resultBitmap = BitmapValueUtil.deserializeToBitmap((byte[]) evaluate); - Assert.assertEquals(1, resultBitmap.cardinality()); - Assert.assertEquals("{2}", resultBitmap.toString()); + Assertions.assertEquals(1, resultBitmap.cardinality()); + Assertions.assertEquals("{2}", resultBitmap.toString()); } @Test @@ -82,8 +82,8 @@ public void bitmapOrTest() throws Exception { Object evaluate = bitmapOrUDF.evaluate(args); BitmapValue resultBitmap = BitmapValueUtil.deserializeToBitmap((byte[]) evaluate); - Assert.assertEquals(4, resultBitmap.cardinality()); - Assert.assertEquals("{1,2,3,4}", resultBitmap.toString()); + Assertions.assertEquals(4, resultBitmap.cardinality()); + Assertions.assertEquals("{1,2,3,4}", resultBitmap.toString()); } @Test @@ -95,8 +95,8 @@ public void bitmapXorTest() throws Exception { Object evaluate = bitmapXorUDF.evaluate(args); BitmapValue resultBitmap = BitmapValueUtil.deserializeToBitmap((byte[]) evaluate); - Assert.assertEquals(3, resultBitmap.cardinality()); - Assert.assertEquals("{1,3,4}", resultBitmap.toString()); + Assertions.assertEquals(3, resultBitmap.cardinality()); + Assertions.assertEquals("{1,3,4}", resultBitmap.toString()); } @Test @@ -104,10 +104,10 @@ public void bitmapCountTest() throws Exception { BitmapCountUDF bitmapCountUDF = new BitmapCountUDF(); bitmapCountUDF.initialize(new ObjectInspector[] { inputOI0 }); Object evaluate = bitmapCountUDF.evaluate(new GenericUDF.DeferredObject[] { new GenericUDF.DeferredJavaObject(bitmapValue0Bytes) }); - Assert.assertEquals(2L, evaluate); + Assertions.assertEquals(2L, evaluate); bitmapCountUDF.initialize(new ObjectInspector[] { inputOI1 }); Object evaluate1 = bitmapCountUDF.evaluate(new GenericUDF.DeferredObject[] { new GenericUDF.DeferredJavaObject(bitmapValue1Bytes) }); - Assert.assertEquals(3L, evaluate1); + Assertions.assertEquals(3L, evaluate1); } } diff --git a/fe/hive-udf/src/test/java/org/apache/doris/HllUDFTest.java b/fe/hive-udf/src/test/java/org/apache/doris/HllUDFTest.java index ca18b3fa9b420f..b188cbdb54f6fe 100644 --- a/fe/hive-udf/src/test/java/org/apache/doris/HllUDFTest.java +++ b/fe/hive-udf/src/test/java/org/apache/doris/HllUDFTest.java @@ -31,8 +31,8 @@ import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; // hive hll udf test public class HllUDFTest { @@ -58,7 +58,7 @@ public void hllCardinalityTest() throws Exception { long actualCardinality = (long) evaluateLarge; double relativeError = Math.abs(actualCardinality - largeInputSize) / (double) largeInputSize; - Assert.assertTrue("Relative error rate should be less than 2%", relativeError <= 0.02); + Assertions.assertTrue(relativeError <= 0.02, "Relative error rate should be less than 2%"); } @Test @@ -88,7 +88,7 @@ public void hllUnionUDAFTest() throws Exception { byte[] mergedHllBytes = (byte[]) evaluator.terminate(aggBuffer); Hll mergedHll = HllUtil.deserializeToHll(mergedHllBytes); - Assert.assertEquals(4L, mergedHll.estimateCardinality()); + Assertions.assertEquals(4L, mergedHll.estimateCardinality()); } @Test @@ -106,6 +106,6 @@ public void toHllUDAFTest() throws Exception { byte[] hllBytes = (byte[]) evaluator.terminate(aggBuffer); Hll hll = HllUtil.deserializeToHll(hllBytes); - Assert.assertEquals(2L, hll.estimateCardinality()); + Assertions.assertEquals(2L, hll.estimateCardinality()); } }