This is an automated email from the ASF dual-hosted git repository.
abhishekrb pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/druid.git
The following commit(s) were added to refs/heads/master by this push:
new 2eb7d7a89b8 Calcite tests remove expected exception (#16046)
2eb7d7a89b8 is described below
commit 2eb7d7a89b871c91cfab02b67ba0ffea92c8666b
Author: Zoltan Haindrich <[email protected]>
AuthorDate: Mon Mar 11 08:53:57 2024 +0100
Calcite tests remove expected exception (#16046)
* Calcite tests remove expected exception
* update testcases using `expectedException` to utilize `assertThrows`
instead
* remove `BaseCalciteQueryTest#expectedException`
* fixes `cannotVectorize` so it doesn't anymore stops further processing
* `msqIncompatible` is not anymore toggles a boolean - its an `Assume`
instead
Fixes #15423
* cleanup
* move msqIncompat
* update test
* cleanup
* remove comment
* empty-commit
* empty-commit
---
extensions-core/multi-stage-query/pom.xml | 5 +
.../druid/msq/test/CalciteArraysQueryMSQTest.java | 3 +-
.../msq/test/CalciteSelectJoinQueryMSQTest.java | 3 +-
.../druid/msq/test/CalciteSelectQueryMSQTest.java | 3 +-
.../druid/msq/test/CalciteUnionQueryMSQTest.java | 3 +-
.../druid/sql/calcite/BaseCalciteQueryTest.java | 82 ++++---
.../druid/sql/calcite/CalciteInsertDmlTest.java | 30 +--
.../druid/sql/calcite/CalciteJoinQueryTest.java | 3 +-
.../calcite/CalciteMultiValueStringQueryTest.java | 56 +++--
.../sql/calcite/CalciteNestedDataQueryTest.java | 24 +-
.../sql/calcite/CalciteParameterQueryTest.java | 67 ++++--
.../apache/druid/sql/calcite/CalciteQueryTest.java | 259 +++++++++------------
.../druid/sql/calcite/CalciteReplaceDmlTest.java | 18 +-
.../druid/sql/calcite/CalciteSelectQueryTest.java | 32 +--
.../druid/sql/calcite/CalciteSubqueryTest.java | 181 +++++++-------
.../druid/sql/calcite/IngestTableFunctionTest.java | 26 ++-
.../apache/druid/sql/calcite/QueryTestBuilder.java | 21 --
.../apache/druid/sql/calcite/QueryTestRunner.java | 35 ++-
18 files changed, 410 insertions(+), 441 deletions(-)
diff --git a/extensions-core/multi-stage-query/pom.xml
b/extensions-core/multi-stage-query/pom.xml
index 5b0af3caaf6..163a90ae09b 100644
--- a/extensions-core/multi-stage-query/pom.xml
+++ b/extensions-core/multi-stage-query/pom.xml
@@ -203,6 +203,11 @@
</dependency>
<!-- Tests -->
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
diff --git
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteArraysQueryMSQTest.java
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteArraysQueryMSQTest.java
index 619cd6d2d1c..7e7d20ebe65 100644
---
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteArraysQueryMSQTest.java
+++
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteArraysQueryMSQTest.java
@@ -78,8 +78,7 @@ public class CalciteArraysQueryMSQTest extends
CalciteArraysQueryTest
return new QueryTestBuilder(new CalciteTestConfig(true))
.addCustomRunner(new ExtractResultsFactory(() ->
(MSQTestOverlordServiceClient) ((MSQTaskSqlEngine)
queryFramework().engine()).overlordClient()))
.skipVectorize(true)
- .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate())
- .msqCompatible(msqCompatible);
+ .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate());
}
}
diff --git
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectJoinQueryMSQTest.java
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectJoinQueryMSQTest.java
index a357b5a48fe..147836536c4 100644
---
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectJoinQueryMSQTest.java
+++
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectJoinQueryMSQTest.java
@@ -144,8 +144,7 @@ public abstract class CalciteSelectJoinQueryMSQTest
.addCustomRunner(
new ExtractResultsFactory(
() -> (MSQTestOverlordServiceClient) ((MSQTaskSqlEngine)
queryFramework().engine()).overlordClient()))
- .skipVectorize(true)
- .msqCompatible(msqCompatible);
+ .skipVectorize(true);
}
}
}
diff --git
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectQueryMSQTest.java
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectQueryMSQTest.java
index 503e17755cf..ac954734e1a 100644
---
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectQueryMSQTest.java
+++
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteSelectQueryMSQTest.java
@@ -83,8 +83,7 @@ public class CalciteSelectQueryMSQTest extends
CalciteQueryTest
return new QueryTestBuilder(new CalciteTestConfig(true))
.addCustomRunner(new ExtractResultsFactory(() ->
(MSQTestOverlordServiceClient) ((MSQTaskSqlEngine)
queryFramework().engine()).overlordClient()))
.skipVectorize(true)
- .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate())
- .msqCompatible(msqCompatible);
+ .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate());
}
@Ignore
diff --git
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteUnionQueryMSQTest.java
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteUnionQueryMSQTest.java
index acea7d675d4..9f1d7cc242d 100644
---
a/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteUnionQueryMSQTest.java
+++
b/extensions-core/multi-stage-query/src/test/java/org/apache/druid/msq/test/CalciteUnionQueryMSQTest.java
@@ -93,8 +93,7 @@ public class CalciteUnionQueryMSQTest extends
CalciteUnionQueryTest
return new QueryTestBuilder(new
BaseCalciteQueryTest.CalciteTestConfig(true))
.addCustomRunner(new ExtractResultsFactory(() ->
(MSQTestOverlordServiceClient) ((MSQTaskSqlEngine)
queryFramework().engine()).overlordClient()))
.skipVectorize(true)
- .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate())
- .msqCompatible(msqCompatible);
+ .verifyNativeQueries(new VerifyMSQSupportedNativeQueriesPredicate());
}
/**
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/BaseCalciteQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/BaseCalciteQueryTest.java
index d9569d31615..c53f5684d25 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/BaseCalciteQueryTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/BaseCalciteQueryTest.java
@@ -115,6 +115,8 @@ import
org.apache.druid.sql.calcite.util.SqlTestFramework.StandardComponentSuppl
import
org.apache.druid.sql.calcite.util.SqlTestFramework.StandardPlannerComponentSupplier;
import org.apache.druid.sql.calcite.view.ViewManager;
import org.apache.druid.sql.http.SqlParameter;
+import org.hamcrest.CoreMatchers;
+import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
@@ -124,7 +126,7 @@ import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
-import org.junit.rules.ExpectedException;
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import org.junit.rules.TemporaryFolder;
import javax.annotation.Nullable;
@@ -139,11 +141,12 @@ import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
-import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
/**
@@ -295,15 +298,11 @@ public class BaseCalciteQueryTest extends CalciteTestBase
public final SqlEngine engine0;
final boolean useDefault = NullHandling.replaceWithDefault();
- @Rule(order = 1)
- public ExpectedException expectedException = ExpectedException.none();
-
@Rule(order = 2)
public TemporaryFolder temporaryFolder = new TemporaryFolder();
public boolean cannotVectorize = false;
public boolean skipVectorize = false;
- public boolean msqCompatible = true;
public QueryLogHook queryLogHook;
@@ -970,8 +969,7 @@ public class BaseCalciteQueryTest extends CalciteTestBase
final String sql,
final AuthenticationResult authenticationResult,
final List<Query<?>> expectedQueries,
- final ResultsVerifier expectedResultsVerifier,
- @Nullable final Consumer<ExpectedException> expectedExceptionInitializer
+ final ResultsVerifier expectedResultsVerifier
)
{
testBuilder()
@@ -982,7 +980,6 @@ public class BaseCalciteQueryTest extends CalciteTestBase
.authResult(authenticationResult)
.expectedQueries(expectedQueries)
.expectedResults(expectedResultsVerifier)
- .expectedException(expectedExceptionInitializer)
.run();
}
@@ -990,8 +987,7 @@ public class BaseCalciteQueryTest extends CalciteTestBase
{
return new QueryTestBuilder(new CalciteTestConfig())
.cannotVectorize(cannotVectorize)
- .skipVectorize(skipVectorize)
- .msqCompatible(msqCompatible);
+ .skipVectorize(skipVectorize);
}
public class CalciteTestConfig implements QueryTestBuilder.QueryTestConfig
@@ -1026,12 +1022,6 @@ public class BaseCalciteQueryTest extends CalciteTestBase
return queryLogHook;
}
- @Override
- public ExpectedException expectedException()
- {
- return expectedException;
- }
-
@Override
public PlannerFixture plannerFixture(PlannerConfig plannerConfig,
AuthConfig authConfig)
{
@@ -1222,29 +1212,53 @@ public class BaseCalciteQueryTest extends
CalciteTestBase
Assert.assertEquals(expectedResults.size(), results.size());
}
- public void testQueryThrows(final String sql, Consumer<ExpectedException>
expectedExceptionInitializer)
+ public <T extends Throwable> void testQueryThrows(
+ final String sql,
+ final DruidExceptionMatcher exceptionMatcher
+ )
{
- testBuilder()
- .sql(sql)
- .expectedException(expectedExceptionInitializer)
- .build()
- .run();
+ testQueryThrows(sql, null, DruidException.class, exceptionMatcher);
+ }
+
+ public <T extends Exception> void testQueryThrows(
+ final String sql,
+ final Class<T> exceptionType,
+ final String exceptionMessage
+ )
+ {
+ testQueryThrows(
+ sql,
+ null,
+ exceptionType,
+
ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo(exceptionMessage))
+ );
+ }
+
+ public <T extends Exception> void testQueryThrows(
+ final String sql,
+ final Class<T> exceptionType,
+ final Matcher<Throwable> exceptionMatcher
+ )
+ {
+ testQueryThrows(sql, null, exceptionType, exceptionMatcher);
}
- public void testQueryThrows(
+ public <T extends Exception> void testQueryThrows(
final String sql,
final Map<String, Object> queryContext,
- final List<Query<?>> expectedQueries,
- final Consumer<ExpectedException> expectedExceptionInitializer
+ final Class<T> exceptionType,
+ final Matcher<Throwable> exceptionMatcher
)
{
- testBuilder()
- .sql(sql)
- .queryContext(queryContext)
- .expectedQueries(expectedQueries)
- .expectedException(expectedExceptionInitializer)
- .build()
- .run();
+ T e = assertThrows(
+ exceptionType,
+ () -> testBuilder()
+ .sql(sql)
+ .queryContext(queryContext)
+ .build()
+ .run()
+ );
+ MatcherAssert.assertThat(e, exceptionMatcher);
}
public void analyzeResources(
@@ -1328,7 +1342,7 @@ public class BaseCalciteQueryTest extends CalciteTestBase
protected void msqIncompatible()
{
- msqCompatible = false;
+ assumeFalse("test case is not MSQ compatible",
testBuilder().config.isRunningMSQ());
}
protected static boolean isRewriteJoinToFilter(final Map<String, Object>
queryContext)
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteInsertDmlTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteInsertDmlTest.java
index 51f4b2265c7..e089b2a9082 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteInsertDmlTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteInsertDmlTest.java
@@ -765,8 +765,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Test correctness of the query when only the CLUSTERED BY clause is
present
@@ -802,8 +801,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -866,8 +864,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Test correctness of the query when only the CLUSTERED BY clause is
present
@@ -900,8 +897,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -973,8 +969,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Test correctness of the query when only the CLUSTERED BY clause is
present
@@ -1005,8 +1000,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -1342,8 +1336,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
@@ -1363,8 +1356,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -1447,8 +1439,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
testQuery(
@@ -1467,8 +1458,7 @@ public class CalciteInsertDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteJoinQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteJoinQueryTest.java
index ac59234576c..9b683cc0388 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteJoinQueryTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteJoinQueryTest.java
@@ -5637,8 +5637,7 @@ public class CalciteJoinQueryTest extends
BaseCalciteQueryTest
),
(sql, result) -> {
// Ignore the results, only need to check that the type of query is
a join.
- },
- null
+ }
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteMultiValueStringQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteMultiValueStringQueryTest.java
index ac6e6ba33a0..a93a02a543d 100644
---
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteMultiValueStringQueryTest.java
+++
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteMultiValueStringQueryTest.java
@@ -22,7 +22,6 @@ package org.apache.druid.sql.calcite;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.common.config.NullHandling;
-import org.apache.druid.error.DruidException;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.math.expr.ExpressionProcessing;
@@ -50,7 +49,9 @@ import
org.apache.druid.segment.virtual.ExpressionVirtualColumn;
import org.apache.druid.segment.virtual.ListFilteredVirtualColumn;
import org.apache.druid.sql.calcite.filtration.Filtration;
import org.apache.druid.sql.calcite.util.CalciteTests;
+import org.hamcrest.CoreMatchers;
import org.junit.Test;
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import java.util.Collections;
import java.util.HashMap;
@@ -122,24 +123,24 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
@Test
public void testMultiValueStringGroupByDoesNotWork()
{
- // Cannot vectorize due to usage of expressions.
- cannotVectorize();
Map<String, Object> groupByOnMultiValueColumnDisabled = new
HashMap<>(QUERY_CONTEXT_DEFAULT);
groupByOnMultiValueColumnDisabled.put(GroupByQueryConfig.CTX_KEY_ENABLE_MULTI_VALUE_UNNESTING,
false);
testQueryThrows(
"SELECT concat(dim3, 'foo'), SUM(cnt) FROM druid.numfoo GROUP BY 1
ORDER BY 2 DESC",
groupByOnMultiValueColumnDisabled,
- ImmutableList.of(),
- exception -> {
- exception.expect(RuntimeException.class);
- expectedException.expectMessage(StringUtils.format(
- "Encountered multi-value dimension [%s] that cannot be processed
with '%s' set to false."
- + " Consider setting '%s' to true in your query context.",
- "v0",
- GroupByQueryConfig.CTX_KEY_ENABLE_MULTI_VALUE_UNNESTING,
- GroupByQueryConfig.CTX_KEY_ENABLE_MULTI_VALUE_UNNESTING
- ));
- }
+ RuntimeException.class,
+ ThrowableMessageMatcher.hasMessage(
+ CoreMatchers.containsString(
+ StringUtils.format(
+
"org.apache.druid.query.groupby.epinephelinae.UnexpectedMultiValueDimensionException:
"
+ + "Encountered multi-value dimension [%s] that cannot
be processed with '%s' set to false."
+ + " Consider setting '%s' to true in your query
context.",
+ "v0",
+ GroupByQueryConfig.CTX_KEY_ENABLE_MULTI_VALUE_UNNESTING,
+ GroupByQueryConfig.CTX_KEY_ENABLE_MULTI_VALUE_UNNESTING
+ )
+ )
+ )
);
}
@@ -2040,10 +2041,7 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY(dim3,dim3) FROM druid.numfoo",
- exception -> {
- exception.expect(DruidException.class);
- exception.expectMessage("Invalid number of arguments to function");
- }
+ invalidSqlContains("Invalid number of arguments to function")
);
}
@@ -2052,10 +2050,7 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY() FROM druid.numfoo",
- exception -> {
- exception.expect(DruidException.class);
- exception.expectMessage("Invalid number of arguments to function");
- }
+ invalidSqlContains("Invalid number of arguments to function")
);
}
@@ -2064,7 +2059,8 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY(concat(dim3,'c')) FROM druid.numfoo",
- exception -> exception.expect(RuntimeException.class)
+ RuntimeException.class,
+ "Function[mv_to_array] argument (concat [dim3, c]) should be an
identifier expression. Use array() instead"
);
}
@@ -2073,7 +2069,8 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY(concat(dim1,'c')) FROM druid.numfoo",
- exception -> exception.expect(RuntimeException.class)
+ RuntimeException.class,
+ "Function[mv_to_array] argument (concat [dim1, c]) should be an
identifier expression. Use array() instead"
);
}
@@ -2082,7 +2079,8 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY(concat(dim1,'c')) FROM druid.numfoo",
- exception -> exception.expect(RuntimeException.class)
+ RuntimeException.class,
+ "Function[mv_to_array] argument (concat [dim1, c]) should be an
identifier expression. Use array() instead"
);
}
@@ -2091,7 +2089,8 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT MV_TO_ARRAY(Array[1,2]) FROM druid.numfoo",
- exception -> exception.expect(RuntimeException.class)
+ RuntimeException.class,
+ "Function[mv_to_array] argument (array [1, 2]) should be an identifier
expression. Use array() instead"
);
}
@@ -2241,10 +2240,7 @@ public class CalciteMultiValueStringQueryTest extends
BaseCalciteQueryTest
testQueryThrows(
"SELECT COALESCE(dim3, 'other') FROM druid.numfoo "
+ "WHERE MV_OVERLAP(COALESCE(dim3, ARRAY['other']), ARRAY['a', 'b',
'other']) LIMIT 5",
- e -> {
- e.expect(invalidSqlContains("Illegal mixing of types in CASE or
COALESCE statement"));
- }
-
+ invalidSqlContains("Illegal mixing of types in CASE or COALESCE
statement")
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteNestedDataQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteNestedDataQueryTest.java
index 6c177e76e7b..ed0c0f97eae 100644
---
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteNestedDataQueryTest.java
+++
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteNestedDataQueryTest.java
@@ -74,7 +74,9 @@ import org.apache.druid.sql.calcite.filtration.Filtration;
import org.apache.druid.sql.calcite.util.TestDataBuilder;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.partition.LinearShardSpec;
+import org.hamcrest.CoreMatchers;
import org.junit.Test;
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import java.io.IOException;
import java.util.Arrays;
@@ -4575,13 +4577,9 @@ public class CalciteNestedDataQueryTest extends
BaseCalciteQueryTest
+ "JSON_VALUE(nester, '.array.[1]'), "
+ "SUM(cnt) "
+ "FROM druid.nested GROUP BY 1",
- (expected) -> {
- expected.expect(
- DruidExceptionMatcher
- .invalidInput()
- .expectMessageIs("JSONPath [.array.[1]] is invalid, it must
start with '$'")
- );
- }
+ DruidExceptionMatcher
+ .invalidInput()
+ .expectMessageIs("JSONPath [.array.[1]] is invalid, it must start
with '$'")
);
}
@@ -4994,12 +4992,12 @@ public class CalciteNestedDataQueryTest extends
BaseCalciteQueryTest
"SELECT "
+ "SUM(JSON_VALUE(nest, '$.z' RETURNING BIGINT ERROR ON EMPTY ERROR ON
ERROR)) "
+ "FROM druid.nested",
- exception -> {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(
- "Unsupported JSON_VALUE parameter 'ON EMPTY' defined - please
re-issue this query without this argument"
- );
- }
+ IllegalArgumentException.class,
+ ThrowableMessageMatcher.hasMessage(
+ CoreMatchers.containsString(
+ "Unsupported JSON_VALUE parameter 'ON EMPTY' defined - please
re-issue this query without this argument"
+ )
+ )
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteParameterQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteParameterQueryTest.java
index 5db298de9aa..5b4c9cd17b4 100644
---
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteParameterQueryTest.java
+++
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteParameterQueryTest.java
@@ -22,6 +22,7 @@ package org.apache.druid.sql.calcite;
import com.google.common.collect.ImmutableList;
import org.apache.calcite.avatica.SqlType;
import org.apache.druid.common.config.NullHandling;
+import org.apache.druid.error.DruidException;
import org.apache.druid.error.DruidExceptionMatcher;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.Intervals;
@@ -46,6 +47,9 @@ import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* This class has copied a subset of the tests in {@link CalciteQueryTest} and
* replaced various parts of queries with dynamic parameters. It is NOT
@@ -589,32 +593,40 @@ public class CalciteParameterQueryTest extends
BaseCalciteQueryTest
@Test
public void testMissingParameter()
{
- expectedException.expect(
- DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [1])")
+ DruidException exception = assertThrows(
+ DruidException.class,
+ () -> testQuery(
+ "SELECT COUNT(*)\n"
+ + "FROM druid.numfoo\n"
+ + "WHERE l1 > ?",
+ ImmutableList.of(),
+ ImmutableList.of(new Object[] {3L}),
+ ImmutableList.of()
+ )
);
- testQuery(
- "SELECT COUNT(*)\n"
- + "FROM druid.numfoo\n"
- + "WHERE l1 > ?",
- ImmutableList.of(),
- ImmutableList.of(new Object[]{3L}),
- ImmutableList.of()
+ assertThat(
+ exception,
+ DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [1])")
);
}
@Test
public void testPartiallyMissingParameter()
{
- expectedException.expect(
- DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [2])")
+ DruidException exception = assertThrows(
+ DruidException.class,
+ () -> testQuery(
+ "SELECT COUNT(*)\n"
+ + "FROM druid.numfoo\n"
+ + "WHERE l1 > ? AND f1 = ?",
+ ImmutableList.of(),
+ ImmutableList.of(new Object[] {3L}),
+ ImmutableList.of(new SqlParameter(SqlType.BIGINT, 3L))
+ )
);
- testQuery(
- "SELECT COUNT(*)\n"
- + "FROM druid.numfoo\n"
- + "WHERE l1 > ? AND f1 = ?",
- ImmutableList.of(),
- ImmutableList.of(new Object[]{3L}),
- ImmutableList.of(new SqlParameter(SqlType.BIGINT, 3L))
+ assertThat(
+ exception,
+ DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [2])")
);
}
@@ -624,14 +636,19 @@ public class CalciteParameterQueryTest extends
BaseCalciteQueryTest
List<SqlParameter> params = new ArrayList<>();
params.add(null);
params.add(new SqlParameter(SqlType.INTEGER, 1));
- expectedException.expect(
- DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [1])")
+ DruidException exception = assertThrows(
+ DruidException.class,
+ () -> testQuery(
+ "SELECT 1 + ?, dim1 FROM foo LIMIT ?",
+ ImmutableList.of(),
+ ImmutableList.of(),
+ params
+ )
);
- testQuery(
- "SELECT 1 + ?, dim1 FROM foo LIMIT ?",
- ImmutableList.of(),
- ImmutableList.of(),
- params
+
+ assertThat(
+ exception,
+ DruidExceptionMatcher.invalidSqlInput().expectMessageIs("No value
bound for parameter (position [1])")
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteQueryTest.java
index e7cfdc6e4b0..c7de263eca4 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteQueryTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteQueryTest.java
@@ -144,7 +144,9 @@ import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;
+import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class CalciteQueryTest extends BaseCalciteQueryTest
{
@@ -827,27 +829,18 @@ public class CalciteQueryTest extends BaseCalciteQueryTest
@Test
public void testEarliestByInvalidTimestamp()
{
- expectedException.expect(DruidException.class);
- expectedException.expectMessage("Cannot apply 'EARLIEST_BY' to arguments
of type 'EARLIEST_BY(<FLOAT>, <BIGINT>)");
-
- testQuery(
+ testQueryThrows(
"SELECT EARLIEST_BY(m1, l1) FROM druid.numfoo",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains("Cannot apply 'EARLIEST_BY' to arguments of type
'EARLIEST_BY(<FLOAT>, <BIGINT>)")
);
}
@Test
public void testLatestByInvalidTimestamp()
{
- expectedException.expect(
- invalidSqlContains("Cannot apply 'LATEST_BY' to arguments of type
'LATEST_BY(<FLOAT>, <BIGINT>)")
- );
-
- testQuery(
+ testQueryThrows(
"SELECT LATEST_BY(m1, l1) FROM druid.numfoo",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains("Cannot apply 'LATEST_BY' to arguments of type
'LATEST_BY(<FLOAT>, <BIGINT>)")
);
}
@@ -2580,7 +2573,7 @@ public class CalciteQueryTest extends BaseCalciteQueryTest
final String sqlQuery = "SELECT COUNT(DISTINCT foo.dim1) FILTER(WHERE
foo.cnt = 1), SUM(foo.cnt) FROM druid.foo";
// When useApproximateCountDistinct=false and
useGroupingSetForExactDistinct=false, planning fails due
// to a bug in the Calcite's rule (AggregateExpandDistinctAggregatesRule)
- Assert.assertThrows(
+ assertThrows(
RuntimeException.class,
() -> testQuery(
PLANNER_CONFIG_NO_HLL.withOverrides(
@@ -5737,7 +5730,6 @@ public class CalciteQueryTest extends BaseCalciteQueryTest
@Test
public void testCountStarWithNotOfDegenerateFilter()
{
-
msqIncompatible();
// HashJoinSegmentStorageAdapter is not vectorizable
cannotVectorize();
@@ -6117,13 +6109,11 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
testQueryThrows(
"SELECT COUNT(*) FROM druid.foo "
+ "WHERE TIME_IN_INTERVAL(__time, '2000-01-01/X')",
- expected -> {
-
expected.expect(CoreMatchers.instanceOf(CalciteContextException.class));
-
expected.expect(ThrowableMessageMatcher.hasMessage(CoreMatchers.containsString(
- "From line 1, column 38 to line 1, column 77: "
- + "Function 'TIME_IN_INTERVAL' second argument is not a valid
ISO8601 interval: "
- + "Invalid format: \"X\"")));
- }
+ CalciteContextException.class,
+ ThrowableMessageMatcher.hasMessage(CoreMatchers.containsString(
+ "From line 1, column 38 to line 1, column 77: "
+ + "Function 'TIME_IN_INTERVAL' second argument is not a valid
ISO8601 interval: "
+ + "Invalid format: \"X\""))
);
}
@@ -6134,11 +6124,12 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
testQueryThrows(
"SELECT COUNT(*) FROM druid.foo "
+ "WHERE TIME_IN_INTERVAL(__time, dim1)",
- expected -> {
- expected.expect(CoreMatchers.instanceOf(DruidException.class));
-
expected.expect(ThrowableMessageMatcher.hasMessage(CoreMatchers.containsString(
- "Argument to function 'TIME_IN_INTERVAL' must be a literal (line
[1], column [63])")));
- }
+ DruidException.class,
+ ThrowableMessageMatcher.hasMessage(
+ CoreMatchers.containsString(
+ "Argument to function 'TIME_IN_INTERVAL' must be a literal
(line [1], column [63])"
+ )
+ )
);
}
@@ -7581,46 +7572,52 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
@Test
public void testHighestMaxNumericInFilter()
{
- expectedException.expect(UOE.class);
- expectedException.expectMessage("Expected parameter[maxNumericInFilters]
cannot exceed system set value of [100]");
+ Throwable exception = assertThrows(UOE.class, () -> {
- testQuery(
- PLANNER_CONFIG_MAX_NUMERIC_IN_FILTER,
- ImmutableMap.of(QueryContexts.MAX_NUMERIC_IN_FILTERS, 20000),
- "SELECT COUNT(*)\n"
- + "FROM druid.numfoo\n"
- + "WHERE dim6 IN (\n"
- + "1,2,3\n"
- + ")\n",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
- );
+ testQuery(
+ PLANNER_CONFIG_MAX_NUMERIC_IN_FILTER,
+ ImmutableMap.of(QueryContexts.MAX_NUMERIC_IN_FILTERS, 20000),
+ "SELECT COUNT(*)\n"
+ + "FROM druid.numfoo\n"
+ + "WHERE dim6 IN (\n"
+ + "1,2,3\n"
+ + ")\n",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(exception.getMessage().contains("Expected
parameter[maxNumericInFilters] cannot exceed system set value of [100]"));
}
@Test
public void testQueryWithMoreThanMaxNumericInFilter()
{
- if (NullHandling.sqlCompatible()) {
- // skip in sql compatible mode, this plans to an OR filter with equality
filter children...
- return;
- }
+ assumeFalse(
+ "skip in sql compatible mode, this plans to an OR filter with equality
filter children",
+ NullHandling.sqlCompatible()
+ );
msqIncompatible();
- expectedException.expect(UOE.class);
- expectedException.expectMessage(
- "The number of values in the IN clause for [dim6] in query exceeds
configured maxNumericFilter limit of [2] for INs. Cast [3] values of IN clause
to String");
- testQuery(
- PLANNER_CONFIG_MAX_NUMERIC_IN_FILTER,
- ImmutableMap.of(QueryContexts.MAX_NUMERIC_IN_FILTERS, 2),
- "SELECT COUNT(*)\n"
- + "FROM druid.numfoo\n"
- + "WHERE dim6 IN (\n"
- + "1,2,3\n"
- + ")\n",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
+ Throwable exception = assertThrows(UOE.class, () -> {
+ testQuery(
+ PLANNER_CONFIG_MAX_NUMERIC_IN_FILTER,
+ ImmutableMap.of(QueryContexts.MAX_NUMERIC_IN_FILTERS, 2),
+ "SELECT COUNT(*)\n"
+ + "FROM druid.numfoo\n"
+ + "WHERE dim6 IN (\n"
+ + "1,2,3\n"
+ + ")\n",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(
+ exception.getMessage().contains(
+ "The number of values in the IN clause for [dim6] in query exceeds
configured "
+ + "maxNumericFilter limit of [2] for INs. Cast [3] values of IN
clause to String"
+ )
);
}
@@ -8082,18 +8079,14 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
// Cannot vectorize due to extractionFn in dimension spec.
cannotVectorize();
- expectedException.expect(DruidException.class);
- expectedException.expectMessage(
- "An invalid pattern [^(.))] was provided for the REGEXP_EXTRACT
function, " +
- "error: [Unmatched closing ')' near index 3\n^(.))\n ^]"
- );
-
- testQuery(
+ testQueryThrows(
"SELECT DISTINCT\n"
+ " REGEXP_EXTRACT(dim1, '^(.))', 1)\n"
+ "FROM foo",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains(
+ "An invalid pattern [^(.))] was provided for the REGEXP_EXTRACT
function, " +
+ "error: [Unmatched closing ')' near index 3\n^(.))\n ^]"
+ )
);
}
@@ -12320,60 +12313,61 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
public void testRequireTimeConditionSimpleQueryNegative()
{
msqIncompatible();
- expectedException.expect(CannotBuildQueryException.class);
- expectedException.expectMessage("__time column");
-
- testQuery(
- PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
- "SELECT SUM(cnt), gran FROM (\n"
- + " SELECT __time as t, floor(__time TO month) AS gran,\n"
- + " cnt FROM druid.foo\n"
- + ") AS x\n"
- + "GROUP BY gran\n"
- + "ORDER BY gran",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
- );
+ Throwable exception = assertThrows(CannotBuildQueryException.class, () -> {
+ testQuery(
+ PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
+ "SELECT SUM(cnt), gran FROM (\n"
+ + " SELECT __time as t, floor(__time TO month) AS gran,\n"
+ + " cnt FROM druid.foo\n"
+ + ") AS x\n"
+ + "GROUP BY gran\n"
+ + "ORDER BY gran",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(exception.getMessage().contains("__time column"));
}
@Test
public void testRequireTimeConditionSubQueryNegative()
{
msqIncompatible();
- expectedException.expect(CannotBuildQueryException.class);
- expectedException.expectMessage("__time column");
-
- testQuery(
- PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
- "SELECT\n"
- + " SUM(cnt),\n"
- + " COUNT(*)\n"
- + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY dim2)",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
- );
+ Throwable exception = assertThrows(CannotBuildQueryException.class, () -> {
+ testQuery(
+ PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
+ "SELECT\n"
+ + " SUM(cnt),\n"
+ + " COUNT(*)\n"
+ + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY
dim2)",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(exception.getMessage().contains("__time column"));
}
@Test
public void testRequireTimeConditionSemiJoinNegative()
{
msqIncompatible();
- expectedException.expect(CannotBuildQueryException.class);
- expectedException.expectMessage("__time column");
+ Throwable exception = assertThrows(CannotBuildQueryException.class, () -> {
- testQuery(
- PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
- "SELECT COUNT(*) FROM druid.foo\n"
- + "WHERE SUBSTRING(dim2, 1, 1) IN (\n"
- + " SELECT SUBSTRING(dim1, 1, 1) FROM druid.foo\n"
- + " WHERE dim1 <> '' AND __time >= '2000-01-01'\n"
- + ")",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
- );
+ testQuery(
+ PLANNER_CONFIG_REQUIRE_TIME_CONDITION,
+ "SELECT COUNT(*) FROM druid.foo\n"
+ + "WHERE SUBSTRING(dim2, 1, 1) IN (\n"
+ + " SELECT SUBSTRING(dim1, 1, 1) FROM druid.foo\n"
+ + " WHERE dim1 <> '' AND __time >= '2000-01-01'\n"
+ + ")",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(exception.getMessage().contains("__time column"));
}
@Test
@@ -12869,36 +12863,27 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
@Test
public void testValidationErrorNullLiteralIllegal()
{
- expectedException.expectMessage("Illegal use of 'NULL'");
-
- testQuery(
+ testQueryThrows(
"SELECT REGEXP_LIKE('x', NULL)",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains("Illegal use of 'NULL'")
);
}
@Test
public void testValidationErrorNonLiteralIllegal()
{
- expectedException.expectMessage("Argument to function 'REGEXP_LIKE' must
be a literal");
-
- testQuery(
+ testQueryThrows(
"SELECT REGEXP_LIKE('x', dim1) FROM foo",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains("Argument to function 'REGEXP_LIKE' must be a
literal")
);
}
@Test
public void testValidationErrorWrongTypeLiteral()
{
- expectedException.expectMessage("Cannot apply 'REGEXP_LIKE' to arguments");
-
- testQuery(
+ testQueryThrows(
"SELECT REGEXP_LIKE('x', 1) FROM foo",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlContains("Cannot apply 'REGEXP_LIKE' to arguments")
);
}
@@ -14095,32 +14080,24 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
@Test
public void testHumanReadableFormatFunctionExceptionWithWrongNumberType()
{
- this.expectedException.expect(DruidException.class);
- this.expectedException.expectMessage("Supported form(s):
HUMAN_READABLE_BINARY_BYTE_FORMAT(Number, [Precision])");
- testQuery(
+ testQueryThrows(
"SELECT HUMAN_READABLE_BINARY_BYTE_FORMAT('45678')",
- Collections.emptyList(),
- Collections.emptyList()
+ invalidSqlContains("Supported form(s):
HUMAN_READABLE_BINARY_BYTE_FORMAT(Number, [Precision])")
);
}
@Test
public void testHumanReadableFormatFunctionWithWrongPrecisionType()
{
- this.expectedException.expect(DruidException.class);
- this.expectedException.expectMessage("Supported form(s):
HUMAN_READABLE_BINARY_BYTE_FORMAT(Number, [Precision])");
- testQuery(
+ testQueryThrows(
"SELECT HUMAN_READABLE_BINARY_BYTE_FORMAT(45678, '2')",
- Collections.emptyList(),
- Collections.emptyList()
+ invalidSqlContains("Supported form(s):
HUMAN_READABLE_BINARY_BYTE_FORMAT(Number, [Precision])")
);
}
@Test
public void testHumanReadableFormatFunctionWithInvalidNumberOfArguments()
{
- this.expectedException.expect(DruidException.class);
-
/*
* frankly speaking, the exception message thrown here is a little bit
confusing
* it says it's 'expecting 1 arguments' but actually
HUMAN_READABLE_BINARY_BYTE_FORMAT supports 1 or 2 arguments
@@ -14129,12 +14106,9 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
* and we can see from its implementation that it gets the min number
arguments to format the exception message.
*
*/
- this.expectedException.expectMessage(
- "Invalid number of arguments to function
'HUMAN_READABLE_BINARY_BYTE_FORMAT'. Was expecting 1 arguments");
- testQuery(
+ testQueryThrows(
"SELECT HUMAN_READABLE_BINARY_BYTE_FORMAT(45678, 2, 1)",
- Collections.emptyList(),
- Collections.emptyList()
+ invalidSqlContains("Invalid number of arguments to function
'HUMAN_READABLE_BINARY_BYTE_FORMAT'. Was expecting 1 arguments")
);
}
@@ -14322,8 +14296,7 @@ public class CalciteQueryTest extends
BaseCalciteQueryTest
),
(sql, result) -> {
// Ignore the results, only need to check that the type of query is
a filter.
- },
- null
+ }
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteReplaceDmlTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteReplaceDmlTest.java
index 95c05cfbafc..cad3945fbd6 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteReplaceDmlTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteReplaceDmlTest.java
@@ -733,8 +733,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
testQuery(
@@ -753,8 +752,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -817,8 +815,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
testQuery(
@@ -837,8 +834,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
@@ -924,8 +920,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
testQuery(
@@ -944,8 +939,7 @@ public class CalciteReplaceDmlTest extends
CalciteIngestionDmlTest
}
),
null
- ),
- null
+ )
);
// Not using testIngestionQuery, so must set didTest manually to satisfy
the check in tearDown.
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSelectQueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSelectQueryTest.java
index e368e900497..0e34c64043f 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSelectQueryTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSelectQueryTest.java
@@ -22,7 +22,6 @@ package org.apache.druid.sql.calcite;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.common.config.NullHandling;
-import org.apache.druid.error.DruidException;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.granularity.Granularities;
@@ -315,28 +314,24 @@ public class CalciteSelectQueryTest extends
BaseCalciteQueryTest
@Test
public void testSelectConstantExpressionEquivalentToNaN()
{
- expectedException.expect(invalidSqlIs(
- "Expression [(log10(0) - log10(0))] evaluates to an unsupported value
[NaN], "
- + "expected something that can be a Double. Consider casting with
'CAST(<col> AS BIGINT)'"
- ));
- testQuery(
+ testQueryThrows(
"SELECT log10(0) - log10(0), dim1 FROM foo LIMIT 1",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlIs(
+ "Expression [(log10(0) - log10(0))] evaluates to an unsupported
value [NaN], "
+ + "expected something that can be a Double. Consider casting
with 'CAST(<col> AS BIGINT)'"
+ )
);
}
@Test
public void testSelectConstantExpressionEquivalentToInfinity()
{
- expectedException.expect(invalidSqlIs(
- "Expression [log10(0)] evaluates to an unsupported value [-Infinity], "
- + "expected something that can be a Double. Consider casting with
'CAST(<col> AS BIGINT)'"
- ));
- testQuery(
+ testQueryThrows(
"SELECT log10(0), dim1 FROM foo LIMIT 1",
- ImmutableList.of(),
- ImmutableList.of()
+ invalidSqlIs(
+ "Expression [log10(0)] evaluates to an unsupported value
[-Infinity], "
+ + "expected something that can be a Double. Consider casting
with 'CAST(<col> AS BIGINT)'"
+ )
);
}
@@ -1031,12 +1026,7 @@ public class CalciteSelectQueryTest extends
BaseCalciteQueryTest
{
testQueryThrows(
"SELECT CURRENT_TIMESTAMP(4)",
- expectedException -> {
- expectedException.expect(DruidException.class);
- expectedException.expectMessage(
- "Argument to function 'CURRENT_TIMESTAMP' must be a valid
precision between '0' and '3'"
- );
- }
+ invalidSqlContains("Argument to function 'CURRENT_TIMESTAMP' must be a
valid precision between '0' and '3'")
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSubqueryTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSubqueryTest.java
index 91316512e35..5a3fac0b077 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSubqueryTest.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/CalciteSubqueryTest.java
@@ -62,9 +62,11 @@ import org.apache.druid.segment.join.JoinType;
import org.apache.druid.sql.calcite.expression.DruidExpression;
import org.apache.druid.sql.calcite.filtration.Filtration;
import org.apache.druid.sql.calcite.util.CalciteTests;
+import org.hamcrest.CoreMatchers;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.junit.Test;
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -76,6 +78,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* Calcite tests which involve subqueries and materializing the intermediate
results on {@link org.apache.druid.server.ClientQuerySegmentWalker}
@@ -675,100 +680,111 @@ public class CalciteSubqueryTest extends
BaseCalciteQueryTest
public void testMaxSubqueryRows()
{
if ("without memory limit".equals(testName)) {
- expectedException.expect(ResourceLimitExceededException.class);
- expectedException.expectMessage(
- "Cannot issue the query, subqueries generated results beyond
maximum[1] rows. Try setting the "
- + "'maxSubqueryBytes' in the query context to 'auto' for enabling
byte based limit, which chooses an optimal "
- + "limit based on memory size and result's heap usage or manually
configure the values of either 'maxSubqueryBytes' "
- + "or 'maxSubqueryRows' in the query context. Manually alter the
value carefully as it can cause the broker to "
- + "go out of memory."
- );
- Map<String, Object> modifiedQueryContext = new HashMap<>(queryContext);
- modifiedQueryContext.put(QueryContexts.MAX_SUBQUERY_ROWS_KEY, 1);
-
- testQuery(
- "SELECT\n"
- + " SUM(cnt),\n"
- + " COUNT(*)\n"
- + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY dim2
LIMIT 2) \n"
- + "WHERE cnt > 0",
- modifiedQueryContext,
- ImmutableList.of(),
- ImmutableList.of()
- );
+ testMaxSubqueryRowsWithoutMemoryLimit();
} else {
- // Since the results are materializable as frames, we are able to use
the memory limit and donot rely on the
- // row limit for the subquery
- Map<String, Object> modifiedQueryContext = new HashMap<>(queryContext);
- modifiedQueryContext.put(QueryContexts.MAX_SUBQUERY_ROWS_KEY, 1);
-
- testQuery(
- "SELECT\n"
- + " SUM(cnt),\n"
- + " COUNT(*)\n"
- + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY dim2
LIMIT 1)\n"
- + "WHERE cnt > 0",
- modifiedQueryContext,
- ImmutableList.of(
- GroupByQuery.builder()
- .setDataSource(
- new QueryDataSource(
- new TopNQueryBuilder()
- .dataSource(CalciteTests.DATASOURCE1)
-
.intervals(querySegmentSpec(Filtration.eternity()))
- .granularity(Granularities.ALL)
- .dimension(new
DefaultDimensionSpec("dim2", "d0"))
- .aggregators(new
LongSumAggregatorFactory("a0", "cnt"))
- .metric(new
DimensionTopNMetricSpec(null, StringComparators.LEXICOGRAPHIC))
- .threshold(1)
- .build()
- )
- )
- .setDimFilter(range("a0", ColumnType.LONG, 0L, null,
true, false))
- .setInterval(querySegmentSpec(Filtration.eternity()))
- .setGranularity(Granularities.ALL)
- .setAggregatorSpecs(aggregators(
- new LongSumAggregatorFactory("_a0", "a0"),
- new CountAggregatorFactory("_a1")
- ))
- .setContext(queryContext)
- .build()
- ),
- NullHandling.replaceWithDefault() ?
- ImmutableList.of(
- new Object[]{3L, 1L}
- ) :
- ImmutableList.of(
- new Object[]{2L, 1L}
- )
- );
+ testMaxSubQueryRowsWithLimit();
}
}
- @Test
- public void testZeroMaxNumericInFilter()
+ private void testMaxSubqueryRowsWithoutMemoryLimit()
{
- expectedException.expect(UOE.class);
- expectedException.expectMessage("[maxNumericInFilters] must be greater
than 0");
-
Map<String, Object> modifiedQueryContext = new HashMap<>(queryContext);
- modifiedQueryContext.put(QueryContexts.MAX_NUMERIC_IN_FILTERS, 0);
+ modifiedQueryContext.put(QueryContexts.MAX_SUBQUERY_ROWS_KEY, 1);
+ testQueryThrows(
+ "SELECT\n"
+ + " SUM(cnt),\n"
+ + " COUNT(*)\n"
+ + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY dim2
LIMIT 2) \n"
+ + "WHERE cnt > 0",
+ modifiedQueryContext,
+ ResourceLimitExceededException.class,
+ ThrowableMessageMatcher.hasMessage(
+ CoreMatchers.containsString(
+ "Cannot issue the query, subqueries generated results beyond
maximum[1] rows. Try setting the "
+ + "'maxSubqueryBytes' in the query context to 'auto' for
enabling byte based limit, which chooses an optimal "
+ + "limit based on memory size and result's heap usage or
manually configure the values of either 'maxSubqueryBytes' "
+ + "or 'maxSubqueryRows' in the query context. Manually
alter the value carefully as it can cause the broker to "
+ + "go out of memory."
+ )
+ )
+ );
+ }
+
+ private void testMaxSubQueryRowsWithLimit()
+ {
+ // Since the results are materializable as frames, we are able to use the
memory limit and donot rely on the
+ // row limit for the subquery
+ Map<String, Object> modifiedQueryContext = new HashMap<>(queryContext);
+ modifiedQueryContext.put(QueryContexts.MAX_SUBQUERY_ROWS_KEY, 1);
testQuery(
- PLANNER_CONFIG_DEFAULT,
+ "SELECT\n"
+ + " SUM(cnt),\n"
+ + " COUNT(*)\n"
+ + "FROM (SELECT dim2, SUM(cnt) AS cnt FROM druid.foo GROUP BY dim2
LIMIT 1)\n"
+ + "WHERE cnt > 0",
modifiedQueryContext,
- "SELECT COUNT(*)\n"
- + "FROM druid.numfoo\n"
- + "WHERE dim6 IN (\n"
- + "1,2,3\n"
- + ")\n",
- CalciteTests.REGULAR_USER_AUTH_RESULT,
- ImmutableList.of(),
- ImmutableList.of()
+ ImmutableList.of(
+ GroupByQuery.builder()
+ .setDataSource(
+ new QueryDataSource(
+ new TopNQueryBuilder()
+ .dataSource(CalciteTests.DATASOURCE1)
+
.intervals(querySegmentSpec(Filtration.eternity()))
+ .granularity(Granularities.ALL)
+ .dimension(new
DefaultDimensionSpec("dim2", "d0"))
+ .aggregators(new
LongSumAggregatorFactory("a0", "cnt"))
+ .metric(new DimensionTopNMetricSpec(null,
StringComparators.LEXICOGRAPHIC))
+ .threshold(1)
+ .build()
+ )
+ )
+ .setDimFilter(range("a0", ColumnType.LONG, 0L, null,
true, false))
+ .setInterval(querySegmentSpec(Filtration.eternity()))
+ .setGranularity(Granularities.ALL)
+ .setAggregatorSpecs(aggregators(
+ new LongSumAggregatorFactory("_a0", "a0"),
+ new CountAggregatorFactory("_a1")
+ ))
+ .setContext(queryContext)
+ .build()
+ ),
+ NullHandling.replaceWithDefault() ?
+ ImmutableList.of(
+ new Object[]{3L, 1L}
+ ) :
+ ImmutableList.of(
+ new Object[]{2L, 1L}
+ )
);
}
+ @Test
+ public void testZeroMaxNumericInFilter()
+ {
+ Throwable exception = assertThrows(UOE.class, () -> {
+
+ Map<String, Object> modifiedQueryContext = new HashMap<>(queryContext);
+ modifiedQueryContext.put(QueryContexts.MAX_NUMERIC_IN_FILTERS, 0);
+
+
+ testQuery(
+ PLANNER_CONFIG_DEFAULT,
+ modifiedQueryContext,
+ "SELECT COUNT(*)\n"
+ + "FROM druid.numfoo\n"
+ + "WHERE dim6 IN (\n"
+ + "1,2,3\n"
+ + ")\n",
+ CalciteTests.REGULAR_USER_AUTH_RESULT,
+ ImmutableList.of(),
+ ImmutableList.of()
+ );
+ });
+ assertTrue(exception.getMessage().contains("[maxNumericInFilters] must be
greater than 0"));
+ }
+
@Test
public void testUseTimeFloorInsteadOfGranularityOnJoinResult()
{
@@ -1302,7 +1318,8 @@ public class CalciteSubqueryTest extends
BaseCalciteQueryTest
cannotVectorize();
testQueryThrows(
"SELECT count(*) FROM wikipedia where channel = (select channel from
wikipedia order by __time desc LIMIT 2 OFFSET 6)",
- exception -> exception.expectMessage("Subquery expression returned
more than one row")
+ RuntimeException.class,
+ "java.util.concurrent.ExecutionException:
org.apache.druid.error.DruidException: Subquery expression returned more than
one row"
);
}
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/IngestTableFunctionTest.java
b/sql/src/test/java/org/apache/druid/sql/calcite/IngestTableFunctionTest.java
index d64902afa1e..2472736719f 100644
---
a/sql/src/test/java/org/apache/druid/sql/calcite/IngestTableFunctionTest.java
+++
b/sql/src/test/java/org/apache/druid/sql/calcite/IngestTableFunctionTest.java
@@ -45,7 +45,10 @@ import org.apache.druid.sql.calcite.filtration.Filtration;
import org.apache.druid.sql.calcite.planner.Calcites;
import org.apache.druid.sql.calcite.util.CalciteTests;
import org.apache.druid.sql.http.SqlParameter;
+import org.hamcrest.CoreMatchers;
+import org.hamcrest.MatcherAssert;
import org.junit.Test;
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import java.io.File;
import java.net.URI;
@@ -53,6 +56,8 @@ import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* Tests the input-source-specific table functions: http, inline and
localfiles.
* Each of these use meta-metadata defined by the catalog to identify the
allowed
@@ -349,16 +354,17 @@ public class IngestTableFunctionTest extends
CalciteIngestionDmlTest
" EXTEND (x VARCHAR, y VARCHAR, z BIGINT)\n" +
"PARTITIONED BY ALL TIME";
didTest = true; // Else the framework will complain
- testBuilder()
- .plannerConfig(PLANNER_CONFIG_NATIVE_QUERY_EXPLAIN)
- .sql(query)
- // Regular user does not have permission on extern or other table
functions
- .authResult(CalciteTests.REGULAR_USER_AUTH_RESULT)
- .expectedException(expected -> {
- expected.expect(ForbiddenException.class);
- expected.expectMessage(Access.DEFAULT_ERROR_MESSAGE);
- })
- .run();
+ ForbiddenException e = assertThrows(
+ ForbiddenException.class,
+ () -> testBuilder()
+ .plannerConfig(PLANNER_CONFIG_NATIVE_QUERY_EXPLAIN)
+ .sql(query)
+ // Regular user does not have permission on extern or other table
functions
+ .authResult(CalciteTests.REGULAR_USER_AUTH_RESULT)
+ .run()
+ );
+ MatcherAssert.assertThat(e,
ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo(Access.DEFAULT_ERROR_MESSAGE)));
+
}
@Test
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestBuilder.java
b/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestBuilder.java
index 961adcf74f5..9ae4d129d8f 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestBuilder.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestBuilder.java
@@ -37,14 +37,10 @@ import org.apache.druid.sql.calcite.util.CalciteTests;
import org.apache.druid.sql.calcite.util.QueryLogHook;
import org.apache.druid.sql.calcite.util.SqlTestFramework.PlannerFixture;
import org.apache.druid.sql.http.SqlParameter;
-import org.junit.rules.ExpectedException;
-
-import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-import java.util.function.Consumer;
import java.util.function.Predicate;
/**
@@ -74,8 +70,6 @@ public class QueryTestBuilder
{
QueryLogHook queryLogHook();
- ExpectedException expectedException();
-
ObjectMapper jsonMapper();
PlannerFixture plannerFixture(PlannerConfig plannerConfig, AuthConfig
authConfig);
@@ -99,10 +93,7 @@ public class QueryTestBuilder
protected RowSignature expectedResultSignature;
protected List<ResourceAction> expectedResources;
protected ResultsVerifier expectedResultsVerifier;
- @Nullable
- protected Consumer<ExpectedException> expectedExceptionInitializer;
protected boolean skipVectorize;
- protected boolean msqCompatible = true;
protected boolean queryCannotVectorize;
protected Predicate<List<Query<?>>> verifyNativeQueries = xs -> true;
protected AuthConfig authConfig = new AuthConfig();
@@ -218,12 +209,6 @@ public class QueryTestBuilder
return this;
}
- public QueryTestBuilder expectedException(Consumer<ExpectedException>
expectedExceptionInitializer)
- {
- this.expectedExceptionInitializer = expectedExceptionInitializer;
- return this;
- }
-
public QueryTestBuilder skipVectorize()
{
return skipVectorize(true);
@@ -235,12 +220,6 @@ public class QueryTestBuilder
return this;
}
- public QueryTestBuilder msqCompatible(boolean msqCompatible)
- {
- this.msqCompatible = msqCompatible;
- return this;
- }
-
public QueryTestBuilder verifyNativeQueries(Predicate<List<Query<?>>>
verifyNativeQueries)
{
this.verifyNativeQueries = verifyNativeQueries;
diff --git
a/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestRunner.java
b/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestRunner.java
index 1dd1df4eea8..ccb2012b94c 100644
--- a/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestRunner.java
+++ b/sql/src/test/java/org/apache/druid/sql/calcite/QueryTestRunner.java
@@ -28,7 +28,6 @@ import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.SqlExplainFormat;
import org.apache.calcite.sql.SqlExplainLevel;
import org.apache.calcite.sql.SqlInsert;
-import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.guava.Sequence;
@@ -46,10 +45,10 @@ import
org.apache.druid.sql.calcite.planner.PlannerCaptureHook;
import org.apache.druid.sql.calcite.planner.PrepareResult;
import org.apache.druid.sql.calcite.table.RowSignatures;
import org.apache.druid.sql.calcite.util.QueryLogHook;
+import org.hamcrest.CoreMatchers;
+import org.hamcrest.MatcherAssert;
import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.rules.ExpectedException;
-
+import org.junit.internal.matchers.ThrowableMessageMatcher;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -598,26 +597,25 @@ public class QueryTestRunner
// The builder specifies one exception, but the query can run multiple
// times. Pick the first failure as that emulates the original code flow
// where the first exception ended the test.
- ExpectedException expectedException = builder.config.expectedException();
for (QueryResults queryResults : execStep.results()) {
if (queryResults.exception == null) {
continue;
}
- // This variation uses JUnit exception validation: we configure the
expected
- // exception, then throw the exception from the run.
- // If the expected exception is not configured here, then the test may
- // have done it outside of the test builder.
+ // Delayed exception checking to let other verify steps run before
running vectorized checks
if (builder.queryCannotVectorize &&
"force".equals(queryResults.vectorizeOption)) {
- expectedException.expect(RuntimeException.class);
- expectedException.expectMessage("Cannot vectorize");
- } else if (builder.expectedExceptionInitializer != null) {
- builder.expectedExceptionInitializer.accept(expectedException);
+ MatcherAssert.assertThat(
+ queryResults.exception,
+ CoreMatchers.allOf(
+ CoreMatchers.instanceOf(RuntimeException.class),
+ ThrowableMessageMatcher.hasMessage(
+ CoreMatchers.containsString("Cannot vectorize!")
+ )
+ )
+ );
+ } else {
+ throw queryResults.exception;
}
- throw queryResults.exception;
- }
- if (builder.expectedExceptionInitializer != null) {
- throw new ISE("Expected query to throw an exception, but none was
thrown.");
}
}
}
@@ -631,9 +629,6 @@ public class QueryTestRunner
public QueryTestRunner(QueryTestBuilder builder)
{
QueryTestConfig config = builder.config;
- if (config.isRunningMSQ()) {
- Assume.assumeTrue(builder.msqCompatible);
- }
if (builder.expectedResultsVerifier == null && builder.expectedResults !=
null) {
builder.expectedResultsVerifier = config.defaultResultsVerifier(
builder.expectedResults,
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]