From 21fb00e0bcf53153292fea7394a5a2017fbb8410 Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Mon, 22 May 2023 14:47:40 +0200 Subject: [PATCH 1/6] GH-4592 Replace a Junit4 Suite with v5 DynamicTest Also replaces a static so more tests should be runnable in parallel in the future. Signed-off-by: Jerven Bolleman --- .../sail/lmdb/LmdbSPARQLComplianceTest.java | 12 +- .../memory/MemorySPARQLComplianceTest.java | 12 +- .../nativerdf/NativeSPARQLComplianceTest.java | 12 +- eclipse-settings/codetemplates.xml | 12 +- .../sparql/AbstractComplianceTest.java | 25 ++- .../RepositorySPARQLComplianceTestSuite.java | 158 ++++++++++++------ .../testsuite/sparql/tests/AggregateTest.java | 150 ++++++++--------- .../sparql/tests/ArbitraryLengthPathTest.java | 142 ++++++++-------- .../testsuite/sparql/tests/BasicTest.java | 37 ++-- .../testsuite/sparql/tests/BindTest.java | 145 +++++++--------- .../sparql/tests/BuiltinFunctionTest.java | 137 +++++++-------- .../testsuite/sparql/tests/ConstructTest.java | 63 ++++--- .../sparql/tests/DefaultGraphTest.java | 40 +++-- .../testsuite/sparql/tests/DescribeTest.java | 79 +++++---- .../testsuite/sparql/tests/ExistsTest.java | 30 ++-- .../testsuite/sparql/tests/GroupByTest.java | 21 ++- .../rdf4j/testsuite/sparql/tests/InTest.java | 44 +++-- .../testsuite/sparql/tests/MinusTest.java | 32 ++-- .../testsuite/sparql/tests/OptionalTest.java | 114 +++++-------- .../testsuite/sparql/tests/OrderByTest.java | 36 ++-- .../sparql/tests/PropertyPathTest.java | 112 ++++++------- .../testsuite/sparql/tests/SubselectTest.java | 91 ++++------ .../testsuite/sparql/tests/UnionTest.java | 87 ++++------ .../testsuite/sparql/tests/ValuesTest.java | 113 ++++++------- 24 files changed, 838 insertions(+), 866 deletions(-) diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQLComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQLComplianceTest.java index 9fd785e5dfd..0ed8cc19228 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQLComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQLComplianceTest.java @@ -15,17 +15,14 @@ import org.eclipse.rdf4j.repository.sail.config.SailRepositoryFactory; import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreFactory; import org.eclipse.rdf4j.testsuite.sparql.RepositorySPARQLComplianceTestSuite; -import org.junit.AfterClass; -import org.junit.BeforeClass; /** * Test additional SPARQL functionality on LMDB store. */ public class LmdbSPARQLComplianceTest extends RepositorySPARQLComplianceTestSuite { - @BeforeClass - public static void setUpFactory() throws Exception { - setRepositoryFactory(new SailRepositoryFactory() { + public LmdbSPARQLComplianceTest() { + super(new SailRepositoryFactory() { @Override public RepositoryImplConfig getConfig() { @@ -33,9 +30,4 @@ public RepositoryImplConfig getConfig() { } }); } - - @AfterClass - public static void tearDownFactory() throws Exception { - setRepositoryFactory(null); - } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQLComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQLComplianceTest.java index fdca61f803f..ff6be48c8e3 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQLComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQLComplianceTest.java @@ -15,26 +15,18 @@ import org.eclipse.rdf4j.repository.sail.config.SailRepositoryFactory; import org.eclipse.rdf4j.sail.memory.config.MemoryStoreFactory; import org.eclipse.rdf4j.testsuite.sparql.RepositorySPARQLComplianceTestSuite; -import org.junit.AfterClass; -import org.junit.BeforeClass; /** * @author jeen */ public class MemorySPARQLComplianceTest extends RepositorySPARQLComplianceTestSuite { - @BeforeClass - public static void setUpFactory() throws Exception { - setRepositoryFactory(new SailRepositoryFactory() { + public MemorySPARQLComplianceTest() { + super(new SailRepositoryFactory() { @Override public RepositoryImplConfig getConfig() { return new SailRepositoryConfig(new MemoryStoreFactory().getConfig()); } }); } - - @AfterClass - public static void tearDownFactory() throws Exception { - setRepositoryFactory(null); - } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQLComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQLComplianceTest.java index 79c4f5946dd..3e9c1774ab1 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQLComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQLComplianceTest.java @@ -15,17 +15,14 @@ import org.eclipse.rdf4j.repository.sail.config.SailRepositoryFactory; import org.eclipse.rdf4j.sail.nativerdf.config.NativeStoreFactory; import org.eclipse.rdf4j.testsuite.sparql.RepositorySPARQLComplianceTestSuite; -import org.junit.AfterClass; -import org.junit.BeforeClass; /** * @author jeen */ public class NativeSPARQLComplianceTest extends RepositorySPARQLComplianceTestSuite { - @BeforeClass - public static void setUpFactory() throws Exception { - setRepositoryFactory(new SailRepositoryFactory() { + public NativeSPARQLComplianceTest() { + super(new SailRepositoryFactory() { @Override public RepositoryImplConfig getConfig() { @@ -33,9 +30,4 @@ public RepositoryImplConfig getConfig() { } }); } - - @AfterClass - public static void tearDownFactory() throws Exception { - setRepositoryFactory(null); - } } diff --git a/eclipse-settings/codetemplates.xml b/eclipse-settings/codetemplates.xml index 59f3253021d..5213e139f6c 100644 --- a/eclipse-settings/codetemplates.xml +++ b/eclipse-settings/codetemplates.xml @@ -1,14 +1,4 @@ - + diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java index 08d3e9f3b0c..7f9fa95172e 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java @@ -46,8 +46,8 @@ import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.function.Executable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,20 +58,31 @@ */ public abstract class AbstractComplianceTest { + protected DynamicTest makeTest(String name, Executable x) { + return DynamicTest.dynamicTest(name, () -> { + setUp(); + x.execute(); + tearDown(); + }); + } + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - protected Repository repo; + protected final Repository repo; protected RepositoryConnection conn; - @Before - public void setUp() throws Exception { - repo = RepositorySPARQLComplianceTestSuite.getEmptyInitializedRepository(this.getClass()); + public AbstractComplianceTest(Repository repo) { + this.repo = repo; + } + + public void setUp() { + repo.init(); conn = new RepositoryConnectionWrapper(repo.getConnection()); } - @After public void tearDown() { try { + conn.clear(); conn.close(); } finally { repo.shutDown(); diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java index bc3ea5f971c..50539b84b9c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java @@ -12,11 +12,10 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Files; +import java.util.stream.Stream; import org.eclipse.rdf4j.common.annotation.Experimental; import org.eclipse.rdf4j.common.exception.RDF4JException; -import org.eclipse.rdf4j.common.io.FileUtil; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.config.RepositoryFactory; @@ -38,77 +37,134 @@ import org.eclipse.rdf4j.testsuite.sparql.tests.SubselectTest; import org.eclipse.rdf4j.testsuite.sparql.tests.UnionTest; import org.eclipse.rdf4j.testsuite.sparql.tests.ValuesTest; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; +import org.junit.jupiter.api.io.TempDir; /** * A suite of custom compliance tests on SPARQL query functionality for RDF4J Repositories. *

* To use this test suite, extend the abstract suite class, making sure that the correct {@link RepositoryFactory} gets - * set on initialization, and torn down after. For example, to run the suite against an RDF4J Memory Store: - * - *

- * 
- * 	@BeforeClass
-	public static void setUpFactory() throws Exception {
-		setRepositoryFactory(new SailRepositoryFactory() {
-			@Override
-			public RepositoryImplConfig getConfig() {
-				return new SailRepositoryConfig(new MemoryStoreFactory().getConfig());
-			}
-		});
-	}
-
-	@AfterClass
-	public static void tearDownFactory() throws Exception {
-		setRepositoryFactory(null);
-	}
- * 
- * 
+ * set on construction, * * @author Jeen Broekstra - * @implNote currently implemented as an abstract JUnit-4 suite. This suite is marked Experimental as we may want to - * make further improvements to its setup (including migrating to JUnit 5 when its suite support matures) in - * future minor releases. */ -@RunWith(Suite.class) -@SuiteClasses({ AggregateTest.class, ArbitraryLengthPathTest.class, BasicTest.class, BindTest.class, - BuiltinFunctionTest.class, ConstructTest.class, DefaultGraphTest.class, DescribeTest.class, GroupByTest.class, - InTest.class, OptionalTest.class, PropertyPathTest.class, SubselectTest.class, UnionTest.class, - ValuesTest.class, OrderByTest.class, ExistsTest.class, MinusTest.class }) @Experimental public abstract class RepositorySPARQLComplianceTestSuite { - @BeforeClass + + @TestFactory + Stream aggregate() throws RDF4JException, IOException { + return new AggregateTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream arbitraryLengthPath() throws RDF4JException, IOException { + return new ArbitraryLengthPathTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream basic() throws RDF4JException, IOException { + return new BasicTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream bind() throws RDF4JException, IOException { + return new BindTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream builtinFunction() throws RDF4JException, IOException { + return new BuiltinFunctionTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream construct() throws RDF4JException, IOException { + return new ConstructTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream defaultGraph() throws RDF4JException, IOException { + return new DefaultGraphTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream describe() throws RDF4JException, IOException { + return new DescribeTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream groupBy() throws RDF4JException, IOException { + return new GroupByTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream in() throws RDF4JException, IOException { + return new InTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream optional() throws RDF4JException, IOException { + return new OptionalTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream propertyPath() throws RDF4JException, IOException { + return new PropertyPathTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream subselect() throws RDF4JException, IOException { + return new SubselectTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream union() throws RDF4JException, IOException { + return new UnionTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream values() throws RDF4JException, IOException { + return new ValuesTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream orderBy() throws RDF4JException, IOException { + return new OrderByTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream exists() throws RDF4JException, IOException { + return new ExistsTest(getEmptyInitializedRepository()).tests(); + } + + @TestFactory + Stream minus() throws RDF4JException, IOException { + return new MinusTest(getEmptyInitializedRepository()).tests(); + } + + @BeforeAll public static void setUpClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "true"); } - @AfterClass + @AfterAll public static void tearDownClass() { System.setProperty("org.eclipse.rdf4j.repository.debug", "false"); } - private static RepositoryFactory factory; + @TempDir + private File dataDir; - private static File dataDir; + protected final RepositoryFactory factory; - public static void setRepositoryFactory(RepositoryFactory factory) throws IOException { - if (dataDir != null && dataDir.isDirectory()) { - FileUtil.deleteDir(dataDir); - dataDir = null; - } - RepositorySPARQLComplianceTestSuite.factory = factory; + public RepositorySPARQLComplianceTestSuite(RepositoryFactory factory) { + super(); + this.factory = factory; } - public static Repository getEmptyInitializedRepository(Class caller) throws RDF4JException, IOException { - if (dataDir != null && dataDir.isDirectory()) { - FileUtil.deleteDir(dataDir); - dataDir = null; - } - dataDir = Files.createTempDirectory(caller.getSimpleName()).toFile(); + public Repository getEmptyInitializedRepository() throws RDF4JException, IOException { Repository repository = factory.getRepository(factory.getConfig()); repository.setDataDir(dataDir); try (RepositoryConnection con = repository.getConnection()) { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java index 0a25c45a38b..814e6fe91f0 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java @@ -21,6 +21,7 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; @@ -34,8 +35,9 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL aggregate function compliance. @@ -44,15 +46,44 @@ */ public class AggregateTest extends AbstractComplianceTest { + public AggregateTest(Repository repo) { + super(repo); + } + + public Stream tests() { + return Stream.of( + makeTest("MaxAggregateWithGroupEmptyResult", this::testMaxAggregateWithGroupEmptyResult), + makeTest("MaxAggregateWithoutGroupEmptySolution", this::testMaxAggregateWithoutGroupEmptySolution), + makeTest("MinAggregateWithGroupEmptyResult", this::testMinAggregateWithGroupEmptyResult), + makeTest("MinAggregateWithoutGroupEmptySolution", this::testMinAggregateWithoutGroupEmptySolution), + makeTest("SampleAggregateWithGroupEmptyResult", this::testSampleAggregateWithGroupEmptyResult), + makeTest("SampleAggregateWithoutGroupEmptySolution", + this::testSampleAggregateWithoutGroupEmptySolution), + makeTest("SES2361UndefMin", this::testSES2361UndefMin), + makeTest("CountOrderBy_ImplicitGroup", this::testCountOrderBy_ImplicitGroup), + makeTest("DistinctMax", this::testDistinctMax), + makeTest("Max", this::testMax), + makeTest("DistinctAvg", this::testDistinctAvg), + makeTest("Avg", this::testAvg), + makeTest("DistinctSum", this::testDistinctSum), + makeTest("Sum", this::testSum), + makeTest("CountHaving", this::testCountHaving), + makeTest("SES1970CountDistinctWildcard", this::testSES1970CountDistinctWildcard), + makeTest("GroupConcatNonDistinct", this::testGroupConcatNonDistinct), + makeTest("GroupConcatDistinct", this::testGroupConcatDistinct), + makeTest("SES1979MinMaxInf", this::testSES1979MinMaxInf), + makeTest("SES2361UndefSum", this::testSES2361UndefSum), + makeTest("SES2361UndefCountWildcard", this::testSES2361UndefCountWildcard), + makeTest("SES2361UndefCount", this::testSES2361UndefCount), + makeTest("SES2361UndefMax", this::testSES2361UndefMax) + ); + } + /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMaxAggregateWithGroupEmptyResult() { - String query = "select ?s (max(?o) as ?omax) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; + private void testMaxAggregateWithGroupEmptyResult() { + String query = "select ?s (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.hasNext()).isFalse(); @@ -62,11 +93,8 @@ public void testMaxAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMaxAggregateWithoutGroupEmptySolution() { - String query = "select (max(?o) as ?omax) {\n" + - " ?s ?p ?o .\n" + - " }\n"; + private void testMaxAggregateWithoutGroupEmptySolution() { + String query = "select (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.next()).isEmpty(); @@ -76,12 +104,9 @@ public void testMaxAggregateWithoutGroupEmptySolution() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMinAggregateWithGroupEmptyResult() { - String query = "select ?s (min(?o) as ?omin) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; + + private void testMinAggregateWithGroupEmptyResult() { + String query = "select ?s (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.hasNext()).isFalse(); @@ -91,11 +116,8 @@ public void testMinAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMinAggregateWithoutGroupEmptySolution() { - String query = "select (min(?o) as ?omin) {\n" + - " ?s ?p ?o .\n" + - " }\n"; + private void testMinAggregateWithoutGroupEmptySolution() { + String query = "select (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.next()).isEmpty(); @@ -105,12 +127,8 @@ public void testMinAggregateWithoutGroupEmptySolution() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testSampleAggregateWithGroupEmptyResult() { - String query = "select ?s (sample(?o) as ?osample) {\n" + - " ?s ?p ?o .\n" + - " }\n" + - " group by ?s\n"; + private void testSampleAggregateWithGroupEmptyResult() { + String query = "select ?s (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.hasNext()).isFalse(); @@ -120,19 +138,15 @@ public void testSampleAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testSampleAggregateWithoutGroupEmptySolution() { - String query = "select (sample(?o) as ?osample) {\n" + - " ?s ?p ?o .\n" + - " }\n"; + private void testSampleAggregateWithoutGroupEmptySolution() { + String query = "select (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n"; try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { assertThat(result.next()).isEmpty(); } } - @Test - public void testSES2361UndefMin() { + private void testSES2361UndefMin() { String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertThat((Iterable) result).isNotNull(); @@ -142,8 +156,7 @@ public void testSES2361UndefMin() { } } - @Test - public void testSES2361UndefMax() { + private void testSES2361UndefMax() { String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertThat((Iterable) result).isNotNull(); @@ -153,8 +166,7 @@ public void testSES2361UndefMax() { } } - @Test - public void testSES2361UndefCount() { + private void testSES2361UndefCount() { String query = "SELECT (COUNT(?v) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertThat((Iterable) result).isNotNull(); @@ -164,8 +176,7 @@ public void testSES2361UndefCount() { } } - @Test - public void testSES2361UndefCountWildcard() { + private void testSES2361UndefCountWildcard() { String query = "SELECT (COUNT(*) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertThat((Iterable) result).isNotNull(); @@ -175,8 +186,7 @@ public void testSES2361UndefCountWildcard() { } } - @Test - public void testSES2361UndefSum() { + private void testSES2361UndefSum() { String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertThat((Iterable) result).isNotNull(); @@ -186,8 +196,7 @@ public void testSES2361UndefSum() { } } - @Test - public void testSES1979MinMaxInf() throws Exception { + private void testSES1979MinMaxInf() throws Exception { loadTestData("/testdata-query/dataset-ses1979.trig"); String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; @@ -205,13 +214,11 @@ public void testSES1979MinMaxInf() throws Exception { } - @Test - public void testGroupConcatDistinct() throws Exception { + private void testGroupConcatDistinct() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + - "WHERE { ex:groupconcat-test ?p ?l . }"; + String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -244,12 +251,10 @@ public void testGroupConcatDistinct() throws Exception { } - @Test - public void testGroupConcatNonDistinct() throws Exception { + private void testGroupConcatNonDistinct() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - "SELECT (GROUP_CONCAT(?l) AS ?concat)" + - "WHERE { ex:groupconcat-test ?p ?l . }"; + String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -282,8 +287,7 @@ public void testGroupConcatNonDistinct() throws Exception { } - @Test - public void testSES1970CountDistinctWildcard() throws Exception { + private void testSES1970CountDistinctWildcard() throws Exception { loadTestData("/testdata-query/dataset-ses1970.trig"); String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; @@ -302,8 +306,7 @@ public void testSES1970CountDistinctWildcard() throws Exception { } } - @Test - public void testCountHaving() { + private void testCountHaving() { BNode bnode1 = bnode(); BNode bnode2 = bnode(); BNode bnode3 = bnode(); @@ -323,8 +326,7 @@ public void testCountHaving() { } } - @Test - public void testSum() { + private void testSum() { mixedDataForNumericAggregates(); String query = "SELECT ?a (SUM(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -342,8 +344,7 @@ public void testSum() { } - @Test - public void testDistinctSum() { + private void testDistinctSum() { mixedDataForNumericAggregates(); String query = "SELECT ?a (SUM(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -360,8 +361,7 @@ public void testDistinctSum() { } - @Test - public void testAvg() { + private void testAvg() { mixedDataForNumericAggregates(); String query = "SELECT ?a (AVG(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -377,8 +377,7 @@ public void testAvg() { } } - @Test - public void testDistinctAvg() { + private void testDistinctAvg() { mixedDataForNumericAggregates(); String query = "SELECT ?a (AVG(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -395,8 +394,7 @@ public void testDistinctAvg() { } } - @Test - public void testMax() { + private void testMax() { mixedDataForNumericAggregates(); String query = "SELECT ?a (MAX(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -414,8 +412,7 @@ public void testMax() { } - @Test - public void testDistinctMax() { + private void testDistinctMax() { mixedDataForNumericAggregates(); String query = "SELECT ?a (MAX(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; @@ -435,14 +432,10 @@ public void testDistinctMax() { /** * @see https://github.com/eclipse/rdf4j/issues/4290 */ - @Test - public void testCountOrderBy_ImplicitGroup() { + private void testCountOrderBy_ImplicitGroup() { mixedDataForNumericAggregates(); - String query = "select (count(*) as ?c) where { \n" - + " ?s ?p ?o .\n" - + "} \n" - + "order by (?s)"; + String query = "select (count(*) as ?c) where { \n" + " ?s ?p ?o .\n" + "} \n" + "order by (?s)"; TupleQuery preparedQuery = conn.prepareTupleQuery(query); @@ -498,4 +491,5 @@ private int countCharOccurrences(String string, char ch) { } return count; } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java index 2bd728762f7..66fbe513183 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java @@ -10,10 +10,12 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.stream.Stream; import org.eclipse.rdf4j.model.vocabulary.OWL; import org.eclipse.rdf4j.query.BindingSet; @@ -22,9 +24,11 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.impl.SimpleDataset; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL property paths involving * or + operators (arbitrary length paths). @@ -35,16 +39,34 @@ */ public class ArbitraryLengthPathTest extends AbstractComplianceTest { + public ArbitraryLengthPathTest(Repository repo) { + super(repo); + } + + public Stream tests() { + return Stream.of(makeTest("PropertyPathInTree", this::testPropertyPathInTree), + makeTest("ArbitraryLengthPathWithBinding1", this::testArbitraryLengthPathWithBinding1), + makeTest("ArbitraryLengthPathWithFilter3", this::testArbitraryLengthPathWithFilter3), + makeTest("ArbitraryLengthPathWithFilter2", this::testArbitraryLengthPathWithFilter2), + makeTest("ArbitraryLengthPathWithFilter1", this::testArbitraryLengthPathWithFilter1), + makeTest("ArbitraryLengthPathWithBinding8", this::testArbitraryLengthPathWithBinding8), + makeTest("ArbitraryLengthPathWithBinding2", this::testArbitraryLengthPathWithBinding2), + makeTest("ArbitraryLengthPathWithBinding3", this::testArbitraryLengthPathWithBinding3), + makeTest("ArbitraryLengthPathWithBinding4", this::testArbitraryLengthPathWithBinding4), + makeTest("ArbitraryLengthPathWithBinding5", this::testArbitraryLengthPathWithBinding5), + makeTest("ArbitraryLengthPathWithBinding6", this::testArbitraryLengthPathWithBinding6), + makeTest("ArbitraryLengthPathWithBinding7", this::testArbitraryLengthPathWithBinding7)); + } + /** * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding1() throws Exception { + + private void testArbitraryLengthPathWithBinding1() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -87,14 +109,13 @@ public void testArbitraryLengthPathWithBinding1() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding2() throws Exception { + + private void testArbitraryLengthPathWithBinding2() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); // query without initializing ?child first. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -137,14 +158,13 @@ public void testArbitraryLengthPathWithBinding2() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding3() throws Exception { + + private void testArbitraryLengthPathWithBinding3() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -187,14 +207,13 @@ public void testArbitraryLengthPathWithBinding3() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding4() throws Exception { + + private void testArbitraryLengthPathWithBinding4() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -237,14 +256,13 @@ public void testArbitraryLengthPathWithBinding4() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding5() throws Exception { + + private void testArbitraryLengthPathWithBinding5() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -293,14 +311,13 @@ public void testArbitraryLengthPathWithBinding5() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding6() throws Exception { + + private void testArbitraryLengthPathWithBinding6() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -349,14 +366,13 @@ public void testArbitraryLengthPathWithBinding6() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding7() throws Exception { + + private void testArbitraryLengthPathWithBinding7() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); SimpleDataset dt = new SimpleDataset(); @@ -408,14 +424,13 @@ public void testArbitraryLengthPathWithBinding7() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding8() throws Exception { + + private void testArbitraryLengthPathWithBinding8() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); // binding on child instead of parent. - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); SimpleDataset dt = new SimpleDataset(); @@ -466,12 +481,11 @@ public void testArbitraryLengthPathWithBinding8() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter1() throws Exception { + + private void testArbitraryLengthPathWithFilter1() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -497,12 +511,11 @@ public void testArbitraryLengthPathWithFilter1() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter2() throws Exception { + + private void testArbitraryLengthPathWithFilter2() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -528,12 +541,11 @@ public void testArbitraryLengthPathWithFilter2() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter3() throws Exception { + + private void testArbitraryLengthPathWithFilter3() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + - "SELECT ?parent ?child " + - "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -555,14 +567,11 @@ public void testArbitraryLengthPathWithFilter3() throws Exception { } - @Test - public void testPropertyPathInTree() throws Exception { + private void testPropertyPathInTree() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - " SELECT ?node ?name " + - " FROM ex:tree-graph " + - " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; + String query = getNamespaceDeclarations() + " SELECT ?node ?name " + " FROM ex:tree-graph " + + " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -581,4 +590,5 @@ public void testPropertyPathInTree() throws Exception { } } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java index d588360a5ac..4fc374278a0 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java @@ -10,8 +10,8 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.util.List; import java.util.stream.Collectors; @@ -24,9 +24,11 @@ import org.eclipse.rdf4j.query.AbstractTupleQueryResultHandler; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Basic SPARQL functionality tests @@ -36,21 +38,28 @@ */ public class BasicTest extends AbstractComplianceTest { - @Test - public void testIdenticalVariablesInStatementPattern() { + public BasicTest(Repository repo) { + super(repo); + } + + private void testIdenticalVariablesInStatementPattern() { conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); - String queryBuilder = "SELECT ?publisher " + - "{ ?publisher ?publisher }"; + String queryBuilder = "SELECT ?publisher " + + "{ ?publisher ?publisher }"; - conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) - .evaluate(new AbstractTupleQueryResultHandler() { + conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder).evaluate(new AbstractTupleQueryResultHandler() { + + @Override + public void handleSolution(BindingSet bindingSet) { + fail("nobody is self published"); + } + }); + } - @Override - public void handleSolution(BindingSet bindingSet) { - fail("nobody is self published"); - } - }); + public Stream tests() { + return Stream.of( + makeTest("testIdenticalVariablesInStatementPattern", this::testIdenticalVariablesInStatementPattern)); } @Test diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java index 2fe31de648a..fcbfe95fb32 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java @@ -12,11 +12,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.rdf4j.model.util.Values.literal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import java.util.List; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -31,8 +32,9 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Test on SPARQL BIND function. @@ -42,35 +44,33 @@ */ public class BindTest extends AbstractComplianceTest { + public BindTest(Repository repo) { + super(repo); + } + /** * See https://github.com/eclipse/rdf4j/issues/1018 */ - @Test - public void testBindError() { + + private void testBindError() { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - String qb = "SELECT * \n" + - "WHERE { \n" + - " VALUES (?NAValue) { () } \n " + - " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " + - " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + - "}\n"; + String qb = "SELECT * \n" + "WHERE { \n" + " VALUES (?NAValue) { () } \n " + + " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " + + " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + "}\n"; List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); - assertEquals("query should return 2 solutions", 2, result.size()); + assertEquals(2, result.size(), "query should return 2 solutions"); } /** * See https://github.com/eclipse/rdf4j/issues/1405 */ - @Test - public void testBindScope() { - String query = "SELECT * {\n" + - " { BIND (\"a\" AS ?a) }\n" + - " { BIND (?a AS ?b) } \n" + - "}"; + + private void testBindScope() { + String query = "SELECT * {\n" + " { BIND (\"a\" AS ?a) }\n" + " { BIND (?a AS ?b) } \n" + "}"; TupleQuery q = conn.prepareTupleQuery(query); List result = QueryResults.asList(q.evaluate()); @@ -84,20 +84,13 @@ public void testBindScope() { /** * See https://github.com/eclipse/rdf4j/issues/1642 */ - @Test - public void testBindScopeUnion() { + + private void testBindScopeUnion() { ValueFactory f = conn.getValueFactory(); - String query = "prefix ex: \n" + - "select * {\n" + - " bind(ex:v1 as ?v)\n" + - " bind(strafter(str(?v),str(ex:)) as ?b)\n" + - " {\n" + - " bind(?b as ?b1)\n" + - " } union {\n" + - " bind(?b as ?b2)\n" + - " }\n" + - "}"; + String query = "prefix ex: \n" + "select * {\n" + " bind(ex:v1 as ?v)\n" + + " bind(strafter(str(?v),str(ex:)) as ?b)\n" + " {\n" + " bind(?b as ?b1)\n" + " } union {\n" + + " bind(?b as ?b2)\n" + " }\n" + "}"; TupleQuery q = conn.prepareTupleQuery(query); List result = QueryResults.asList(q.evaluate()); @@ -114,48 +107,34 @@ public void testBindScopeUnion() { } - @Test - public void testSES2250BindErrors() { + private void testSES2250BindErrors() { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - String qb = "SELECT * {\n" + - " ?s1 ?p1 ?blank . " + - " FILTER(isBlank(?blank))" + - " BIND (iri(?blank) as ?biri)" + - " ?biri ?p2 ?o2 ." + - "}"; + String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + " ?biri ?p2 ?o2 ." + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse("The query should not return a result", evaluate.hasNext()); + assertFalse(evaluate.hasNext(), "The query should not return a result"); } } - @Test - public void testSES2250BindErrorsInPath() { + private void testSES2250BindErrorsInPath() { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - String qb = "SELECT * {\n" + - " ?s1 ?p1 ?blank . " + - " FILTER(isBlank(?blank))" + - " BIND (iri(?blank) as ?biri)" + - " ?biri * ?o2 ." + - "}"; + String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + " ?biri * ?o2 ." + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse("The query should not return a result", evaluate.hasNext()); + assertFalse(evaluate.hasNext(), "The query should not return a result"); } } - @Test - public void testSelectBindOnly() { - String query = "select ?b1 ?b2 ?b3\n" - + "where {\n" - + " bind(1 as ?b1)\n" - + "}"; + private void testSelectBindOnly() { + String query = "select ?b1 ?b2 ?b3\n" + "where {\n" + " bind(1 as ?b1)\n" + "}"; List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); @@ -167,8 +146,7 @@ public void testSelectBindOnly() { assertThat(solution.getValue("b3")).isNull(); } - @Test - public void testGH3696Bind() { + private void testGH3696Bind() { Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:unit1") .add(RDF.TYPE, "ex:Unit") @@ -180,22 +158,16 @@ public void testGH3696Bind() { .build(); conn.add(testData); - String query = "PREFIX ex: \n" + - "SELECT * {\n" + - " ?bind rdfs:label ?b1 ;\n" + - " a ex:Unit .\n" + - " FILTER (?b1 = 'Unit2') .\n" + - " BIND(?bind AS ?n0)\n" + - " ?n0 ex:has ?n1 \n" + - " }"; + String query = "PREFIX ex: \n" + "SELECT * {\n" + " ?bind rdfs:label ?b1 ;\n" + + " a ex:Unit .\n" + " FILTER (?b1 = 'Unit2') .\n" + " BIND(?bind AS ?n0)\n" + + " ?n0 ex:has ?n1 \n" + " }"; List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); assertThat(result).isEmpty(); } - @Test - public void testGH4499BindFilterNotExist1() { + private void testGH4499BindFilterNotExist1() { Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:a") .add("ex:p", "ex:c1") @@ -209,15 +181,10 @@ public void testGH4499BindFilterNotExist1() { .build(); conn.add(testData); - String query = "PREFIX ex: \n" - + "SELECT *\n" - + " WHERE {\n" - + " BIND ( ex:a AS ?a )\n" - + " BIND ( ex:b AS ?b )\n" - + " ?a ex:p* ?c .\n" - + " FILTER EXISTS { ?c rdf:type ex:T }\n" - + " FILTER NOT EXISTS { ?c ex:q ?d}\n" - + "}"; + String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" + + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" + + " ?a ex:p* ?c .\n" + " FILTER EXISTS { ?c rdf:type ex:T }\n" + + " FILTER NOT EXISTS { ?c ex:q ?d}\n" + "}"; List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); @@ -230,8 +197,7 @@ public void testGH4499BindFilterNotExist1() { assertThat(bs.getValue("d")).isNull(); } - @Test - public void testGH4499BindFilterNotExist2() { + private void testGH4499BindFilterNotExist2() { Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:a") .add("ex:p", "ex:c1") @@ -245,15 +211,10 @@ public void testGH4499BindFilterNotExist2() { .build(); conn.add(testData); - String query = "PREFIX ex: \n" - + "SELECT *\n" - + " WHERE {\n" - + " FILTER EXISTS { ?c rdf:type ex:T }\n" - + " FILTER NOT EXISTS { ?c ex:q ?d }\n" - + " BIND ( ex:a AS ?a )\n" - + " BIND ( ex:b AS ?b )\n" - + " ?a ex:p* ?c .\n" - + "}"; + String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" + + " FILTER EXISTS { ?c rdf:type ex:T }\n" + " FILTER NOT EXISTS { ?c ex:q ?d }\n" + + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" + + " ?a ex:p* ?c .\n" + "}"; List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); @@ -266,4 +227,14 @@ public void testGH4499BindFilterNotExist2() { assertThat(bs.getValue("d")).isNull(); } + + public Stream tests() { + return Stream.of(makeTest("GH4499BindFilterNotExist2", this::testGH4499BindFilterNotExist2), + makeTest("GH4499BindFilterNotExist1", this::testGH4499BindFilterNotExist1), + makeTest("GH3696Bind", this::testGH3696Bind), makeTest("SelectBindOnly", this::testSelectBindOnly), + makeTest("SES2250BindErrorsInPath", this::testSES2250BindErrorsInPath), + makeTest("SES2250BindErrors", this::testSES2250BindErrors), + makeTest("BindScopeUnion", this::testBindScopeUnion), makeTest("BindScope", this::testBindScope), + makeTest("BindError", this::testBindError)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java index 1619f473da8..6b71c64aaa7 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java @@ -11,13 +11,13 @@ package org.eclipse.rdf4j.testsuite.sparql.tests; import static org.eclipse.rdf4j.model.util.Values.iri; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.stream.Stream; @@ -30,8 +30,9 @@ import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on various SPARQL built-in functions. @@ -41,11 +42,15 @@ */ public class BuiltinFunctionTest extends AbstractComplianceTest { + public BuiltinFunctionTest(Repository repo) { + super(repo); + } + /** * See https://github.com/eclipse/rdf4j/issues/1267 */ - @Test - public void testSeconds() { + + private void testSeconds() { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13\"^^xsd:dateTime) AS ?sec) { }"; @@ -60,8 +65,8 @@ public void testSeconds() { /** * See https://github.com/eclipse/rdf4j/issues/1267 */ - @Test - public void testSecondsMilliseconds() { + + private void testSecondsMilliseconds() { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13.815-05:00\"^^xsd:dateTime) AS ?sec) { }"; @@ -73,8 +78,7 @@ public void testSecondsMilliseconds() { } } - @Test - public void testSES1991NOWEvaluation() throws Exception { + private void testSES1991NOWEvaluation() throws Exception { loadTestData("/testdata-query/defaultgraph.ttl"); String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; @@ -95,8 +99,7 @@ public void testSES1991NOWEvaluation() throws Exception { } } - @Test - public void testSES869ValueOfNow() { + private void testSES869ValueOfNow() { TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); @@ -115,8 +118,7 @@ public void testSES869ValueOfNow() { } } - @Test - public void testSES1991UUIDEvaluation() throws Exception { + private void testSES1991UUIDEvaluation() throws Exception { loadTestData("/testdata-query/defaultgraph.ttl"); String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; @@ -137,8 +139,7 @@ public void testSES1991UUIDEvaluation() throws Exception { } } - @Test - public void testSES1991STRUUIDEvaluation() throws Exception { + private void testSES1991STRUUIDEvaluation() throws Exception { loadTestData("/testdata-query/defaultgraph.ttl"); String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; @@ -158,8 +159,7 @@ public void testSES1991STRUUIDEvaluation() throws Exception { } } - @Test - public void testSES1991RANDEvaluation() throws Exception { + private void testSES1991RANDEvaluation() throws Exception { loadTestData("/testdata-query/defaultgraph.ttl"); String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; @@ -186,8 +186,7 @@ public void testSES1991RANDEvaluation() throws Exception { } } - @Test - public void testSES2121URIFunction() { + private void testSES2121URIFunction() { String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { @@ -195,7 +194,7 @@ public void testSES2121URIFunction() { assertTrue(result.hasNext()); BindingSet bs = result.next(); IRI uri = (IRI) bs.getValue("uri"); - assertNull("uri result for invalid URI should be unbound", uri); + assertNull(uri, "uri result for invalid URI should be unbound"); } query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; @@ -205,12 +204,11 @@ public void testSES2121URIFunction() { assertTrue(result.hasNext()); BindingSet bs = result.next(); IRI uri = (IRI) bs.getValue("uri"); - assertNotNull("uri result for valid URI reference should be bound", uri); + assertNotNull(uri, "uri result for valid URI reference should be bound"); } } - @Test - public void test27NormalizeIRIFunction() { + private void test27NormalizeIRIFunction() { String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); try (TupleQueryResult result = tq.evaluate()) { @@ -219,18 +217,15 @@ public void test27NormalizeIRIFunction() { BindingSet bs = result.next(); IRI actual = (IRI) bs.getValue("Iri"); IRI expected = iri("http://example.com/bar"); - assertEquals("IRI result for relative IRI should be normalized", expected, actual); + assertEquals(expected, actual, "IRI result for relative IRI should be normalized"); } } - @Test - public void testSES2052If1() throws Exception { + private void testSES2052If1() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + - "WHERE { \n" + - " ?s ?p ?o . \n" + - " FILTER(IF(BOUND(?p), ?p = , false)) \n" + - "}"; + String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" + + " FILTER(IF(BOUND(?p), ?p = , false)) \n" + + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { @@ -249,14 +244,11 @@ public void testSES2052If1() throws Exception { } - @Test - public void testSES2052If2() throws Exception { + private void testSES2052If2() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + - "WHERE { \n" + - " ?s ?p ?o . \n" + - " FILTER(IF(!BOUND(?p), false , ?p = )) \n" + - "}"; + String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" + + " FILTER(IF(!BOUND(?p), false , ?p = )) \n" + + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (TupleQueryResult result = tq.evaluate()) { @@ -275,32 +267,25 @@ public void testSES2052If2() throws Exception { } - @Test - public void testRegexCaseNonAscii() { + private void testRegexCaseNonAscii() { String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; - assertTrue("case-insensitive match on Cyrillic should succeed", conn.prepareBooleanQuery(query).evaluate()); + assertTrue(conn.prepareBooleanQuery(query).evaluate(), "case-insensitive match on Cyrillic should succeed"); query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; - assertFalse("case-sensitive match on Cyrillic should fail", conn.prepareBooleanQuery(query).evaluate()); + assertFalse(conn.prepareBooleanQuery(query).evaluate(), "case-sensitive match on Cyrillic should fail"); } - @Test - public void testFilterRegexBoolean() throws Exception { + private void testFilterRegexBoolean() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); // test case for issue SES-1050 - String query = getNamespaceDeclarations() + - " SELECT *" + - " WHERE { " + - " ?x foaf:name ?name ; " + - " foaf:mbox ?mbox . " + - " FILTER(EXISTS { " + - " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + + String query = getNamespaceDeclarations() + " SELECT *" + " WHERE { " + " ?x foaf:name ?name ; " + + " foaf:mbox ?mbox . " + " FILTER(EXISTS { " + + " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); - " } )" + - " } "; + " } )" + " } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -310,8 +295,7 @@ public void testFilterRegexBoolean() throws Exception { } } - @Test - public void testDateCastFunction_date() { + private void testDateCastFunction_date() { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; @@ -323,8 +307,7 @@ public void testDateCastFunction_date() { } } - @Test - public void testDateCastFunction_date_withTimeZone_utc() { + private void testDateCastFunction_date_withTimeZone_utc() { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; @@ -336,8 +319,7 @@ public void testDateCastFunction_date_withTimeZone_utc() { } } - @Test - public void testDateCastFunction_dateTime_withTimeZone_offset() { + private void testDateCastFunction_dateTime_withTimeZone_offset() { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; @@ -349,17 +331,36 @@ public void testDateCastFunction_dateTime_withTimeZone_offset() { } } - @Test - public void testDateCastFunction_invalidInput() { + private void testDateCastFunction_invalidInput() { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-xx\") AS ?date) { }"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { assertNotNull(result); assertTrue(result.hasNext()); - assertFalse("There should be no binding because the cast should have failed.", - result.next().hasBinding("date")); + assertFalse(result.next().hasBinding("date"), + "There should be no binding because the cast should have failed."); assertFalse(result.hasNext()); } } + + public Stream tests() { + return Stream.of(makeTest("Seconds", this::testSeconds), + makeTest("SecondsMilliseconds", this::testSecondsMilliseconds), + makeTest("DateCastFunction_invalidInput", this::testDateCastFunction_invalidInput), + makeTest("DateCastFunction_dateTime_withTimeZone_offset", + this::testDateCastFunction_dateTime_withTimeZone_offset), + makeTest("DateCastFunction_date_withTimeZone_utc", this::testDateCastFunction_date_withTimeZone_utc), + makeTest("DateCastFunction_date", this::testDateCastFunction_date), + makeTest("FilterRegexBoolean", this::testFilterRegexBoolean), + makeTest("RegexCaseNonAscii", this::testRegexCaseNonAscii), + makeTest("SES2052If2", this::testSES2052If2), makeTest("SES2052If1", this::testSES2052If1), + makeTest("27NormalizeIRIFunction", this::test27NormalizeIRIFunction), + makeTest("SES2121URIFunction", this::testSES2121URIFunction), + makeTest("SES1991RANDEvaluation", this::testSES1991RANDEvaluation), + makeTest("SES1991STRUUIDEvaluation", this::testSES1991STRUUIDEvaluation), + makeTest("SES1991UUIDEvaluation", this::testSES1991UUIDEvaluation), + makeTest("SES869ValueOfNow", this::testSES869ValueOfNow), + makeTest("SES1991NOWEvaluation", this::testSES1991NOWEvaluation)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java index a1a12f32d3b..20b1282e6de 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java @@ -14,12 +14,13 @@ import static org.eclipse.rdf4j.model.util.Statements.statement; import static org.eclipse.rdf4j.model.util.Values.iri; import static org.eclipse.rdf4j.model.util.Values.literal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.StringReader; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; @@ -30,9 +31,10 @@ import org.eclipse.rdf4j.query.GraphQueryResult; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResults; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL CONSTRUCT queries. @@ -42,22 +44,16 @@ */ public class ConstructTest extends AbstractComplianceTest { - @Test - public void testConstructModifiers() throws Exception { + public ConstructTest(Repository repo) { + super(repo); + } + + private void testConstructModifiers() throws Exception { loadTestData("/testdata-query/dataset-construct-modifiers.ttl"); - String qry = "PREFIX foaf: \n" - + "PREFIX site: \n" - + "CONSTRUCT { \n" - + " ?iri foaf:name ?name . \n" - + " ?iri foaf:nick ?nick . \n" - + "} \n" - + "WHERE { \n" - + " ?iri foaf:name ?name ; \n" - + " site:hits ?hits ; \n" - + " foaf:nick ?nick . \n" - + "} \n" - + "ORDER BY desc(?hits) \n" - + "LIMIT 3"; + String qry = "PREFIX foaf: \n" + "PREFIX site: \n" + + "CONSTRUCT { \n" + " ?iri foaf:name ?name . \n" + " ?iri foaf:nick ?nick . \n" + "} \n" + + "WHERE { \n" + " ?iri foaf:name ?name ; \n" + " site:hits ?hits ; \n" + " foaf:nick ?nick . \n" + + "} \n" + "ORDER BY desc(?hits) \n" + "LIMIT 3"; Statement[] correctResult = { statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), @@ -66,8 +62,7 @@ public void testConstructModifiers() throws Exception { statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), - }; + statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), }; GraphQuery gq = conn.prepareGraphQuery(qry); try (GraphQueryResult result = gq.evaluate()) { assertNotNull(result); @@ -86,20 +81,13 @@ public void testConstructModifiers() throws Exception { /** * See https://github.com/eclipse/rdf4j/issues/3011 */ - @Test - public void testConstruct_CyclicPathWithJoin() { + + private void testConstruct_CyclicPathWithJoin() { IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); conn.add(test, RDF.TYPE, DCAT.CATALOG); - String query = "PREFIX dcat: \n" - + "\n" - + "CONSTRUCT {\n" - + " ?x .\n" - + " ?x ?x .\n" - + "}\n" - + "WHERE {\n" - + " ?x a dcat:Catalog .\n" - + "}"; + String query = "PREFIX dcat: \n" + "\n" + "CONSTRUCT {\n" + " ?x .\n" + + " ?x ?x .\n" + "}\n" + "WHERE {\n" + " ?x a dcat:Catalog .\n" + "}"; Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); @@ -107,8 +95,7 @@ public void testConstruct_CyclicPathWithJoin() { assertThat(result.contains(test, c, test)).isTrue(); } - @Test - public void testSES2104ConstructBGPSameURI() throws Exception { + private void testSES2104ConstructBGPSameURI() throws Exception { final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); @@ -125,4 +112,10 @@ public void testSES2104ConstructBGPSameURI() throws Exception { assertTrue(result.contains(x, p, x)); } } + + public Stream tests() { + return Stream.of(makeTest("ConstructModifiers", this::testConstructModifiers), + makeTest("SES2104ConstructBGPSameURI", this::testSES2104ConstructBGPSameURI), + makeTest("Construct_CyclicPathWithJoin", this::testConstruct_CyclicPathWithJoin)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java index c173b1879a2..ce746c64f1c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java @@ -11,11 +11,12 @@ package org.eclipse.rdf4j.testsuite.sparql.tests; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.util.List; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.query.BindingSet; @@ -24,9 +25,11 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on handling default graph identification (DEFAULT keyword, rf4j:nil). @@ -36,12 +39,13 @@ */ public class DefaultGraphTest extends AbstractComplianceTest { - @Test - public void testNullContext1() throws Exception { + public DefaultGraphTest(Repository repo) { + super(repo); + } + + private void testNullContext1() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + - " FROM DEFAULT " + - " WHERE { ?s ?p ?o } "; + String query = " SELECT * " + " FROM DEFAULT " + " WHERE { ?s ?p ?o } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -67,12 +71,9 @@ public void testNullContext1() throws Exception { } } - @Test - public void testNullContext2() throws Exception { + private void testNullContext2() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + - " FROM rdf4j:nil " + - " WHERE { ?s ?p ?o } "; + String query = " SELECT * " + " FROM rdf4j:nil " + " WHERE { ?s ?p ?o } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -98,11 +99,9 @@ public void testNullContext2() throws Exception { } } - @Test - public void testSesameNilAsGraph() throws Exception { + private void testSesameNilAsGraph() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + - " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; + String query = " SELECT * " + " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; // query.append(" WHERE { ?s ?p ?o } "); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -125,4 +124,9 @@ public void testSesameNilAsGraph() throws Exception { fail(e.getMessage()); } } + + public Stream tests() { + return Stream.of(makeTest("SesameNilAsGraph", this::testSesameNilAsGraph), + makeTest("NullContext2", this::testNullContext2), makeTest("NullContext1", this::testNullContext1)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java index c2854b03b9d..5cee875421b 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.BNode; import org.eclipse.rdf4j.model.IRI; @@ -26,8 +27,10 @@ import org.eclipse.rdf4j.query.GraphQueryResult; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResults; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL DESCRIBE queries @@ -36,11 +39,13 @@ */ public class DescribeTest extends AbstractComplianceTest { - @Test - public void testDescribeA() throws Exception { + public DescribeTest(Repository repo) { + super(repo); + } + + private void testDescribeA() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:a"; + String query = getNamespaceDeclarations() + "DESCRIBE ex:a"; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -60,11 +65,9 @@ public void testDescribeA() throws Exception { } } - @Test - public void testDescribeAWhere() throws Exception { + private void testDescribeAWhere() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; + String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -84,11 +87,9 @@ public void testDescribeAWhere() throws Exception { } } - @Test - public void testDescribeWhere() throws Exception { + private void testDescribeWhere() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; + String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -120,11 +121,9 @@ public void testDescribeWhere() throws Exception { } } - @Test - public void testDescribeB() throws Exception { + private void testDescribeB() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:b"; + String query = getNamespaceDeclarations() + "DESCRIBE ex:b"; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -143,11 +142,9 @@ public void testDescribeB() throws Exception { } } - @Test - public void testDescribeD() throws Exception { + private void testDescribeD() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:d"; + String query = getNamespaceDeclarations() + "DESCRIBE ex:d"; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -177,11 +174,9 @@ public void testDescribeD() throws Exception { } } - @Test - public void testDescribeF() throws Exception { + private void testDescribeF() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:f"; + String query = getNamespaceDeclarations() + "DESCRIBE ex:f"; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -208,13 +203,11 @@ public void testDescribeF() throws Exception { } } - @Test - public void testDescribeMultipleA() { + private void testDescribeMultipleA() { String update = "insert data { . [] . . } "; conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + - "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -233,13 +226,11 @@ public void testDescribeMultipleA() { } } - @Test - public void testDescribeMultipleB() { + private void testDescribeMultipleB() { String update = "insert data { . [] . . } "; conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + - "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -258,13 +249,11 @@ public void testDescribeMultipleB() { } } - @Test - public void testDescribeMultipleC() { + private void testDescribeMultipleC() { String update = "insert data { . [] . [] . . } "; conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + - "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -284,13 +273,11 @@ public void testDescribeMultipleC() { } } - @Test - public void testDescribeMultipleD() { + private void testDescribeMultipleD() { String update = "insert data { . [] . . [] . . [] .} "; conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + - "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); @@ -312,4 +299,14 @@ public void testDescribeMultipleD() { } } + public Stream tests() { + return Stream.of(makeTest("DescribeMultipleD", this::testDescribeMultipleD), + makeTest("DescribeMultipleC", this::testDescribeMultipleC), + makeTest("DescribeMultipleB", this::testDescribeMultipleB), + makeTest("DescribeMultipleA", this::testDescribeMultipleA), makeTest("DescribeF", this::testDescribeF), + makeTest("DescribeD", this::testDescribeD), makeTest("DescribeB", this::testDescribeB), + makeTest("DescribeWhere", this::testDescribeWhere), + makeTest("DescribeAWhere", this::testDescribeAWhere), makeTest("DescribeA", this::testDescribeA)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java index 3a97f138e5c..8cc086b2cc9 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.stream.Collectors; @@ -20,8 +20,10 @@ import org.eclipse.rdf4j.model.util.Values; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.TupleQuery; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Test for queries using EXISTS @@ -30,8 +32,11 @@ */ public class ExistsTest extends AbstractComplianceTest { - @Test - public void testFilterNotExistsBindingToCurrentSolutionMapping() { + public ExistsTest(Repository repo) { + super(repo); + } + + private void testFilterNotExistsBindingToCurrentSolutionMapping() { String ex = "http://example/"; IRI a1 = Values.iri(ex, "a1"); @@ -48,15 +53,9 @@ public void testFilterNotExistsBindingToCurrentSolutionMapping() { conn.add(a2, predicate1, both); conn.add(a2, predicate2, Values.bnode()); - TupleQuery tupleQuery = conn.prepareTupleQuery( - "PREFIX : \n" + - "SELECT * WHERE {\n" + - " ?a :predicate1 ?p1\n" + - " FILTER NOT EXISTS {\n" + - " ?a :predicate2 ?p2 .\n" + - " FILTER(?p2 = ?p1)\n" + - " }\n" + - "}\n"); + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX : \n" + "SELECT * WHERE {\n" + + " ?a :predicate1 ?p1\n" + " FILTER NOT EXISTS {\n" + " ?a :predicate2 ?p2 .\n" + + " FILTER(?p2 = ?p1)\n" + " }\n" + "}\n"); try (Stream stream = tupleQuery.evaluate().stream()) { List collect = stream.collect(Collectors.toList()); @@ -66,4 +65,9 @@ public void testFilterNotExistsBindingToCurrentSolutionMapping() { } + public Stream tests() { + return Stream.of(makeTest("FilterNotExistsBindingToCurrentSolutionMapping", + this::testFilterNotExistsBindingToCurrentSolutionMapping)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java index a50c27abe01..ab60e476490 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java @@ -10,13 +10,17 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.stream.Stream; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL GROUP BY @@ -25,8 +29,11 @@ */ public class GroupByTest extends AbstractComplianceTest { - @Test - public void testGroupByEmpty() { + public GroupByTest(Repository repo) { + super(repo); + } + + private void testGroupByEmpty() { // see issue https://github.com/eclipse/rdf4j/issues/573 String query = "select ?x where {?x ?p ?o} group by ?x"; @@ -37,4 +44,8 @@ public void testGroupByEmpty() { } } + public Stream tests() { + return Stream.of(makeTest("GroupByEmpty", this::testGroupByEmpty)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java index 0bd09c237c5..fc4f14f282a 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java @@ -11,10 +11,12 @@ package org.eclipse.rdf4j.testsuite.sparql.tests; import static org.eclipse.rdf4j.model.util.Values.literal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; @@ -24,8 +26,10 @@ import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on the IN operator. @@ -35,11 +39,14 @@ */ public class InTest extends AbstractComplianceTest { - @Test - public void testInComparison1() throws Exception { + public InTest(Repository repo) { + super(repo); + } + + private void testInComparison1() throws Exception { loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -55,11 +62,10 @@ public void testInComparison1() throws Exception { } } - @Test - public void testInComparison2() throws Exception { + private void testInComparison2() throws Exception { loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -69,11 +75,10 @@ public void testInComparison2() throws Exception { } } - @Test - public void testInComparison3() throws Exception { + private void testInComparison3() throws Exception { loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" + - " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -89,4 +94,9 @@ public void testInComparison3() throws Exception { } } + public Stream tests() { + return Stream.of(makeTest("InComparison1", this::testInComparison1), + makeTest("InComparison2", this::testInComparison2), makeTest("InComparison3", this::testInComparison3)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java index 69e2eef2b39..0a6226fd39a 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.stream.Collectors; @@ -21,8 +21,9 @@ import org.eclipse.rdf4j.model.util.Values; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.TupleQuery; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Test for queries using MINUS @@ -31,8 +32,11 @@ */ public class MinusTest extends AbstractComplianceTest { - @Test - public void testScopingOfFilterInMinus() { + public MinusTest(Repository repo) { + super(repo); + } + + private void testScopingOfFilterInMinus() { String ex = "http://example/"; IRI a1 = Values.iri(ex, "a1"); @@ -50,29 +54,23 @@ public void testScopingOfFilterInMinus() { conn.add(a2, predicate2, Values.bnode()); TupleQuery tupleQuery = conn.prepareTupleQuery( - "PREFIX : \n" + - "SELECT * WHERE {\n" + - " ?a :predicate1 ?p1\n" + - " MINUS {\n" + - " ?a :predicate2 ?p2 .\n" + - " FILTER(?p2 = ?p1)\n" + - " }\n" + - "} ORDER BY ?a\n" - ); + "PREFIX : \n" + "SELECT * WHERE {\n" + " ?a :predicate1 ?p1\n" + " MINUS {\n" + + " ?a :predicate2 ?p2 .\n" + " FILTER(?p2 = ?p1)\n" + " }\n" + "} ORDER BY ?a\n"); try (Stream stream = tupleQuery.evaluate().stream()) { List collect = stream.collect(Collectors.toList()); assertEquals(2, collect.size()); List expectedValues = List.of(a1, a2); - List actualValues = collect - .stream() - .map(b -> b.getValue("a")) - .collect(Collectors.toList()); + List actualValues = collect.stream().map(b -> b.getValue("a")).collect(Collectors.toList()); assertEquals(expectedValues, actualValues); } } + public Stream tests() { + return Stream.of(makeTest("ScopingOfFilterInMinus", this::testScopingOfFilterInMinus)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java index 6aed034b3cc..14e6684db78 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java @@ -11,11 +11,11 @@ package org.eclipse.rdf4j.testsuite.sparql.tests; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.StringReader; import java.util.List; @@ -29,9 +29,11 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on OPTIONAL clause behavior. @@ -41,15 +43,14 @@ */ public class OptionalTest extends AbstractComplianceTest { - @Test - public void testSES1898LeftJoinSemantics1() throws Exception { + public OptionalTest(Repository repo) { + super(repo); + } + + private void testSES1898LeftJoinSemantics1() throws Exception { loadTestData("/testdata-query/dataset-ses1898.trig"); - String query = " PREFIX : " + - " SELECT * WHERE { " + - " ?s :p1 ?v1 . " + - " OPTIONAL {?s :p2 ?v2 } ." + - " ?s :p3 ?v2 . " + - " } "; + String query = " PREFIX : " + " SELECT * WHERE { " + " ?s :p1 ?v1 . " + + " OPTIONAL {?s :p2 ?v2 } ." + " ?s :p3 ?v2 . " + " } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try (Stream result = tq.evaluate().stream()) { @@ -58,28 +59,19 @@ public void testSES1898LeftJoinSemantics1() throws Exception { } } - @Test - public void testSES1121VarNamesInOptionals() throws Exception { + private void testSES1121VarNamesInOptionals() throws Exception { // Verifying that variable names have no influence on order of optionals // in query. See SES-1121. loadTestData("/testdata-query/dataset-ses1121.trig"); - String query1 = getNamespaceDeclarations() + - " SELECT DISTINCT *\n" + - " WHERE { GRAPH ?g { \n" + - " OPTIONAL { ?var35 ex:p ?b . } \n " + - " OPTIONAL { ?b ex:q ?c . } \n " + - " } \n" + - " } \n"; - - String query2 = getNamespaceDeclarations() + - " SELECT DISTINCT *\n" + - " WHERE { GRAPH ?g { \n" + - " OPTIONAL { ?var35 ex:p ?b . } \n " + - " OPTIONAL { ?b ex:q ?var2 . } \n " + - " } \n" + - " } \n"; + String query1 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?c . } \n " + + " } \n" + " } \n"; + + String query2 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?var2 . } \n " + + " } \n" + " } \n"; TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); @@ -105,29 +97,15 @@ public void testSES1121VarNamesInOptionals() throws Exception { } - @Test - public void testSameTermRepeatInOptional() throws Exception { + private void testSameTermRepeatInOptional() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - " SELECT ?l ?opt1 ?opt2 " + - " FROM ex:optional-sameterm-graph " + - " WHERE { " + - " ?s ex:p ex:A ; " + - " { " + - " { " + - " ?s ?p ?l ." + - " FILTER(?p = rdfs:label) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt1 . " + - " FILTER (?p = ex:prop1) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt2 . " + - " FILTER (?p = ex:prop2) " + - " } " + - " }" + - " } "; + String query = getNamespaceDeclarations() + " SELECT ?l ?opt1 ?opt2 " + " FROM ex:optional-sameterm-graph " + + " WHERE { " + " ?s ex:p ex:A ; " + " { " + " { " + + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " + " } " + + " OPTIONAL { " + " ?s ?p ?opt1 . " + + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " + + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " + " } " + + " }" + " } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -164,26 +142,24 @@ public void testSameTermRepeatInOptional() throws Exception { * See https://github.com/eclipse/rdf4j/issues/3072 * */ - @Test - public void testValuesAfterOptional() throws Exception { - String data = "@prefix rdfs: . \n" - + "@prefix : . \n" - + ":r1 a rdfs:Resource . \n" - + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; - - String query = "" - + "prefix rdfs: \n" - + "prefix : \n" - + "\n" - + "select ?resource ?label where { \n" - + " ?resource a rdfs:Resource . \n" - + " optional { ?resource rdfs:label ?label } \n" - + " values ?label { undef } \n" - + "}"; + private void testValuesAfterOptional() throws Exception { + String data = "@prefix rdfs: . \n" + "@prefix : . \n" + + ":r1 a rdfs:Resource . \n" + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; + + String query = "" + "prefix rdfs: \n" + "prefix : \n" + + "\n" + "select ?resource ?label where { \n" + " ?resource a rdfs:Resource . \n" + + " optional { ?resource rdfs:label ?label } \n" + " values ?label { undef } \n" + "}"; conn.add(new StringReader(data), RDFFormat.TURTLE); List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); assertThat(result).hasSize(2); } + + public Stream tests() { + return Stream.of(makeTest("SameTermRepeatInOptional", this::testSameTermRepeatInOptional), + makeTest("ValuesAfterOptional", this::testValuesAfterOptional), + makeTest("SES1121VarNamesInOptionals", this::testSES1121VarNamesInOptionals), + makeTest("SES1898LeftJoinSemantics1", this::testSES1898LeftJoinSemantics1)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java index fdf3c05c524..8c642ebf98e 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java @@ -10,7 +10,7 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.StringReader; import java.util.stream.Stream; @@ -18,17 +18,21 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; public class OrderByTest extends AbstractComplianceTest { - @Test - public void testDistinctOptionalOrderBy() throws Exception { + public OrderByTest(Repository repo) { + super(repo); + } + + private void testDistinctOptionalOrderBy() throws Exception { - conn.add(new StringReader("[] a .\n" + - "[] a ; 123 ."), "", RDFFormat.TURTLE); + conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by ?nr"; @@ -39,11 +43,11 @@ public void testDistinctOptionalOrderBy() throws Exception { } } - @Test - public void testOrderByVariableNotInUse() throws Exception { + private void testOrderByVariableNotInUse() throws Exception { - conn.add(new StringReader("_:bob1 a ; rdfs:label \"Bob1\" .\n" + - "_:bob2 a ; rdfs:label \"Bob2\" ."), "", RDFFormat.TURTLE); + conn.add(new StringReader( + "_:bob1 a ; rdfs:label \"Bob1\" .\n" + "_:bob2 a ; rdfs:label \"Bob2\" ."), + "", RDFFormat.TURTLE); String query = "SELECT * WHERE { ?person a } ORDER BY ?score\n"; @@ -55,11 +59,9 @@ public void testOrderByVariableNotInUse() throws Exception { } } - @Test - public void testDistinctOptionalOrderByMath() throws Exception { + private void testDistinctOptionalOrderByMath() throws Exception { - conn.add(new StringReader("[] a .\n" + - "[] a ; 123 ."), "", RDFFormat.TURTLE); + conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by (?nr + STRLEN(?o))"; @@ -70,4 +72,10 @@ public void testDistinctOptionalOrderByMath() throws Exception { } } + public Stream tests() { + return Stream.of(makeTest("DistinctOptionalOrderBy", this::testDistinctOptionalOrderBy), + makeTest("OrderByVariableNotInUse", this::testOrderByVariableNotInUse), + makeTest("DistinctOptionalOrderByMath", this::testDistinctOptionalOrderByMath)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java index ea63fd10f59..0608609295c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java @@ -12,12 +12,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.rdf4j.model.util.Values.iri; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.StringReader; import java.util.List; @@ -41,10 +41,12 @@ import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.impl.MapBindingSet; import org.eclipse.rdf4j.query.impl.SimpleBinding; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL property paths. @@ -55,24 +57,21 @@ */ public class PropertyPathTest extends AbstractComplianceTest { - @Test - public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { + public PropertyPathTest(Repository repo) { + super(repo); + } + + private void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { - String data = " .\n" + - " .\n" + - " .\n" + - " .\n" + - " .\n"; + String data = " .\n" + " .\n" + + " .\n" + " .\n" + " .\n"; conn.begin(); conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); conn.commit(); - String query = getNamespaceDeclarations() + - "SELECT ?x \n" + - "WHERE { ?x */ . \n" + - " ?x */ . \n" + - "} \n"; + String query = getNamespaceDeclarations() + "SELECT ?x \n" + "WHERE { ?x */ . \n" + + " ?x */ . \n" + "} \n"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -91,8 +90,7 @@ public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { } } - @Test - public void testSES2024PropertyPathAnonVarSharing() throws Exception { + private void testSES2024PropertyPathAnonVarSharing() throws Exception { loadTestData("/testdata-query/dataset-ses2024.trig"); String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; @@ -113,11 +111,8 @@ public void testSES2024PropertyPathAnonVarSharing() throws Exception { } } - @Test - public void testPropertyPathNegationInversion() throws Exception { - String data = "@prefix : .\n" - + ":Mary :parentOf :Jim.\n" - + ":Jim :knows :Jane.\n" + private void testPropertyPathNegationInversion() throws Exception { + String data = "@prefix : .\n" + ":Mary :parentOf :Jim.\n" + ":Jim :knows :Jane.\n" + ":Jane :worksFor :IBM."; conn.add(new StringReader(data), "", RDFFormat.TURTLE); @@ -133,8 +128,7 @@ public void testPropertyPathNegationInversion() throws Exception { } - @Test - public void testSES2336NegatedPropertyPathMod() throws Exception { + private void testSES2336NegatedPropertyPathMod() throws Exception { loadTestData("/testdata-query/dataset-ses2336.trig"); String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; @@ -168,8 +162,7 @@ public void testSES2336NegatedPropertyPathMod() throws Exception { } - @Test - public void testSES1685propPathSameVar() throws Exception { + private void testSES1685propPathSameVar() throws Exception { final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); @@ -182,8 +175,7 @@ public void testSES1685propPathSameVar() throws Exception { } } - @Test - public void testSES1073InverseSymmetricPattern() { + private void testSES1073InverseSymmetricPattern() { IRI a = iri("http://example.org/a"); IRI b1 = iri("http://example.org/b1"); IRI b2 = iri("http://example.org/b2"); @@ -210,20 +202,14 @@ public void testSES1073InverseSymmetricPattern() { /** * @see GH-2727 */ - @Test - public void testNestedInversePropertyPathWithZeroLength() { - String insert = "insert data {\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + " .\n" - + "}"; - - String query = "select * where { \n" - + " (^)? ?o .\n" - + "}"; + + private void testNestedInversePropertyPathWithZeroLength() { + String insert = "insert data {\n" + " .\n" + + " .\n" + " .\n" + + " .\n" + " .\n" + + " .\n" + "}"; + + String query = "select * where { \n" + " (^)? ?o .\n" + "}"; conn.prepareUpdate(insert).execute(); @@ -233,34 +219,27 @@ public void testNestedInversePropertyPathWithZeroLength() { assertThat(result).hasSize(4); } - @Test - public void testComplexPath() { + private void testComplexPath() { conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX skos: \r\n" + - " SELECT * " + - " WHERE {\r\n" + - " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + - " }"); + TupleQuery tupleQuery = conn.prepareTupleQuery( + "PREFIX skos: \r\n" + " SELECT * " + " WHERE {\r\n" + + " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + " }"); try (TupleQueryResult evaluate = tupleQuery.evaluate()) { List collect = evaluate.stream().collect(Collectors.toList()); assertEquals(2, collect.size()); } } - @Test - public void testInversePath() { + private void testInversePath() { BNode bnode1 = Values.bnode("bnode1"); conn.add(Values.bnode(), FOAF.KNOWS, bnode1); conn.add(Values.bnode(), FOAF.KNOWS, bnode1); - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" + - "SELECT * WHERE {\n" + - " ?x foaf:knows/^foaf:knows ?y . \n" + - " FILTER(?x != ?y)\n" + - "}"); + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" + "SELECT * WHERE {\n" + + " ?x foaf:knows/^foaf:knows ?y . \n" + " FILTER(?x != ?y)\n" + "}"); try (TupleQueryResult evaluate = tupleQuery.evaluate()) { List collect = evaluate.stream().collect(Collectors.toList()); @@ -275,4 +254,17 @@ private boolean containsSolution(List result, Binding... solution) { } return result.contains(bs); } + + public Stream tests() { + return Stream.of( + makeTest("SES2147PropertyPathsWithIdenticalSubsPreds", + this::testSES2147PropertyPathsWithIdenticalSubsPreds), + makeTest("InversePath", this::testInversePath), makeTest("ComplexPath", this::testComplexPath), + makeTest("NestedInversePropertyPathWithZeroLength", this::testNestedInversePropertyPathWithZeroLength), + makeTest("SES1073InverseSymmetricPattern", this::testSES1073InverseSymmetricPattern), + makeTest("SES1685propPathSameVar", this::testSES1685propPathSameVar), + makeTest("SES2336NegatedPropertyPathMod", this::testSES2336NegatedPropertyPathMod), + makeTest("PropertyPathNegationInversion", this::testPropertyPathNegationInversion), + makeTest("SES2024PropertyPathAnonVarSharing", this::testSES2024PropertyPathAnonVarSharing)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java index 286075efe06..a6947459928 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java @@ -10,10 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.query.BindingSet; @@ -21,8 +22,10 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL nested SELECT query handling. @@ -31,8 +34,11 @@ */ public class SubselectTest extends AbstractComplianceTest { - @Test - public void testSES2373SubselectOptional() { + public SubselectTest(Repository repo) { + super(repo); + } + + private void testSES2373SubselectOptional() { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data {" + " ." + " 1 ." + " ." + " ." + " 2 ." + " ." @@ -41,75 +47,52 @@ public void testSES2373SubselectOptional() { + " ." + " 5 ." + " ." + "}") .execute(); - String qb = "select ?x { \n" + - " { select ?v { ?v filter (?v = ) } }.\n" + - " optional { select ?val { ?v ?val .} }\n" + - " ?v ?x \n" + - "}\n"; + String qb = "select ?x { \n" + " { select ?v { ?v filter (?v = ) } }.\n" + + " optional { select ?val { ?v ?val .} }\n" + " ?v ?x \n" + "}\n"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); try (TupleQueryResult result = tq.evaluate()) { - assertTrue("The query should return a result", result.hasNext()); + assertTrue(result.hasNext(), "The query should return a result"); BindingSet b = result.next(); - assertTrue("?x is from the mandatory part of the query and should be bound", b.hasBinding("x")); + assertTrue(b.hasBinding("x"), "?x is from the mandatory part of the query and should be bound"); } } - @Test - public void testSES2154SubselectOptional() { + private void testSES2154SubselectOptional() { - String ub = "insert data { \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " a . \n" + - " \"01\" . \n" + - " \"02\" . \n" + - " \"03\" . \n" + - " \"04\" . \n" + - " \"05\" . \n" + - " \"06\" . \n" + - " \"07\" . \n" + - " \"08\" . \n" + - " \"09\" . \n" + - " \"10\" . \n" + - " \"11\" . \n" + - " \"12\" . \n" + - "} \n"; + String ub = "insert data { \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " \"01\" . \n" + " \"02\" . \n" + + " \"03\" . \n" + " \"04\" . \n" + " \"05\" . \n" + + " \"06\" . \n" + " \"07\" . \n" + " \"08\" . \n" + + " \"09\" . \n" + " \"10\" . \n" + + " \"11\" . \n" + " \"12\" . \n" + "} \n"; conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - String qb = "SELECT ?s ?label\n" + - "WHERE { \n" + - " ?s a \n .\n" + - " OPTIONAL { {SELECT ?label WHERE { \n" + - " ?s ?label . \n" + - " } ORDER BY ?label LIMIT 2 \n" + - " }\n" + - " }\n" + - "}\n" + - "ORDER BY ?s\n" + - "LIMIT 10 \n"; + String qb = "SELECT ?s ?label\n" + "WHERE { \n" + " ?s a \n .\n" + + " OPTIONAL { {SELECT ?label WHERE { \n" + " ?s ?label . \n" + + " } ORDER BY ?label LIMIT 2 \n" + " }\n" + " }\n" + "}\n" + "ORDER BY ?s\n" + + "LIMIT 10 \n"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); try (TupleQueryResult evaluate = tq.evaluate()) { - assertTrue("The query should return a result", evaluate.hasNext()); + assertTrue(evaluate.hasNext(), "The query should return a result"); List result = QueryResults.asList(evaluate); assertEquals(10, result.size()); for (BindingSet bs : result) { Literal label = (Literal) bs.getValue("label"); - assertTrue("wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')", - label.stringValue().equals("01") || label.stringValue().equals("02")); + assertTrue(label.stringValue().equals("01") || label.stringValue().equals("02"), + "wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')"); } } } + + public Stream tests() { + return Stream.of(makeTest("SES2373SubselectOptional", this::testSES2373SubselectOptional), + makeTest("SES2154SubselectOptional", this::testSES2154SubselectOptional)); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java index c37b129a1be..910da3d7b2c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java @@ -10,12 +10,14 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql.tests; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -25,8 +27,10 @@ import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPRQL UNION clauses. @@ -36,32 +40,26 @@ */ public class UnionTest extends AbstractComplianceTest { - @Test - public void testEmptyUnion() { - String query = "PREFIX : " - + "SELECT ?visibility WHERE {" + public UnionTest(Repository repo) { + super(repo); + } + + private void testEmptyUnion() { + String query = "PREFIX : " + "SELECT ?visibility WHERE {" + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." - + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" - + "}"; + + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + "}"; try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { assertNotNull(result); assertFalse(result.hasNext()); } } - @Test - public void testSameTermRepeatInUnion() throws Exception { + private void testSameTermRepeatInUnion() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = "PREFIX foaf:\n" + - "SELECT * {\n" + - " {\n" + - " ?sameTerm foaf:mbox ?mbox\n" + - " FILTER sameTerm(?sameTerm,$william)\n" + - " } UNION {\n" + - " ?x foaf:knows ?sameTerm\n" + - " FILTER sameTerm(?sameTerm,$william)\n" + - " }\n" + - "}"; + String query = "PREFIX foaf:\n" + "SELECT * {\n" + " {\n" + + " ?sameTerm foaf:mbox ?mbox\n" + " FILTER sameTerm(?sameTerm,$william)\n" + + " } UNION {\n" + " ?x foaf:knows ?sameTerm\n" + + " FILTER sameTerm(?sameTerm,$william)\n" + " }\n" + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); @@ -90,33 +88,16 @@ public void testSameTermRepeatInUnion() throws Exception { } - @Test - public void testSameTermRepeatInUnionAndOptional() throws Exception { + private void testSameTermRepeatInUnionAndOptional() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + - "SELECT * {\n" + - " {\n" + - " ex:a ?p ?prop1\n" + - " FILTER (?p = ex:prop1)\n" + - " } UNION {\n" + - " ?s ex:p ex:A ; " + - " { " + - " { " + - " ?s ?p ?l ." + - " FILTER(?p = rdfs:label) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt1 . " + - " FILTER (?p = ex:prop1) " + - " } " + - " OPTIONAL { " + - " ?s ?p ?opt2 . " + - " FILTER (?p = ex:prop2) " + - " } " + - " }" + - " }\n" + - "}"; + String query = getNamespaceDeclarations() + "SELECT * {\n" + " {\n" + " ex:a ?p ?prop1\n" + + " FILTER (?p = ex:prop1)\n" + " } UNION {\n" + " ?s ex:p ex:A ; " + " { " + + " { " + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " + + " } " + " OPTIONAL { " + " ?s ?p ?opt1 . " + + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " + + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " + " } " + + " }" + " }\n" + "}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -151,4 +132,10 @@ public void testSameTermRepeatInUnionAndOptional() throws Exception { } + public Stream tests() { + return Stream.of(makeTest("EmptyUnion", this::testEmptyUnion), + makeTest("SameTermRepeatInUnion", this::testSameTermRepeatInUnion), + makeTest("SameTermRepeatInUnionAndOptional", this::testSameTermRepeatInUnionAndOptional)); + } + } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java index 89191e18661..ec75c54a67c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java @@ -12,15 +12,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.rdf4j.model.util.Values.iri; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.StringReader; import java.util.List; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -34,9 +35,11 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.Update; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; /** * Tests on SPARQL VALUES clauses. @@ -45,11 +48,14 @@ */ public class ValuesTest extends AbstractComplianceTest { - @Test - public void testValuesInOptional() throws Exception { + public ValuesTest(Repository repo) { + super(repo); + } + + private void testValuesInOptional() throws Exception { loadTestData("/testdata-query/dataset-ses1692.trig"); - String query = " PREFIX : \n" + - " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; + String query = " PREFIX : \n" + + " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -77,22 +83,17 @@ public void testValuesInOptional() throws Exception { } } - @Test - public void testValuesClauseNamedGraph() throws Exception { + private void testValuesClauseNamedGraph() throws Exception { String ex = "http://example.org/"; - String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" - + "@prefix ex: <" + ex + "> .\n" - + "ex:graph1 {\n" + - " ex:Person1 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" + - " foaf:name \"Person 3\" .\n" + - "}"; + String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + "@prefix ex: <" + ex + "> .\n" + "ex:graph1 {\n" + + " ex:Person1 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 3\" .\n" + "}"; conn.add(new StringReader(data), "", RDFFormat.TRIG); - String query = "SELECT ?person ?name ?__index \n" - + "WHERE { " + String query = "SELECT ?person ?name ?__index \n" + "WHERE { " + " VALUES (?person ?name ?__index) { \n" + " ( UNDEF \"0\") \n" + " ( UNDEF \"2\") } \n" @@ -104,29 +105,20 @@ public void testValuesClauseNamedGraph() throws Exception { assertThat(result).hasSize(2); } - @Test - public void testValuesCartesianProduct() { - final String queryString = "" - + "select ?x ?y where { " - + " values ?x { undef 67 } " - + " values ?y { undef 42 } " - + "}"; + private void testValuesCartesianProduct() { + final String queryString = "" + "select ?x ?y where { " + " values ?x { undef 67 } " + + " values ?y { undef 42 } " + "}"; final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); List bindingSets = QueryResults.asList(tupleQuery.evaluate()); assertThat(bindingSets).hasSize(4); } - @Test - public void testSES1081SameTermWithValues() throws Exception { + private void testSES1081SameTermWithValues() throws Exception { loadTestData("/testdata-query/dataset-ses1081.trig"); - String query = "PREFIX ex: \n" + - " SELECT * \n" + - " WHERE { \n " + - " ?s ex:p ?a . \n" + - " FILTER sameTerm(?a, ?e) \n " + - " VALUES ?e { ex:b } \n " + - " } "; + String query = "PREFIX ex: \n" + " SELECT * \n" + " WHERE { \n " + + " ?s ex:p ?a . \n" + " FILTER sameTerm(?a, ?e) \n " + + " VALUES ?e { ex:b } \n " + " } "; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -155,14 +147,10 @@ public void testSES1081SameTermWithValues() throws Exception { } - @Test - public void testSES2136() throws Exception { + private void testSES2136() throws Exception { loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl"); - String query = "PREFIX : \n" + - "SELECT ?s ?o { \n" + - " { SELECT * WHERE { ?s ?p ?o . } }\n" + - " VALUES (?o) { (:b) }\n" + - "}\n"; + String query = "PREFIX : \n" + "SELECT ?s ?o { \n" + " { SELECT * WHERE { ?s ?p ?o . } }\n" + + " VALUES (?o) { (:b) }\n" + "}\n"; ValueFactory vf = conn.getValueFactory(); final IRI a = vf.createIRI("http://example.org/a"); @@ -174,7 +162,7 @@ public void testSES2136() throws Exception { assertNotNull(result); assertTrue(result.hasNext()); BindingSet bs = result.next(); - assertFalse("only one result expected", result.hasNext()); + assertFalse(result.hasNext(), "only one result expected"); assertEquals(a, bs.getValue("s")); assertEquals(b, bs.getValue("o")); } @@ -183,29 +171,23 @@ public void testSES2136() throws Exception { /** * https://github.com/eclipse/rdf4j/issues/1026 */ - @Test - public void testFilterExistsExternalValuesClause() { - String ub = "insert data {\n" + - " a .\n" + - " a .\n" + - " .\n" + - " .\n" + - "}"; + + private void testFilterExistsExternalValuesClause() { + String ub = "insert data {\n" + " a .\n" + " a .\n" + + " .\n" + + " .\n" + "}"; conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - String query = "select ?s {\n" - + " ?s a* .\n" - + " FILTER EXISTS {?s ?o}\n" - + "} limit 100 values ?o {}"; + String query = "select ?s {\n" + " ?s a* .\n" + + " FILTER EXISTS {?s ?o}\n" + "} limit 100 values ?o {}"; TupleQuery tq = conn.prepareTupleQuery(query); List result = QueryResults.asList(tq.evaluate()); - assertEquals("single result expected", 1, result.size()); + assertEquals(1, result.size(), "single result expected"); assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); } - @Test public void testMultipleValuesClauses() { Update update = conn.prepareUpdate("PREFIX ex: \n" + "\n" + @@ -221,4 +203,13 @@ public void testMultipleValuesClauses() { update.execute(); } + public Stream tests() { + return Stream.of(makeTest("ValuesInOptional", this::testValuesInOptional), + makeTest("ValuesClauseNamedGraph", this::testValuesClauseNamedGraph), + makeTest("ValuesCartesianProduct", this::testValuesCartesianProduct), + makeTest("SES1081SameTermWithValues", this::testSES1081SameTermWithValues), + makeTest("SES2136", this::testSES2136), + makeTest("FilterExistsExternalValuesClause", this::testFilterExistsExternalValuesClause), + makeTest("MultipleValuesClauses", this::testMultipleValuesClauses)); + } } From b7fc16bdeb51107024f63ea71af8ef1bc72c4212 Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Mon, 22 May 2023 21:31:51 +0200 Subject: [PATCH 2/6] GH-4592 Replace more Junit4 Suite with v5 DynamicTest Also delete some deprecated tests classes that are no longer compatible with the junit5 way of doing things. Signed-off-by: Jerven Bolleman --- .../geosparql/MemoryGeoSPARQLQueryTest.java | 6 - .../parser/sparql/HTTPSparqlUpdateTest.java | 6 +- .../sparql/manifest/SPARQL12QueryTest.java | 6 - .../W3CApprovedSPARQL10QueryTest.java | 15 - .../W3CApprovedSPARQL11QueryTest.java | 79 -- .../W3CApprovedSPARQL11SyntaxTest.java | 13 - .../W3CApprovedSPARQL11UpdateTest.java | 10 - .../FedXSPARQL11QueryComplianceTest.java | 22 +- .../lmdb/LmdbPARQL11UpdateComplianceTest.java | 20 +- .../lmdb/LmdbSPARQL11QueryComplianceTest.java | 17 +- .../MemorySPARQL11QueryComplianceTest.java | 6 - .../MemorySPARQL11UpdateComplianceTest.java | 11 - .../NativeSPARQL11QueryComplianceTest.java | 17 +- .../NativeSPARQL11UpdateComplianceTest.java | 20 +- .../geosparql/GeoSPARQLManifestTest.java | 42 +- .../query/parser/sparql/SPARQLUpdateTest.java | 162 ++--- .../sparql/manifest/SPARQL10ManifestTest.java | 172 ----- .../manifest/SPARQL10QueryComplianceTest.java | 89 +-- .../sparql/manifest/SPARQL11ManifestTest.java | 231 ------ .../manifest/SPARQL11QueryComplianceTest.java | 67 +- .../SPARQL11SyntaxComplianceTest.java | 50 +- .../sparql/manifest/SPARQL11SyntaxTest.java | 307 -------- .../SPARQL11UpdateComplianceTest.java | 334 +++++---- .../manifest/SPARQL12QueryComplianceTest.java | 57 +- .../sparql/manifest/SPARQLComplianceTest.java | 257 ++++--- .../manifest/SPARQLQueryComplianceTest.java | 530 +++++++------- .../sparql/manifest/SPARQLQueryTest.java | 672 ------------------ .../manifest/SPARQLSyntaxComplianceTest.java | 204 +++--- .../manifest/SPARQLUpdateConformanceTest.java | 400 ----------- 29 files changed, 843 insertions(+), 2979 deletions(-) delete mode 100644 compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11QueryTest.java delete mode 100644 testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10ManifestTest.java delete mode 100644 testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11ManifestTest.java delete mode 100644 testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java delete mode 100644 testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java delete mode 100644 testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java diff --git a/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java b/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java index fc351f8358d..ba9250eb0dd 100644 --- a/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java +++ b/compliance/geosparql/src/test/java/org/eclipse/rdf4j/query/algebra/geosparql/MemoryGeoSPARQLQueryTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.algebra.geosparql; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.memory.MemoryStore; @@ -18,11 +17,6 @@ public class MemoryGeoSPARQLQueryTest extends GeoSPARQLManifestTest { - public MemoryGeoSPARQLQueryTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - @Override protected Repository newRepository() { return new SailRepository(new MemoryStore()); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java index 115c3f4bc25..4610069edd7 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/HTTPSparqlUpdateTest.java @@ -10,9 +10,9 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.parser.sparql; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/SPARQL12QueryTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/SPARQL12QueryTest.java index b1b668cbf3e..c4a06e0aa70 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/SPARQL12QueryTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/SPARQL12QueryTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.parser.sparql.manifest; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,11 +23,6 @@ */ public class SPARQL12QueryTest extends SPARQL12QueryComplianceTest { - public SPARQL12QueryTest(String displayName, String testURI, String name, String queryFileURL, String resultFileURL, - Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - @Override protected Repository newRepository() { return new DatasetRepository(new SailRepository(new MemoryStore())); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL10QueryTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL10QueryTest.java index 173749bef7d..b24c0231789 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL10QueryTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL10QueryTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.parser.sparql.manifest; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -24,20 +23,6 @@ */ public class W3CApprovedSPARQL10QueryTest extends SPARQL10QueryComplianceTest { - /** - * @param displayName - * @param testURI - * @param name - * @param queryFileURL - * @param resultFileURL - * @param dataset - * @param ordered - */ - public W3CApprovedSPARQL10QueryTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - @Override protected Repository newRepository() { return new DatasetRepository(new SailRepository(new MemoryStore())); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11QueryTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11QueryTest.java deleted file mode 100644 index 75285728428..00000000000 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11QueryTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.query.parser.sparql.manifest; - -import java.net.URL; - -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.dataset.DatasetRepository; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11ManifestTest; -import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQLQueryTest; -import org.junit.jupiter.api.Disabled; - -import junit.framework.Test; - -@Disabled("replaced by org.eclipse.rdf4j.sail.memory.MemorySPARQL11QueryComplianceTest") -@Deprecated -public class W3CApprovedSPARQL11QueryTest extends SPARQLQueryTest { - - public static Test suite() throws Exception { - URL manifestUrl = SPARQL11ManifestTest.class.getResource("/testcases-sparql-1.1-w3c/manifest-all.ttl"); - - return SPARQL11ManifestTest.suite(new Factory() { - - @Override - public W3CApprovedSPARQL11QueryTest createSPARQLQueryTest(String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataSet, boolean laxCardinality) { - return createSPARQLQueryTest(testURI, name, queryFileURL, resultFileURL, dataSet, laxCardinality, - false); - } - - @Override - public W3CApprovedSPARQL11QueryTest createSPARQLQueryTest(String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataSet, boolean laxCardinality, boolean checkOrder) { - String[] ignoredTests = { - // test case incompatible with RDF 1.1 - see - // http://lists.w3.org/Archives/Public/public-sparql-dev/2013AprJun/0006.html - "STRDT TypeErrors", - // test case incompatible with RDF 1.1 - see - // http://lists.w3.org/Archives/Public/public-sparql-dev/2013AprJun/0006.html - "STRLANG TypeErrors", - // known issue: SES-937 - "sq03 - Subquery within graph pattern, graph variable is not bound", - // test case is incorrect wrt SPARQL 1.1 spec, see https://github.com/eclipse/rdf4j/issues/1978 -// "agg empty group", -// "Aggregate over empty group resulting in a row with unbound variables" - }; - - return new W3CApprovedSPARQL11QueryTest(testURI, name, queryFileURL, resultFileURL, dataSet, - laxCardinality, checkOrder, ignoredTests); - } - }, manifestUrl.toString(), true, "service"); - } - - protected W3CApprovedSPARQL11QueryTest(String testURI, String name, String queryFileURL, String resultFileURL, - Dataset dataSet, boolean laxCardinality, String... ignoredTests) { - this(testURI, name, queryFileURL, resultFileURL, dataSet, laxCardinality, false, ignoredTests); - } - - protected W3CApprovedSPARQL11QueryTest(String testURI, String name, String queryFileURL, String resultFileURL, - Dataset dataSet, boolean laxCardinality, boolean checkOrder, String... ignoredTests) { - super(testURI, name, queryFileURL, resultFileURL, dataSet, laxCardinality, checkOrder, ignoredTests); - } - - @Override - protected Repository newRepository() { - return new DatasetRepository(new SailRepository(new MemoryStore())); - } -} diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11SyntaxTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11SyntaxTest.java index fba3f3846b0..d7217d7b400 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11SyntaxTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11SyntaxTest.java @@ -18,19 +18,6 @@ public class W3CApprovedSPARQL11SyntaxTest extends SPARQL11SyntaxComplianceTest { - /** - * @param displayName - * @param testURI - * @param name - * @param queryFileURL - * @param resultFileURL - * @param positiveTest - */ - public W3CApprovedSPARQL11SyntaxTest(String displayName, String testURI, String name, String queryFileURL, - boolean positiveTest) { - super(displayName, testURI, name, queryFileURL, positiveTest); - } - @Override protected ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException { return QueryParserUtil.parseOperation(QueryLanguage.SPARQL, operation, fileURL); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java index 96700874565..b62c570d90d 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/query/parser/sparql/manifest/W3CApprovedSPARQL11UpdateTest.java @@ -10,9 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.query.parser.sparql.manifest; -import java.util.Map; - -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.memory.MemoryStore; @@ -26,13 +23,6 @@ @Deprecated public class W3CApprovedSPARQL11UpdateTest extends SPARQL11UpdateComplianceTest { - public W3CApprovedSPARQL11UpdateTest(String displayName, String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs) { - super(displayName, testURI, name, requestFile, defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, - resultNamedGraphs); - } - @Override protected Repository newRepository() { SailRepository repo = new SailRepository(new MemoryStore()); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java index efb4c30a8bb..8a690294b67 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/federation/FedXSPARQL11QueryComplianceTest.java @@ -10,11 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.federation; +import java.io.File; import java.io.IOException; import org.eclipse.rdf4j.federated.FedXFactory; import org.eclipse.rdf4j.federated.repository.FedXRepository; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.config.RepositoryConfig; @@ -26,24 +26,20 @@ import org.eclipse.rdf4j.repository.sail.config.SailRepositoryConfig; import org.eclipse.rdf4j.sail.memory.config.MemoryStoreConfig; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11QueryComplianceTest; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; /** * @author jeen */ public class FedXSPARQL11QueryComplianceTest extends SPARQL11QueryComplianceTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - private static final String dirName = "testmanager"; + @TempDir + public File tempFolder; private RepositoryManager manager; - public FedXSPARQL11QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); + public FedXSPARQL11QueryComplianceTest() { + super(); // FIXME see https://github.com/eclipse/rdf4j/issues/2173 addIgnoredTest("sq04 - Subquery within graph pattern, default graph does not apply"); @@ -51,11 +47,7 @@ public FedXSPARQL11QueryComplianceTest(String displayName, String testURI, Strin private void initManager() { if (manager == null) { - try { - manager = RepositoryProvider.getRepositoryManager(tempFolder.newFolder(dirName)); - } catch (IOException e) { - throw new RuntimeException(e); - } + manager = RepositoryProvider.getRepositoryManager(tempFolder); } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbPARQL11UpdateComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbPARQL11UpdateComplianceTest.java index c734156f8b5..90d1bb689a0 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbPARQL11UpdateComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbPARQL11UpdateComplianceTest.java @@ -10,36 +10,26 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.lmdb; -import java.util.Map; +import java.io.File; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreConfig; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11UpdateComplianceTest; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; /** * Test SPARQL 1.1 Update functionality on LMDB store. */ public class LmdbPARQL11UpdateComplianceTest extends SPARQL11UpdateComplianceTest { - public LmdbPARQL11UpdateComplianceTest(String displayName, String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs) { - super(displayName, testURI, name, requestFile, defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, - resultNamedGraphs); - // TODO Auto-generated constructor stub - } - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; @Override protected Repository newRepository() throws Exception { return new DatasetRepository( - new SailRepository(new LmdbStore(folder.newFolder(), new LmdbStoreConfig("spoc")))); + new SailRepository(new LmdbStore(folder, new LmdbStoreConfig("spoc")))); } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQL11QueryComplianceTest.java index 25da92fd8ef..6b6b5cc90ea 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/lmdb/LmdbSPARQL11QueryComplianceTest.java @@ -10,32 +10,27 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.lmdb; -import org.eclipse.rdf4j.query.Dataset; +import java.io.File; + import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.sail.lmdb.config.LmdbStoreConfig; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11QueryComplianceTest; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; /** * Test SPARQL 1.1 query functionality on LMDB store. */ public class LmdbSPARQL11QueryComplianceTest extends SPARQL11QueryComplianceTest { - public LmdbSPARQL11QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; @Override protected Repository newRepository() throws Exception { return new DatasetRepository( - new SailRepository(new LmdbStore(folder.newFolder(), new LmdbStoreConfig("spoc")))); + new SailRepository(new LmdbStore(folder, new LmdbStoreConfig("spoc")))); } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java index 4c6728fa658..34300f7b6cc 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11QueryComplianceTest.java @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.memory; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; @@ -23,11 +22,6 @@ */ public class MemorySPARQL11QueryComplianceTest extends SPARQL11QueryComplianceTest { - public MemorySPARQL11QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - @Override protected Repository newRepository() { return new DatasetRepository(new SailRepository(new MemoryStore())); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java index 3df69511d07..8960255393b 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/memory/MemorySPARQL11UpdateComplianceTest.java @@ -10,9 +10,6 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.memory; -import java.util.Map; - -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11UpdateComplianceTest; @@ -24,14 +21,6 @@ */ public class MemorySPARQL11UpdateComplianceTest extends SPARQL11UpdateComplianceTest { - public MemorySPARQL11UpdateComplianceTest(String displayName, String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs) { - super(displayName, testURI, name, requestFile, defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, - resultNamedGraphs); - // TODO Auto-generated constructor stub - } - @Override protected Repository newRepository() { return new SailRepository(new MemoryStore()); diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11QueryComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11QueryComplianceTest.java index 2851281fb42..6fc88fe700f 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11QueryComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11QueryComplianceTest.java @@ -10,30 +10,25 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.nativerdf; -import org.eclipse.rdf4j.query.Dataset; +import java.io.File; + import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11QueryComplianceTest; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; /** * @author jeen */ public class NativeSPARQL11QueryComplianceTest extends SPARQL11QueryComplianceTest { - public NativeSPARQL11QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; @Override protected Repository newRepository() throws Exception { - return new DatasetRepository(new SailRepository(new NativeStore(folder.newFolder(), "spoc"))); + return new DatasetRepository(new SailRepository(new NativeStore(folder, "spoc"))); } } diff --git a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11UpdateComplianceTest.java b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11UpdateComplianceTest.java index be54ec7bff3..03128de0857 100644 --- a/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11UpdateComplianceTest.java +++ b/compliance/sparql/src/test/java/org/eclipse/rdf4j/sail/nativerdf/NativeSPARQL11UpdateComplianceTest.java @@ -10,15 +10,13 @@ *******************************************************************************/ package org.eclipse.rdf4j.sail.nativerdf; -import java.util.Map; +import java.io.File; -import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.dataset.DatasetRepository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQL11UpdateComplianceTest; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; /** * Test SPARQL 1.1 Update functionality on a native store. @@ -27,19 +25,11 @@ */ public class NativeSPARQL11UpdateComplianceTest extends SPARQL11UpdateComplianceTest { - public NativeSPARQL11UpdateComplianceTest(String displayName, String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs) { - super(displayName, testURI, name, requestFile, defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, - resultNamedGraphs); - // TODO Auto-generated constructor stub - } - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; @Override protected Repository newRepository() throws Exception { - return new DatasetRepository(new SailRepository(new NativeStore(folder.newFolder(), "spoc"))); + return new DatasetRepository(new SailRepository(new NativeStore(folder, "spoc"))); } } diff --git a/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java b/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java index 46cbd1256f3..4afe05485b4 100644 --- a/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java +++ b/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java @@ -10,50 +10,14 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.algebra.geosparql; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Deque; -import java.util.List; -import org.eclipse.rdf4j.query.Dataset; import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQLQueryComplianceTest; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; -@RunWith(Parameterized.class) public abstract class GeoSPARQLManifestTest extends SPARQLQueryComplianceTest { - public GeoSPARQLManifestTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } - - private static Object[][] getTestData() { - - List tests = new ArrayList<>(); - - Deque manifests = new ArrayDeque<>(); - manifests.add( - GeoSPARQLManifestTest.class.getClassLoader() - .getResource("testcases-geosparql/functions/manifest.ttl") - .toExternalForm()); - while (!manifests.isEmpty()) { - String pop = manifests.pop(); - SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, null, false); - tests.addAll(manifest.getTests()); - manifests.addAll(manifest.getSubManifests()); - } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; + public Collection tests() { + return getTestData("testcases-geosparql/functions/manifest.ttl"); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java index 8db2c5e358b..f44b38acbd3 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/SPARQLUpdateTest.java @@ -10,12 +10,12 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.parser.sparql; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.io.InputStream; @@ -393,35 +393,34 @@ public void testInsertWhereWithBlankNode() { operation.execute(); - RepositoryResult sts = con.getStatements(bob, complexAge, null, true); + Value v1; + try (RepositoryResult sts = con.getStatements(bob, complexAge, null, true)) { - assertTrue(sts.hasNext()); + assertTrue(sts.hasNext()); - Value v1 = sts.next().getObject(); - - sts.close(); - - sts = con.getStatements(null, RDF.VALUE, null, true); + v1 = sts.next().getObject(); + } - assertTrue(sts.hasNext()); + try (RepositoryResult sts = con.getStatements(null, RDF.VALUE, null, true)) { - Value v2 = sts.next().getSubject(); + assertTrue(sts.hasNext()); - assertEquals(v1, v2); + Value v2 = sts.next().getSubject(); - sts.close(); + assertEquals(v1, v2); + } String query = getNamespaceDeclarations() + " SELECT ?bn ?age ?l WHERE { ex:bob ex:complexAge ?bn. ?bn rdf:value ?age. ?bn rdfs:label ?l .} "; - TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); + try (TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertTrue(result.hasNext()); + assertTrue(result.hasNext()); - BindingSet bs = result.next(); - - assertFalse(result.hasNext()); + BindingSet bs = result.next(); + assertFalse(result.hasNext()); + } } @Test @@ -666,10 +665,10 @@ public void testInsertWhereGraph() { operation.execute(); String message = "labels should have been inserted in corresponding named graphs only."; - assertTrue(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1)); - assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2)); - assertTrue(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph2)); - assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph1)); + assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1), message); + assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2), message); + assertTrue(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph2), message); + assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph1), message); } @Test @@ -684,10 +683,10 @@ public void testInsertWhereUsing() { operation.execute(); String message = "label should have been inserted in default graph, for ex:bob only"; - assertTrue(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true)); - assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1)); - assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2)); - assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true)); + assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true), message); + assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1), message); + assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2), message); + assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true), message); } @Test @@ -702,9 +701,9 @@ public void testInsertWhereUsingWith() { operation.execute(); String message = "label should have been inserted in graph2, for ex:bob only"; - assertTrue(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2)); - assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1)); - assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true)); + assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2), message); + assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1), message); + assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true), message); } @Test @@ -719,10 +718,10 @@ public void testInsertWhereWith() { operation.execute(); String message = "label should have been inserted in graph1 only, for ex:bob only"; - assertTrue(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1)); - assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2)); - assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph2)); - assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph1)); + assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1), message); + assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2), message); + assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph2), message); + assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true, graph1), message); } @Test @@ -740,12 +739,12 @@ public void testDeleteWhereShortcut() { operation.execute(); String msg = "foaf:name properties should have been deleted"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true), msg); msg = "foaf:knows properties should not have been deleted"; - assertTrue(msg, con.hasStatement(bob, FOAF.KNOWS, null, true)); - assertTrue(msg, con.hasStatement(alice, FOAF.KNOWS, null, true)); + assertTrue(con.hasStatement(bob, FOAF.KNOWS, null, true), msg); + assertTrue(con.hasStatement(alice, FOAF.KNOWS, null, true), msg); } @Test @@ -763,8 +762,8 @@ public void testDeleteWhere() { operation.execute(); String msg = "foaf:name properties should have been deleted"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true), msg); } @@ -783,12 +782,12 @@ public void testDeleteTransformedWhere() { operation.execute(); String msg = "foaf:name properties should have been deleted"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true), msg); msg = "ex:containsPerson properties should not have been deleted"; - assertTrue(msg, con.hasStatement(graph1, f.createIRI(EX_NS, "containsPerson"), bob, true)); - assertTrue(msg, con.hasStatement(graph2, f.createIRI(EX_NS, "containsPerson"), alice, true)); + assertTrue(con.hasStatement(graph1, f.createIRI(EX_NS, "containsPerson"), bob, true), msg); + assertTrue(con.hasStatement(graph2, f.createIRI(EX_NS, "containsPerson"), alice, true), msg); } @@ -809,8 +808,8 @@ public void testInsertData() { operation.execute(); String msg = "two new statements about ex:book1 should have been inserted"; - assertTrue(msg, con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true)); - assertTrue(msg, con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true)); + assertTrue(con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true), msg); + assertTrue(con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true), msg); } @Test @@ -830,8 +829,9 @@ public void testInsertData2() { String msg = "new statement about ex:book1 should have been inserted"; - assertTrue(msg, - con.hasStatement(book1, DC.TITLE, f.createLiteral("the number four", CoreDatatype.XSD.INTEGER), true)); + assertTrue( + con.hasStatement(book1, DC.TITLE, f.createLiteral("the number four", CoreDatatype.XSD.INTEGER), true), + msg); } @Test @@ -850,7 +850,7 @@ public void testInsertDataLangTaggedLiteral() { operation.execute(); String msg = "new statement about ex:book1 should have been inserted"; - assertTrue(msg, con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1", "en"), true)); + assertTrue(con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1", "en"), true), msg); } @Test @@ -984,9 +984,9 @@ public void testInsertDataMultiplePatterns() { operation.execute(); String msg = "newly inserted statement missing"; - assertTrue(msg, con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true)); - assertTrue(msg, con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true)); - assertTrue(msg, con.hasStatement(book2, DC.CREATOR, f.createLiteral("George"), true)); + assertTrue(con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true), msg); + assertTrue(con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true), msg); + assertTrue(con.hasStatement(book2, DC.CREATOR, f.createLiteral("George"), true), msg); } @Test @@ -1006,8 +1006,8 @@ public void testInsertDataInGraph() { operation.execute(); String msg = "two new statements about ex:book1 should have been inserted in graph1"; - assertTrue(msg, con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true, graph1)); - assertTrue(msg, con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true, graph1)); + assertTrue(con.hasStatement(book1, DC.TITLE, f.createLiteral("book 1"), true, graph1), msg); + assertTrue(con.hasStatement(book1, DC.CREATOR, f.createLiteral("Ringo"), true, graph1), msg); } @Test @@ -1042,7 +1042,7 @@ public void testDeleteData() { operation.execute(); String msg = "statement should have been deleted."; - assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true)); + assertFalse(con.hasStatement(alice, FOAF.KNOWS, bob, true), msg); } @Test @@ -1061,7 +1061,7 @@ public void testDeleteDataUnicode() { operation.execute(); String msg = "statement should have been deleted."; - assertFalse(msg, con.hasStatement(i18n, FOAF.KNOWS, bob, true)); + assertFalse(con.hasStatement(i18n, FOAF.KNOWS, bob, true), msg); } @Test @@ -1077,8 +1077,8 @@ public void testDeleteDataMultiplePatterns() { operation.execute(); String msg = "statement should have been deleted."; - assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true)); - assertFalse(msg, con.hasStatement(alice, FOAF.MBOX, f.createLiteral("alice@example.org"), true)); + assertFalse(con.hasStatement(alice, FOAF.KNOWS, bob, true), msg); + assertFalse(con.hasStatement(alice, FOAF.MBOX, f.createLiteral("alice@example.org"), true), msg); } @Test @@ -1094,7 +1094,7 @@ public void testDeleteDataFromGraph() { operation.execute(); String msg = "statement should have been deleted from graph1"; - assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1)); + assertFalse(con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1), msg); } @Test @@ -1113,7 +1113,7 @@ public void testDeleteDataFromWrongGraph() { operation.execute(); String msg = "statement should have not have been deleted from graph1"; - assertTrue(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1)); + assertTrue(con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1), msg); } @Test @@ -1528,12 +1528,12 @@ public void testUpdateSequenceDeleteInsert() { operation.execute(); String msg = "foaf:name properties should have been deleted"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true), msg); msg = "foaf:name properties with value 'foo' should have been added"; - assertTrue(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true)); - assertTrue(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true)); + assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true), msg); + assertTrue(con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true), msg); } @Test @@ -1553,12 +1553,12 @@ public void testUpdateSequenceInsertDelete() { operation.execute(); String msg = "foaf:name properties should have been deleted"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true), msg); msg = "foaf:name properties with value 'foo' should not have been added"; - assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true)); - assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true)); + assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true), msg); + assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true), msg); } @Test @@ -1578,12 +1578,12 @@ public void testUpdateSequenceInsertDelete2() { operation.execute(); String msg = "statements about bob should have been removed from graph1"; - assertFalse(msg, con.hasStatement(bob, null, null, true, graph1)); + assertFalse(con.hasStatement(bob, null, null, true, graph1), msg); msg = "statements about bob should have been added to graph2"; - assertTrue(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true, graph2)); - assertTrue(msg, con.hasStatement(bob, FOAF.MBOX, null, true, graph2)); - assertTrue(msg, con.hasStatement(bob, FOAF.KNOWS, alice, true, graph2)); + assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true, graph2), msg); + assertTrue(con.hasStatement(bob, FOAF.MBOX, null, true, graph2), msg); + assertTrue(con.hasStatement(bob, FOAF.KNOWS, alice, true, graph2), msg); } @Test @@ -1626,12 +1626,12 @@ public void testUpdateSequenceInsertDeleteExample9() throws Exception { operation.execute(); String msg = "statements about book1 should have been removed from bookStore"; - assertFalse(msg, con.hasStatement(book1, null, null, true, bookStore)); + assertFalse(con.hasStatement(book1, null, null, true, bookStore), msg); msg = "statements about book1 should have been added to bookStore2"; - assertTrue(msg, con.hasStatement(book1, RDF.TYPE, null, true, bookStore2)); - assertTrue(msg, con.hasStatement(book1, DC.DATE, null, true, bookStore2)); - assertTrue(msg, con.hasStatement(book1, DC.TITLE, null, true, bookStore2)); + assertTrue(con.hasStatement(book1, RDF.TYPE, null, true, bookStore2), msg); + assertTrue(con.hasStatement(book1, DC.DATE, null, true, bookStore2), msg); + assertTrue(con.hasStatement(book1, DC.TITLE, null, true, bookStore2), msg); } @Test @@ -1678,8 +1678,8 @@ public void contextualInsertDeleteData() updDelete.execute(); String msg = "statement should have been deleted."; - assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true, graph2)); - assertFalse(msg, con.hasStatement(alice, FOAF.MBOX, f.createLiteral("alice@example.org"), true, graph2)); + assertFalse(con.hasStatement(alice, FOAF.KNOWS, bob, true, graph2), msg); + assertFalse(con.hasStatement(alice, FOAF.MBOX, f.createLiteral("alice@example.org"), true, graph2), msg); } @Test diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10ManifestTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10ManifestTest.java deleted file mode 100644 index d3f74ebbaff..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10ManifestTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 Eclipse RDF4J contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.JarURLConnection; -import java.net.URL; -import java.nio.file.Files; -import java.util.Objects; -import java.util.jar.JarFile; - -import org.eclipse.rdf4j.common.io.FileUtil; -import org.eclipse.rdf4j.common.io.ZipUtil; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.util.RDFInserter; -import org.eclipse.rdf4j.rio.RDFHandlerException; -import org.eclipse.rdf4j.rio.RDFParseException; -import org.eclipse.rdf4j.rio.RDFParser; -import org.eclipse.rdf4j.rio.turtle.TurtleParser; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestResult; -import junit.framework.TestSuite; - -@Deprecated -public class SPARQL10ManifestTest { - - static final Logger logger = LoggerFactory.getLogger(SPARQL10ManifestTest.class); - - private static final boolean REMOTE = false; - - public static TestSuite suite(SPARQLQueryTest.Factory factory) throws Exception { - final String manifestFile; - final File tmpDir; - - if (REMOTE) { - manifestFile = "http://www.w3.org/2001/sw/DataAccess/tests/data-r2/manifest-evaluation.ttl"; - tmpDir = null; - } else { - URL url = SPARQL10ManifestTest.class - .getResource("/testcases-sparql-1.0-w3c/data-r2/manifest-evaluation.ttl"); - - if ("jar".equals(url.getProtocol())) { - // Extract manifest files to a temporary directory - try { - tmpDir = Files.createTempDirectory("sparql-evaluation").toFile(); - - JarURLConnection con = (JarURLConnection) url.openConnection(); - JarFile jar = con.getJarFile(); - - ZipUtil.extract(jar, tmpDir); - - File localFile = new File(tmpDir, con.getEntryName()); - manifestFile = localFile.toURI().toURL().toString(); - } catch (IOException e) { - throw new AssertionError(e); - } - } else { - manifestFile = url.toString(); - tmpDir = null; - } - } - - TestSuite suite = new TestSuite(factory.getClass().getName()) { - - @Override - public void run(TestResult result) { - try { - super.run(result); - } finally { - if (tmpDir != null) { - try { - FileUtil.deleteDir(tmpDir); - } catch (IOException e) { - System.err.println( - "Unable to clean up temporary directory '" + tmpDir + "': " + e.getMessage()); - } - } - } - } - }; - - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - addTurtle(con, new URL(manifestFile), manifestFile); - - String query = "" - + "PREFIX mf: \n " - + "PRFIX qt: " - + "SELECT DISTINCT ?manifestFile\n" - + "WHERE { ?x rdf:first ?manifestFile .} "; - - TupleQueryResult manifestResults = con.prepareTupleQuery(QueryLanguage.SPARQL, query, manifestFile) - .evaluate(); - - while (manifestResults.hasNext()) { - BindingSet bindingSet = manifestResults.next(); - String subManifestFile = bindingSet.getValue("manifestFile").stringValue(); - suite.addTest(SPARQLQueryTest.suite(subManifestFile, factory)); - } - - manifestResults.close(); - } - manifestRep.shutDown(); - - logger.info("Created aggregated test suite with " + suite.countTestCases() + " test cases."); - return suite; - } - - static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts) - throws IOException, RepositoryException, RDFParseException, RDFHandlerException { - Objects.requireNonNull(contexts, - "contexts argument may not be null; either the value should be cast to Resource or an empty array should be supplied"); - if (baseURI == null) { - baseURI = url.toExternalForm(); - } - - try (InputStream in = url.openStream()) { - final ValueFactory vf = con.getRepository().getValueFactory(); - RDFParser rdfParser = new TurtleParser(); - rdfParser.setValueFactory(vf); - - RDFInserter rdfInserter = new RDFInserter(con); - rdfInserter.enforceContext(contexts); - rdfParser.setRDFHandler(rdfInserter); - - con.begin(); - - try { - rdfParser.parse(in, baseURI); - con.commit(); - } catch (RDFHandlerException e) { - if (con.isActive()) { - con.rollback(); - } - if (e.getCause() != null && e.getCause() instanceof RepositoryException) { - // RDFInserter only throws wrapped RepositoryExceptions - throw (RepositoryException) e.getCause(); - } else { - throw e; - } - - } catch (RuntimeException e) { - if (con.isActive()) { - con.rollback(); - } - throw e; - } - } - } -} diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java index c424c451cf5..662996c185e 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java @@ -10,17 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; -import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Deque; import java.util.List; -import org.eclipse.rdf4j.query.Dataset; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; /** * A test suite that runs the W3C Approved SPARQL 1.0 query tests. @@ -29,74 +23,35 @@ * * @see sparql docs test */ -@RunWith(Parameterized.class) public abstract class SPARQL10QueryComplianceTest extends SPARQLQueryComplianceTest { - private static final String[] defaultIgnoredTests = { - // incompatible with SPARQL 1.1 - syntax for decimals was modified - "Basic - Term 6", - // incompatible with SPARQL 1.1 - syntax for decimals was modified - "Basic - Term 7", - // Test is incorrect: assumes timezoned date is comparable with non-timezoned - "date-2", - // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are identical - "Strings: Distinct", - // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are identical - "All: Distinct", - // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are identical - "SELECT REDUCED ?x with strings" + private final List defaultIgnoredTests = new ArrayList<>(); + { + // incompatible with SPARQL 1.1 - syntax for decimals was modified + defaultIgnoredTests.add("Basic - Term 6"); + // incompatible with SPARQL 1.1 - syntax for decimals was modified + defaultIgnoredTests.add("Basic - Term 7"); + // Test is incorrect: assumes timezoned date is comparable with non-timezoned + defaultIgnoredTests.add("date-2"); + // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are + // identical + defaultIgnoredTests.add("Strings: Distinct"); + // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are + // identical + defaultIgnoredTests.add("All: Distinct"); + // Incompatible with SPARQL 1.1 - string-typed literals and plain literals are + // identical + defaultIgnoredTests.add("SELECT REDUCED ?x with strings"); }; - private static final List excludedSubdirs = List.of("service"); - - /** - * @param displayName - * @param testURI - * @param name - * @param queryFileURL - * @param resultFileURL - * @param dataset - * @param ordered - */ - public SPARQL10QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); + public SPARQL10QueryComplianceTest() { + super(List.of("service")); for (String defaultIgnoredTest : defaultIgnoredTests) { addIgnoredTest(defaultIgnoredTest); } } - private static Object[][] getTestData() { - - List tests = new ArrayList<>(); - - Deque manifests = new ArrayDeque<>(); - manifests.add( - SPARQL10QueryComplianceTest.class.getClassLoader() - .getResource("testcases-sparql-1.0-w3c/data-r2/manifest-evaluation.ttl") - .toExternalForm()); - while (!manifests.isEmpty()) { - String pop = manifests.pop(); - SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs); - tests.addAll(manifest.getTests()); - manifests.addAll(manifest.getSubManifests()); - } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; + public Collection tests() { + return getTestData("testcases-sparql-1.0-w3c/data-r2/manifest-evaluation.ttl"); } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11ManifestTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11ManifestTest.java deleted file mode 100644 index 44eba2dc6cd..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11ManifestTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Objects; - -import org.eclipse.rdf4j.common.io.FileUtil; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.util.RDFInserter; -import org.eclipse.rdf4j.rio.RDFHandlerException; -import org.eclipse.rdf4j.rio.RDFParseException; -import org.eclipse.rdf4j.rio.RDFParser; -import org.eclipse.rdf4j.rio.turtle.TurtleParser; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestResult; -import junit.framework.TestSuite; - -/** - * Functionality for creating a JUnit test suite out of a W3C Working Group-style manifest for SPARQL query and update - * tests. - * - * @author Jeen Broekstra - */ -@Deprecated -public class SPARQL11ManifestTest { - - static final Logger logger = LoggerFactory.getLogger(SPARQL11ManifestTest.class); - - private static File tmpDir; - - /** - * Creates a new {@link TestSuite} for execution of {@link SPARQLQueryTest} s. - * - * @param factory a factory class that creates each individual test case. - * @param manifestFile url of the manifest file (may be remote or local). - * @param approvedTestsOnly if true, use working group-approved tests only. - * @param excludedSubdirs an (optionally empty) list of subdirectories to exclude from testing. If specified, test - * cases in one of the supplied subdirs will not be executed. If left empty, all tests will - * be executed. - * @return a TestSuite. - * @throws Exception - */ - public static TestSuite suite(SPARQLQueryTest.Factory factory, String manifestFile, - boolean approvedTestsOnly, String... excludedSubdirs) throws Exception { - TestSuite suite = new TestSuite(factory.getClass().getName()) { - - @Override - public void run(TestResult result) { - try { - super.run(result); - } finally { - if (tmpDir != null) { - try { - FileUtil.deleteDir(tmpDir); - } catch (IOException e) { - System.err.println( - "Unable to clean up temporary directory '" + tmpDir + "': " + e.getMessage()); - } - } - } - } - }; - - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - addTurtle(con, new URL(manifestFile), manifestFile); - - String query = " PREFIX qt: " - + "PREFIX mf: " - + "SELECT DISTINCT ?manifestFile " - + "WHERE { [] mf:include [ rdf:rest*/rdf:first ?manifestFile ] . } "; - - TupleQueryResult manifestResults = con.prepareTupleQuery(QueryLanguage.SPARQL, query, manifestFile) - .evaluate(); - - for (BindingSet bindingSet : manifestResults) { - String subManifestFile = bindingSet.getValue("manifestFile").stringValue(); - - if (includeSubManifest(subManifestFile, excludedSubdirs)) { - suite.addTest(SPARQLQueryTest.suite(subManifestFile, factory, approvedTestsOnly)); - } - } - } - manifestRep.shutDown(); - - logger.info("Created aggregated test suite with " + suite.countTestCases() + " test cases."); - return suite; - } - - /** - * Creates a new {@link TestSuite} for execution of {@link SPARQLUpdateConformanceTest} s. - * - * @param factory a factory class that creates each individual test case. - * @param manifestFile url of the manifest file (may be remote or local). - * @param approvedTestsOnly if true, use working group-approved tests only. - * @param excludedSubdirs an (optionally empty) list of subdirectories to exclude from testing. If specified, test - * cases in one of the supplied subdirs will not be executed. If left empty, all tests will - * be executed. - * @return a TestSuite. - * @throws Exception - */ - public static TestSuite suite(SPARQLUpdateConformanceTest.Factory factory, String manifestFile, - boolean approvedTestsOnly, String... excludedSubdirs) throws Exception { - - TestSuite suite = new TestSuite(factory.getClass().getName()) { - - @Override - public void run(TestResult result) { - try { - super.run(result); - } finally { - if (tmpDir != null) { - try { - FileUtil.deleteDir(tmpDir); - } catch (IOException e) { - System.err.println( - "Unable to clean up temporary directory '" + tmpDir + "': " + e.getMessage()); - } - } - } - } - }; - - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - addTurtle(con, new URL(manifestFile), manifestFile); - - String query = " PREFIX qt: " - + "PREFIX mf: " - + "SELECT DISTINCT ?manifestFile " - + "WHERE { [] mf:include [ rdf:rest*/rdf:first ?manifestFile ] . } "; - - TupleQueryResult manifestResults = con.prepareTupleQuery(QueryLanguage.SPARQL, query, manifestFile) - .evaluate(); - - for (BindingSet bindingSet : manifestResults) { - String subManifestFile = bindingSet.getValue("manifestFile").stringValue(); - - if (includeSubManifest(subManifestFile, excludedSubdirs)) { - suite.addTest(SPARQLUpdateConformanceTest.suite(subManifestFile, factory, approvedTestsOnly)); - } - } - } - manifestRep.shutDown(); - - logger.info("Created aggregated test suite with " + suite.countTestCases() + " test cases."); - return suite; - } - - /** - * Verifies if the selected subManifest occurs in the supplied list of excluded subdirs. - * - * @param subManifestFile the url of a sub-manifest - * @param excludedSubdirs an array of directory names. May be null. - * @return false if the supplied list of excluded subdirs is not empty and contains a match for the - * supplied sub-manifest, true otherwise. - */ - private static boolean includeSubManifest(String subManifestFile, String[] excludedSubdirs) { - boolean result = true; - - if (excludedSubdirs != null && excludedSubdirs.length > 0) { - int index = subManifestFile.lastIndexOf('/'); - String path = subManifestFile.substring(0, index); - String sd = path.substring(path.lastIndexOf('/') + 1); - - for (String subdir : excludedSubdirs) { - if (sd.equals(subdir)) { - result = false; - break; - } - } - } - return result; - } - - static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts) - throws IOException, RepositoryException, RDFParseException { - if (baseURI == null) { - baseURI = url.toExternalForm(); - } - - try (InputStream in = url.openStream()) { - Objects.requireNonNull(contexts, - "contexts argument may not be null; either the value should be cast to Resource or an empty array should be supplied"); - final ValueFactory vf = con.getRepository().getValueFactory(); - RDFParser rdfParser = new TurtleParser(); - rdfParser.setValueFactory(vf); - - RDFInserter rdfInserter = new RDFInserter(con); - rdfInserter.enforceContext(contexts); - rdfParser.setRDFHandler(rdfInserter); - - con.begin(); - try { - rdfParser.parse(in, baseURI); - con.commit(); - } catch (RDFHandlerException e) { - con.rollback(); - // RDFInserter only throws wrapped RepositoryExceptions - throw (RepositoryException) e.getCause(); - } catch (RuntimeException e) { - con.rollback(); - } - } - } -} diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11QueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11QueryComplianceTest.java index e54bb811d93..d8281fdd503 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11QueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11QueryComplianceTest.java @@ -10,18 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; -import java.net.URL; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Deque; import java.util.List; -import org.eclipse.rdf4j.query.Dataset; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; /** * A test suite that runs the W3C Approved SPARQL 1.1 query tests. @@ -30,9 +23,14 @@ * * @see sparql docs tests */ -@RunWith(Parameterized.class) public abstract class SPARQL11QueryComplianceTest extends SPARQLQueryComplianceTest { + public SPARQL11QueryComplianceTest() { + super(List.of("service")); + for (String ig : defaultIgnoredTests) + addIgnoredTest(ig); + } + private static final String[] defaultIgnoredTests = { // test case incompatible with RDF 1.1 - see // http://lists.w3.org/Archives/Public/public-sparql-dev/2013AprJun/0006.html @@ -41,51 +39,10 @@ public abstract class SPARQL11QueryComplianceTest extends SPARQLQueryComplianceT // http://lists.w3.org/Archives/Public/public-sparql-dev/2013AprJun/0006.html "STRLANG() TypeErrors", // known issue: SES-937 - "sq03 - Subquery within graph pattern, graph variable is not bound" - }; - - private static final List excludedSubdirs = List.of("service"); - - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } - - protected static Object[][] getTestData() { - List tests = new ArrayList<>(); - - Deque manifests = new ArrayDeque<>(); - manifests.add(getManifestURL().toExternalForm()); - while (!manifests.isEmpty()) { - String pop = manifests.pop(); - SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs); - tests.addAll(manifest.getTests()); - manifests.addAll(manifest.getSubManifests()); - } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); + "sq03 - Subquery within graph pattern, graph variable is not bound" }; - return result; + @TestFactory + public Collection tests() { + return getTestData("testcases-sparql-1.1-w3c/manifest-all.ttl"); } - - protected static URL getManifestURL() { - return SPARQL11QueryComplianceTest.class.getClassLoader() - .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl"); - } - - public SPARQL11QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - for (String defaultIgnoredTest : defaultIgnoredTests) { - addIgnoredTest(defaultIgnoredTest); - } - } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxComplianceTest.java index ba4fd6721b9..721753ed157 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxComplianceTest.java @@ -10,18 +10,8 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Deque; -import java.util.List; - import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.parser.ParsedOperation; -import org.eclipse.rdf4j.repository.Repository; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; /** * A test suite that runs the W3C Approved SPARQL 1.1 Syntax tests. @@ -30,47 +20,9 @@ * * @see sparql docs tests */ -@RunWith(Parameterized.class) -public abstract class SPARQL11SyntaxComplianceTest extends SPARQLSyntaxComplianceTest { - - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } - - public SPARQL11SyntaxComplianceTest(String displayName, String testURI, String name, String queryFileURL, - boolean positiveTest) { - super(displayName, testURI, name, queryFileURL, positiveTest); - } - - private static Object[][] getTestData() { - - List tests = new ArrayList<>(); - Deque manifests = new ArrayDeque<>(); - manifests.add( - SPARQL11SyntaxComplianceTest.class.getClassLoader() - .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") - .toExternalForm()); - while (!manifests.isEmpty()) { - String pop = manifests.pop(); - SPARQLSyntaxManifest manifest = new SPARQLSyntaxManifest(pop); - tests.addAll(manifest.tests); - manifests.addAll(manifest.subManifests); - } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; - } +public abstract class SPARQL11SyntaxComplianceTest extends SPARQLSyntaxComplianceTest { @Override protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException; - - @Override - protected Repository getDataRepository() { - return null; // not needed in syntax tests - } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java deleted file mode 100644 index 0eb9d8c7afe..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11SyntaxTest.java +++ /dev/null @@ -1,307 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.JarURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import org.eclipse.rdf4j.common.io.FileUtil; -import org.eclipse.rdf4j.common.io.IOUtil; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.query.algebra.DeleteData; -import org.eclipse.rdf4j.query.algebra.InsertData; -import org.eclipse.rdf4j.query.algebra.UpdateExpr; -import org.eclipse.rdf4j.query.parser.ParsedOperation; -import org.eclipse.rdf4j.query.parser.ParsedUpdate; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.sail.helpers.SailUpdateExecutor; -import org.eclipse.rdf4j.rio.RDFParseException; -import org.eclipse.rdf4j.sail.NotifyingSailConnection; -import org.eclipse.rdf4j.sail.SailException; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestResult; -import junit.framework.TestSuite; - -/** - * A SPARQL 1.1 syntax test, created by reading in a W3C working-group style manifest. - * - * @author Jeen Broekstra - * @deprecated Use {@link SPARQL11SyntaxComplianceTest} instead. - */ -@Deprecated(since = "3.3.0") -public abstract class SPARQL11SyntaxTest extends TestCase { - - /*-----------* - * Constants * - *-----------*/ - - private static final Logger logger = LoggerFactory.getLogger(SPARQL11SyntaxTest.class); - - private static final String SUBMANIFEST_QUERY, TESTCASE_QUERY; - - static { - StringBuilder sb = new StringBuilder(512); - - sb.append("PREFIX mf: "); - sb.append("PREFIX qt: "); - sb.append("SELECT ?subManifest "); - sb.append("WHERE { [] mf:include [ rdf:rest*/rdf:first ?subManifest ] . } "); - SUBMANIFEST_QUERY = sb.toString(); - - sb.setLength(0); - sb.append("PREFIX mf: "); - sb.append("PREFIX qt: "); - sb.append("PREFIX dawgt: "); - sb.append("SELECT ?TestURI ?Name ?Action ?Type "); - sb.append("WHERE { [] rdf:first ?TestURI. "); - sb.append(" ?TestURI a ?Type ; "); - sb.append(" mf:name ?Name ;"); - sb.append(" mf:action ?Action ;"); - sb.append(" dawgt:approval dawgt:Approved . "); - sb.append( - " FILTER(?Type IN (mf:PositiveSyntaxTest11, mf:NegativeSyntaxTest11, mf:PositiveUpdateSyntaxTest11, mf:NegativeUpdateSyntaxTest11)) "); - sb.append(" } "); - TESTCASE_QUERY = sb.toString(); - } - - /*-----------* - * Variables * - *-----------*/ - - protected final String testURI; - - protected final String queryFileURL; - - protected final boolean positiveTest; - - /*--------------* - * Constructors * - *--------------*/ - - public SPARQL11SyntaxTest(String testURI, String name, String queryFileURL, boolean positiveTest) { - super(name); - this.testURI = testURI; - this.queryFileURL = queryFileURL; - this.positiveTest = positiveTest; - } - - /*---------* - * Methods * - *---------*/ - - @Override - protected void runTest() throws Exception { - InputStream stream = new URL(queryFileURL).openStream(); - String query = IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - stream.close(); - - try { - ParsedOperation operation = parseOperation(query, queryFileURL); - - if (!positiveTest) { - boolean dataBlockUpdate = false; - if (operation instanceof ParsedUpdate) { - for (UpdateExpr updateExpr : ((ParsedUpdate) operation).getUpdateExprs()) { - if (updateExpr instanceof InsertData || updateExpr instanceof DeleteData) { - // parsing for these operation happens during actual - // execution, so try and execute. - dataBlockUpdate = true; - - MemoryStore store = new MemoryStore(); - store.init(); - NotifyingSailConnection conn = store.getConnection(); - try { - conn.begin(); - SailUpdateExecutor exec = new SailUpdateExecutor(conn, store.getValueFactory(), null); - exec.executeUpdate(updateExpr, null, null, true, -1); - conn.rollback(); - fail("Negative test case should have failed to parse"); - } catch (SailException e) { - if (!(e.getCause() instanceof RDFParseException)) { - logger.error("unexpected error in negative test case", e); - fail("unexpected error in negative test case"); - } - // fall through - a parse exception is expected for a - // negative test case - conn.rollback(); - } finally { - conn.close(); - } - } - } - } - if (!dataBlockUpdate) { - fail("Negative test case should have failed to parse"); - } - } - } catch (MalformedQueryException e) { - if (positiveTest) { - e.printStackTrace(); - fail("Positive test case failed: " + e.getMessage()); - } - } - } - - protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException; - - public static Test suite() { - return new TestSuite(); - } - - public interface Factory { - - SPARQL11SyntaxTest createSPARQLSyntaxTest(String testURI, String testName, String testAction, - boolean positiveTest); - } - - public static Test suite(Factory factory, boolean useRemote) throws Exception { - // manifest of W3C Data Access Working Group SPARQL syntax tests - final File tmpDir; - String host; - if (useRemote) { - host = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/"; - tmpDir = null; - } else { - URL url = SPARQL11SyntaxTest.class.getResource("/testcases-sparql-1.1-w3c/"); - if ("jar".equals(url.getProtocol())) { - try { - tmpDir = Files.createTempDirectory("sparql-syntax").toFile(); - JarURLConnection con = (JarURLConnection) url.openConnection(); - JarFile jar = con.getJarFile(); - Enumeration entries = jar.entries(); - while (entries.hasMoreElements()) { - JarEntry file = entries.nextElement(); - File f = new File(tmpDir + File.separator + file.getName()); - if (file.isDirectory()) { - f.mkdir(); - continue; - } - InputStream is = jar.getInputStream(file); - try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(f))) { - while (is.available() > 0) { - fos.write(is.read()); - } - } - is.close(); - } - File localFile = new File(tmpDir, con.getEntryName()); - host = localFile.toURI().toURL().toString(); - } catch (IOException e) { - throw new AssertionError(e); - } - } else { - host = url.toString(); - tmpDir = null; - } - } - - String manifestFile = host + "manifest-all.ttl"; - - TestSuite suite = new TestSuite() { - - @Override - public void run(TestResult result) { - try { - super.run(result); - } finally { - if (tmpDir != null) { - try { - FileUtil.deleteDir(tmpDir); - } catch (IOException e) { - System.err.println( - "Unable to clean up temporary directory '" + tmpDir + "': " + e.getMessage()); - } - } - } - } - }; - - // Read manifest and create declared test cases - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - logger.debug("Loading manifest data"); - URL manifest = new URL(manifestFile); - SPARQL11ManifestTest.addTurtle(con, manifest, manifestFile); - - logger.info("Searching for sub-manifests"); - List subManifestList = new ArrayList<>(); - - TupleQueryResult subManifests = con.prepareTupleQuery(QueryLanguage.SPARQL, SUBMANIFEST_QUERY).evaluate(); - while (subManifests.hasNext()) { - BindingSet bindings = subManifests.next(); - subManifestList.add(bindings.getValue("subManifest").toString()); - } - subManifests.close(); - - logger.info("Found {} sub-manifests", subManifestList.size()); - - for (String subManifest : subManifestList) { - logger.info("Loading sub manifest {}", subManifest); - con.clear(); - - URL subManifestURL = new URL(subManifest); - SPARQL11ManifestTest.addTurtle(con, subManifestURL, subManifest); - - TestSuite subSuite = new TestSuite(subManifest.substring(host.length())); - - logger.info("Creating test cases for {}", subManifest); - TupleQueryResult tests = con.prepareTupleQuery(QueryLanguage.SPARQL, TESTCASE_QUERY).evaluate(); - while (tests.hasNext()) { - BindingSet bindingSet = tests.next(); - - String testURI = bindingSet.getValue("TestURI").toString(); - String testName = bindingSet.getValue("Name").toString(); - String testAction = bindingSet.getValue("Action").toString(); - - String type = bindingSet.getValue("Type").toString(); - boolean positiveTest = type - .equals("http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveSyntaxTest11") - || type.equals( - "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveUpdateSyntaxTest11"); - - subSuite.addTest(factory.createSPARQLSyntaxTest(testURI, testName, testAction, positiveTest)); - } - tests.close(); - - suite.addTest(subSuite); - } - } - manifestRep.shutDown(); - - logger.info("Added {} tests to suite ", suite.countTestCases()); - return suite; - } -} diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java index 91d092aa503..8f62db4c39a 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL11UpdateComplianceTest.java @@ -19,7 +19,6 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.HashMap; @@ -47,10 +46,8 @@ import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.junit.After; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,7 +57,6 @@ * @author Jeen Broekstra * @see sparql docs tests */ -@RunWith(Parameterized.class) public abstract class SPARQL11UpdateComplianceTest extends SPARQLComplianceTest { private static final Logger logger = LoggerFactory.getLogger(SPARQL11UpdateComplianceTest.class); @@ -78,109 +74,172 @@ public abstract class SPARQL11UpdateComplianceTest extends SPARQLComplianceTest private static final List excludedSubdirs = List.of("service"); - private String queryFileURL; - private String resultFileURL; - private final Dataset dataset; - private boolean ordered; - private Repository dataRep; - protected Repository expectedResultRepo; - private final String requestFile; + public SPARQL11UpdateComplianceTest() { - private final IRI inputDefaultGraphURI; + } - private final Map inputNamedGraphs; + protected class DynamicSPARQL11UpdateComplianceTest extends DynamicSparqlComplianceTest { + private String queryFileURL; + private String resultFileURL; + private final Dataset dataset; + private boolean ordered; + private Repository dataRep; + private final String requestFile; + + private final IRI inputDefaultGraphURI; + + private final Map inputNamedGraphs; + + private final IRI resultDefaultGraphURI; + + private final Map resultNamedGraphs; + + public DynamicSPARQL11UpdateComplianceTest(String displayName, String testURI, String name, String requestFile, + IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, + Map resultNamedGraphs) { + super(displayName, testURI, name); + this.requestFile = requestFile; + this.inputDefaultGraphURI = defaultGraphURI; + this.inputNamedGraphs = inputNamedGraphs; + this.resultDefaultGraphURI = resultDefaultGraphURI; + this.resultNamedGraphs = resultNamedGraphs; + + final SimpleDataset ds = new SimpleDataset(); + + // This ensures that the repository operates in 'exclusive + // mode': the default graph _only_ consists of the null-context (instead + // of the entire repository). + ds.addDefaultGraph(null); + ds.addDefaultRemoveGraph(null); + ds.setDefaultInsertGraph(null); + + if (this.inputNamedGraphs.size() > 0) { + for (String ng : inputNamedGraphs.keySet()) { + IRI namedGraph = SimpleValueFactory.getInstance().createIRI(ng); + ds.addNamedGraph(namedGraph); + } + } + this.dataset = ds; + } - private final IRI resultDefaultGraphURI; + @Override + protected Repository getDataRepository() { + return this.dataRep; + } - private final Map resultNamedGraphs; + @Override + protected final void runTest() throws Exception { - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } + logger.debug("running {}", getName()); - public SPARQL11UpdateComplianceTest(String displayName, String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs) { - super(displayName, testURI, name); - this.requestFile = requestFile; - this.inputDefaultGraphURI = defaultGraphURI; - this.inputNamedGraphs = inputNamedGraphs; - this.resultDefaultGraphURI = resultDefaultGraphURI; - this.resultNamedGraphs = resultNamedGraphs; - - final SimpleDataset ds = new SimpleDataset(); - - // This ensures that the repository operates in 'exclusive - // mode': the default graph _only_ consists of the null-context (instead - // of the entire repository). - ds.addDefaultGraph(null); - ds.addDefaultRemoveGraph(null); - ds.setDefaultInsertGraph(null); - - if (this.inputNamedGraphs.size() > 0) { - for (String ng : inputNamedGraphs.keySet()) { - IRI namedGraph = SimpleValueFactory.getInstance().createIRI(ng); - ds.addNamedGraph(namedGraph); - } - } - this.dataset = ds; - } + RepositoryConnection con = dataRep.getConnection(); + RepositoryConnection erCon = expectedResultRepo.getConnection(); + try { + String updateString = readUpdateString(); + + con.begin(); + + Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFile); + + assertThatNoException().isThrownBy(() -> { + int hashCode = update.hashCode(); + if (hashCode == System.identityHashCode(update)) { + throw new UnsupportedOperationException( + "hashCode() result is the same as the identityHashCode in " + + update.getClass().getName()); + } + }); + + update.setDataset(dataset); + update.execute(); - @Before - public void setUp() throws Exception { - dataRep = createRepository(); + con.commit(); - try (RepositoryConnection conn = dataRep.getConnection()) { - conn.clear(); + // check default graph + logger.info("checking default graph"); + compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, (Resource) null)), + Iterations.asList(erCon.getStatements(null, null, null, true, (Resource) null))); - if (inputDefaultGraphURI != null) { - URL graphURL = new URL(inputDefaultGraphURI.stringValue()); - conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); + for (String namedGraph : inputNamedGraphs.keySet()) { + logger.info("checking named graph {}", namedGraph); + IRI contextURI = con.getValueFactory().createIRI(namedGraph.replaceAll("\"", "")); + compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, contextURI)), + Iterations.asList(erCon.getStatements(null, null, null, true, contextURI))); + } + } catch (Exception e) { + if (con.isActive()) { + con.rollback(); + } + throw e; + } finally { + con.close(); + erCon.close(); } + } - for (String ng : inputNamedGraphs.keySet()) { - URL graphURL = new URL(inputNamedGraphs.get(ng).stringValue()); - conn.add(graphURL, null, - Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), - dataRep.getValueFactory().createIRI(ng)); + private String readUpdateString() throws IOException { + try (InputStream stream = new URL(requestFile).openStream()) { + return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); } } - expectedResultRepo = createRepository(); + @Override + public void setUp() throws Exception { + dataRep = createRepository(); + + try (RepositoryConnection conn = dataRep.getConnection()) { + conn.clear(); - try (RepositoryConnection conn = expectedResultRepo.getConnection()) { - conn.clear(); + if (inputDefaultGraphURI != null) { + URL graphURL = new URL(inputDefaultGraphURI.stringValue()); + conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) + .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); + } - if (resultDefaultGraphURI != null) { - URL graphURL = new URL(resultDefaultGraphURI.stringValue()); - conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); + for (String ng : inputNamedGraphs.keySet()) { + URL graphURL = new URL(inputNamedGraphs.get(ng).stringValue()); + conn.add(graphURL, null, + Rio.getParserFormatForFileName(graphURL.toString()) + .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), + dataRep.getValueFactory().createIRI(ng)); + } } - for (String ng : resultNamedGraphs.keySet()) { - URL graphURL = new URL(resultNamedGraphs.get(ng).stringValue()); - conn.add(graphURL, null, - Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), - dataRep.getValueFactory().createIRI(ng)); + expectedResultRepo = createRepository(); + + try (RepositoryConnection conn = expectedResultRepo.getConnection()) { + conn.clear(); + + if (resultDefaultGraphURI != null) { + URL graphURL = new URL(resultDefaultGraphURI.stringValue()); + conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) + .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); + } + + for (String ng : resultNamedGraphs.keySet()) { + URL graphURL = new URL(resultNamedGraphs.get(ng).stringValue()); + conn.add(graphURL, null, + Rio.getParserFormatForFileName(graphURL.toString()) + .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), + dataRep.getValueFactory().createIRI(ng)); + } } } - } - @After - public void tearDown() { - if (dataRep != null) { - dataRep.shutDown(); - dataRep = null; - } - if (expectedResultRepo != null) { - expectedResultRepo.shutDown(); - expectedResultRepo = null; + @Override + public void tearDown() throws Exception { + if (dataRep != null) { + clear(dataRep); + dataRep.shutDown(); + dataRep = null; + } + if (expectedResultRepo != null) { + clear(expectedResultRepo); + expectedResultRepo.shutDown(); + expectedResultRepo = null; + } } } @@ -195,20 +254,15 @@ private Repository createRepository() throws Exception { protected abstract Repository newRepository() throws Exception; - @Override - protected Repository getDataRepository() { - return this.dataRep; - } - - private static Object[][] getTestData() { + @TestFactory + public Collection getTestData() { - List tests = new ArrayList<>(); + List tests = new ArrayList<>(); Deque manifests = new ArrayDeque<>(); - manifests.add( - SPARQL11UpdateComplianceTest.class.getClassLoader() - .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") - .toExternalForm()); + manifests.add(SPARQL11UpdateComplianceTest.class.getClassLoader() + .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") + .toExternalForm()); while (!manifests.isEmpty()) { String pop = manifests.pop(); SPARQLUpdateTestManifest manifest = new SPARQLUpdateTestManifest(pop); @@ -216,14 +270,11 @@ private static Object[][] getTestData() { manifests.addAll(manifest.subManifests); } - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; + return tests; } - static class SPARQLUpdateTestManifest { - List tests = new ArrayList<>(); + class SPARQLUpdateTestManifest { + List tests = new ArrayList<>(); List subManifests = new ArrayList<>(); public SPARQLUpdateTestManifest(String filename) { @@ -284,10 +335,9 @@ public SPARQLUpdateTestManifest(String filename) { for (BindingSet bs : result) { // FIXME I'm sure there's a neater way to do this String testName = bs.getValue("testName").stringValue(); - String displayName = filename.substring( - filename.lastIndexOf("testcases-sparql-1.1-w3c/") - + "testcases-sparql-1.1-w3c/".length(), - filename.lastIndexOf("/")) + String displayName = filename + .substring(filename.lastIndexOf("testcases-sparql-1.1-w3c/") + + "testcases-sparql-1.1-w3c/".length(), filename.lastIndexOf("/")) + ": " + testName; IRI testURI = (IRI) bs.getValue("testURI"); @@ -330,75 +380,15 @@ public SPARQLUpdateTestManifest(String filename) { resultNamedGraphs.put(namedGraphLabel, namedGraphData); } } - - tests.add(new Object[] { - displayName, - testURI.stringValue(), - testName, - requestFile.stringValue(), - defaultGraphURI, - inputNamedGraphs, - resultDefaultGraphURI, - resultNamedGraphs - }); + DynamicSPARQL11UpdateComplianceTest ds11ut = new DynamicSPARQL11UpdateComplianceTest( + displayName, testURI.stringValue(), testName, requestFile.stringValue(), + defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, resultNamedGraphs); + if (!shouldIgnoredTest(testName)) + tests.add(DynamicTest.dynamicTest(displayName, ds11ut::test)); } } } } } - @Override - protected void runTest() throws Exception { - - logger.debug("running {}", getName()); - - RepositoryConnection con = dataRep.getConnection(); - RepositoryConnection erCon = expectedResultRepo.getConnection(); - try { - String updateString = readUpdateString(); - - con.begin(); - - Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFile); - - assertThatNoException().isThrownBy(() -> { - int hashCode = update.hashCode(); - if (hashCode == System.identityHashCode(update)) { - throw new UnsupportedOperationException( - "hashCode() result is the same as the identityHashCode in " + update.getClass().getName()); - } - }); - - update.setDataset(dataset); - update.execute(); - - con.commit(); - - // check default graph - logger.info("checking default graph"); - compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, (Resource) null)), - Iterations.asList(erCon.getStatements(null, null, null, true, (Resource) null))); - - for (String namedGraph : inputNamedGraphs.keySet()) { - logger.info("checking named graph {}", namedGraph); - IRI contextURI = con.getValueFactory().createIRI(namedGraph.replaceAll("\"", "")); - compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, contextURI)), - Iterations.asList(erCon.getStatements(null, null, null, true, contextURI))); - } - } catch (Exception e) { - if (con.isActive()) { - con.rollback(); - } - throw e; - } finally { - con.close(); - erCon.close(); - } - } - - private String readUpdateString() throws IOException { - try (InputStream stream = new URL(requestFile).openStream()) { - return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL12QueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL12QueryComplianceTest.java index b58d6397ce3..e8cf944dd46 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL12QueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL12QueryComplianceTest.java @@ -10,18 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; -import java.net.URL; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Deque; import java.util.List; -import org.eclipse.rdf4j.query.Dataset; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; /** * A test suite that runs the SPARQL 1.2 community group's query tests. @@ -30,52 +23,20 @@ * * @see sparql 1.2 */ -@RunWith(Parameterized.class) public abstract class SPARQL12QueryComplianceTest extends SPARQLQueryComplianceTest { private static final String[] defaultIgnoredTests = {}; private static final List excludedSubdirs = List.of(); - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); + public SPARQL12QueryComplianceTest() { + super(excludedSubdirs); + for (String ig : defaultIgnoredTests) + addIgnoredTest(ig); } - protected static Object[][] getTestData() { - List tests = new ArrayList<>(); - - Deque manifests = new ArrayDeque<>(); - manifests.add(getManifestURL().toExternalForm()); - while (!manifests.isEmpty()) { - String pop = manifests.pop(); - SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs, false); - tests.addAll(manifest.getTests()); - manifests.addAll(manifest.getSubManifests()); - } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; - } - - protected static URL getManifestURL() { - return SPARQL12QueryComplianceTest.class.getClassLoader().getResource("testcases-sparql-1.2/manifest-all.ttl"); + @TestFactory + public Collection tests() { + return getTestData("testcases-sparql-1.2/manifest-all.ttl"); } - - public SPARQL12QueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name, queryFileURL, resultFileURL, dataset, ordered, laxCardinality); - } - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - for (String defaultIgnoredTest : defaultIgnoredTests) { - addIgnoredTest(defaultIgnoredTest); - } - } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java index 83131e831f6..22c13b13d27 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLComplianceTest.java @@ -34,7 +34,6 @@ import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFParser; import org.eclipse.rdf4j.rio.Rio; -import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,118 +49,146 @@ public abstract class SPARQLComplianceTest { private List ignoredTests = new ArrayList<>(); - private final String displayName; - private final String testURI; - private final String name; + public SPARQLComplianceTest() { + } /** * @param displayName * @param testURI * @param name */ - public SPARQLComplianceTest(String displayName, String testURI, String name) { - this.displayName = displayName; - this.testURI = testURI; - this.name = name; - } + protected abstract class DynamicSparqlComplianceTest { + private final String displayName; + private final String testURI; + private final String name; + + public DynamicSparqlComplianceTest(String displayName, String testURI, String name) { + this.displayName = displayName; + this.testURI = testURI; + this.name = name; + } - @Test - public void test() throws Exception { - assumeThat(getIgnoredTests().contains(getName())).withFailMessage("test case '%s' is ignored", getName()) - .isFalse(); - runTest(); - } + public void test() { + assumeThat(getIgnoredTests().contains(getName())).withFailMessage("test case '%s' is ignored", getName()) + .isFalse(); + try { + setUp(); + runTest(); + } catch (Exception e) { + try { + tearDown(); + } catch (Exception e2) { - /** - * @return the displayName - */ - public String getDisplayName() { - return displayName; - } + } + } + } - /** - * @return the testURI - */ - public String getTestURI() { - return testURI; - } + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the testURI + */ + public String getTestURI() { + return testURI; + } - protected abstract void runTest() throws Exception; + /** + * @return the name + */ + public String getName() { + return name; + } - protected abstract Repository getDataRepository(); + protected void uploadDataset(Dataset dataset) throws Exception { + try (RepositoryConnection con = getDataRepository().getConnection()) { + // Merge default and named graphs to filter duplicates + Set graphURIs = new HashSet<>(); + graphURIs.addAll(dataset.getDefaultGraphs()); + graphURIs.addAll(dataset.getNamedGraphs()); - /** - * Verifies if the selected subManifest occurs in the supplied list of excluded subdirs. - * - * @param subManifestFile the url of a sub-manifest - * @param excludedSubdirs an array of directory names. May be null. - * @return false if the supplied list of excluded subdirs is not empty and contains a match for the - * supplied sub-manifest, true otherwise. - */ - protected static boolean includeSubManifest(String subManifestFile, List excludedSubdirs) { - boolean result = true; + for (Resource graphURI : graphURIs) { + upload(((IRI) graphURI), graphURI); + } + } + } - if (excludedSubdirs != null && !excludedSubdirs.isEmpty()) { - int index = subManifestFile.lastIndexOf('/'); - String path = subManifestFile.substring(0, index); - String sd = path.substring(path.lastIndexOf('/') + 1); + protected abstract Repository getDataRepository(); - for (String subdir : excludedSubdirs) { - if (sd.equals(subdir)) { - result = false; - break; + protected void upload(IRI graphURI, Resource context) throws Exception { + + RepositoryConnection con = getDataRepository().getConnection(); + try { + con.begin(); + RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE); + RDFParser rdfParser = Rio.createParser(rdfFormat, getDataRepository().getValueFactory()); + // rdfParser.setPreserveBNodeIDs(true); + + RDFInserter rdfInserter = new RDFInserter(con); + rdfInserter.enforceContext(context); + rdfParser.setRDFHandler(rdfInserter); + + URL graphURL = new URL(graphURI.toString()); + try (InputStream in = graphURL.openStream()) { + rdfParser.parse(in, graphURI.toString()); } + + con.commit(); + } catch (Exception e) { + if (con.isActive()) { + con.rollback(); + } + throw e; + } finally { + con.close(); } } - return result; - } - protected void uploadDataset(Dataset dataset) throws Exception { - try (RepositoryConnection con = getDataRepository().getConnection()) { - // Merge default and named graphs to filter duplicates - Set graphURIs = new HashSet<>(); - graphURIs.addAll(dataset.getDefaultGraphs()); - graphURIs.addAll(dataset.getNamedGraphs()); + protected void compareGraphs(Iterable queryResult, Iterable expectedResult) + throws Exception { + if (!Models.isomorphic(expectedResult, queryResult)) { + StringBuilder message = new StringBuilder(128); + message.append("\n============ "); + message.append(getName()); + message.append(" =======================\n"); + message.append("Expected result: \n"); + for (Statement st : expectedResult) { + message.append(st.toString()); + message.append("\n"); + } + message.append("============="); + StringUtil.appendN('=', getName().length(), message); + message.append("========================\n"); + + message.append("Query result: \n"); + for (Statement st : queryResult) { + message.append(st.toString()); + message.append("\n"); + } + message.append("============="); + StringUtil.appendN('=', getName().length(), message); + message.append("========================\n"); - for (Resource graphURI : graphURIs) { - upload(((IRI) graphURI), graphURI); + logger.error(message.toString()); + fail(message.toString()); } } - } - - protected void upload(IRI graphURI, Resource context) throws Exception { - RepositoryConnection con = getDataRepository().getConnection(); - try { - con.begin(); - RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE); - RDFParser rdfParser = Rio.createParser(rdfFormat, getDataRepository().getValueFactory()); - // rdfParser.setPreserveBNodeIDs(true); + protected abstract void runTest() throws Exception; - RDFInserter rdfInserter = new RDFInserter(con); - rdfInserter.enforceContext(context); - rdfParser.setRDFHandler(rdfInserter); + public abstract void tearDown() throws Exception; - URL graphURL = new URL(graphURI.toString()); - try (InputStream in = graphURL.openStream()) { - rdfParser.parse(in, graphURI.toString()); - } + public abstract void setUp() throws Exception; - con.commit(); - } catch (Exception e) { - if (con.isActive()) { - con.rollback(); + protected void clear(Repository repo) { + try (RepositoryConnection con = repo.getConnection()) { + con.clear(); + con.clearNamespaces(); } - throw e; - } finally { - con.close(); } } @@ -178,6 +205,32 @@ protected static final void printBindingSet(BindingSet bs, StringBuilder appenda appendable.append("\n"); } + /** + * Verifies if the selected subManifest occurs in the supplied list of excluded subdirs. + * + * @param subManifestFile the url of a sub-manifest + * @param excludedSubdirs an array of directory names. May be null. + * @return false if the supplied list of excluded subdirs is not empty and contains a match for the + * supplied sub-manifest, true otherwise. + */ + protected static boolean includeSubManifest(String subManifestFile, List excludedSubdirs) { + boolean result = true; + + if (excludedSubdirs != null && !excludedSubdirs.isEmpty()) { + int index = subManifestFile.lastIndexOf('/'); + String path = subManifestFile.substring(0, index); + String sd = path.substring(path.lastIndexOf('/') + 1); + + for (String subdir : excludedSubdirs) { + if (sd.equals(subdir)) { + result = false; + break; + } + } + } + return result; + } + /** * @return the ignoredTests */ @@ -189,6 +242,10 @@ protected void addIgnoredTest(String ignoredTest) { this.ignoredTests.add(ignoredTest); } + protected boolean shouldIgnoredTest(String ignoredTest) { + return this.ignoredTests.contains(ignoredTest); + } + /** * @param ignoredTests the ignoredTests to set */ @@ -196,32 +253,4 @@ protected void setIgnoredTests(List ignoredTests) { this.ignoredTests = ignoredTests; } - protected void compareGraphs(Iterable queryResult, Iterable expectedResult) { - if (!Models.isomorphic(expectedResult, queryResult)) { - StringBuilder message = new StringBuilder(128); - message.append("\n============ "); - message.append(getName()); - message.append(" =======================\n"); - message.append("Expected result: \n"); - for (Statement st : expectedResult) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - message.append("Query result: \n"); - for (Statement st : queryResult) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - logger.error(message.toString()); - fail(message.toString()); - } - } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java index 54b6647e679..0082777e594 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java @@ -20,7 +20,10 @@ import java.io.StringWriter; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; @@ -63,8 +66,8 @@ import org.eclipse.rdf4j.rio.helpers.BasicParserSettings; import org.eclipse.rdf4j.rio.helpers.StatementCollector; import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,16 +77,19 @@ * @author Jeen Broekstra */ public abstract class SPARQLQueryComplianceTest extends SPARQLComplianceTest { + private final List excludedSubdirs; - private static final Logger logger = LoggerFactory.getLogger(SPARQLQueryComplianceTest.class); + public SPARQLQueryComplianceTest() { + super(); + this.excludedSubdirs = List.of(); + } - private final String queryFileURL; - private final String resultFileURL; - private final Dataset dataset; - private final boolean ordered; - private final boolean laxCardinality; + public SPARQLQueryComplianceTest(List excludedSubdirs) { + super(); + this.excludedSubdirs = excludedSubdirs; + } - private Repository dataRepository; + private static final Logger logger = LoggerFactory.getLogger(SPARQLQueryComplianceTest.class); /** * @param displayName @@ -94,300 +100,302 @@ public abstract class SPARQLQueryComplianceTest extends SPARQLComplianceTest { * @param dataset * @param ordered */ - public SPARQLQueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, - String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { - super(displayName, testURI, name); - this.queryFileURL = queryFileURL; - this.resultFileURL = resultFileURL; - this.dataset = dataset; - this.ordered = ordered; - this.laxCardinality = laxCardinality; - } + public class DynamicSPARQLQueryComplianceTest extends DynamicSparqlComplianceTest { + + private final String queryFileURL; + private final String resultFileURL; + private final Dataset dataset; + private final boolean ordered; + private final boolean laxCardinality; + private Repository dataRepository; + + public DynamicSPARQLQueryComplianceTest(String displayName, String testURI, String name, String queryFileURL, + String resultFileURL, Dataset dataset, boolean ordered, boolean laxCardinality) { + super(displayName, testURI, name); + this.queryFileURL = queryFileURL; + this.resultFileURL = resultFileURL; + this.dataset = dataset; + this.ordered = ordered; + this.laxCardinality = laxCardinality; + } - @Before - public void setUp() throws Exception { - dataRepository = createRepository(); - if (dataset != null) { - try { - uploadDataset(dataset); - } catch (Exception exc) { - try { - dataRepository.shutDown(); - dataRepository = null; - } catch (Exception e2) { - logger.error(e2.toString(), e2); - } - throw exc; + private String readQueryString() throws IOException { + try (InputStream stream = new URL(queryFileURL).openStream()) { + return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); } } - } - @After - public void tearDown() { - if (dataRepository != null) { - dataRepository.shutDown(); - dataRepository = null; - } - } + private TupleQueryResult readExpectedTupleQueryResult() throws Exception { + Optional tqrFormat = QueryResultIO.getParserFormatForFileName(resultFileURL); - @Override - protected void runTest() throws Exception { + if (tqrFormat.isPresent()) { + try (InputStream in = new URL(resultFileURL).openStream()) { + TupleQueryResultParser parser = QueryResultIO.createTupleParser(tqrFormat.get()); + parser.setValueFactory(getDataRepository().getValueFactory()); - logger.debug("running {}", getName()); + TupleQueryResultBuilder qrBuilder = new TupleQueryResultBuilder(); + parser.setQueryResultHandler(qrBuilder); - try (RepositoryConnection conn = getDataRepository().getConnection()) { - // Some SPARQL Tests have non-XSD datatypes that must pass for the test - // suite to complete successfully - conn.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, Boolean.FALSE); - conn.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, Boolean.FALSE); + parser.parseQueryResult(in); + return qrBuilder.getQueryResult(); + } + } else { + Set resultGraph = readExpectedGraphQueryResult(); + return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph); + } + } - String queryString = readQueryString(); - Query query = conn.prepareQuery(QueryLanguage.SPARQL, queryString, queryFileURL); + private boolean readExpectedBooleanQueryResult() throws Exception { + Optional bqrFormat = BooleanQueryResultParserRegistry.getInstance() + .getFileFormatForFileName(resultFileURL); - assertThatNoException().isThrownBy(() -> { - int hashCode = query.hashCode(); - if (hashCode == System.identityHashCode(query)) { - throw new UnsupportedOperationException( - "hashCode() result is the same as the identityHashCode in " + query.getClass().getName()); + if (bqrFormat.isPresent()) { + try (InputStream in = new URL(resultFileURL).openStream()) { + return QueryResultIO.parseBoolean(in, bqrFormat.get()); } - }); + } else { + Set resultGraph = readExpectedGraphQueryResult(); + return DAWGTestResultSetUtil.toBooleanQueryResult(resultGraph); + } + } + @Override + public void setUp() throws Exception { + dataRepository = createRepository(); if (dataset != null) { - query.setDataset(dataset); + try { + uploadDataset(dataset); + } catch (Exception exc) { + try { + dataRepository.shutDown(); + dataRepository = null; + } catch (Exception e2) { + logger.error(e2.toString(), e2); + } + throw exc; + } } + } - if (query instanceof TupleQuery) { - TupleQueryResult actualResult = ((TupleQuery) query).evaluate(); - TupleQueryResult expectedResult = readExpectedTupleQueryResult(); - compareTupleQueryResults(actualResult, expectedResult); - } else if (query instanceof GraphQuery) { - GraphQueryResult gqr = ((GraphQuery) query).evaluate(); - Set actualResult = Iterations.asSet(gqr); - Set expectedResult = readExpectedGraphQueryResult(); - - compareGraphs(actualResult, expectedResult); - } else if (query instanceof BooleanQuery) { - boolean actualResult = ((BooleanQuery) query).evaluate(); - boolean expectedResult = readExpectedBooleanQueryResult(); - assertThat(actualResult).isEqualTo(expectedResult); - } else { - throw new RuntimeException("Unexpected query type: " + query.getClass()); + @Override + public void tearDown() throws Exception { + if (dataRepository != null) { + clear(dataRepository); + dataRepository.shutDown(); + dataRepository = null; } } - } - protected abstract Repository newRepository() throws Exception; + @Override + protected void runTest() throws Exception { - private Repository createRepository() throws Exception { - Repository repo = newRepository(); - try (RepositoryConnection con = repo.getConnection()) { - con.clear(); - con.clearNamespaces(); - } - return repo; - } + logger.debug("running {}", getName()); - private String readQueryString() throws IOException { - try (InputStream stream = new URL(queryFileURL).openStream()) { - return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - } + try (RepositoryConnection conn = getDataRepository().getConnection()) { + // Some SPARQL Tests have non-XSD datatypes that must pass for the test + // suite to complete successfully + conn.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, Boolean.FALSE); + conn.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, Boolean.FALSE); - private TupleQueryResult readExpectedTupleQueryResult() throws Exception { - Optional tqrFormat = QueryResultIO.getParserFormatForFileName(resultFileURL); + String queryString = readQueryString(); + Query query = conn.prepareQuery(QueryLanguage.SPARQL, queryString, queryFileURL); - if (tqrFormat.isPresent()) { - try (InputStream in = new URL(resultFileURL).openStream()) { - TupleQueryResultParser parser = QueryResultIO.createTupleParser(tqrFormat.get()); - parser.setValueFactory(getDataRepository().getValueFactory()); + assertThatNoException().isThrownBy(() -> { + int hashCode = query.hashCode(); + if (hashCode == System.identityHashCode(query)) { + throw new UnsupportedOperationException( + "hashCode() result is the same as the identityHashCode in " + + query.getClass().getName()); + } + }); - TupleQueryResultBuilder qrBuilder = new TupleQueryResultBuilder(); - parser.setQueryResultHandler(qrBuilder); + if (dataset != null) { + query.setDataset(dataset); + } - parser.parseQueryResult(in); - return qrBuilder.getQueryResult(); + if (query instanceof TupleQuery) { + TupleQueryResult actualResult = ((TupleQuery) query).evaluate(); + TupleQueryResult expectedResult = readExpectedTupleQueryResult(); + compareTupleQueryResults(actualResult, expectedResult); + } else if (query instanceof GraphQuery) { + GraphQueryResult gqr = ((GraphQuery) query).evaluate(); + Set actualResult = Iterations.asSet(gqr); + Set expectedResult = readExpectedGraphQueryResult(); + + compareGraphs(actualResult, expectedResult); + } else if (query instanceof BooleanQuery) { + boolean actualResult = ((BooleanQuery) query).evaluate(); + boolean expectedResult = readExpectedBooleanQueryResult(); + assertThat(actualResult).isEqualTo(expectedResult); + } else { + throw new RuntimeException("Unexpected query type: " + query.getClass()); + } } - } else { - Set resultGraph = readExpectedGraphQueryResult(); - return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph); } - } - private boolean readExpectedBooleanQueryResult() throws Exception { - Optional bqrFormat = BooleanQueryResultParserRegistry.getInstance() - .getFileFormatForFileName(resultFileURL); + @Override + protected Repository getDataRepository() { + return this.dataRepository; + } + + private Set readExpectedGraphQueryResult() throws Exception { + RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFileURL) + .orElseThrow(Rio.unsupportedFormat(resultFileURL)); + + RDFParser parser = Rio.createParser(rdfFormat); + parser.setPreserveBNodeIDs(true); + parser.setValueFactory(getDataRepository().getValueFactory()); + + Set result = new LinkedHashSet<>(); + parser.setRDFHandler(new StatementCollector(result)); - if (bqrFormat.isPresent()) { try (InputStream in = new URL(resultFileURL).openStream()) { - return QueryResultIO.parseBoolean(in, bqrFormat.get()); + parser.parse(in, resultFileURL); } - } else { - Set resultGraph = readExpectedGraphQueryResult(); - return DAWGTestResultSetUtil.toBooleanQueryResult(resultGraph); + + return result; } - } - private Set readExpectedGraphQueryResult() throws Exception { - RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFileURL) - .orElseThrow(Rio.unsupportedFormat(resultFileURL)); + private void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult) + throws Exception { + // Create MutableTupleQueryResult to be able to re-iterate over the + // results + MutableTupleQueryResult queryResultTable = new MutableTupleQueryResult(queryResult); + MutableTupleQueryResult expectedResultTable = new MutableTupleQueryResult(expectedResult); - RDFParser parser = Rio.createParser(rdfFormat); - parser.setPreserveBNodeIDs(true); - parser.setValueFactory(getDataRepository().getValueFactory()); + boolean resultsEqual; + if (laxCardinality) { + resultsEqual = QueryResults.isSubset(queryResultTable, expectedResultTable); + } else { + resultsEqual = QueryResults.equals(queryResultTable, expectedResultTable); - Set result = new LinkedHashSet<>(); - parser.setRDFHandler(new StatementCollector(result)); + if (ordered) { + // also check the order in which solutions occur. + queryResultTable.beforeFirst(); + expectedResultTable.beforeFirst(); - try (InputStream in = new URL(resultFileURL).openStream()) { - parser.parse(in, resultFileURL); - } + while (queryResultTable.hasNext()) { + BindingSet bs = queryResultTable.next(); + BindingSet expectedBs = expectedResultTable.next(); - return result; - } + if (!bs.equals(expectedBs)) { + resultsEqual = false; + break; + } + } + } + } - private void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult) - throws Exception { - // Create MutableTupleQueryResult to be able to re-iterate over the - // results - MutableTupleQueryResult queryResultTable = new MutableTupleQueryResult(queryResult); - MutableTupleQueryResult expectedResultTable = new MutableTupleQueryResult(expectedResult); - - boolean resultsEqual; - if (laxCardinality) { - resultsEqual = QueryResults.isSubset(queryResultTable, expectedResultTable); - } else { - resultsEqual = QueryResults.equals(queryResultTable, expectedResultTable); - - if (ordered) { - // also check the order in which solutions occur. + if (!resultsEqual) { queryResultTable.beforeFirst(); expectedResultTable.beforeFirst(); - while (queryResultTable.hasNext()) { - BindingSet bs = queryResultTable.next(); - BindingSet expectedBs = expectedResultTable.next(); + /* + * StringBuilder message = new StringBuilder(128); message.append("\n============ "); + * message.append(getName()); message.append(" =======================\n"); message.append( + * "Expected result: \n"); while (expectedResultTable.hasNext()) { + * message.append(expectedResultTable.next()); message.append("\n"); } message.append("============="); + * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); + * message.append("Query result: \n"); while (queryResultTable.hasNext()) { + * message.append(queryResultTable.next()); message.append("\n"); } message.append("============="); + * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); + */ - if (!bs.equals(expectedBs)) { - resultsEqual = false; - break; - } - } - } - } + List queryBindings = Iterations.asList(queryResultTable); - if (!resultsEqual) { - queryResultTable.beforeFirst(); - expectedResultTable.beforeFirst(); - - /* - * StringBuilder message = new StringBuilder(128); message.append("\n============ "); - * message.append(getName()); message.append(" =======================\n"); message.append( - * "Expected result: \n"); while (expectedResultTable.hasNext()) { - * message.append(expectedResultTable.next()); message.append("\n"); } message.append("============="); - * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); - * message.append("Query result: \n"); while (queryResultTable.hasNext()) { - * message.append(queryResultTable.next()); message.append("\n"); } message.append("============="); - * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); - */ - - List queryBindings = Iterations.asList(queryResultTable); - - List expectedBindings = Iterations.asList(expectedResultTable); - - List missingBindings = new ArrayList<>(expectedBindings); - missingBindings.removeAll(queryBindings); - - List unexpectedBindings = new ArrayList<>(queryBindings); - unexpectedBindings.removeAll(expectedBindings); - - StringBuilder message = new StringBuilder(); - String header = "=================================== " + getName() + " ==================================="; - String footer = StringUtils.leftPad("", header.length(), "="); - message.append("\n").append(header).append("\n"); - - message.append("# Query:\n\n"); - message.append(readQueryString().trim()).append("\n"); - message.append(footer).append("\n"); - - message.append("# Data:\n\n"); - try (RepositoryConnection connection = dataRepository.getConnection()) { - try (RepositoryResult statements = connection.getStatements(null, null, null)) { - List collect = statements.stream().collect(Collectors.toList()); - StringWriter stringWriter = new StringWriter(); - Rio.write(collect, stringWriter, RDFFormat.TRIG); - message.append(stringWriter.toString().trim()).append("\n"); - } - } - message.append(footer).append("\n"); + List expectedBindings = Iterations.asList(expectedResultTable); - message.append("# Expected bindings:\n\n"); - for (BindingSet bs : expectedBindings) { - printBindingSet(bs, message); - } - message.append(footer).append("\n"); + List missingBindings = new ArrayList<>(expectedBindings); + missingBindings.removeAll(queryBindings); - message.append("# Actual bindings:\n\n"); - for (BindingSet bs : queryBindings) { - printBindingSet(bs, message); - } - message.append(footer).append("\n"); + List unexpectedBindings = new ArrayList<>(queryBindings); + unexpectedBindings.removeAll(expectedBindings); - if (!missingBindings.isEmpty()) { + StringBuilder message = new StringBuilder(); + String header = "=================================== " + getName() + + " ==================================="; + String footer = StringUtils.leftPad("", header.length(), "="); + message.append("\n").append(header).append("\n"); - message.append("# Missing bindings: \n\n"); - for (BindingSet bs : missingBindings) { - printBindingSet(bs, message); - } + message.append("# Query:\n\n"); + message.append(readQueryString().trim()).append("\n"); message.append(footer).append("\n"); - } - if (!unexpectedBindings.isEmpty()) { - message.append("# Unexpected bindings: \n\n"); - for (BindingSet bs : unexpectedBindings) { + message.append("# Expected bindings:\n\n"); + for (BindingSet bs : expectedBindings) { printBindingSet(bs, message); } message.append(footer).append("\n"); - } - if (ordered && missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { - message.append("# Results are not in expected order.\n"); - message.append(footer).append("\n"); - message.append("# query result: \n\n"); + message.append("# Actual bindings:\n\n"); for (BindingSet bs : queryBindings) { printBindingSet(bs, message); } message.append(footer).append("\n"); - message.append("# expected result: \n\n"); - for (BindingSet bs : expectedBindings) { - printBindingSet(bs, message); + + if (!missingBindings.isEmpty()) { + + message.append("# Missing bindings: \n\n"); + for (BindingSet bs : missingBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); } - message.append(footer).append("\n"); - } else if (missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { - message.append("# unexpected duplicate in result.\n"); - message.append(footer).append("\n"); - message.append("# query result: \n\n"); - for (BindingSet bs : queryBindings) { - printBindingSet(bs, message); + + if (!unexpectedBindings.isEmpty()) { + message.append("# Unexpected bindings: \n\n"); + for (BindingSet bs : unexpectedBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); } - message.append(footer).append("\n"); - message.append("# expected result: \n\n"); - for (BindingSet bs : expectedBindings) { - printBindingSet(bs, message); + + if (ordered && missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { + message.append("# Results are not in expected order.\n"); + message.append(footer).append("\n"); + message.append("# query result: \n\n"); + for (BindingSet bs : queryBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); + message.append("# expected result: \n\n"); + for (BindingSet bs : expectedBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); + } else if (missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { + message.append("# unexpected duplicate in result.\n"); + message.append(footer).append("\n"); + message.append("# query result: \n\n"); + for (BindingSet bs : queryBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); + message.append("# expected result: \n\n"); + for (BindingSet bs : expectedBindings) { + printBindingSet(bs, message); + } + message.append(footer).append("\n"); } - message.append(footer).append("\n"); - } - fail(message.toString()); + fail(message.toString()); + } } } - @Override - protected Repository getDataRepository() { - return this.dataRepository; + protected abstract Repository newRepository() throws Exception; + + private Repository createRepository() throws Exception { + Repository repo = newRepository(); + try (RepositoryConnection con = repo.getConnection()) { + con.clear(); + con.clearNamespaces(); + } + return repo; } - protected static class SPARQLQueryTestManifest { - private final List tests = new ArrayList<>(); + protected class SPARQLQueryTestManifest { + private final List tests = new ArrayList<>(); private final List subManifests = new ArrayList<>(); public SPARQLQueryTestManifest(String filename, List excludedSubdirs) { @@ -485,31 +493,18 @@ public SPARQLQueryTestManifest(String filename, List excludedSubdirs, bo } } } - - getTests().add(new Object[] { - displayName, - bs.getValue("testURI").stringValue(), - testName, - bs.getValue("queryFile").stringValue(), - bs.getValue("resultFile").stringValue(), - dataset, - Literals.getBooleanValue(ordered, false), - bs.hasBinding("laxCardinality") - }); + DynamicSPARQLQueryComplianceTest ds11ut = new DynamicSPARQLQueryComplianceTest(displayName, + bs.getValue("testURI").stringValue(), testName, bs.getValue("queryFile").stringValue(), + bs.getValue("resultFile").stringValue(), dataset, + Literals.getBooleanValue(ordered, false), bs.hasBinding("laxCardinality")); + if (!shouldIgnoredTest(testName)) + tests.add(DynamicTest.dynamicTest(displayName, ds11ut::test)); } } - } } - /** - * @return the tests - */ - public List getTests() { - return tests; - } - /** * @return the subManifests */ @@ -518,4 +513,23 @@ public List getSubManifests() { } } + + @TestFactory + public abstract Collection tests(); + + public Collection getTestData(String manifestResource) { + List tests = new ArrayList<>(); + + Deque manifests = new ArrayDeque<>(); + manifests.add( + SPARQL11UpdateComplianceTest.class.getClassLoader().getResource(manifestResource).toExternalForm()); + while (!manifests.isEmpty()) { + String pop = manifests.pop(); + SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs); + tests.addAll(manifest.tests); + manifests.addAll(manifest.subManifests); + } + + return tests; + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java deleted file mode 100644 index a388f8220b2..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryTest.java +++ /dev/null @@ -1,672 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.eclipse.rdf4j.common.io.IOUtil; -import org.eclipse.rdf4j.common.iteration.Iterations; -import org.eclipse.rdf4j.common.text.StringUtil; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.util.Models; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.BooleanQuery; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.GraphQuery; -import org.eclipse.rdf4j.query.GraphQueryResult; -import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.Query; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.QueryResults; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.query.dawg.DAWGTestResultSetUtil; -import org.eclipse.rdf4j.query.impl.MutableTupleQueryResult; -import org.eclipse.rdf4j.query.impl.SimpleDataset; -import org.eclipse.rdf4j.query.impl.TupleQueryResultBuilder; -import org.eclipse.rdf4j.query.resultio.BooleanQueryResultParserRegistry; -import org.eclipse.rdf4j.query.resultio.QueryResultFormat; -import org.eclipse.rdf4j.query.resultio.QueryResultIO; -import org.eclipse.rdf4j.query.resultio.TupleQueryResultParser; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.util.RDFInserter; -import org.eclipse.rdf4j.rio.RDFFormat; -import org.eclipse.rdf4j.rio.RDFParser; -import org.eclipse.rdf4j.rio.Rio; -import org.eclipse.rdf4j.rio.helpers.BasicParserSettings; -import org.eclipse.rdf4j.rio.helpers.StatementCollector; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * A SPARQL query test suite, created by reading in a W3C working-group style manifest. - * - * @author Jeen Broekstra - * @deprecated Use {@link SPARQL11QueryComplianceTest} instead. - */ -@Deprecated(since = "3.3.0") -public abstract class SPARQLQueryTest extends TestCase { - - /*-----------* - * Constants * - *-----------*/ - - // Logger for non-static tests, so these results can be isolated based on - // where they are run - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - - // Logger for static methods which are not overridden - private final static Logger LOGGER = LoggerFactory.getLogger(SPARQLQueryTest.class); - - protected final String testURI; - - protected final String queryFileURL; - - protected final String resultFileURL; - - protected final Dataset dataset; - - protected final boolean laxCardinality; - - protected final boolean checkOrder; - - protected final String[] ignoredTests; - - /*-----------* - * Variables * - *-----------*/ - - protected Repository dataRep; - - /*--------------* - * Constructors * - *--------------*/ - - public SPARQLQueryTest(String testURI, String name, String queryFileURL, String resultFileURL, Dataset dataSet, - boolean laxCardinality, String... ignoredTests) { - this(testURI, name, queryFileURL, resultFileURL, dataSet, laxCardinality, false); - } - - public SPARQLQueryTest(String testURI, String name, String queryFileURL, String resultFileURL, Dataset dataSet, - boolean laxCardinality, boolean checkOrder, String... ignoredTests) { - super(name.replaceAll("\\(", " ").replaceAll("\\)", " ")); - - this.testURI = testURI; - this.queryFileURL = queryFileURL; - this.resultFileURL = resultFileURL; - this.dataset = dataSet; - this.laxCardinality = laxCardinality; - this.checkOrder = checkOrder; - this.ignoredTests = ignoredTests; - } - - /*---------* - * Methods * - *---------*/ - - @Override - protected void setUp() throws Exception { - dataRep = createRepository(); - - if (dataset != null) { - try { - uploadDataset(dataset); - } catch (Exception exc) { - try { - dataRep.shutDown(); - dataRep = null; - } catch (Exception e2) { - logger.error(e2.toString(), e2); - } - throw exc; - } - } - } - - protected final Repository createRepository() { - Repository repo = newRepository(); - try (RepositoryConnection con = repo.getConnection()) { - con.clear(); - con.clearNamespaces(); - } - return repo; - } - - protected abstract Repository newRepository(); - - @Override - protected void tearDown() { - if (dataRep != null) { - dataRep.shutDown(); - dataRep = null; - } - } - - @Override - protected void runTest() throws Exception { - // FIXME this reports a test error because we still rely on JUnit 3 here. - // org.junit.Assume.assumeFalse(Arrays.asList(ignoredTests).contains(this.getName())); - // FIXME temporary fix is to report as succeeded and just ignore. - if (Arrays.asList(ignoredTests).contains(this.getName())) { - logger.warn("Query test ignored: " + this.getName()); - return; - } - - // Some SPARQL Tests have non-XSD datatypes that must pass for the test - // suite to complete successfully - try (RepositoryConnection con = dataRep.getConnection()) { - con.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, Boolean.FALSE); - con.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, Boolean.FALSE); - String queryString = readQueryString(); - Query query = con.prepareQuery(QueryLanguage.SPARQL, queryString, queryFileURL); - if (dataset != null) { - query.setDataset(dataset); - } - - String name = this.getName(); - - if (name.contains("pp34")) { - System.out.println(name); - } - - if (query instanceof TupleQuery) { - TupleQueryResult queryResult = ((TupleQuery) query).evaluate(); - - TupleQueryResult expectedResult = readExpectedTupleQueryResult(); - - compareTupleQueryResults(queryResult, expectedResult); - - // Graph queryGraph = RepositoryUtil.asGraph(queryResult); - // Graph expectedGraph = readExpectedTupleQueryResult(); - // compareGraphs(queryGraph, expectedGraph); - } else if (query instanceof GraphQuery) { - GraphQueryResult gqr = ((GraphQuery) query).evaluate(); - Set queryResult = Iterations.asSet(gqr); - - Set expectedResult = readExpectedGraphQueryResult(); - - compareGraphs(queryResult, expectedResult); - } else if (query instanceof BooleanQuery) { - boolean queryResult = ((BooleanQuery) query).evaluate(); - boolean expectedResult = readExpectedBooleanQueryResult(); - assertEquals(expectedResult, queryResult); - } else { - throw new RuntimeException("Unexpected query type: " + query.getClass()); - } - } - } - - protected final void compareTupleQueryResults(TupleQueryResult queryResult, TupleQueryResult expectedResult) { - // Create MutableTupleQueryResult to be able to re-iterate over the - // results - MutableTupleQueryResult queryResultTable = new MutableTupleQueryResult(queryResult); - MutableTupleQueryResult expectedResultTable = new MutableTupleQueryResult(expectedResult); - - boolean resultsEqual; - if (laxCardinality) { - resultsEqual = QueryResults.isSubset(queryResultTable, expectedResultTable); - } else { - resultsEqual = QueryResults.equals(queryResultTable, expectedResultTable); - - if (checkOrder) { - // also check the order in which solutions occur. - queryResultTable.beforeFirst(); - expectedResultTable.beforeFirst(); - - while (queryResultTable.hasNext()) { - BindingSet bs = queryResultTable.next(); - BindingSet expectedBs = expectedResultTable.next(); - - if (!bs.equals(expectedBs)) { - resultsEqual = false; - break; - } - } - } - } - - if (!resultsEqual) { - queryResultTable.beforeFirst(); - expectedResultTable.beforeFirst(); - - /* - * StringBuilder message = new StringBuilder(128); message.append("\n============ "); - * message.append(getName()); message.append(" =======================\n"); message.append( - * "Expected result: \n"); while (expectedResultTable.hasNext()) { - * message.append(expectedResultTable.next()); message.append("\n"); } message.append("============="); - * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); - * message.append("Query result: \n"); while (queryResultTable.hasNext()) { - * message.append(queryResultTable.next()); message.append("\n"); } message.append("============="); - * StringUtil.appendN('=', getName().length(), message); message.append("========================\n"); - */ - - List queryBindings = Iterations.asList(queryResultTable); - - List expectedBindings = Iterations.asList(expectedResultTable); - - List missingBindings = new ArrayList<>(expectedBindings); - missingBindings.removeAll(queryBindings); - - List unexpectedBindings = new ArrayList<>(queryBindings); - unexpectedBindings.removeAll(expectedBindings); - - StringBuilder message = new StringBuilder(128); - message.append("\n============ "); - message.append(getName()); - message.append(" =======================\n"); - - if (!missingBindings.isEmpty()) { - - message.append("Missing bindings: \n"); - for (BindingSet bs : missingBindings) { - printBindingSet(bs, message); - } - - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - } - - if (!unexpectedBindings.isEmpty()) { - message.append("Unexpected bindings: \n"); - for (BindingSet bs : unexpectedBindings) { - printBindingSet(bs, message); - } - - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - } - - if (checkOrder && missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { - message.append("Results are not in expected order.\n"); - message.append(" =======================\n"); - message.append("query result: \n"); - for (BindingSet bs : queryBindings) { - printBindingSet(bs, message); - } - message.append(" =======================\n"); - message.append("expected result: \n"); - for (BindingSet bs : expectedBindings) { - printBindingSet(bs, message); - } - message.append(" =======================\n"); - - System.out.print(message.toString()); - } else if (missingBindings.isEmpty() && unexpectedBindings.isEmpty()) { - message.append("unexpected duplicate in result.\n"); - message.append(" =======================\n"); - message.append("query result: \n"); - for (BindingSet bs : queryBindings) { - printBindingSet(bs, message); - } - message.append(" =======================\n"); - message.append("expected result: \n"); - for (BindingSet bs : expectedBindings) { - printBindingSet(bs, message); - } - message.append(" =======================\n"); - - System.out.print(message.toString()); - } - - logger.error(message.toString()); - fail(message.toString()); - } - /* - * debugging only: print out result when test succeeds else { queryResultTable.beforeFirst(); List - * queryBindings = Iterations.asList(queryResultTable); StringBuilder message = new StringBuilder(128); - * message.append("\n============ "); message.append(getName()); message.append( " =======================\n"); - * message.append(" =======================\n"); message.append( "query result: \n"); for (BindingSet bs: - * queryBindings) { message.append(bs); message.append("\n"); } System.out.print(message.toString()); } - */ - } - - protected final void printBindingSet(BindingSet bs, StringBuilder appendable) { - List names = new ArrayList<>(bs.getBindingNames()); - Collections.sort(names); - - for (String name : names) { - if (bs.hasBinding(name)) { - appendable.append(bs.getBinding(name)); - appendable.append(' '); - } - } - appendable.append("\n"); - } - - protected final void compareGraphs(Set queryResult, Set expectedResult) { - if (!Models.isomorphic(expectedResult, queryResult)) { - // Don't use RepositoryUtil.difference, it reports incorrect diffs - /* - * Collection unexpectedStatements = RepositoryUtil.difference(queryResult, - * expectedResult); Collection missingStatements = - * RepositoryUtil.difference(expectedResult, queryResult); StringBuilder message = new StringBuilder(128); - * message.append("\n=======Diff: "); message.append(getName()); - * message.append("========================\n"); if (!unexpectedStatements.isEmpty()) { - * message.append("Unexpected statements in result: \n"); for (Statement st : unexpectedStatements) { - * message.append(st.toString()); message.append("\n"); } message.append("============="); for (int i = 0; i - * < getName().length(); i++) { message.append("="); } message.append("========================\n"); } if - * (!missingStatements.isEmpty()) { message.append("Statements missing in result: \n"); for (Statement st : - * missingStatements) { message.append(st.toString()); message.append("\n"); } - * message.append("============="); for (int i = 0; i < getName().length(); i++) { message.append("="); } - * message.append("========================\n"); } - */ - StringBuilder message = new StringBuilder(128); - message.append("\n============ "); - message.append(getName()); - message.append(" =======================\n"); - message.append("Expected result: \n"); - for (Statement st : expectedResult) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - message.append("Query result: \n"); - for (Statement st : queryResult) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - logger.error(message.toString()); - fail(message.toString()); - } - } - - protected final void uploadDataset(Dataset dataset) throws Exception { - // Merge default and named graphs to filter duplicates - Set graphURIs = new HashSet<>(); - graphURIs.addAll(dataset.getDefaultGraphs()); - graphURIs.addAll(dataset.getNamedGraphs()); - - for (IRI graphURI : graphURIs) { - upload(graphURI, graphURI); - } - } - - private void upload(IRI graphURI, Resource context) throws Exception { - try (RepositoryConnection con = dataRep.getConnection()) { - try { - con.begin(); - RDFFormat rdfFormat = Rio.getParserFormatForFileName(graphURI.toString()).orElse(RDFFormat.TURTLE); - RDFParser rdfParser = Rio.createParser(rdfFormat, dataRep.getValueFactory()); - // rdfParser.setPreserveBNodeIDs(true); - - RDFInserter rdfInserter = new RDFInserter(con); - rdfInserter.enforceContext(context); - rdfParser.setRDFHandler(rdfInserter); - - URL graphURL = new URL(graphURI.toString()); - try (InputStream in = graphURL.openStream()) { - rdfParser.parse(in, graphURI.toString()); - } - - con.commit(); - } catch (Exception e) { - if (con.isActive()) { - con.rollback(); - } - throw e; - } - } - } - - protected final String readQueryString() throws IOException { - try (InputStream stream = new URL(queryFileURL).openStream()) { - return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - } - - protected final TupleQueryResult readExpectedTupleQueryResult() throws Exception { - Optional tqrFormat = QueryResultIO.getParserFormatForFileName(resultFileURL); - - if (tqrFormat.isPresent()) { - try (InputStream in = new URL(resultFileURL).openStream()) { - TupleQueryResultParser parser = QueryResultIO.createTupleParser(tqrFormat.get()); - parser.setValueFactory(dataRep.getValueFactory()); - - TupleQueryResultBuilder qrBuilder = new TupleQueryResultBuilder(); - parser.setQueryResultHandler(qrBuilder); - - parser.parseQueryResult(in); - return qrBuilder.getQueryResult(); - } - } else { - Set resultGraph = readExpectedGraphQueryResult(); - return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph); - } - } - - protected final boolean readExpectedBooleanQueryResult() throws Exception { - Optional bqrFormat = BooleanQueryResultParserRegistry.getInstance() - .getFileFormatForFileName(resultFileURL); - - if (bqrFormat.isPresent()) { - try (InputStream in = new URL(resultFileURL).openStream()) { - return QueryResultIO.parseBoolean(in, bqrFormat.get()); - } - } else { - Set resultGraph = readExpectedGraphQueryResult(); - return DAWGTestResultSetUtil.toBooleanQueryResult(resultGraph); - } - } - - protected final Set readExpectedGraphQueryResult() throws Exception { - RDFFormat rdfFormat = Rio.getParserFormatForFileName(resultFileURL) - .orElseThrow(Rio.unsupportedFormat(resultFileURL)); - - RDFParser parser = Rio.createParser(rdfFormat); - parser.setPreserveBNodeIDs(true); - parser.setValueFactory(dataRep.getValueFactory()); - - Set result = new LinkedHashSet<>(); - parser.setRDFHandler(new StatementCollector(result)); - - try (InputStream in = new URL(resultFileURL).openStream()) { - parser.parse(in, resultFileURL); - } - - return result; - } - - public interface Factory { - - SPARQLQueryTest createSPARQLQueryTest(String testURI, String name, String queryFileURL, String resultFileURL, - Dataset dataSet, boolean laxCardinality); - - SPARQLQueryTest createSPARQLQueryTest(String testURI, String name, String queryFileURL, String resultFileURL, - Dataset dataSet, boolean laxCardinality, boolean checkOrder); - } - - public static TestSuite suite(String manifestFileURL, Factory factory) throws Exception { - return suite(manifestFileURL, factory, true); - } - - public static TestSuite suite(String manifestFileURL, Factory factory, boolean approvedOnly) throws Exception { - LOGGER.info("Building test suite for {}", manifestFileURL); - - TestSuite suite = new TestSuite(factory.getClass().getName()); - - // Read manifest and create declared test cases - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - SPARQL11ManifestTest.addTurtle(con, new URL(manifestFileURL), manifestFileURL); - - suite.setName(getManifestName(manifestRep, con, manifestFileURL)); - - // Extract test case information from the manifest file. Note that we only - // select those test cases that are mentioned in the list. - StringBuilder query = new StringBuilder(512); - query.append(" PREFIX mf: \n"); - query.append(" PREFIX dawgt: \n"); - query.append(" PREFIX qt: \n"); - query.append(" PREFIX sd: \n"); - query.append(" PREFIX ent: \n"); - query.append( - " SELECT DISTINCT ?testURI ?testName ?resultFile ?action ?queryFile ?defaultGraph ?ordered \n"); - query.append(" WHERE { [] rdf:first ?testURI . \n"); - if (approvedOnly) { - query.append(" ?testURI dawgt:approval dawgt:Approved . \n"); - } - query.append(" ?testURI mf:name ?testName; \n"); - query.append(" mf:result ?resultFile . \n"); - query.append(" OPTIONAL { ?testURI mf:checkOrder ?ordered } \n"); - query.append(" OPTIONAL { ?testURI mf:requires ?requirement } \n"); - query.append(" ?testURI mf:action ?action. \n"); - query.append(" ?action qt:query ?queryFile . \n"); - query.append(" OPTIONAL { ?action qt:data ?defaultGraph } \n"); - query.append(" OPTIONAL { ?action sd:entailmentRegime ?regime } \n"); - // skip tests involving CSV result files, these are not query tests - query.append(" FILTER(!STRENDS(STR(?resultFile), \"csv\")) \n"); - // skip tests involving entailment regimes - query.append(" FILTER(!BOUND(?regime)) \n"); - // skip test involving basic federation, these are tested separately. - query.append(" FILTER (!BOUND(?requirement) || (?requirement != mf:BasicFederation)) \n"); - query.append(" }\n"); - - TupleQuery testCaseQuery = con.prepareTupleQuery(query.toString()); - - query.setLength(0); - query.append(" PREFIX qt: \n"); - query.append(" SELECT ?graph \n"); - query.append(" WHERE { ?action qt:graphData ?graph } \n"); - TupleQuery namedGraphsQuery = con.prepareTupleQuery(query.toString()); - - query.setLength(0); - query.append(" PREFIX mf: \n"); - query.append("ASK \n"); - query.append(" WHERE { ?testURI mf:resultCardinality mf:LaxCardinality .} \n"); - BooleanQuery laxCardinalityQuery = con.prepareBooleanQuery(query.toString()); - - LOGGER.debug("evaluating query.."); - try (TupleQueryResult testCases = testCaseQuery.evaluate()) { - for (BindingSet testCase : testCases) { - IRI testURI = (IRI) testCase.getValue("testURI"); - String testName = testCase.getValue("testName").stringValue(); - String resultFile = testCase.getValue("resultFile").stringValue(); - String queryFile = testCase.getValue("queryFile").stringValue(); - IRI defaultGraphURI = (IRI) testCase.getValue("defaultGraph"); - Value action = testCase.getValue("action"); - Value ordered = testCase.getValue("ordered"); - - LOGGER.debug("found test case : {}", testName); - - SimpleDataset dataset = null; - - // Query named graphs - namedGraphsQuery.setBinding("action", action); - try (TupleQueryResult namedGraphs = namedGraphsQuery.evaluate()) { - if (defaultGraphURI != null || namedGraphs.hasNext()) { - dataset = new SimpleDataset(); - if (defaultGraphURI != null) { - dataset.addDefaultGraph(defaultGraphURI); - } - while (namedGraphs.hasNext()) { - BindingSet graphBindings = namedGraphs.next(); - IRI namedGraphURI = (IRI) graphBindings.getValue("graph"); - LOGGER.debug(" adding named graph : {}", namedGraphURI); - dataset.addNamedGraph(namedGraphURI); - } - } - } - - // Check for lax-cardinality conditions - boolean laxCardinality; - laxCardinalityQuery.setBinding("testURI", testURI); - laxCardinality = laxCardinalityQuery.evaluate(); - - // if this is enabled, RDF4J passes all tests, showing that the only - // difference is the semantics of arbitrary-length - // paths - /* - * if (!laxCardinality) { // property-path tests always with lax cardinality because Sesame filters - * out duplicates by design if (testURI.stringValue().contains("property-path")) { laxCardinality = - * true; } } - */ - - // Two SPARQL distinctness tests fail in RDF-1.1 if the only difference - // is in the number of results - if (!laxCardinality) { - if (testURI.stringValue().contains("distinct/manifest#distinct-2") - || testURI.stringValue().contains("distinct/manifest#distinct-9")) { - laxCardinality = true; - } - } - - LOGGER.debug("testURI={} name={} queryFile={}", testURI.stringValue(), testName, queryFile); - - // check if we should test for query result ordering - boolean checkOrder = false; - if (ordered != null) { - checkOrder = Boolean.parseBoolean(ordered.stringValue()); - } - - SPARQLQueryTest test = factory.createSPARQLQueryTest(testURI.stringValue(), testName, queryFile, - resultFile, dataset, laxCardinality, checkOrder); - if (test != null) { - suite.addTest(test); - } - } - } - } - manifestRep.shutDown(); - LOGGER.info("Created test suite with " + suite.countTestCases() + " test cases."); - return suite; - } - - protected static String getManifestName(Repository manifestRep, RepositoryConnection con, String manifestFileURL) - throws QueryEvaluationException, RepositoryException, MalformedQueryException { - // Try to extract suite name from manifest file - TupleQuery manifestNameQuery = con - .prepareTupleQuery("SELECT ?ManifestName WHERE { ?ManifestURL rdfs:label ?ManifestName .}"); - manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createIRI(manifestFileURL)); - try (TupleQueryResult manifestNames = manifestNameQuery.evaluate()) { - if (manifestNames.hasNext()) { - return manifestNames.next().getValue("ManifestName").stringValue(); - } - } - - // Derive name from manifest URL - int lastSlashIdx = manifestFileURL.lastIndexOf('/'); - int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1); - return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx); - } -} diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLSyntaxComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLSyntaxComplianceTest.java index 9bc71506995..dfa91721dff 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLSyntaxComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLSyntaxComplianceTest.java @@ -20,7 +20,6 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.List; @@ -37,6 +36,7 @@ import org.eclipse.rdf4j.query.algebra.UpdateExpr; import org.eclipse.rdf4j.query.parser.ParsedOperation; import org.eclipse.rdf4j.query.parser.ParsedUpdate; +import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.repository.sail.helpers.SailUpdateExecutor; @@ -45,7 +45,8 @@ import org.eclipse.rdf4j.sail.NotifyingSailConnection; import org.eclipse.rdf4j.sail.SailException; import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,46 +61,116 @@ public abstract class SPARQLSyntaxComplianceTest extends SPARQLComplianceTest { private static final List excludedSubdirs = List.of(); - private final String queryFileURL; - private final boolean positiveTest; + public class DynamicSPARQLSyntaxComplianceTest extends DynamicSparqlComplianceTest { + private final String queryFileURL; + private final boolean positiveTest; - @Parameterized.Parameters(name = "{0}") - public static Collection data() { - return Arrays.asList(getTestData()); - } + public DynamicSPARQLSyntaxComplianceTest(String displayName, String testURI, String name, String queryFileURL, + boolean positiveTest) { - public SPARQLSyntaxComplianceTest(String displayName, String testURI, String name, String queryFileURL, - boolean positiveTest) { + super(displayName, testURI, name); + this.queryFileURL = queryFileURL; + this.positiveTest = positiveTest; + } - super(displayName, testURI, name); - this.queryFileURL = queryFileURL; - this.positiveTest = positiveTest; - } + @Override + protected void runTest() throws Exception { + InputStream stream = new URL(queryFileURL).openStream(); + String query = IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + stream.close(); + + try { + ParsedOperation operation = parseOperation(query, queryFileURL); + + assertThatNoException().isThrownBy(() -> { + int hashCode = operation.hashCode(); + if (hashCode == System.identityHashCode(operation)) { + throw new UnsupportedOperationException( + "hashCode() result is the same as the identityHashCode in " + + operation.getClass().getName()); + } + }); + + if (!positiveTest) { + boolean dataBlockUpdate = false; + if (operation instanceof ParsedUpdate) { + for (UpdateExpr updateExpr : ((ParsedUpdate) operation).getUpdateExprs()) { + if (updateExpr instanceof InsertData || updateExpr instanceof DeleteData) { + // parsing for these operation happens during actual + // execution, so try and execute. + dataBlockUpdate = true; + + MemoryStore store = new MemoryStore(); + store.init(); + NotifyingSailConnection conn = store.getConnection(); + try { + conn.begin(); + SailUpdateExecutor exec = new SailUpdateExecutor(conn, store.getValueFactory(), + null); + exec.executeUpdate(updateExpr, null, null, true, -1); + conn.rollback(); + fail("Negative test case should have failed to parse"); + } catch (SailException e) { + if (!(e.getCause() instanceof RDFParseException)) { + logger.error("unexpected error in negative test case", e); + fail("unexpected error in negative test case"); + } + // fall through - a parse exception is expected for a + // negative test case + conn.rollback(); + } finally { + conn.close(); + } + } + } + } + if (!dataBlockUpdate) { + fail("Negative test case should have failed to parse"); + } + } + } catch (MalformedQueryException e) { + if (positiveTest) { + e.printStackTrace(); + fail("Positive test case failed: " + e.getMessage()); + } + } + } - private static Object[][] getTestData() { + @Override + protected Repository getDataRepository() { + return null; // not needed in syntax tests + } - List tests = new ArrayList<>(); + @Override + public void tearDown() throws Exception { + // not needed in syntax tests + } + + @Override + public void setUp() throws Exception { + // not needed in syntax tests + } + } + + @TestFactory + public Collection getTestData() { + List tests = new ArrayList<>(); Deque manifests = new ArrayDeque<>(); - manifests.add( - SPARQLSyntaxComplianceTest.class.getClassLoader() - .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") - .toExternalForm()); + manifests.add(SPARQLSyntaxComplianceTest.class.getClassLoader() + .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") + .toExternalForm()); while (!manifests.isEmpty()) { String pop = manifests.pop(); SPARQLSyntaxManifest manifest = new SPARQLSyntaxManifest(pop); tests.addAll(manifest.tests); manifests.addAll(manifest.subManifests); } - - Object[][] result = new Object[tests.size()][6]; - tests.toArray(result); - - return result; + return tests; } - static class SPARQLSyntaxManifest { - List tests = new ArrayList<>(); + class SPARQLSyntaxManifest { + List tests = new ArrayList<>(); List subManifests = new ArrayList<>(); public SPARQLSyntaxManifest(String filename) { @@ -146,10 +217,9 @@ public SPARQLSyntaxManifest(String filename) { for (BindingSet bs : result) { // FIXME I'm sure there's a neater way to do this String testName = bs.getValue("Name").stringValue(); - String displayName = filename.substring( - filename.lastIndexOf("testcases-sparql-1.1-w3c/") - + "testcases-sparql-1.1-w3c/".length(), - filename.lastIndexOf("/")) + String displayName = filename + .substring(filename.lastIndexOf("testcases-sparql-1.1-w3c/") + + "testcases-sparql-1.1-w3c/".length(), filename.lastIndexOf("/")) + ": " + testName; IRI testURI = (IRI) bs.getValue("TestURI"); @@ -160,12 +230,11 @@ public SPARQLSyntaxManifest(String filename) { || type.equals( "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveUpdateSyntaxTest11"); - tests.add(new Object[] { - displayName, - testURI.stringValue(), - testName, - action.stringValue(), - positiveTest }); + DynamicSPARQLSyntaxComplianceTest ds11ut = new DynamicSPARQLSyntaxComplianceTest(displayName, + testURI.stringValue(), testName, action.stringValue(), + positiveTest); + if (!shouldIgnoredTest(testName)) + tests.add(DynamicTest.dynamicTest(displayName, ds11ut::test)); } } @@ -176,65 +245,4 @@ public SPARQLSyntaxManifest(String filename) { } protected abstract ParsedOperation parseOperation(String operation, String fileURL) throws MalformedQueryException; - - @Override - protected void runTest() throws Exception { - InputStream stream = new URL(queryFileURL).openStream(); - String query = IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - stream.close(); - - try { - ParsedOperation operation = parseOperation(query, queryFileURL); - - assertThatNoException().isThrownBy(() -> { - int hashCode = operation.hashCode(); - if (hashCode == System.identityHashCode(operation)) { - throw new UnsupportedOperationException("hashCode() result is the same as the identityHashCode in " - + operation.getClass().getName()); - } - }); - - if (!positiveTest) { - boolean dataBlockUpdate = false; - if (operation instanceof ParsedUpdate) { - for (UpdateExpr updateExpr : ((ParsedUpdate) operation).getUpdateExprs()) { - if (updateExpr instanceof InsertData || updateExpr instanceof DeleteData) { - // parsing for these operation happens during actual - // execution, so try and execute. - dataBlockUpdate = true; - - MemoryStore store = new MemoryStore(); - store.init(); - NotifyingSailConnection conn = store.getConnection(); - try { - conn.begin(); - SailUpdateExecutor exec = new SailUpdateExecutor(conn, store.getValueFactory(), null); - exec.executeUpdate(updateExpr, null, null, true, -1); - conn.rollback(); - fail("Negative test case should have failed to parse"); - } catch (SailException e) { - if (!(e.getCause() instanceof RDFParseException)) { - logger.error("unexpected error in negative test case", e); - fail("unexpected error in negative test case"); - } - // fall through - a parse exception is expected for a - // negative test case - conn.rollback(); - } finally { - conn.close(); - } - } - } - } - if (!dataBlockUpdate) { - fail("Negative test case should have failed to parse"); - } - } - } catch (MalformedQueryException e) { - if (positiveTest) { - e.printStackTrace(); - fail("Positive test case failed: " + e.getMessage()); - } - } - } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java deleted file mode 100644 index ff242f45df3..00000000000 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLUpdateConformanceTest.java +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Distribution License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * SPDX-License-Identifier: BSD-3-Clause - *******************************************************************************/ -package org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.rdf4j.common.io.IOUtil; -import org.eclipse.rdf4j.common.iteration.Iterations; -import org.eclipse.rdf4j.common.text.StringUtil; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Literal; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import org.eclipse.rdf4j.model.util.Models; -import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Dataset; -import org.eclipse.rdf4j.query.MalformedQueryException; -import org.eclipse.rdf4j.query.QueryEvaluationException; -import org.eclipse.rdf4j.query.QueryLanguage; -import org.eclipse.rdf4j.query.TupleQuery; -import org.eclipse.rdf4j.query.TupleQueryResult; -import org.eclipse.rdf4j.query.Update; -import org.eclipse.rdf4j.query.impl.SimpleDataset; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.sail.SailRepository; -import org.eclipse.rdf4j.repository.util.Repositories; -import org.eclipse.rdf4j.rio.Rio; -import org.eclipse.rdf4j.sail.memory.MemoryStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * A SPARQL 1.1 Update test, created by reading in a W3C working-group style manifest. - * - * @author Jeen Broekstra - * - * @deprecated Use {@link SPARQL11UpdateComplianceTest} instead. - */ -@Deprecated(since = "3.3.0") -public abstract class SPARQLUpdateConformanceTest extends TestCase { - - /*-----------* - * Constants * - *-----------*/ - - static final Logger logger = LoggerFactory.getLogger(SPARQLUpdateConformanceTest.class); - - protected final String testURI; - - protected final String requestFileURL; - - /*-----------* - * Variables * - *-----------*/ - - protected Repository dataRep; - - protected Repository expectedResultRepo; - - private final IRI inputDefaultGraph; - - private final Map inputNamedGraphs; - - private final IRI resultDefaultGraph; - - private final Map resultNamedGraphs; - - protected final Dataset dataset; - - /*--------------* - * Constructors * - *--------------*/ - - public SPARQLUpdateConformanceTest(String testURI, String name, String requestFile, IRI defaultGraphURI, - Map inputNamedGraphs, IRI resultDefaultGraphURI, Map resultNamedGraphs) { - super(name); - - this.testURI = testURI; - this.requestFileURL = requestFile; - this.inputDefaultGraph = defaultGraphURI; - this.inputNamedGraphs = inputNamedGraphs; - this.resultDefaultGraph = resultDefaultGraphURI; - this.resultNamedGraphs = resultNamedGraphs; - - final SimpleDataset ds = new SimpleDataset(); - - // This ensures that the repository operates in 'exclusive - // mode': the default graph _only_ consists of the null-context (instead - // of the entire repository). - ds.addDefaultGraph(null); - ds.addDefaultRemoveGraph(null); - ds.setDefaultInsertGraph(null); - - if (this.inputNamedGraphs.size() > 0) { - for (String ng : inputNamedGraphs.keySet()) { - IRI namedGraph = SimpleValueFactory.getInstance().createIRI(ng); - ds.addNamedGraph(namedGraph); - } - } - this.dataset = ds; - } - - /*---------* - * Methods * - *---------*/ - - @Override - protected void setUp() throws Exception { - dataRep = createRepository(); - - try (RepositoryConnection conn = dataRep.getConnection()) { - conn.clear(); - - if (inputDefaultGraph != null) { - URL graphURL = new URL(inputDefaultGraph.stringValue()); - conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); - } - - for (String ng : inputNamedGraphs.keySet()) { - URL graphURL = new URL(inputNamedGraphs.get(ng).stringValue()); - conn.add(graphURL, null, - Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), - dataRep.getValueFactory().createIRI(ng)); - } - } - - expectedResultRepo = createRepository(); - - try (RepositoryConnection conn = expectedResultRepo.getConnection()) { - conn.clear(); - - if (resultDefaultGraph != null) { - URL graphURL = new URL(resultDefaultGraph.stringValue()); - conn.add(graphURL, null, Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString()))); - } - - for (String ng : resultNamedGraphs.keySet()) { - URL graphURL = new URL(resultNamedGraphs.get(ng).stringValue()); - conn.add(graphURL, null, - Rio.getParserFormatForFileName(graphURL.toString()) - .orElseThrow(Rio.unsupportedFormat(graphURL.toString())), - dataRep.getValueFactory().createIRI(ng)); - } - } - } - - protected Repository createRepository() { - Repository repo = newRepository(); - Repositories.consume(repo, con -> { - con.clear(); - con.clearNamespaces(); - }); - - return repo; - } - - protected abstract Repository newRepository(); - - @Override - protected void tearDown() { - if (dataRep != null) { - dataRep.shutDown(); - dataRep = null; - } - } - - @Override - protected void runTest() throws Exception { - RepositoryConnection con = dataRep.getConnection(); - RepositoryConnection erCon = expectedResultRepo.getConnection(); - try { - String updateString = readUpdateString(); - - con.begin(); - - Update update = con.prepareUpdate(QueryLanguage.SPARQL, updateString, requestFileURL); - update.setDataset(dataset); - update.execute(); - - con.commit(); - - // check default graph - logger.info("checking default graph"); - compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, (Resource) null)), - Iterations.asList(erCon.getStatements(null, null, null, true, (Resource) null))); - - for (String namedGraph : inputNamedGraphs.keySet()) { - logger.info("checking named graph {}", namedGraph); - IRI contextURI = con.getValueFactory().createIRI(namedGraph.replaceAll("\"", "")); - compareGraphs(Iterations.asList(con.getStatements(null, null, null, true, contextURI)), - Iterations.asList(erCon.getStatements(null, null, null, true, contextURI))); - } - } catch (Exception e) { - if (con.isActive()) { - con.rollback(); - } - throw e; - } finally { - con.close(); - erCon.close(); - } - } - - private void compareGraphs(Iterable actual, Iterable expected) { - if (!Models.isomorphic(expected, actual)) { - StringBuilder message = new StringBuilder(128); - message.append("\n============ "); - message.append(getName()); - message.append(" =======================\n"); - message.append("Expected result: \n"); - for (Statement st : expected) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - message.append("Actual result: \n"); - for (Statement st : actual) { - message.append(st.toString()); - message.append("\n"); - } - message.append("============="); - StringUtil.appendN('=', getName().length(), message); - message.append("========================\n"); - - logger.error(message.toString()); - fail(message.toString()); - } - } - - private String readUpdateString() throws IOException { - try (InputStream stream = new URL(requestFileURL).openStream()) { - return IOUtil.readString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - } - } - - public interface Factory { - - SPARQLUpdateConformanceTest createSPARQLUpdateConformanceTest(String testURI, String name, String requestFile, - IRI defaultGraphURI, Map inputNamedGraphs, IRI resultDefaultGraphURI, - Map resultNamedGraphs); - - } - - public static TestSuite suite(String manifestFileURL, Factory factory) throws Exception { - return suite(manifestFileURL, factory, true); - } - - public static TestSuite suite(String manifestFileURL, Factory factory, boolean approvedOnly) throws Exception { - logger.info("Building test suite for {}", manifestFileURL); - - TestSuite suite = new TestSuite(factory.getClass().getName()); - - // Read manifest and create declared test cases - Repository manifestRep = new SailRepository(new MemoryStore()); - try (RepositoryConnection con = manifestRep.getConnection()) { - - SPARQL11ManifestTest.addTurtle(con, new URL(manifestFileURL), manifestFileURL); - - suite.setName(getManifestName(manifestRep, con, manifestFileURL)); - - // Extract test case information from the manifest file. Note that we - // only select those test cases that are mentioned in the list. - StringBuilder query = new StringBuilder(512); - query.append("PREFIX mf: \n "); - query.append("PREFIX dawgt = \n"); - query.append("PREFIX qt: \n"); - query.append("PREFIX ut: \n"); - query.append("PREFIX sd: \n"); - query.append("PREFIX ent: \n"); - query.append( - " SELECT DISTINCT ?testURI ?testName ?result ?action ?requestFile ?defaultGraph ?resultDefaultGraph \n"); - query.append(" WHERE { [] rdf:first ?testURI. ?testURI a mf:UpdateEvaluationTest; "); - if (approvedOnly) { - query.append(" dawgt:approval dawgt:Approved; "); - } - query.append(" mf:name ?testName; "); - query.append(" mf:action ?action. ?action ut:request ?requestFile. "); - query.append(" OPTIONAL {?action ut:data ?defaultGraph .} "); - query.append(" ?testURI mf:result ?result . \n"); - query.append(" OPTIONAL { ?result ut:data ?resultDefaultGraph }} "); - - TupleQuery testCaseQuery = con.prepareTupleQuery(query.toString()); - - query.setLength(0); - query.append("PREFIX ut: \n"); - query.append(" SELECT DISTINCT ?namedGraphData ?namedGraphLabel "); - query.append(" WHERE { ?graphDef ut:graphData [ ut:graph ?namedGraphData ; "); - query.append(" rdfs:label ?namedGraphLabel].} "); - - TupleQuery namedGraphsQuery = con.prepareTupleQuery(query.toString()); - - logger.debug("evaluating query.."); - TupleQueryResult testCases = testCaseQuery.evaluate(); - while (testCases.hasNext()) { - BindingSet bindingSet = testCases.next(); - - IRI testURI = (IRI) bindingSet.getValue("testURI"); - String testName = bindingSet.getValue("testName").toString(); - Value result = bindingSet.getValue("result"); - Value action = bindingSet.getValue("action"); - IRI requestFile = (IRI) bindingSet.getValue("requestFile"); - IRI defaultGraphURI = (IRI) bindingSet.getValue("defaultGraph"); - IRI resultDefaultGraphURI = (IRI) bindingSet.getValue("resultDefaultGraph"); - - logger.debug("found test case : {}", testName); - - // Query input named graphs - namedGraphsQuery.setBinding("graphDef", action); - TupleQueryResult inputNamedGraphsResult = namedGraphsQuery.evaluate(); - - HashMap inputNamedGraphs = new HashMap<>(); - - if (inputNamedGraphsResult.hasNext()) { - while (inputNamedGraphsResult.hasNext()) { - BindingSet graphBindings = inputNamedGraphsResult.next(); - IRI namedGraphData = (IRI) graphBindings.getValue("namedGraphData"); - String namedGraphLabel = ((Literal) graphBindings.getValue("namedGraphLabel")).getLabel(); - logger.debug(" adding named graph : {}", namedGraphLabel); - inputNamedGraphs.put(namedGraphLabel, namedGraphData); - } - } - - // Query result named graphs - namedGraphsQuery.setBinding("graphDef", result); - TupleQueryResult resultNamedGraphsResult = namedGraphsQuery.evaluate(); - - HashMap resultNamedGraphs = new HashMap<>(); - - if (resultNamedGraphsResult.hasNext()) { - while (resultNamedGraphsResult.hasNext()) { - BindingSet graphBindings = resultNamedGraphsResult.next(); - IRI namedGraphData = (IRI) graphBindings.getValue("namedGraphData"); - String namedGraphLabel = ((Literal) graphBindings.getValue("namedGraphLabel")).getLabel(); - logger.debug(" adding named graph : {}", namedGraphLabel); - resultNamedGraphs.put(namedGraphLabel, namedGraphData); - } - } - - SPARQLUpdateConformanceTest test = factory.createSPARQLUpdateConformanceTest(testURI.toString(), - testName, - requestFile.toString(), defaultGraphURI, inputNamedGraphs, resultDefaultGraphURI, - resultNamedGraphs); - - if (test != null) { - suite.addTest(test); - } - } - - testCases.close(); - } - manifestRep.shutDown(); - logger.info("Created test suite with " + suite.countTestCases() + " test cases."); - return suite; - } - - protected static String getManifestName(Repository manifestRep, RepositoryConnection con, String manifestFileURL) - throws QueryEvaluationException, RepositoryException, MalformedQueryException { - // Try to extract suite name from manifest file - TupleQuery manifestNameQuery = con.prepareTupleQuery( - "SELECT ?ManifestName WHERE { ?ManifestURL rdfs:label ?ManifestName .}"); - manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createIRI(manifestFileURL)); - try (TupleQueryResult manifestNames = manifestNameQuery.evaluate()) { - if (manifestNames.hasNext()) { - return manifestNames.next().getValue("ManifestName").stringValue(); - } - } - - // Derive name from manifest URL - int lastSlashIdx = manifestFileURL.lastIndexOf('/'); - int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1); - return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx); - } -} From 940e316bfaff616cdbf61aced8654ee59965eee9 Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Fri, 3 Nov 2023 11:10:54 +0100 Subject: [PATCH 3/6] GH-4592 Make sure tests do not share state as they run concurrently. Signed-off-by: Jerven Bolleman --- .../sparql/AbstractComplianceTest.java | 37 +- .../RepositorySPARQLComplianceTestSuite.java | 66 +- .../testsuite/sparql/tests/AggregateTest.java | 584 ++++++++------ .../sparql/tests/ArbitraryLengthPathTest.java | 729 ++++++++++-------- .../testsuite/sparql/tests/BasicTest.java | 60 +- .../testsuite/sparql/tests/BindTest.java | 302 +++++--- .../sparql/tests/BuiltinFunctionTest.java | 470 ++++++----- .../testsuite/sparql/tests/ConstructTest.java | 101 +-- .../sparql/tests/DefaultGraphTest.java | 142 ++-- .../testsuite/sparql/tests/DescribeTest.java | 455 ++++++----- .../testsuite/sparql/tests/ExistsTest.java | 58 +- .../testsuite/sparql/tests/GroupByTest.java | 24 +- .../rdf4j/testsuite/sparql/tests/InTest.java | 98 ++- .../testsuite/sparql/tests/MinusTest.java | 49 +- .../testsuite/sparql/tests/OptionalTest.java | 173 +++-- .../testsuite/sparql/tests/OrderByTest.java | 78 +- .../sparql/tests/PropertyPathTest.java | 313 ++++---- .../testsuite/sparql/tests/SubselectTest.java | 91 ++- .../testsuite/sparql/tests/UnionTest.java | 152 ++-- .../testsuite/sparql/tests/ValuesTest.java | 273 ++++--- 20 files changed, 2400 insertions(+), 1855 deletions(-) diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java index 7f9fa95172e..10255c775b7 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java @@ -15,6 +15,7 @@ import java.io.InputStream; import java.io.Reader; import java.net.URL; +import java.util.function.Supplier; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.transaction.IsolationLevel; @@ -60,36 +61,36 @@ public abstract class AbstractComplianceTest { protected DynamicTest makeTest(String name, Executable x) { return DynamicTest.dynamicTest(name, () -> { - setUp(); x.execute(); - tearDown(); }); } - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - - protected final Repository repo; - protected RepositoryConnection conn; - - public AbstractComplianceTest(Repository repo) { - this.repo = repo; + protected Repository openRepository() { + Repository r = repo.get(); + r.init(); + return r; } - public void setUp() { - repo.init(); - conn = new RepositoryConnectionWrapper(repo.getConnection()); + protected RepositoryConnection openConnection(Repository r) { + return new RepositoryConnectionWrapper(r.getConnection()); } - public void tearDown() { - try { + protected void closeRepository(Repository r) { + try (RepositoryConnection conn = r.getConnection()) { conn.clear(); - conn.close(); - } finally { - repo.shutDown(); } + r.shutDown(); + } + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + protected final Supplier repo; + + public AbstractComplianceTest(Supplier repo) { + this.repo = repo; } - protected void loadTestData(String dataFile, Resource... contexts) + protected void loadTestData(String dataFile, RepositoryConnection conn, Resource... contexts) throws RDFParseException, RepositoryException, IOException { logger.debug("loading dataset {}", dataFile); try (InputStream dataset = this.getClass().getResourceAsStream(dataFile)) { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java index 50539b84b9c..377e15a2cc7 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/RepositorySPARQLComplianceTestSuite.java @@ -10,8 +10,11 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.eclipse.rdf4j.common.annotation.Experimental; @@ -56,92 +59,92 @@ public abstract class RepositorySPARQLComplianceTestSuite { @TestFactory Stream aggregate() throws RDF4JException, IOException { - return new AggregateTest(getEmptyInitializedRepository()).tests(); + return new AggregateTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream arbitraryLengthPath() throws RDF4JException, IOException { - return new ArbitraryLengthPathTest(getEmptyInitializedRepository()).tests(); + return new ArbitraryLengthPathTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream basic() throws RDF4JException, IOException { - return new BasicTest(getEmptyInitializedRepository()).tests(); + return new BasicTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream bind() throws RDF4JException, IOException { - return new BindTest(getEmptyInitializedRepository()).tests(); + return new BindTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream builtinFunction() throws RDF4JException, IOException { - return new BuiltinFunctionTest(getEmptyInitializedRepository()).tests(); + return new BuiltinFunctionTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream construct() throws RDF4JException, IOException { - return new ConstructTest(getEmptyInitializedRepository()).tests(); + return new ConstructTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream defaultGraph() throws RDF4JException, IOException { - return new DefaultGraphTest(getEmptyInitializedRepository()).tests(); + return new DefaultGraphTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream describe() throws RDF4JException, IOException { - return new DescribeTest(getEmptyInitializedRepository()).tests(); + return new DescribeTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream groupBy() throws RDF4JException, IOException { - return new GroupByTest(getEmptyInitializedRepository()).tests(); + return new GroupByTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream in() throws RDF4JException, IOException { - return new InTest(getEmptyInitializedRepository()).tests(); + return new InTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream optional() throws RDF4JException, IOException { - return new OptionalTest(getEmptyInitializedRepository()).tests(); + return new OptionalTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream propertyPath() throws RDF4JException, IOException { - return new PropertyPathTest(getEmptyInitializedRepository()).tests(); + return new PropertyPathTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream subselect() throws RDF4JException, IOException { - return new SubselectTest(getEmptyInitializedRepository()).tests(); + return new SubselectTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream union() throws RDF4JException, IOException { - return new UnionTest(getEmptyInitializedRepository()).tests(); + return new UnionTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream values() throws RDF4JException, IOException { - return new ValuesTest(getEmptyInitializedRepository()).tests(); + return new ValuesTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream orderBy() throws RDF4JException, IOException { - return new OrderByTest(getEmptyInitializedRepository()).tests(); + return new OrderByTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream exists() throws RDF4JException, IOException { - return new ExistsTest(getEmptyInitializedRepository()).tests(); + return new ExistsTest(this::getEmptyInitializedRepository).tests(); } @TestFactory Stream minus() throws RDF4JException, IOException { - return new MinusTest(getEmptyInitializedRepository()).tests(); + return new MinusTest(this::getEmptyInitializedRepository).tests(); } @BeforeAll @@ -157,6 +160,8 @@ public static void tearDownClass() { @TempDir private File dataDir; + private static final AtomicInteger tempDirNameForRepoCounter = new AtomicInteger(); + protected final RepositoryFactory factory; public RepositorySPARQLComplianceTestSuite(RepositoryFactory factory) { @@ -164,13 +169,24 @@ public RepositorySPARQLComplianceTestSuite(RepositoryFactory factory) { this.factory = factory; } - public Repository getEmptyInitializedRepository() throws RDF4JException, IOException { - Repository repository = factory.getRepository(factory.getConfig()); - repository.setDataDir(dataDir); - try (RepositoryConnection con = repository.getConnection()) { - con.clear(); - con.clearNamespaces(); + public Repository getEmptyInitializedRepository() { + try { + Repository repository = factory.getRepository(factory.getConfig()); + dataDir.mkdir(); + File tmpDirPerRepo = new File(dataDir, "tmpDirPerRepo" + tempDirNameForRepoCounter.getAndIncrement()); + if (!tmpDirPerRepo.mkdir()) { + fail("Could not create temporary directory for test"); + } + repository.setDataDir(tmpDirPerRepo); + try (RepositoryConnection con = repository.getConnection()) { + con.clear(); + con.clearNamespaces(); + } + return repository; + + } catch (RDF4JException e) { + fail(e); + return null; } - return repository; } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java index 814e6fe91f0..12fcbc1df0a 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java @@ -21,6 +21,7 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.BNode; @@ -36,6 +37,7 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -46,13 +48,12 @@ */ public class AggregateTest extends AbstractComplianceTest { - public AggregateTest(Repository repo) { + public AggregateTest(Supplier repo) { super(repo); } public Stream tests() { - return Stream.of( - makeTest("MaxAggregateWithGroupEmptyResult", this::testMaxAggregateWithGroupEmptyResult), + return Stream.of(makeTest("MaxAggregateWithGroupEmptyResult", this::testMaxAggregateWithGroupEmptyResult), makeTest("MaxAggregateWithoutGroupEmptySolution", this::testMaxAggregateWithoutGroupEmptySolution), makeTest("MinAggregateWithGroupEmptyResult", this::testMinAggregateWithGroupEmptyResult), makeTest("MinAggregateWithoutGroupEmptySolution", this::testMinAggregateWithoutGroupEmptySolution), @@ -61,12 +62,9 @@ public Stream tests() { this::testSampleAggregateWithoutGroupEmptySolution), makeTest("SES2361UndefMin", this::testSES2361UndefMin), makeTest("CountOrderBy_ImplicitGroup", this::testCountOrderBy_ImplicitGroup), - makeTest("DistinctMax", this::testDistinctMax), - makeTest("Max", this::testMax), - makeTest("DistinctAvg", this::testDistinctAvg), - makeTest("Avg", this::testAvg), - makeTest("DistinctSum", this::testDistinctSum), - makeTest("Sum", this::testSum), + makeTest("DistinctMax", this::testDistinctMax), makeTest("Max", this::testMax), + makeTest("DistinctAvg", this::testDistinctAvg), makeTest("Avg", this::testAvg), + makeTest("DistinctSum", this::testDistinctSum), makeTest("Sum", this::testSum), makeTest("CountHaving", this::testCountHaving), makeTest("SES1970CountDistinctWildcard", this::testSES1970CountDistinctWildcard), makeTest("GroupConcatNonDistinct", this::testGroupConcatNonDistinct), @@ -75,18 +73,22 @@ public Stream tests() { makeTest("SES2361UndefSum", this::testSES2361UndefSum), makeTest("SES2361UndefCountWildcard", this::testSES2361UndefCountWildcard), makeTest("SES2361UndefCount", this::testSES2361UndefCount), - makeTest("SES2361UndefMax", this::testSES2361UndefMax) - ); + makeTest("SES2361UndefMax", this::testSES2361UndefMax)); } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ private void testMaxAggregateWithGroupEmptyResult() { - String query = "select ?s (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select ?s (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); + } + } finally { + closeRepository(repo); } } @@ -94,10 +96,15 @@ private void testMaxAggregateWithGroupEmptyResult() { * See https://github.com/eclipse/rdf4j/issues/1978 */ private void testMaxAggregateWithoutGroupEmptySolution() { - String query = "select (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); + } + } finally { + closeRepository(repo); } } @@ -106,10 +113,15 @@ private void testMaxAggregateWithoutGroupEmptySolution() { */ private void testMinAggregateWithGroupEmptyResult() { - String query = "select ?s (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select ?s (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); + } + } finally { + closeRepository(repo); } } @@ -117,10 +129,15 @@ private void testMinAggregateWithGroupEmptyResult() { * See https://github.com/eclipse/rdf4j/issues/1978 */ private void testMinAggregateWithoutGroupEmptySolution() { - String query = "select (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); + } + } finally { + closeRepository(repo); } } @@ -128,10 +145,15 @@ private void testMinAggregateWithoutGroupEmptySolution() { * See https://github.com/eclipse/rdf4j/issues/1978 */ private void testSampleAggregateWithGroupEmptyResult() { - String query = "select ?s (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select ?s (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); + } + } finally { + closeRepository(repo); } } @@ -139,317 +161,405 @@ private void testSampleAggregateWithGroupEmptyResult() { * See https://github.com/eclipse/rdf4j/issues/1978 */ private void testSampleAggregateWithoutGroupEmptySolution() { - String query = "select (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); + } + } finally { + closeRepository(repo); } } private void testSES2361UndefMin() { - String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("min").stringValue()).isEqualTo("1"); - assertThat(result.hasNext()).isFalse(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("min").stringValue()).isEqualTo("1"); + assertThat(result.hasNext()).isFalse(); + } + } finally { + closeRepository(repo); } } private void testSES2361UndefMax() { - String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("max").stringValue()).isEqualTo("7"); - assertThat((Iterable) result).isEmpty(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("max").stringValue()).isEqualTo("7"); + assertThat((Iterable) result).isEmpty(); + } + } finally { + closeRepository(repo); } } private void testSES2361UndefCount() { String query = "SELECT (COUNT(?v) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat((Iterable) result).isEmpty(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); + assertThat((Iterable) result).isEmpty(); + } + } finally { + closeRepository(repo); } } private void testSES2361UndefCountWildcard() { String query = "SELECT (COUNT(*) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat((Iterable) result).isEmpty(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); + assertThat((Iterable) result).isEmpty(); + } + } finally { + closeRepository(repo); } } private void testSES2361UndefSum() { - String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("s").stringValue()).isEqualTo("10"); - assertThat((Iterable) result).isEmpty(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("s").stringValue()).isEqualTo("10"); + assertThat((Iterable) result).isEmpty(); + } + } finally { + closeRepository(repo); } } private void testSES1979MinMaxInf() throws Exception { - loadTestData("/testdata-query/dataset-ses1979.trig"); - String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertThat((Iterable) result).isNotNull().hasSize(1); - assertThat(result.get(0).getValue("min")).isEqualTo(literal(Float.NEGATIVE_INFINITY)); - assertThat(result.get(0).getValue("max")).isEqualTo(literal(Float.POSITIVE_INFINITY)); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1979.trig", conn); + String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertThat((Iterable) result).isNotNull().hasSize(1); + assertThat(result.get(0).getValue("min")).isEqualTo(literal(Float.NEGATIVE_INFINITY)); + assertThat(result.get(0).getValue("max")).isEqualTo(literal(Float.POSITIVE_INFINITY)); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); } } private void testGroupConcatDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" - + "WHERE { ex:groupconcat-test ?p ?l . }"; + String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); - while (result.hasNext()) { - BindingSet bs = result.next(); - assertThat(bs).isNotNull(); + while (result.hasNext()) { + BindingSet bs = result.next(); + assertThat(bs).isNotNull(); - Value concat = bs.getValue("concat"); + Value concat = bs.getValue("concat"); - assertThat(concat).isInstanceOf(Literal.class); + assertThat(concat).isInstanceOf(Literal.class); - String lexValue = ((Literal) concat).getLabel(); + String lexValue = ((Literal) concat).getLabel(); - int occ = countCharOccurrences(lexValue, 'a'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'b'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'c'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'd'); - assertThat(occ).isEqualTo(1); + int occ = countCharOccurrences(lexValue, 'a'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'b'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'c'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'd'); + assertThat(occ).isEqualTo(1); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } } private void testGroupConcatNonDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(?l) AS ?concat)" - + "WHERE { ex:groupconcat-test ?p ?l . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertThat(bs).isNotNull(); - - Value concat = bs.getValue("concat"); - - assertThat(concat).isInstanceOf(Literal.class); - - String lexValue = ((Literal) concat).getLabel(); - - int occ = countCharOccurrences(lexValue, 'a'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'b'); - assertThat(occ).isEqualTo(2); - occ = countCharOccurrences(lexValue, 'c'); - assertThat(occ).isEqualTo(2); - occ = countCharOccurrences(lexValue, 'd'); - assertThat(occ).isEqualTo(1); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); + + while (result.hasNext()) { + BindingSet bs = result.next(); + assertThat(bs).isNotNull(); + + Value concat = bs.getValue("concat"); + + assertThat(concat).isInstanceOf(Literal.class); + + String lexValue = ((Literal) concat).getLabel(); + + int occ = countCharOccurrences(lexValue, 'a'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'b'); + assertThat(occ).isEqualTo(2); + occ = countCharOccurrences(lexValue, 'c'); + assertThat(occ).isEqualTo(2); + occ = countCharOccurrences(lexValue, 'd'); + assertThat(occ).isEqualTo(1); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } } private void testSES1970CountDistinctWildcard() throws Exception { - loadTestData("/testdata-query/dataset-ses1970.trig"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1970.trig", conn); - String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; + String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - BindingSet s = result.next(); - assertThat(getIntValue(s.getValue("c"), 0)).isEqualTo(3); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertThat(result.hasNext()).isTrue(); + BindingSet s = result.next(); + assertThat(getIntValue(s.getValue("c"), 0)).isEqualTo(3); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); } } private void testCountHaving() { - BNode bnode1 = bnode(); - BNode bnode2 = bnode(); - BNode bnode3 = bnode(); - - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - conn.add(bnode2, FOAF.KNOWS, bnode()); - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - - String query = "SELECT ?a WHERE { ?a ?b ?c } GROUP BY ?a HAVING( (COUNT(?c) > 1 ) && ( COUNT(?c) != 0 ) ) "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - assertThat(collect).hasSize(2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + BNode bnode1 = bnode(); + BNode bnode2 = bnode(); + BNode bnode3 = bnode(); + + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + conn.add(bnode2, FOAF.KNOWS, bnode()); + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + + String query = "SELECT ?a WHERE { ?a ?b ?c } GROUP BY ?a HAVING( (COUNT(?c) > 1 ) && ( COUNT(?c) != 0 ) ) "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + assertThat(collect).hasSize(2); + } + } finally { + closeRepository(repo); } } private void testSum() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (SUM(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("89.4786576482391284723864721567342354783275234"))); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + String query = "SELECT ?a (SUM(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("89.4786576482391284723864721567342354783275234"))); - } + } + } finally { + closeRepository(repo); + } } private void testDistinctSum() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (SUM(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("55.4786576482391284723864721567342354783275234"))); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (SUM(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("55.4786576482391284723864721567342354783275234"))); + } + } finally { + closeRepository(repo); } } private void testAvg() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (AVG(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("17.89573152964782569447729443134684709566550468"))); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (AVG(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("17.89573152964782569447729443134684709566550468"))); + } + } finally { + closeRepository(repo); } } private void testDistinctAvg() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (AVG(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("18.492885882746376157462157"))); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (AVG(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("18.492885882746376157462157"))); + } + } finally { + closeRepository(repo); } } private void testMax() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (MAX(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (MAX(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); + } + } finally { + closeRepository(repo); } - } private void testDistinctMax() { - mixedDataForNumericAggregates(); - - String query = "SELECT ?a (MAX(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (MAX(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); + } + } finally { + closeRepository(repo); } } /** - * @see https://github.com/eclipse/rdf4j/issues/4290 + * @see https://github.com/eclipse/rdf4j/issues/4290 */ private void testCountOrderBy_ImplicitGroup() { - mixedDataForNumericAggregates(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + mixedDataForNumericAggregates(conn); - String query = "select (count(*) as ?c) where { \n" + " ?s ?p ?o .\n" + "} \n" + "order by (?s)"; + String query = "select (count(*) as ?c) where { \n" + " ?s ?p ?o .\n" + "} \n" + "order by (?s)"; - TupleQuery preparedQuery = conn.prepareTupleQuery(query); + TupleQuery preparedQuery = conn.prepareTupleQuery(query); - List result = QueryResults.asList(preparedQuery.evaluate()); - assertThat(result).hasSize(1); + List result = QueryResults.asList(preparedQuery.evaluate()); + assertThat(result).hasSize(1); - BindingSet bs = result.get(0); - assertThat(bs.size()).isEqualTo(1); - assertThat(getIntValue(bs.getValue("c"), 0)).isEqualTo(19); + BindingSet bs = result.get(0); + assertThat(bs.size()).isEqualTo(1); + assertThat(getIntValue(bs.getValue("c"), 0)).isEqualTo(19); + } finally { + closeRepository(repo); + } } // private methods - private void mixedDataForNumericAggregates() { + private void mixedDataForNumericAggregates(RepositoryConnection conn) { IRI node1 = iri("http://example.com/1"); IRI node2 = iri("http://example.com/2"); IRI node3 = iri("http://example.com/3"); diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java index 66fbe513183..b8da5ce7734 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java @@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.vocabulary.OWL; @@ -25,10 +26,10 @@ import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.impl.SimpleDataset; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL property paths involving * or + operators (arbitrary length paths). @@ -39,7 +40,7 @@ */ public class ArbitraryLengthPathTest extends AbstractComplianceTest { - public ArbitraryLengthPathTest(Repository repo) { + public ArbitraryLengthPathTest(Supplier repo) { super(repo); } @@ -64,45 +65,49 @@ public Stream tests() { */ private void testArbitraryLengthPathWithBinding1() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - count = 0; - while (result2.hasNext()) { + int count = 0; + while (result.hasNext()) { count++; - BindingSet bs = result2.next(); + BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(4, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("parent", OWL.THING); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(4, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -111,47 +116,51 @@ private void testArbitraryLengthPathWithBinding1() throws Exception { */ private void testArbitraryLengthPathWithBinding2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - - // query without initializing ?child first. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + // query without initializing ?child first. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - count = 0; - while (result2.hasNext()) { + int count = 0; + while (result.hasNext()) { count++; - BindingSet bs = result2.next(); + BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(4, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("parent", OWL.THING); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(4, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -160,47 +169,51 @@ private void testArbitraryLengthPathWithBinding2() throws Exception { */ private void testArbitraryLengthPathWithBinding3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - count = 0; - while (result2.hasNext()) { + int count = 0; + while (result.hasNext()) { count++; - BindingSet bs = result2.next(); + BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -209,47 +222,51 @@ private void testArbitraryLengthPathWithBinding3() throws Exception { */ private void testArbitraryLengthPathWithBinding4() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - count = 0; - while (result2.hasNext()) { + int count = 0; + while (result.hasNext()) { count++; - BindingSet bs = result2.next(); + BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -258,53 +275,57 @@ private void testArbitraryLengthPathWithBinding4() throws Exception { */ private void testArbitraryLengthPathWithBinding5() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding5 - // ---"); + // System.out.println("--- testArbitraryLengthPathWithBinding5 + // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + // System.out.println(bs); - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -313,53 +334,57 @@ private void testArbitraryLengthPathWithBinding5() throws Exception { */ private void testArbitraryLengthPathWithBinding6() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - // System.out.println("--- testArbitraryLengthPathWithBinding6 - // ---"); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + // System.out.println("--- testArbitraryLengthPathWithBinding6 + // ---"); - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + // System.out.println(bs); - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -368,56 +393,60 @@ private void testArbitraryLengthPathWithBinding6() throws Exception { */ private void testArbitraryLengthPathWithBinding7() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(EX.ALICE); - tq.setDataset(dt); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - // System.out.println("--- testArbitraryLengthPathWithBinding7 - // ---"); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + SimpleDataset dt = new SimpleDataset(); + dt.addDefaultGraph(EX.ALICE); + tq.setDataset(dt); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - // System.out.println(bs); + // System.out.println("--- testArbitraryLengthPathWithBinding7 + // ---"); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + // System.out.println(bs); - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -426,55 +455,59 @@ private void testArbitraryLengthPathWithBinding7() throws Exception { */ private void testArbitraryLengthPathWithBinding8() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(EX.ALICE); - dt.addDefaultGraph(EX.BOB); - tq.setDataset(dt); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding8 - // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - - // System.out.println(bs); - - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); + + // binding on child instead of parent. + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + SimpleDataset dt = new SimpleDataset(); + dt.addDefaultGraph(EX.ALICE); + dt.addDefaultGraph(EX.BOB); + tq.setDataset(dt); + + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); + // System.out.println("--- testArbitraryLengthPathWithBinding8 + // ---"); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); + // System.out.println(bs); - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(2, count); + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -483,28 +516,32 @@ private void testArbitraryLengthPathWithBinding8() throws Exception { */ private void testArbitraryLengthPathWithFilter1() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(4, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -513,28 +550,32 @@ private void testArbitraryLengthPathWithFilter1() throws Exception { */ private void testArbitraryLengthPathWithFilter2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(4, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -543,52 +584,60 @@ private void testArbitraryLengthPathWithFilter2() throws Exception { */ private void testArbitraryLengthPathWithFilter3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(2, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } private void testPropertyPathInTree() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + " SELECT ?node ?name " + " FROM ex:tree-graph " - + " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; + String query = getNamespaceDeclarations() + " SELECT ?node ?name " + " FROM ex:tree-graph " + + " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); - // System.out.println(bs); + // System.out.println(bs); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java index 4fc374278a0..f558459abf4 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java @@ -14,6 +14,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -25,6 +26,7 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; @@ -38,23 +40,27 @@ */ public class BasicTest extends AbstractComplianceTest { - public BasicTest(Repository repo) { + public BasicTest(Supplier repo) { super(repo); } private void testIdenticalVariablesInStatementPattern() { - conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); - String queryBuilder = "SELECT ?publisher " - + "{ ?publisher ?publisher }"; + String queryBuilder = "SELECT ?publisher " + + "{ ?publisher ?publisher }"; - conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder).evaluate(new AbstractTupleQueryResultHandler() { + conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder).evaluate(new AbstractTupleQueryResultHandler() { - @Override - public void handleSolution(BindingSet bindingSet) { - fail("nobody is self published"); - } - }); + @Override + public void handleSolution(BindingSet bindingSet) { + fail("nobody is self published"); + } + }); + } + closeRepository(repo); } public Stream tests() { @@ -64,26 +70,26 @@ public Stream tests() { @Test public void testIdenticalVariablesSubjectContextInStatementPattern() { - conn.add(EX.ALICE, FOAF.KNOWS, EX.BOB, EX.ALICE); - conn.add(EX.ALICE, RDF.TYPE, FOAF.PERSON, EX.ALICE); - conn.add(EX.ALICE, FOAF.KNOWS, EX.A, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.B, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.C, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.MARY, EX.BOB); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(EX.ALICE, FOAF.KNOWS, EX.BOB, EX.ALICE); + conn.add(EX.ALICE, RDF.TYPE, FOAF.PERSON, EX.ALICE); + conn.add(EX.ALICE, FOAF.KNOWS, EX.A, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.B, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.C, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.MARY, EX.BOB); - String queryBuilder = "SELECT ?knows { " + - " graph ?alice {" + - " ?alice a <" + FOAF.PERSON + ">; " + - " <" + FOAF.KNOWS + "> ?knows ." + - " }" + - "}"; + String queryBuilder = "SELECT ?knows { " + " graph ?alice {" + " ?alice a <" + FOAF.PERSON + ">; " + + " <" + FOAF.KNOWS + "> ?knows ." + " }" + "}"; - try (Stream stream = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) - .evaluate() - .stream()) { - List knows = stream.map(b -> b.getValue("knows")).collect(Collectors.toList()); - assertEquals(List.of(EX.BOB), knows); + try (Stream stream = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) + .evaluate() + .stream()) { + List knows = stream.map(b -> b.getValue("knows")).collect(Collectors.toList()); + assertEquals(List.of(EX.BOB), knows); + } } + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java index fcbfe95fb32..2d37d2067fd 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -33,6 +34,7 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -44,7 +46,7 @@ */ public class BindTest extends AbstractComplianceTest { - public BindTest(Repository repo) { + public BindTest(Supplier repo) { super(repo); } @@ -53,16 +55,21 @@ public BindTest(Repository repo) { */ private void testBindError() { + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") + .execute(); - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); + String qb = "SELECT * \n" + "WHERE { \n" + " VALUES (?NAValue) { () } \n " + + " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " + + " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + "}\n"; - String qb = "SELECT * \n" + "WHERE { \n" + " VALUES (?NAValue) { () } \n " - + " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " - + " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + "}\n"; + List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); - List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); - - assertEquals(2, result.size(), "query should return 2 solutions"); + assertEquals(2, result.size(), "query should return 2 solutions"); + } finally { + closeRepository(repo); + } } /** @@ -70,15 +77,20 @@ private void testBindError() { */ private void testBindScope() { - String query = "SELECT * {\n" + " { BIND (\"a\" AS ?a) }\n" + " { BIND (?a AS ?b) } \n" + "}"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT * {\n" + " { BIND (\"a\" AS ?a) }\n" + " { BIND (?a AS ?b) } \n" + "}"; - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); + TupleQuery q = conn.prepareTupleQuery(query); + List result = QueryResults.asList(q.evaluate()); - assertEquals(1, result.size()); + assertEquals(1, result.size()); - assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a")); - assertNull(result.get(0).getValue("b")); + assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a")); + assertNull(result.get(0).getValue("b")); + } finally { + closeRepository(repo); + } } /** @@ -86,145 +98,179 @@ private void testBindScope() { */ private void testBindScopeUnion() { - - ValueFactory f = conn.getValueFactory(); - String query = "prefix ex: \n" + "select * {\n" + " bind(ex:v1 as ?v)\n" - + " bind(strafter(str(?v),str(ex:)) as ?b)\n" + " {\n" + " bind(?b as ?b1)\n" + " } union {\n" - + " bind(?b as ?b2)\n" + " }\n" + "}"; - - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); - - assertEquals(2, result.size()); - - IRI v1 = f.createIRI("http://example.org/v1"); - Literal b = f.createLiteral("v1"); - for (BindingSet bs : result) { - assertThat(bs.getValue("v")).isEqualTo(v1); - assertThat(bs.getValue("b1")).isNull(); - assertThat(bs.getValue("b2")).isNull(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + ValueFactory f = conn.getValueFactory(); + String query = "prefix ex: \n" + "select * {\n" + " bind(ex:v1 as ?v)\n" + + " bind(strafter(str(?v),str(ex:)) as ?b)\n" + " {\n" + " bind(?b as ?b1)\n" + " } union {\n" + + " bind(?b as ?b2)\n" + " }\n" + "}"; + + TupleQuery q = conn.prepareTupleQuery(query); + List result = QueryResults.asList(q.evaluate()); + + assertEquals(2, result.size()); + + IRI v1 = f.createIRI("http://example.org/v1"); + Literal b = f.createLiteral("v1"); + for (BindingSet bs : result) { + assertThat(bs.getValue("v")).isEqualTo(v1); + assertThat(bs.getValue("b1")).isNull(); + assertThat(bs.getValue("b2")).isNull(); + } + } finally { + closeRepository(repo); } } private void testSES2250BindErrors() { - - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri ?p2 ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse(evaluate.hasNext(), "The query should not return a result"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") + .execute(); + + String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + " ?biri ?p2 ?o2 ." + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertFalse(evaluate.hasNext(), "The query should not return a result"); + } + } finally { + closeRepository(repo); } } private void testSES2250BindErrorsInPath() { - - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri * ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse(evaluate.hasNext(), "The query should not return a result"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") + .execute(); + + String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + " ?biri * ?o2 ." + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertFalse(evaluate.hasNext(), "The query should not return a result"); + } + } finally { + closeRepository(repo); } } private void testSelectBindOnly() { - String query = "select ?b1 ?b2 ?b3\n" + "where {\n" + " bind(1 as ?b1)\n" + "}"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "select ?b1 ?b2 ?b3\n" + "where {\n" + " bind(1 as ?b1)\n" + "}"; - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - assertThat(result.size()).isEqualTo(1); - BindingSet solution = result.get(0); + assertThat(result.size()).isEqualTo(1); + BindingSet solution = result.get(0); - assertThat(solution.getValue("b1")).isEqualTo(literal("1", CoreDatatype.XSD.INTEGER)); - assertThat(solution.getValue("b2")).isNull(); - assertThat(solution.getValue("b3")).isNull(); + assertThat(solution.getValue("b1")).isEqualTo(literal("1", CoreDatatype.XSD.INTEGER)); + assertThat(solution.getValue("b2")).isNull(); + assertThat(solution.getValue("b3")).isNull(); + } finally { + closeRepository(repo); + } } private void testGH3696Bind() { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:unit1") - .add(RDF.TYPE, "ex:Unit") - .add(RDFS.LABEL, "Unit1") - .add("ex:has", "Unit1") - .subject("ex:unit2") - .add(RDF.TYPE, "ex:Unit") - .add(RDFS.LABEL, "Unit2") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT * {\n" + " ?bind rdfs:label ?b1 ;\n" - + " a ex:Unit .\n" + " FILTER (?b1 = 'Unit2') .\n" + " BIND(?bind AS ?n0)\n" - + " ?n0 ex:has ?n1 \n" + " }"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).isEmpty(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:unit1") + .add(RDF.TYPE, "ex:Unit") + .add(RDFS.LABEL, "Unit1") + .add("ex:has", "Unit1") + .subject("ex:unit2") + .add(RDF.TYPE, "ex:Unit") + .add(RDFS.LABEL, "Unit2") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + "SELECT * {\n" + " ?bind rdfs:label ?b1 ;\n" + + " a ex:Unit .\n" + " FILTER (?b1 = 'Unit2') .\n" + " BIND(?bind AS ?n0)\n" + + " ?n0 ex:has ?n1 \n" + " }"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).isEmpty(); + } finally { + closeRepository(repo); + } } private void testGH4499BindFilterNotExist1() { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:a") - .add("ex:p", "ex:c1") - .add("ex:p", "ex:c2") - .add("ex:p", "ex:c3") - .subject("ex:c1") - .add(RDF.TYPE, "ex:T") - .add("ex:q", "something") - .subject("ex:c2") - .add(RDF.TYPE, "ex:T") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" - + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" - + " ?a ex:p* ?c .\n" + " FILTER EXISTS { ?c rdf:type ex:T }\n" - + " FILTER NOT EXISTS { ?c ex:q ?d}\n" + "}"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).hasSize(1); - - var bs = result.get(0); - - assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); - assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); - assertThat(bs.getValue("d")).isNull(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:a") + .add("ex:p", "ex:c1") + .add("ex:p", "ex:c2") + .add("ex:p", "ex:c3") + .subject("ex:c1") + .add(RDF.TYPE, "ex:T") + .add("ex:q", "something") + .subject("ex:c2") + .add(RDF.TYPE, "ex:T") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" + + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" + + " ?a ex:p* ?c .\n" + " FILTER EXISTS { ?c rdf:type ex:T }\n" + + " FILTER NOT EXISTS { ?c ex:q ?d}\n" + "}"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).hasSize(1); + + var bs = result.get(0); + + assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); + assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); + assertThat(bs.getValue("d")).isNull(); + } finally { + closeRepository(repo); + } } private void testGH4499BindFilterNotExist2() { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:a") - .add("ex:p", "ex:c1") - .add("ex:p", "ex:c2") - .add("ex:p", "ex:c3") - .subject("ex:c1") - .add(RDF.TYPE, "ex:T") - .add("ex:q", "something") - .subject("ex:c2") - .add(RDF.TYPE, "ex:T") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" - + " FILTER EXISTS { ?c rdf:type ex:T }\n" + " FILTER NOT EXISTS { ?c ex:q ?d }\n" - + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" - + " ?a ex:p* ?c .\n" + "}"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).hasSize(1); - - var bs = result.get(0); - - assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); - assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); - assertThat(bs.getValue("d")).isNull(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:a") + .add("ex:p", "ex:c1") + .add("ex:p", "ex:c2") + .add("ex:p", "ex:c3") + .subject("ex:c1") + .add(RDF.TYPE, "ex:T") + .add("ex:q", "something") + .subject("ex:c2") + .add(RDF.TYPE, "ex:T") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" + + " FILTER EXISTS { ?c rdf:type ex:T }\n" + + " FILTER NOT EXISTS { ?c ex:q ?d }\n" + " BIND ( ex:a AS ?a )\n" + + " BIND ( ex:b AS ?b )\n" + " ?a ex:p* ?c .\n" + "}"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).hasSize(1); + + var bs = result.get(0); + + assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); + assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); + assertThat(bs.getValue("d")).isNull(); + } finally { + closeRepository(repo); + } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java index 6b71c64aaa7..01dfe7b0831 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -31,6 +32,7 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -42,7 +44,7 @@ */ public class BuiltinFunctionTest extends AbstractComplianceTest { - public BuiltinFunctionTest(Repository repo) { + public BuiltinFunctionTest(Supplier repo) { super(repo); } @@ -53,13 +55,16 @@ public BuiltinFunctionTest(Repository repo) { private void testSeconds() { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13\"^^xsd:dateTime) AS ?sec) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("13", result.next().getValue("sec").stringValue()); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } /** @@ -70,278 +75,341 @@ private void testSecondsMilliseconds() { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13.815-05:00\"^^xsd:dateTime) AS ?sec) { }"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13.815", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("13.815", result.next().getValue("sec").stringValue()); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } private void testSES1991NOWEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - Literal d1 = (Literal) result.next().getValue("d"); - assertTrue(result.hasNext()); - Literal d2 = (Literal) result.next().getValue("d"); - assertFalse(result.hasNext()); - assertNotNull(d1); - assertEquals(d1, d2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + Literal d1 = (Literal) result.next().getValue("d"); + assertTrue(result.hasNext()); + Literal d2 = (Literal) result.next().getValue("d"); + assertFalse(result.hasNext()); + assertNotNull(d1); + assertEquals(d1, d2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } } + closeRepository(repo); } private void testSES869ValueOfNow() { - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, - "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, + "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); - BindingSet bs = result.next(); - Value p = bs.getValue("p"); - Value n = bs.getValue("n"); + BindingSet bs = result.next(); + Value p = bs.getValue("p"); + Value n = bs.getValue("n"); - assertNotNull(p); - assertNotNull(n); - assertEquals(p, n); - assertTrue(p == n); + assertNotNull(p); + assertNotNull(n); + assertEquals(p, n); + assertTrue(p == n); + } } + closeRepository(repo); } private void testSES1991UUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - IRI uuid1 = (IRI) result.next().getValue("uid"); - IRI uuid2 = (IRI) result.next().getValue("uid"); + IRI uuid1 = (IRI) result.next().getValue("uid"); + IRI uuid2 = (IRI) result.next().getValue("uid"); - assertNotNull(uuid1); - assertNotNull(uuid2); - assertNotEquals(uuid1, uuid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertNotNull(uuid1); + assertNotNull(uuid2); + assertNotEquals(uuid1, uuid2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } } + closeRepository(repo); } private void testSES1991STRUUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - Literal uid1 = (Literal) result.next().getValue("uid"); - Literal uid2 = (Literal) result.next().getValue("uid"); + Literal uid1 = (Literal) result.next().getValue("uid"); + Literal uid2 = (Literal) result.next().getValue("uid"); - assertNotNull(uid1); - assertNotEquals(uid1, uid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertNotNull(uid1); + assertNotEquals(uid1, uid2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } } + closeRepository(repo); } private void testSES1991RANDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); - String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - Literal r1 = (Literal) result.next().getValue("r"); - Literal r2 = (Literal) result.next().getValue("r"); - Literal r3 = (Literal) result.next().getValue("r"); - - assertNotNull(r1); - - // there is a small chance that two successive calls to the random - // number generator will generate the exact same value, so we check - // for - // three successive calls (still theoretically possible to be - // identical, but phenomenally unlikely). - assertFalse(r1.equals(r2) && r1.equals(r3)); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + Literal r1 = (Literal) result.next().getValue("r"); + Literal r2 = (Literal) result.next().getValue("r"); + Literal r3 = (Literal) result.next().getValue("r"); + + assertNotNull(r1); + + // there is a small chance that two successive calls to the random + // number generator will generate the exact same value, so we check + // for + // three successive calls (still theoretically possible to be + // identical, but phenomenally unlikely). + assertFalse(r1.equals(r2) && r1.equals(r3)); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } } + closeRepository(repo); } private void testSES2121URIFunction() { - String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNull(uri, "uri result for invalid URI should be unbound"); - } + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI uri = (IRI) bs.getValue("uri"); + assertNull(uri, "uri result for invalid URI should be unbound"); + } - query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNotNull(uri, "uri result for valid URI reference should be bound"); + query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; + tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI uri = (IRI) bs.getValue("uri"); + assertNotNull(uri, "uri result for valid URI reference should be bound"); + } } + closeRepository(repo); } private void test27NormalizeIRIFunction() { - String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI actual = (IRI) bs.getValue("Iri"); - IRI expected = iri("http://example.com/bar"); - assertEquals(expected, actual, "IRI result for relative IRI should be normalized"); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI actual = (IRI) bs.getValue("Iri"); + IRI expected = iri("http://example.com/bar"); + assertEquals(expected, actual, "IRI result for relative IRI should be normalized"); + } } + closeRepository(repo); } private void testSES2052If1() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" - + " FILTER(IF(BOUND(?p), ?p = , false)) \n" - + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" + + " FILTER(IF(BOUND(?p), ?p = , false)) \n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + while (result.hasNext()) { + BindingSet bs = result.next(); + + IRI p = (IRI) bs.getValue("p"); + assertNotNull(p); + assertEquals(RDF.TYPE, p); + } + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); } + closeRepository(repo); } private void testSES2052If2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" - + " FILTER(IF(!BOUND(?p), false , ?p = )) \n" - + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" + + " FILTER(IF(!BOUND(?p), false , ?p = )) \n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + while (result.hasNext()) { + BindingSet bs = result.next(); + + IRI p = (IRI) bs.getValue("p"); + assertNotNull(p); + assertEquals(RDF.TYPE, p); + } + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); } - + closeRepository(repo); } private void testRegexCaseNonAscii() { - String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; - assertTrue(conn.prepareBooleanQuery(query).evaluate(), "case-insensitive match on Cyrillic should succeed"); + assertTrue(conn.prepareBooleanQuery(query).evaluate(), "case-insensitive match on Cyrillic should succeed"); - query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; + query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; - assertFalse(conn.prepareBooleanQuery(query).evaluate(), "case-sensitive match on Cyrillic should fail"); + assertFalse(conn.prepareBooleanQuery(query).evaluate(), "case-sensitive match on Cyrillic should fail"); + } + closeRepository(repo); } private void testFilterRegexBoolean() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - // test case for issue SES-1050 - String query = getNamespaceDeclarations() + " SELECT *" + " WHERE { " + " ?x foaf:name ?name ; " - + " foaf:mbox ?mbox . " + " FILTER(EXISTS { " - + " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + - // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); - " } )" + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(1, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + + // test case for issue SES-1050 + String query = getNamespaceDeclarations() + " SELECT *" + " WHERE { " + " ?x foaf:name ?name ; " + + " foaf:mbox ?mbox . " + " FILTER(EXISTS { " + + " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + + // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); + " } )" + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(1, count); + } } + closeRepository(repo); } private void testDateCastFunction_date() { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } private void testDateCastFunction_date_withTimeZone_utc() { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09Z", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09Z", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } private void testDateCastFunction_dateTime_withTimeZone_offset() { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09+03:00", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09+03:00", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } private void testDateCastFunction_invalidInput() { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-xx\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertFalse(result.next().hasBinding("date"), - "There should be no binding because the cast should have failed."); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-xx\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertFalse(result.next().hasBinding("date"), + "There should be no binding because the cast should have failed."); + assertFalse(result.hasNext()); + } } + closeRepository(repo); } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java index 20b1282e6de..d7476c0e8ef 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.StringReader; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -32,6 +33,7 @@ import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -44,38 +46,42 @@ */ public class ConstructTest extends AbstractComplianceTest { - public ConstructTest(Repository repo) { + public ConstructTest(Supplier repo) { super(repo); } private void testConstructModifiers() throws Exception { - loadTestData("/testdata-query/dataset-construct-modifiers.ttl"); - String qry = "PREFIX foaf: \n" + "PREFIX site: \n" - + "CONSTRUCT { \n" + " ?iri foaf:name ?name . \n" + " ?iri foaf:nick ?nick . \n" + "} \n" - + "WHERE { \n" + " ?iri foaf:name ?name ; \n" + " site:hits ?hits ; \n" + " foaf:nick ?nick . \n" - + "} \n" + "ORDER BY desc(?hits) \n" + "LIMIT 3"; - Statement[] correctResult = { - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), - - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/name"), literal("Eve"), null), - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), - - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), }; - GraphQuery gq = conn.prepareGraphQuery(qry); - try (GraphQueryResult result = gq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - int resultNo = 0; - while (result.hasNext()) { - Statement st = result.next(); - assertThat(resultNo).isLessThan(correctResult.length); - assertEquals(correctResult[resultNo], st); - resultNo++; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-construct-modifiers.ttl", conn); + String qry = "PREFIX foaf: \n" + "PREFIX site: \n" + + "CONSTRUCT { \n" + " ?iri foaf:name ?name . \n" + " ?iri foaf:nick ?nick . \n" + "} \n" + + "WHERE { \n" + " ?iri foaf:name ?name ; \n" + " site:hits ?hits ; \n" + + " foaf:nick ?nick . \n" + "} \n" + "ORDER BY desc(?hits) \n" + "LIMIT 3"; + Statement[] correctResult = { + statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), + statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), + + statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/name"), literal("Eve"), null), + statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), + + statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), + statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), }; + GraphQuery gq = conn.prepareGraphQuery(qry); + try (GraphQueryResult result = gq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + int resultNo = 0; + while (result.hasNext()) { + Statement st = result.next(); + assertThat(resultNo).isLessThan(correctResult.length); + assertEquals(correctResult[resultNo], st); + resultNo++; + } + assertEquals(correctResult.length, resultNo); } - assertEquals(correctResult.length, resultNo); } + closeRepository(repo); } /** @@ -83,34 +89,43 @@ private void testConstructModifiers() throws Exception { */ private void testConstruct_CyclicPathWithJoin() { - IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); - conn.add(test, RDF.TYPE, DCAT.CATALOG); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); + conn.add(test, RDF.TYPE, DCAT.CATALOG); - String query = "PREFIX dcat: \n" + "\n" + "CONSTRUCT {\n" + " ?x .\n" - + " ?x ?x .\n" + "}\n" + "WHERE {\n" + " ?x a dcat:Catalog .\n" + "}"; + String query = "PREFIX dcat: \n" + "\n" + "CONSTRUCT {\n" + + " ?x .\n" + " ?x ?x .\n" + "}\n" + "WHERE {\n" + " ?x a dcat:Catalog .\n" + + "}"; - Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); + Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); - assertThat(result.contains(a, b, test)).isTrue(); - assertThat(result.contains(test, c, test)).isTrue(); + assertThat(result.contains(a, b, test)).isTrue(); + assertThat(result.contains(test, c, test)).isTrue(); + } + closeRepository(repo); } private void testSES2104ConstructBGPSameURI() throws Exception { - final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; - conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); + conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); - final IRI x = conn.getValueFactory().createIRI("urn:x"); - final IRI p = conn.getValueFactory().createIRI("urn:p"); + final IRI x = conn.getValueFactory().createIRI("urn:x"); + final IRI p = conn.getValueFactory().createIRI("urn:p"); - GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr); - try (GraphQueryResult evaluate = query.evaluate()) { - Model result = QueryResults.asModel(evaluate); + GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr); + try (GraphQueryResult evaluate = query.evaluate()) { + Model result = QueryResults.asModel(evaluate); - assertNotNull(result); - assertFalse(result.isEmpty()); - assertTrue(result.contains(x, p, x)); + assertNotNull(result); + assertFalse(result.isEmpty()); + assertTrue(result.contains(x, p, x)); + } } + closeRepository(repo); } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java index ce746c64f1c..20e86934b89 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.Resource; @@ -26,10 +27,10 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on handling default graph identification (DEFAULT keyword, rf4j:nil). @@ -39,89 +40,104 @@ */ public class DefaultGraphTest extends AbstractComplianceTest { - public DefaultGraphTest(Repository repo) { + public DefaultGraphTest(Supplier repo) { super(repo); } private void testNullContext1() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + " FROM DEFAULT " + " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(EX.BOB, s); // should not be present in default - // graph - assertNotEquals(EX.ALICE, s); // should not be present in - // default - // graph + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + " FROM DEFAULT " + " WHERE { ?s ?p ?o } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); + + Resource s = (Resource) bs.getValue("s"); + + assertNotNull(s); + assertNotEquals(EX.BOB, s); // should not be present in default + // graph + assertNotEquals(EX.ALICE, s); // should not be present in + // default + // graph + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); } + closeRepository(repo); } private void testNullContext2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + " FROM rdf4j:nil " + " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(EX.BOB, s); // should not be present in default - // graph - assertNotEquals(EX.ALICE, s); // should not be present in - // default - // graph + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + " FROM rdf4j:nil " + " WHERE { ?s ?p ?o } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); + + Resource s = (Resource) bs.getValue("s"); + + assertNotNull(s); + assertNotEquals(EX.BOB, s); // should not be present in default + // graph + assertNotEquals(EX.ALICE, s); // should not be present in + // default + // graph + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } } private void testSesameNilAsGraph() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = " SELECT * " + " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; // query.append(" WHERE { ?s ?p ?o } "); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try { - List result = QueryResults.asList(tq.evaluate()); + try { + List result = QueryResults.asList(tq.evaluate()); - // nil graph should not be empty - assertThat(result.size()).isGreaterThan(1); + // nil graph should not be empty + assertThat(result.size()).isGreaterThan(1); - for (BindingSet bs : result) { - Resource s = (Resource) bs.getValue("s"); + for (BindingSet bs : result) { + Resource s = (Resource) bs.getValue("s"); - assertNotNull(s); - assertThat(s).withFailMessage("%s should not be present in nil graph", EX.BOB).isNotEqualTo(EX.BOB); - assertThat(s).withFailMessage("%s should not be present in nil graph", EX.ALICE).isNotEqualTo(EX.ALICE); + assertNotNull(s); + assertThat(s).withFailMessage("%s should not be present in nil graph", EX.BOB).isNotEqualTo(EX.BOB); + assertThat(s).withFailMessage("%s should not be present in nil graph", EX.ALICE) + .isNotEqualTo(EX.ALICE); + } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java index 5cee875421b..0812d301fdb 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.BNode; @@ -28,9 +29,9 @@ import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL DESCRIBE queries @@ -39,263 +40,313 @@ */ public class DescribeTest extends AbstractComplianceTest { - public DescribeTest(Repository repo) { + public DescribeTest(Supplier repo) { super(repo); } private void testDescribeA() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ex:a"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:a"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI a = f.createIRI("http://example.org/a"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); + } } } + } finally { + closeRepository(repo); } } private void testDescribeAWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI a = f.createIRI("http://example.org/a"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); + } } } + } finally { + closeRepository(repo); } } private void testDescribeWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI a = vf.createIRI("http://example.org/a"); - IRI b = vf.createIRI("http://example.org/b"); - IRI c = vf.createIRI("http://example.org/c"); - IRI e = vf.createIRI("http://example.org/e"); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertThat(result.contains(a, p, null)).isTrue(); - assertThat(result.contains(b, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(c, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(null, p, b)).isTrue(); - assertThat(result.contains(e, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(null, p, e)).isTrue(); - assertThat(result.contains(f, null, null)).isFalse(); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI a = vf.createIRI("http://example.org/a"); + IRI b = vf.createIRI("http://example.org/b"); + IRI c = vf.createIRI("http://example.org/c"); + IRI e = vf.createIRI("http://example.org/e"); + IRI f = vf.createIRI("http://example.org/f"); + IRI p = vf.createIRI("http://example.org/p"); + + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + assertThat(result.contains(a, p, null)).isTrue(); + assertThat(result.contains(b, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(c, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(null, p, b)).isTrue(); + assertThat(result.contains(e, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(null, p, e)).isTrue(); + assertThat(result.contains(f, null, null)).isFalse(); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); + } } } + } finally { + closeRepository(repo); } } private void testDescribeB() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ex:b"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI b = f.createIRI("http://example.org/b"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set subjects = result.filter(null, p, b).subjects(); - assertThat(subjects).isNotNull(); - for (Value subject : subjects) { - if (subject instanceof BNode) { - assertThat(result.contains(null, null, subject)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:b"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI b = f.createIRI("http://example.org/b"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set subjects = result.filter(null, p, b).subjects(); + assertThat(subjects).isNotNull(); + for (Value subject : subjects) { + if (subject instanceof BNode) { + assertThat(result.contains(null, null, subject)).isTrue(); + } } } + } finally { + closeRepository(repo); } } private void testDescribeD() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ex:d"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI d = f.createIRI("http://example.org/d"); - IRI p = f.createIRI("http://example.org/p"); - IRI e = f.createIRI("http://example.org/e"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(null, p, e)).isTrue(); - assertThat(result.contains(e, null, null)).isFalse(); - - Set objects = result.filter(d, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertThat(childObjects).isNotEmpty(); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertThat(result.contains((BNode) childObject, null, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:d"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI d = f.createIRI("http://example.org/d"); + IRI p = f.createIRI("http://example.org/p"); + IRI e = f.createIRI("http://example.org/e"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(null, p, e)).isTrue(); + assertThat(result.contains(e, null, null)).isFalse(); + + Set objects = result.filter(d, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + Set childObjects = result.filter((BNode) object, null, null).objects(); + assertThat(childObjects).isNotEmpty(); + for (Value childObject : childObjects) { + if (childObject instanceof BNode) { + assertThat(result.contains((BNode) childObject, null, null)).isTrue(); + } } } } } + } finally { + closeRepository(repo); } } private void testDescribeF() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + "DESCRIBE ex:f"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result).isNotNull().hasSize(4); - - Set objects = result.filter(f, p, null).objects(); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertThat(childObjects).isNotEmpty(); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertThat(result.contains((BNode) childObject, null, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:f"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI f = vf.createIRI("http://example.org/f"); + IRI p = vf.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result).isNotNull().hasSize(4); + + Set objects = result.filter(f, p, null).objects(); + for (Value object : objects) { + if (object instanceof BNode) { + Set childObjects = result.filter((BNode) object, null, null).objects(); + assertThat(childObjects).isNotEmpty(); + for (Value childObject : childObjects) { + if (childObject instanceof BNode) { + assertThat(result.contains((BNode) childObject, null, null)).isTrue(); + } } } } } + } finally { + closeRepository(repo); } } private void testDescribeMultipleA() { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String update = "insert data { . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); + + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); + } + } finally { + closeRepository(repo); } } private void testDescribeMultipleB() { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(urn1, blank, null)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String update = "insert data { . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(urn1, blank, null)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); + } + } finally { + closeRepository(repo); } } private void testDescribeMultipleC() { - String update = "insert data { . [] . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(urn1, blank, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String update = "insert data { . [] . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(urn1, blank, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); + } + } finally { + closeRepository(repo); } } private void testDescribeMultipleD() { - String update = "insert data { . [] . . [] . . [] .} "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI urn4 = vf.createIRI("urn:4"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); - assertThat(result.contains(urn4, p2, null)).isTrue(); - assertThat(result.contains(urn4, blank, null)).isTrue(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String update = "insert data { . [] . . [] . . [] .} "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI urn4 = vf.createIRI("urn:4"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); + assertThat(result.contains(urn4, p2, null)).isTrue(); + assertThat(result.contains(urn4, blank, null)).isTrue(); + } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java index 8cc086b2cc9..dc0808f7b06 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java @@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -21,9 +22,9 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Test for queries using EXISTS @@ -32,37 +33,40 @@ */ public class ExistsTest extends AbstractComplianceTest { - public ExistsTest(Repository repo) { + public ExistsTest(Supplier repo) { super(repo); } private void testFilterNotExistsBindingToCurrentSolutionMapping() { - - String ex = "http://example/"; - IRI a1 = Values.iri(ex, "a1"); - IRI a2 = Values.iri(ex, "a2"); - - IRI both = Values.iri(ex, "both"); - - IRI predicate1 = Values.iri(ex, "predicate1"); - IRI predicate2 = Values.iri(ex, "predicate2"); - - conn.add(a1, predicate1, both); - conn.add(a1, predicate2, both); - - conn.add(a2, predicate1, both); - conn.add(a2, predicate2, Values.bnode()); - - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX : \n" + "SELECT * WHERE {\n" - + " ?a :predicate1 ?p1\n" + " FILTER NOT EXISTS {\n" + " ?a :predicate2 ?p2 .\n" - + " FILTER(?p2 = ?p1)\n" + " }\n" + "}\n"); - - try (Stream stream = tupleQuery.evaluate().stream()) { - List collect = stream.collect(Collectors.toList()); - assertEquals(1, collect.size()); - assertEquals(a2, collect.get(0).getValue("a")); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String ex = "http://example/"; + IRI a1 = Values.iri(ex, "a1"); + IRI a2 = Values.iri(ex, "a2"); + + IRI both = Values.iri(ex, "both"); + + IRI predicate1 = Values.iri(ex, "predicate1"); + IRI predicate2 = Values.iri(ex, "predicate2"); + + conn.add(a1, predicate1, both); + conn.add(a1, predicate2, both); + + conn.add(a2, predicate1, both); + conn.add(a2, predicate2, Values.bnode()); + + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX : \n" + "SELECT * WHERE {\n" + + " ?a :predicate1 ?p1\n" + " FILTER NOT EXISTS {\n" + " ?a :predicate2 ?p2 .\n" + + " FILTER(?p2 = ?p1)\n" + " }\n" + "}\n"); + + try (Stream stream = tupleQuery.evaluate().stream()) { + List collect = stream.collect(Collectors.toList()); + assertEquals(1, collect.size()); + assertEquals(a2, collect.get(0).getValue("a")); + } + } finally { + closeRepository(repo); } - } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java index ab60e476490..c5913728458 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java @@ -13,14 +13,15 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL GROUP BY @@ -29,18 +30,23 @@ */ public class GroupByTest extends AbstractComplianceTest { - public GroupByTest(Repository repo) { + public GroupByTest(Supplier repo) { super(repo); } private void testGroupByEmpty() { - // see issue https://github.com/eclipse/rdf4j/issues/573 - String query = "select ?x where {?x ?p ?o} group by ?x"; - - TupleQuery tq = conn.prepareTupleQuery(query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + // see issue https://github.com/eclipse/rdf4j/issues/573 + String query = "select ?x where {?x ?p ?o} group by ?x"; + + TupleQuery tq = conn.prepareTupleQuery(query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); + } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java index fc4f14f282a..e139d5f869f 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; @@ -27,9 +28,9 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on the IN operator. @@ -39,58 +40,73 @@ */ public class InTest extends AbstractComplianceTest { - public InTest(Repository repo) { + public InTest(Supplier repo) { super(repo); } private void testInComparison1() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(literal("1", CoreDatatype.XSD.INTEGER), y); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + BindingSet bs = result.next(); + Value y = bs.getValue("y"); + assertNotNull(y); + assertTrue(y instanceof Literal); + assertEquals(literal("1", CoreDatatype.XSD.INTEGER), y); + } + } finally { + closeRepository(repo); } } private void testInComparison2() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); + } + } finally { + closeRepository(repo); } } private void testInComparison3() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(literal("1", XSD.INTEGER), y); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + BindingSet bs = result.next(); + Value y = bs.getValue("y"); + assertNotNull(y); + assertTrue(y instanceof Literal); + assertEquals(literal("1", XSD.INTEGER), y); + } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java index 0a6226fd39a..58c8ebf1b25 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java @@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -22,6 +23,7 @@ import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -32,41 +34,44 @@ */ public class MinusTest extends AbstractComplianceTest { - public MinusTest(Repository repo) { + public MinusTest(Supplier repo) { super(repo); } private void testScopingOfFilterInMinus() { + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String ex = "http://example/"; + IRI a1 = Values.iri(ex, "a1"); + IRI a2 = Values.iri(ex, "a2"); - String ex = "http://example/"; - IRI a1 = Values.iri(ex, "a1"); - IRI a2 = Values.iri(ex, "a2"); + IRI both = Values.iri(ex, "both"); - IRI both = Values.iri(ex, "both"); + IRI predicate1 = Values.iri(ex, "predicate1"); + IRI predicate2 = Values.iri(ex, "predicate2"); - IRI predicate1 = Values.iri(ex, "predicate1"); - IRI predicate2 = Values.iri(ex, "predicate2"); + conn.add(a1, predicate1, both); + conn.add(a1, predicate2, both); - conn.add(a1, predicate1, both); - conn.add(a1, predicate2, both); + conn.add(a2, predicate1, both); + conn.add(a2, predicate2, Values.bnode()); - conn.add(a2, predicate1, both); - conn.add(a2, predicate2, Values.bnode()); + TupleQuery tupleQuery = conn.prepareTupleQuery( + "PREFIX : \n" + "SELECT * WHERE {\n" + " ?a :predicate1 ?p1\n" + " MINUS {\n" + + " ?a :predicate2 ?p2 .\n" + " FILTER(?p2 = ?p1)\n" + " }\n" + "} ORDER BY ?a\n"); - TupleQuery tupleQuery = conn.prepareTupleQuery( - "PREFIX : \n" + "SELECT * WHERE {\n" + " ?a :predicate1 ?p1\n" + " MINUS {\n" - + " ?a :predicate2 ?p2 .\n" + " FILTER(?p2 = ?p1)\n" + " }\n" + "} ORDER BY ?a\n"); + try (Stream stream = tupleQuery.evaluate().stream()) { + List collect = stream.collect(Collectors.toList()); + assertEquals(2, collect.size()); - try (Stream stream = tupleQuery.evaluate().stream()) { - List collect = stream.collect(Collectors.toList()); - assertEquals(2, collect.size()); + List expectedValues = List.of(a1, a2); + List actualValues = collect.stream().map(b -> b.getValue("a")).collect(Collectors.toList()); - List expectedValues = List.of(a1, a2); - List actualValues = collect.stream().map(b -> b.getValue("a")).collect(Collectors.toList()); - - assertEquals(expectedValues, actualValues); + assertEquals(expectedValues, actualValues); + } + } finally { + closeRepository(repo); } - } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java index 14e6684db78..9d0e4a57da8 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java @@ -19,6 +19,7 @@ import java.io.StringReader; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; @@ -30,10 +31,10 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on OPTIONAL clause behavior. @@ -43,99 +44,112 @@ */ public class OptionalTest extends AbstractComplianceTest { - public OptionalTest(Repository repo) { + public OptionalTest(Supplier repo) { super(repo); } private void testSES1898LeftJoinSemantics1() throws Exception { - loadTestData("/testdata-query/dataset-ses1898.trig"); - String query = " PREFIX : " + " SELECT * WHERE { " + " ?s :p1 ?v1 . " - + " OPTIONAL {?s :p2 ?v2 } ." + " ?s :p3 ?v2 . " + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(0, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1898.trig", conn); + String query = " PREFIX : " + " SELECT * WHERE { " + " ?s :p1 ?v1 . " + + " OPTIONAL {?s :p2 ?v2 } ." + " ?s :p3 ?v2 . " + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(0, count); + } + } finally { + closeRepository(repo); } } private void testSES1121VarNamesInOptionals() throws Exception { // Verifying that variable names have no influence on order of optionals // in query. See SES-1121. + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1121.trig", conn); - loadTestData("/testdata-query/dataset-ses1121.trig"); - - String query1 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" - + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?c . } \n " - + " } \n" + " } \n"; + String query1 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?c . } \n " + + " } \n" + " } \n"; - String query2 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" - + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?var2 . } \n " - + " } \n" + " } \n"; + String query2 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?var2 . } \n " + + " } \n" + " } \n"; - TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); - TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); + TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); + TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); - try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate()) { - assertNotNull(result1); - assertNotNull(result2); + try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate()) { + assertNotNull(result1); + assertNotNull(result2); - List qr1 = QueryResults.asList(result1); - List qr2 = QueryResults.asList(result2); + List qr1 = QueryResults.asList(result1); + List qr2 = QueryResults.asList(result2); - // System.out.println(qr1); - // System.out.println(qr2); + // System.out.println(qr1); + // System.out.println(qr2); - // if optionals are not kept in same order, query results will be - // different size. - assertEquals(qr1.size(), qr2.size()); + // if optionals are not kept in same order, query results will be + // different size. + assertEquals(qr1.size(), qr2.size()); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); } } private void testSameTermRepeatInOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = getNamespaceDeclarations() + " SELECT ?l ?opt1 ?opt2 " + " FROM ex:optional-sameterm-graph " - + " WHERE { " + " ?s ex:p ex:A ; " + " { " + " { " - + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " + " } " - + " OPTIONAL { " + " ?s ?p ?opt1 . " - + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " - + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " + " } " - + " }" + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value l = bs.getValue("l"); - assertTrue(l instanceof Literal); - assertEquals("label", ((Literal) l).getLabel()); - - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = getNamespaceDeclarations() + " SELECT ?l ?opt1 ?opt2 " + " FROM ex:optional-sameterm-graph " + + " WHERE { " + " ?s ex:p ex:A ; " + " { " + " { " + + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " + " } " + + " OPTIONAL { " + " ?s ?p ?opt1 . " + + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " + + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " + + " } " + " }" + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + // System.out.println(bs); + + Value l = bs.getValue("l"); + assertTrue(l instanceof Literal); + assertEquals("label", ((Literal) l).getLabel()); + + Value opt1 = bs.getValue("opt1"); + assertNull(opt1); + + Value opt2 = bs.getValue("opt2"); + assertNull(opt2); + } + assertEquals(1, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } /** @@ -143,17 +157,22 @@ private void testSameTermRepeatInOptional() throws Exception { * */ private void testValuesAfterOptional() throws Exception { - String data = "@prefix rdfs: . \n" + "@prefix : . \n" - + ":r1 a rdfs:Resource . \n" + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String data = "@prefix rdfs: . \n" + "@prefix : . \n" + + ":r1 a rdfs:Resource . \n" + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; - String query = "" + "prefix rdfs: \n" + "prefix : \n" - + "\n" + "select ?resource ?label where { \n" + " ?resource a rdfs:Resource . \n" - + " optional { ?resource rdfs:label ?label } \n" + " values ?label { undef } \n" + "}"; + String query = "" + "prefix rdfs: \n" + "prefix : \n" + + "\n" + "select ?resource ?label where { \n" + " ?resource a rdfs:Resource . \n" + + " optional { ?resource rdfs:label ?label } \n" + " values ?label { undef } \n" + "}"; - conn.add(new StringReader(data), RDFFormat.TURTLE); + conn.add(new StringReader(data), RDFFormat.TURTLE); - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - assertThat(result).hasSize(2); + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + assertThat(result).hasSize(2); + } finally { + closeRepository(repo); + } } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java index 8c642ebf98e..771501f54bc 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java @@ -13,62 +13,76 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.StringReader; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; public class OrderByTest extends AbstractComplianceTest { - public OrderByTest(Repository repo) { + public OrderByTest(Supplier repo) { super(repo); } private void testDistinctOptionalOrderBy() throws Exception { - - conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); - - String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by ?nr"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", + RDFFormat.TURTLE); + + String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by ?nr"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); + } + } finally { + closeRepository(repo); } } private void testOrderByVariableNotInUse() throws Exception { - - conn.add(new StringReader( - "_:bob1 a ; rdfs:label \"Bob1\" .\n" + "_:bob2 a ; rdfs:label \"Bob2\" ."), - "", RDFFormat.TURTLE); - - String query = "SELECT * WHERE { ?person a } ORDER BY ?score\n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - // use distinct because the issue is that the query produces duplicates - long count = result.distinct().count(); - assertEquals(2, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(new StringReader("_:bob1 a ; rdfs:label \"Bob1\" .\n" + + "_:bob2 a ; rdfs:label \"Bob2\" ."), "", RDFFormat.TURTLE); + + String query = "SELECT * WHERE { ?person a } ORDER BY ?score\n"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + // use distinct because the issue is that the query produces duplicates + long count = result.distinct().count(); + assertEquals(2, count); + } + } finally { + closeRepository(repo); } } private void testDistinctOptionalOrderByMath() throws Exception { - - conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); - - String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by (?nr + STRLEN(?o))"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", + RDFFormat.TURTLE); + + String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by (?nr + STRLEN(?o))"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); + } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java index 0608609295c..70e44098537 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java @@ -21,6 +21,7 @@ import java.io.StringReader; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -42,11 +43,11 @@ import org.eclipse.rdf4j.query.impl.MapBindingSet; import org.eclipse.rdf4j.query.impl.SimpleBinding; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL property paths. @@ -57,145 +58,176 @@ */ public class PropertyPathTest extends AbstractComplianceTest { - public PropertyPathTest(Repository repo) { + public PropertyPathTest(Supplier repo) { super(repo); } private void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { - String data = " .\n" + " .\n" - + " .\n" + " .\n" + " .\n"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String data = " .\n" + " .\n" + + " .\n" + " .\n" + + " .\n"; - conn.begin(); - conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); - conn.commit(); + conn.begin(); + conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); + conn.commit(); - String query = getNamespaceDeclarations() + "SELECT ?x \n" + "WHERE { ?x */ . \n" - + " ?x */ . \n" + "} \n"; + String query = getNamespaceDeclarations() + "SELECT ?x \n" + "WHERE { ?x */ . \n" + + " ?x */ . \n" + "} \n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { + try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); + assertNotNull(result); + assertTrue(result.hasNext()); - Value x = result.next().getValue("x"); - assertNotNull(x); - assertTrue(x instanceof IRI); - assertEquals("urn:s1", x.stringValue()); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Value x = result.next().getValue("x"); + assertNotNull(x); + assertTrue(x instanceof IRI); + assertEquals("urn:s1", x.stringValue()); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); } } private void testSES2024PropertyPathAnonVarSharing() throws Exception { - loadTestData("/testdata-query/dataset-ses2024.trig"); - String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - BindingSet bs = result.next(); - Literal l1 = (Literal) bs.getValue("l1"); - Literal l2 = (Literal) bs.getValue("l2"); - - assertNotNull(l1); - assertNotEquals(l1, l2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses2024.trig", conn); + String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + BindingSet bs = result.next(); + Literal l1 = (Literal) bs.getValue("l1"); + Literal l2 = (Literal) bs.getValue("l2"); + + assertNotNull(l1); + assertNotEquals(l1, l2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); } } private void testPropertyPathNegationInversion() throws Exception { - String data = "@prefix : .\n" + ":Mary :parentOf :Jim.\n" + ":Jim :knows :Jane.\n" - + ":Jane :worksFor :IBM."; - - conn.add(new StringReader(data), "", RDFFormat.TURTLE); - String query1 = "prefix : ASK WHERE { :IBM ^(:|!:) :Jane } "; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String data = "@prefix : .\n" + ":Mary :parentOf :Jim.\n" + ":Jim :knows :Jane.\n" + + ":Jane :worksFor :IBM."; - assertTrue(conn.prepareBooleanQuery(query1).evaluate()); + conn.add(new StringReader(data), "", RDFFormat.TURTLE); + String query1 = "prefix : ASK WHERE { :IBM ^(:|!:) :Jane } "; - String query2 = "prefix : ASK WHERE { :IBM ^(:|!:) ?a } "; - assertTrue(conn.prepareBooleanQuery(query2).evaluate()); + assertTrue(conn.prepareBooleanQuery(query1).evaluate()); - String query3 = "prefix : ASK WHERE { :IBM (^(:|!:))* :Mary } "; - assertTrue(conn.prepareBooleanQuery(query3).evaluate()); + String query2 = "prefix : ASK WHERE { :IBM ^(:|!:) ?a } "; + assertTrue(conn.prepareBooleanQuery(query2).evaluate()); + String query3 = "prefix : ASK WHERE { :IBM (^(:|!:))* :Mary } "; + assertTrue(conn.prepareBooleanQuery(query3).evaluate()); + } finally { + closeRepository(repo); + } } private void testSES2336NegatedPropertyPathMod() throws Exception { - loadTestData("/testdata-query/dataset-ses2336.trig"); - String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; - - ValueFactory vf = conn.getValueFactory(); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertNotNull(result); - - IRI a = vf.createIRI(EX.NAMESPACE, "a"); - IRI b = vf.createIRI(EX.NAMESPACE, "b"); - IRI c = vf.createIRI(EX.NAMESPACE, "c"); - IRI d = vf.createIRI(EX.NAMESPACE, "d"); - IRI e = vf.createIRI(EX.NAMESPACE, "e"); - IRI test = vf.createIRI(EX.NAMESPACE, "Test"); - - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", a))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", test))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", c))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", d))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", e))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", test))); - - assertFalse(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", b))); - - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + + loadTestData("/testdata-query/dataset-ses2336.trig", conn); + String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; + + ValueFactory vf = conn.getValueFactory(); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertNotNull(result); + + IRI a = vf.createIRI(EX.NAMESPACE, "a"); + IRI b = vf.createIRI(EX.NAMESPACE, "b"); + IRI c = vf.createIRI(EX.NAMESPACE, "c"); + IRI d = vf.createIRI(EX.NAMESPACE, "d"); + IRI e = vf.createIRI(EX.NAMESPACE, "e"); + IRI test = vf.createIRI(EX.NAMESPACE, "Test"); + + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", a))); + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", test))); + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", c))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", d))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", e))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", test))); + + assertFalse(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", b))); + + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } finally { + closeRepository(repo); + } } private void testSES1685propPathSameVar() throws Exception { - final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; - conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); + conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); - TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); + TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); - try (Stream result = query.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); + try (Stream result = query.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); + } + } finally { + closeRepository(repo); } } private void testSES1073InverseSymmetricPattern() { - IRI a = iri("http://example.org/a"); - IRI b1 = iri("http://example.org/b1"); - IRI b2 = iri("http://example.org/b2"); - IRI c1 = iri("http://example.org/c1"); - IRI c2 = iri("http://example.org/c2"); - IRI a2b = iri("http://example.org/a2b"); - IRI b2c = iri("http://example.org/b2c"); - conn.add(a, a2b, b1); - conn.add(a, a2b, b2); - conn.add(b1, b2c, c1); - conn.add(b2, b2c, c2); - String query = "select * "; - query += "where{ "; - query += "?c1 ^/^// ?c2 . "; - query += " } "; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(4, count); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + IRI a = iri("http://example.org/a"); + IRI b1 = iri("http://example.org/b1"); + IRI b2 = iri("http://example.org/b2"); + IRI c1 = iri("http://example.org/c1"); + IRI c2 = iri("http://example.org/c2"); + IRI a2b = iri("http://example.org/a2b"); + IRI b2c = iri("http://example.org/b2c"); + conn.add(a, a2b, b1); + conn.add(a, a2b, b2); + conn.add(b1, b2c, c1); + conn.add(b2, b2c, c2); + String query = "select * "; + query += "where{ "; + query += "?c1 ^/^// ?c2 . "; + query += " } "; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(4, count); + } + } finally { + closeRepository(repo); } } @@ -204,46 +236,63 @@ private void testSES1073InverseSymmetricPattern() { */ private void testNestedInversePropertyPathWithZeroLength() { - String insert = "insert data {\n" + " .\n" - + " .\n" + " .\n" - + " .\n" + " .\n" - + " .\n" + "}"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String insert = "insert data {\n" + " .\n" + + " .\n" + " .\n" + + " .\n" + " .\n" + + " .\n" + "}"; - String query = "select * where { \n" + " (^)? ?o .\n" + "}"; + String query = "select * where { \n" + " (^)? ?o .\n" + "}"; - conn.prepareUpdate(insert).execute(); + conn.prepareUpdate(insert).execute(); - TupleQuery tq = conn.prepareTupleQuery(query); + TupleQuery tq = conn.prepareTupleQuery(query); - List result = QueryResults.asList(tq.evaluate()); - assertThat(result).hasSize(4); + try (final TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertThat(result).hasSize(4); + } + } finally { + closeRepository(repo); + } } private void testComplexPath() { - conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); - conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); - - TupleQuery tupleQuery = conn.prepareTupleQuery( - "PREFIX skos: \r\n" + " SELECT * " + " WHERE {\r\n" - + " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + " }"); - try (TupleQueryResult evaluate = tupleQuery.evaluate()) { - List collect = evaluate.stream().collect(Collectors.toList()); - assertEquals(2, collect.size()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); + conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); + + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX skos: \r\n" + + " SELECT * " + " WHERE {\r\n" + + " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + " }"); + try (TupleQueryResult evaluate = tupleQuery.evaluate()) { + List collect = evaluate.stream().collect(Collectors.toList()); + assertEquals(2, collect.size()); + } + } finally { + closeRepository(repo); } } private void testInversePath() { - BNode bnode1 = Values.bnode("bnode1"); - - conn.add(Values.bnode(), FOAF.KNOWS, bnode1); - conn.add(Values.bnode(), FOAF.KNOWS, bnode1); - - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" + "SELECT * WHERE {\n" - + " ?x foaf:knows/^foaf:knows ?y . \n" + " FILTER(?x != ?y)\n" + "}"); - - try (TupleQueryResult evaluate = tupleQuery.evaluate()) { - List collect = evaluate.stream().collect(Collectors.toList()); - assertEquals(2, collect.size()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + BNode bnode1 = Values.bnode("bnode1"); + + conn.add(Values.bnode(), FOAF.KNOWS, bnode1); + conn.add(Values.bnode(), FOAF.KNOWS, bnode1); + + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" + + "SELECT * WHERE {\n" + " ?x foaf:knows/^foaf:knows ?y . \n" + " FILTER(?x != ?y)\n" + "}"); + + try (TupleQueryResult evaluate = tupleQuery.evaluate()) { + List collect = evaluate.stream().collect(Collectors.toList()); + assertEquals(2, collect.size()); + } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java index a6947459928..c835192e332 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java @@ -14,6 +14,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; @@ -23,9 +24,9 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL nested SELECT query handling. @@ -34,60 +35,70 @@ */ public class SubselectTest extends AbstractComplianceTest { - public SubselectTest(Repository repo) { + public SubselectTest(Supplier repo) { super(repo); } private void testSES2373SubselectOptional() { - conn.prepareUpdate(QueryLanguage.SPARQL, - "insert data {" + " ." + " 1 ." + " ." - + " ." + " 2 ." + " ." - + " ." + " 3 ." + " ." - + " ." + " 4 ." + " ." - + " ." + " 5 ." + " ." + "}") - .execute(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + conn.prepareUpdate(QueryLanguage.SPARQL, + "insert data {" + " ." + " 1 ." + " ." + + " ." + " 2 ." + " ." + + " ." + " 3 ." + " ." + + " ." + " 4 ." + " ." + + " ." + " 5 ." + " ." + "}") + .execute(); - String qb = "select ?x { \n" + " { select ?v { ?v filter (?v = ) } }.\n" - + " optional { select ?val { ?v ?val .} }\n" + " ?v ?x \n" + "}\n"; + String qb = "select ?x { \n" + " { select ?v { ?v filter (?v = ) } }.\n" + + " optional { select ?val { ?v ?val .} }\n" + " ?v ?x \n" + "}\n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult result = tq.evaluate()) { - assertTrue(result.hasNext(), "The query should return a result"); - BindingSet b = result.next(); - assertTrue(b.hasBinding("x"), "?x is from the mandatory part of the query and should be bound"); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult result = tq.evaluate()) { + assertTrue(result.hasNext(), "The query should return a result"); + BindingSet b = result.next(); + assertTrue(b.hasBinding("x"), "?x is from the mandatory part of the query and should be bound"); + } + } finally { + closeRepository(repo); } } private void testSES2154SubselectOptional() { + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String ub = "insert data { \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " a . \n" + " a . \n" + + " a . \n" + " \"01\" . \n" + " \"02\" . \n" + + " \"03\" . \n" + " \"04\" . \n" + + " \"05\" . \n" + " \"06\" . \n" + + " \"07\" . \n" + " \"08\" . \n" + + " \"09\" . \n" + " \"10\" . \n" + + " \"11\" . \n" + " \"12\" . \n" + "} \n"; - String ub = "insert data { \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " \"01\" . \n" + " \"02\" . \n" - + " \"03\" . \n" + " \"04\" . \n" + " \"05\" . \n" - + " \"06\" . \n" + " \"07\" . \n" + " \"08\" . \n" - + " \"09\" . \n" + " \"10\" . \n" - + " \"11\" . \n" + " \"12\" . \n" + "} \n"; - - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); + conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - String qb = "SELECT ?s ?label\n" + "WHERE { \n" + " ?s a \n .\n" - + " OPTIONAL { {SELECT ?label WHERE { \n" + " ?s ?label . \n" - + " } ORDER BY ?label LIMIT 2 \n" + " }\n" + " }\n" + "}\n" + "ORDER BY ?s\n" - + "LIMIT 10 \n"; + String qb = "SELECT ?s ?label\n" + "WHERE { \n" + " ?s a \n .\n" + + " OPTIONAL { {SELECT ?label WHERE { \n" + " ?s ?label . \n" + + " } ORDER BY ?label LIMIT 2 \n" + " }\n" + " }\n" + "}\n" + + "ORDER BY ?s\n" + "LIMIT 10 \n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertTrue(evaluate.hasNext(), "The query should return a result"); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertTrue(evaluate.hasNext(), "The query should return a result"); - List result = QueryResults.asList(evaluate); - assertEquals(10, result.size()); - for (BindingSet bs : result) { - Literal label = (Literal) bs.getValue("label"); - assertTrue(label.stringValue().equals("01") || label.stringValue().equals("02"), - "wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')"); + List result = QueryResults.asList(evaluate); + assertEquals(10, result.size()); + for (BindingSet bs : result) { + Literal label = (Literal) bs.getValue("label"); + assertTrue(label.stringValue().equals("01") || label.stringValue().equals("02"), + "wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')"); + } } + } finally { + closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java index 910da3d7b2c..804a7123676 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -28,9 +29,9 @@ import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPRQL UNION clauses. @@ -40,96 +41,109 @@ */ public class UnionTest extends AbstractComplianceTest { - public UnionTest(Repository repo) { + public UnionTest(Supplier repo) { super(repo); } private void testEmptyUnion() { - String query = "PREFIX : " + "SELECT ?visibility WHERE {" - + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." - + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + "}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String query = "PREFIX : " + "SELECT ?visibility WHERE {" + + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." + + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + "}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); + } + } finally { + closeRepository(repo); } } private void testSameTermRepeatInUnion() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - String query = "PREFIX foaf:\n" + "SELECT * {\n" + " {\n" - + " ?sameTerm foaf:mbox ?mbox\n" + " FILTER sameTerm(?sameTerm,$william)\n" - + " } UNION {\n" + " ?x foaf:knows ?sameTerm\n" - + " FILTER sameTerm(?sameTerm,$william)\n" + " }\n" + "}"; + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "PREFIX foaf:\n" + "SELECT * {\n" + " {\n" + + " ?sameTerm foaf:mbox ?mbox\n" + " FILTER sameTerm(?sameTerm,$william)\n" + + " } UNION {\n" + " ?x foaf:knows ?sameTerm\n" + + " FILTER sameTerm(?sameTerm,$william)\n" + " }\n" + "}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); - // System.out.println(bs); + // System.out.println(bs); - Value mbox = bs.getValue("mbox"); - Value x = bs.getValue("x"); + Value mbox = bs.getValue("mbox"); + Value x = bs.getValue("x"); - assertTrue(mbox instanceof Literal || x instanceof IRI); + assertTrue(mbox instanceof Literal || x instanceof IRI); + } + assertEquals(3, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(3, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } private void testSameTermRepeatInUnionAndOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); - - String query = getNamespaceDeclarations() + "SELECT * {\n" + " {\n" + " ex:a ?p ?prop1\n" - + " FILTER (?p = ex:prop1)\n" + " } UNION {\n" + " ?s ex:p ex:A ; " + " { " - + " { " + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " - + " } " + " OPTIONAL { " + " ?s ?p ?opt1 . " - + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " - + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " + " } " - + " }" + " }\n" + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value prop1 = bs.getValue("prop1"); - Value l = bs.getValue("l"); - - assertTrue(prop1 instanceof Literal || l instanceof Literal); - if (l instanceof Literal) { - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-query.trig", conn); + + String query = getNamespaceDeclarations() + "SELECT * {\n" + " {\n" + " ex:a ?p ?prop1\n" + + " FILTER (?p = ex:prop1)\n" + " } UNION {\n" + " ?s ex:p ex:A ; " + + " { " + " { " + " ?s ?p ?l ." + + " FILTER(?p = rdfs:label) " + " } " + " OPTIONAL { " + + " ?s ?p ?opt1 . " + " FILTER (?p = ex:prop1) " + + " } " + " OPTIONAL { " + " ?s ?p ?opt2 . " + + " FILTER (?p = ex:prop2) " + " } " + " }" + " }\n" + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + // System.out.println(bs); + + Value prop1 = bs.getValue("prop1"); + Value l = bs.getValue("l"); + + assertTrue(prop1 instanceof Literal || l instanceof Literal); + if (l instanceof Literal) { + Value opt1 = bs.getValue("opt1"); + assertNull(opt1); + + Value opt2 = bs.getValue("opt2"); + assertNull(opt2); + } } + assertEquals(2, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java index ec75c54a67c..dc4bf759f77 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java @@ -21,6 +21,7 @@ import java.io.StringReader; import java.util.List; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -36,10 +37,10 @@ import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.query.Update; import org.eclipse.rdf4j.repository.Repository; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Tests on SPARQL VALUES clauses. @@ -48,123 +49,147 @@ */ public class ValuesTest extends AbstractComplianceTest { - public ValuesTest(Repository repo) { + public ValuesTest(Supplier repo) { super(repo); } private void testValuesInOptional() throws Exception { - loadTestData("/testdata-query/dataset-ses1692.trig"); - String query = " PREFIX : \n" - + " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - // System.out.println(bs); - IRI a = (IRI) bs.getValue("a"); - assertNotNull(a); - Value isX = bs.getValue("isX"); - Literal name = (Literal) bs.getValue("name"); - assertNotNull(name); - if (a.stringValue().endsWith("a1")) { - assertNotNull(isX); - } else if (a.stringValue().endsWith(("a2"))) { - assertNull(isX); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1692.trig", conn); + String query = " PREFIX : \n" + + " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + // System.out.println(bs); + IRI a = (IRI) bs.getValue("a"); + assertNotNull(a); + Value isX = bs.getValue("isX"); + Literal name = (Literal) bs.getValue("name"); + assertNotNull(name); + if (a.stringValue().endsWith("a1")) { + assertNotNull(isX); + } else if (a.stringValue().endsWith(("a2"))) { + assertNull(isX); + } } + assertEquals(2, count); } - assertEquals(2, count); + } finally { + closeRepository(repo); } } private void testValuesClauseNamedGraph() throws Exception { - String ex = "http://example.org/"; - String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + "@prefix ex: <" + ex + "> .\n" + "ex:graph1 {\n" - + " ex:Person1 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 3\" .\n" + "}"; - - conn.add(new StringReader(data), "", RDFFormat.TRIG); - - String query = "SELECT ?person ?name ?__index \n" + "WHERE { " - + " VALUES (?person ?name ?__index) { \n" - + " ( UNDEF \"0\") \n" - + " ( UNDEF \"2\") } \n" - + " GRAPH { ?person ?name . } }"; - - TupleQuery q = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(q.evaluate()); - assertThat(result).hasSize(2); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String ex = "http://example.org/"; + String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + "@prefix ex: <" + ex + "> .\n" + + "ex:graph1 {\n" + " ex:Person1 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 3\" .\n" + "}"; + + conn.add(new StringReader(data), "", RDFFormat.TRIG); + + String query = "SELECT ?person ?name ?__index \n" + "WHERE { " + + " VALUES (?person ?name ?__index) { \n" + + " ( UNDEF \"0\") \n" + + " ( UNDEF \"2\") } \n" + + " GRAPH { ?person ?name . } }"; + + TupleQuery q = conn.prepareTupleQuery(query); + + List result = QueryResults.asList(q.evaluate()); + assertThat(result).hasSize(2); + } finally { + closeRepository(repo); + } } private void testValuesCartesianProduct() { - final String queryString = "" + "select ?x ?y where { " + " values ?x { undef 67 } " - + " values ?y { undef 42 } " + "}"; - final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); - - List bindingSets = QueryResults.asList(tupleQuery.evaluate()); - assertThat(bindingSets).hasSize(4); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + final String queryString = "" + "select ?x ?y where { " + " values ?x { undef 67 } " + + " values ?y { undef 42 } " + "}"; + final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); + + List bindingSets = QueryResults.asList(tupleQuery.evaluate()); + assertThat(bindingSets).hasSize(4); + } finally { + closeRepository(repo); + } } private void testSES1081SameTermWithValues() throws Exception { - loadTestData("/testdata-query/dataset-ses1081.trig"); - String query = "PREFIX ex: \n" + " SELECT * \n" + " WHERE { \n " - + " ?s ex:p ?a . \n" + " FILTER sameTerm(?a, ?e) \n " - + " VALUES ?e { ex:b } \n " + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - Value s = bs.getValue("s"); - Value a = bs.getValue("a"); - - assertNotNull(s); - assertNotNull(a); - assertEquals(iri("http://example.org/a"), s); - assertEquals(iri("http://example.org/b"), a); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testdata-query/dataset-ses1081.trig", conn); + String query = "PREFIX ex: \n" + " SELECT * \n" + " WHERE { \n " + + " ?s ex:p ?a . \n" + " FILTER sameTerm(?a, ?e) \n " + + " VALUES ?e { ex:b } \n " + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + Value s = bs.getValue("s"); + Value a = bs.getValue("a"); + + assertNotNull(s); + assertNotNull(a); + assertEquals(iri("http://example.org/a"), s); + assertEquals(iri("http://example.org/b"), a); + } + assertEquals(1, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + } finally { + closeRepository(repo); } - } private void testSES2136() throws Exception { - loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl"); - String query = "PREFIX : \n" + "SELECT ?s ?o { \n" + " { SELECT * WHERE { ?s ?p ?o . } }\n" - + " VALUES (?o) { (:b) }\n" + "}\n"; - - ValueFactory vf = conn.getValueFactory(); - final IRI a = vf.createIRI("http://example.org/a"); - final IRI b = vf.createIRI("http://example.org/b"); - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - assertFalse(result.hasNext(), "only one result expected"); - assertEquals(a, bs.getValue("s")); - assertEquals(b, bs.getValue("o")); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl", conn); + String query = "PREFIX : \n" + "SELECT ?s ?o { \n" + + " { SELECT * WHERE { ?s ?p ?o . } }\n" + " VALUES (?o) { (:b) }\n" + "}\n"; + + ValueFactory vf = conn.getValueFactory(); + final IRI a = vf.createIRI("http://example.org/a"); + final IRI b = vf.createIRI("http://example.org/b"); + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + assertFalse(result.hasNext(), "only one result expected"); + assertEquals(a, bs.getValue("s")); + assertEquals(b, bs.getValue("o")); + } + } finally { + closeRepository(repo); } } @@ -173,34 +198,38 @@ private void testSES2136() throws Exception { */ private void testFilterExistsExternalValuesClause() { - String ub = "insert data {\n" + " a .\n" + " a .\n" - + " .\n" - + " .\n" + "}"; - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - - String query = "select ?s {\n" + " ?s a* .\n" - + " FILTER EXISTS {?s ?o}\n" + "} limit 100 values ?o {}"; - - TupleQuery tq = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(tq.evaluate()); - assertEquals(1, result.size(), "single result expected"); - assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + String ub = "insert data {\n" + " a .\n" + + " a .\n" + " .\n" + + " .\n" + "}"; + conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); + + String query = "select ?s {\n" + " ?s a* .\n" + + " FILTER EXISTS {?s ?o}\n" + "} limit 100 values ?o {}"; + + TupleQuery tq = conn.prepareTupleQuery(query); + + List result = QueryResults.asList(tq.evaluate()); + assertEquals(1, result.size(), "single result expected"); + assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); + } finally { + closeRepository(repo); + } } public void testMultipleValuesClauses() { - Update update = conn.prepareUpdate("PREFIX ex: \n" + - "\n" + - "INSERT DATA { ex:sub ex:somePred \"value\" . };\n" + - "\n" + - "INSERT { ?s ?newPred ?newObj }\n" + - "WHERE {\n" + - " # If one combines these into a single VALUES clause then it also works\n" + - " VALUES ?newPred { ex:somePred2 }\n" + - " VALUES ?newObj { \"value2\" }\n" + - " ?s ex:somePred [] .\n" + - "}"); - update.execute(); + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection()) { + Update update = conn.prepareUpdate("PREFIX ex: \n" + "\n" + + "INSERT DATA { ex:sub ex:somePred \"value\" . };\n" + "\n" + "INSERT { ?s ?newPred ?newObj }\n" + + "WHERE {\n" + " # If one combines these into a single VALUES clause then it also works\n" + + " VALUES ?newPred { ex:somePred2 }\n" + " VALUES ?newObj { \"value2\" }\n" + + " ?s ex:somePred [] .\n" + "}"); + update.execute(); + } finally { + closeRepository(repo); + } } public Stream tests() { From 7beed163b2a0daf1d53660bc095469f601cf6c9c Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Fri, 3 Nov 2023 12:34:54 +0100 Subject: [PATCH 4/6] GH-4592 Reduce code duplication and difference to the develop branch. Signed-off-by: Jerven Bolleman --- .../sparql/AbstractComplianceTest.java | 16 +- .../testsuite/sparql/tests/AggregateTest.java | 628 ++++++--------- .../sparql/tests/ArbitraryLengthPathTest.java | 761 +++++++++--------- .../testsuite/sparql/tests/BasicTest.java | 67 +- .../testsuite/sparql/tests/BindTest.java | 357 ++++---- .../sparql/tests/BuiltinFunctionTest.java | 496 +++++------- .../testsuite/sparql/tests/ConstructTest.java | 124 +-- .../sparql/tests/DefaultGraphTest.java | 148 ++-- .../testsuite/sparql/tests/DescribeTest.java | 457 +++++------ .../testsuite/sparql/tests/ExistsTest.java | 61 +- .../testsuite/sparql/tests/GroupByTest.java | 21 +- .../rdf4j/testsuite/sparql/tests/InTest.java | 99 +-- .../testsuite/sparql/tests/MinusTest.java | 58 +- .../testsuite/sparql/tests/OptionalTest.java | 215 ++--- .../testsuite/sparql/tests/OrderByTest.java | 80 +- .../sparql/tests/PropertyPathTest.java | 339 ++++---- .../testsuite/sparql/tests/SubselectTest.java | 117 +-- .../testsuite/sparql/tests/UnionTest.java | 188 +++-- .../testsuite/sparql/tests/ValuesTest.java | 290 ++++--- 19 files changed, 2137 insertions(+), 2385 deletions(-) diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java index 10255c775b7..eb53a736837 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/AbstractComplianceTest.java @@ -49,6 +49,7 @@ import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.api.function.ThrowingConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,10 +60,17 @@ */ public abstract class AbstractComplianceTest { - protected DynamicTest makeTest(String name, Executable x) { - return DynamicTest.dynamicTest(name, () -> { - x.execute(); - }); + protected DynamicTest makeTest(String name, ThrowingConsumer x) { + Executable e = () -> { + Repository repo = openRepository(); + try (RepositoryConnection conn = repo.getConnection();) { + x.accept(conn); + } finally { + closeRepository(repo); + } + }; + return DynamicTest.dynamicTest(name, e); + } protected Repository openRepository() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java index 12fcbc1df0a..40d2b1ed981 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/AggregateTest.java @@ -53,7 +53,8 @@ public AggregateTest(Supplier repo) { } public Stream tests() { - return Stream.of(makeTest("MaxAggregateWithGroupEmptyResult", this::testMaxAggregateWithGroupEmptyResult), + return Stream.of( + makeTest("MaxAggregateWithGroupEmptyResult", this::testMaxAggregateWithGroupEmptyResult), makeTest("MaxAggregateWithoutGroupEmptySolution", this::testMaxAggregateWithoutGroupEmptySolution), makeTest("MinAggregateWithGroupEmptyResult", this::testMinAggregateWithGroupEmptyResult), makeTest("MinAggregateWithoutGroupEmptySolution", this::testMinAggregateWithoutGroupEmptySolution), @@ -62,9 +63,12 @@ public Stream tests() { this::testSampleAggregateWithoutGroupEmptySolution), makeTest("SES2361UndefMin", this::testSES2361UndefMin), makeTest("CountOrderBy_ImplicitGroup", this::testCountOrderBy_ImplicitGroup), - makeTest("DistinctMax", this::testDistinctMax), makeTest("Max", this::testMax), - makeTest("DistinctAvg", this::testDistinctAvg), makeTest("Avg", this::testAvg), - makeTest("DistinctSum", this::testDistinctSum), makeTest("Sum", this::testSum), + makeTest("DistinctMax", this::testDistinctMax), + makeTest("Max", this::testMax), + makeTest("DistinctAvg", this::testDistinctAvg), + makeTest("Avg", this::testAvg), + makeTest("DistinctSum", this::testDistinctSum), + makeTest("Sum", this::testSum), makeTest("CountHaving", this::testCountHaving), makeTest("SES1970CountDistinctWildcard", this::testSES1970CountDistinctWildcard), makeTest("GroupConcatNonDistinct", this::testGroupConcatNonDistinct), @@ -73,38 +77,34 @@ public Stream tests() { makeTest("SES2361UndefSum", this::testSES2361UndefSum), makeTest("SES2361UndefCountWildcard", this::testSES2361UndefCountWildcard), makeTest("SES2361UndefCount", this::testSES2361UndefCount), - makeTest("SES2361UndefMax", this::testSES2361UndefMax)); + makeTest("SES2361UndefMax", this::testSES2361UndefMax) + ); } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testMaxAggregateWithGroupEmptyResult() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select ?s (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; - - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } finally { - closeRepository(repo); + public void testMaxAggregateWithGroupEmptyResult(RepositoryConnection conn) { + String query = "select ?s (max(?o) as ?omax) {\n" + + " ?s ?p ?o .\n" + + " }\n" + + " group by ?s\n"; + + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); } } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testMaxAggregateWithoutGroupEmptySolution() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n"; + private void testMaxAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { + String query = "select (max(?o) as ?omax) {\n" + + " ?s ?p ?o .\n" + + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); } } @@ -112,449 +112,356 @@ private void testMaxAggregateWithoutGroupEmptySolution() { * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testMinAggregateWithGroupEmptyResult() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select ?s (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + private void testMinAggregateWithGroupEmptyResult(RepositoryConnection conn) { + String query = "select ?s (min(?o) as ?omin) {\n" + + " ?s ?p ?o .\n" + + " }\n" + + " group by ?s\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); } } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testMinAggregateWithoutGroupEmptySolution() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n"; + private void testMinAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { + String query = "select (min(?o) as ?omin) {\n" + + " ?s ?p ?o .\n" + + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); } } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testSampleAggregateWithGroupEmptyResult() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select ?s (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + private void testSampleAggregateWithGroupEmptyResult(RepositoryConnection conn) { - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.hasNext()).isFalse(); - } - } finally { - closeRepository(repo); + String query = "select ?s (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n" + " group by ?s\n"; + + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.hasNext()).isFalse(); } } /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - private void testSampleAggregateWithoutGroupEmptySolution() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n"; + private void testSampleAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { + String query = "select (sample(?o) as ?osample) {\n" + + " ?s ?p ?o .\n" + + " }\n"; - try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { - assertThat(result.next()).isEmpty(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(query).evaluate()) { + assertThat(result.next()).isEmpty(); } } - private void testSES2361UndefMin() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("min").stringValue()).isEqualTo("1"); - assertThat(result.hasNext()).isFalse(); - } - } finally { - closeRepository(repo); + private void testSES2361UndefMin(RepositoryConnection conn) { + String query = "SELECT (MIN(?v) as ?min) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("min").stringValue()).isEqualTo("1"); + assertThat(result.hasNext()).isFalse(); } } - private void testSES2361UndefMax() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("max").stringValue()).isEqualTo("7"); - assertThat((Iterable) result).isEmpty(); - } - } finally { - closeRepository(repo); + private void testSES2361UndefMax(RepositoryConnection conn) { + String query = "SELECT (MAX(?v) as ?max) WHERE { VALUES ?v { 1 2 7 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("max").stringValue()).isEqualTo("7"); + assertThat((Iterable) result).isEmpty(); } } - private void testSES2361UndefCount() { + private void testSES2361UndefCount(RepositoryConnection conn) { String query = "SELECT (COUNT(?v) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat((Iterable) result).isEmpty(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); + assertThat((Iterable) result).isEmpty(); } } - private void testSES2361UndefCountWildcard() { + private void testSES2361UndefCountWildcard(RepositoryConnection conn) { String query = "SELECT (COUNT(*) as ?c) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); - assertThat((Iterable) result).isEmpty(); - } - } finally { - closeRepository(repo); + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("c").stringValue()).isEqualTo("4"); + assertThat((Iterable) result).isEmpty(); } } - private void testSES2361UndefSum() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - assertThat(result.next().getValue("s").stringValue()).isEqualTo("10"); - assertThat((Iterable) result).isEmpty(); - } - } finally { - closeRepository(repo); + private void testSES2361UndefSum(RepositoryConnection conn) { + String query = "SELECT (SUM(?v) as ?s) WHERE { VALUES ?v { 1 2 undef 3 4 }}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertThat((Iterable) result).isNotNull(); + assertThat(result.hasNext()).isTrue(); + assertThat(result.next().getValue("s").stringValue()).isEqualTo("10"); + assertThat((Iterable) result).isEmpty(); } } - private void testSES1979MinMaxInf() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1979.trig", conn); - String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertThat((Iterable) result).isNotNull().hasSize(1); - assertThat(result.get(0).getValue("min")).isEqualTo(literal(Float.NEGATIVE_INFINITY)); - assertThat(result.get(0).getValue("max")).isEqualTo(literal(Float.POSITIVE_INFINITY)); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); + private void testSES1979MinMaxInf(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1979.trig", conn); + String query = "prefix : select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertThat((Iterable) result).isNotNull().hasSize(1); + assertThat(result.get(0).getValue("min")).isEqualTo(literal(Float.NEGATIVE_INFINITY)); + assertThat(result.get(0).getValue("max")).isEqualTo(literal(Float.POSITIVE_INFINITY)); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testGroupConcatDistinct() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); + private void testGroupConcatDistinct(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" - + "WHERE { ex:groupconcat-test ?p ?l . }"; + String query = getNamespaceDeclarations() + + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); - while (result.hasNext()) { - BindingSet bs = result.next(); - assertThat(bs).isNotNull(); + while (result.hasNext()) { + BindingSet bs = result.next(); + assertThat(bs).isNotNull(); - Value concat = bs.getValue("concat"); + Value concat = bs.getValue("concat"); - assertThat(concat).isInstanceOf(Literal.class); + assertThat(concat).isInstanceOf(Literal.class); - String lexValue = ((Literal) concat).getLabel(); + String lexValue = ((Literal) concat).getLabel(); - int occ = countCharOccurrences(lexValue, 'a'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'b'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'c'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'd'); - assertThat(occ).isEqualTo(1); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + int occ = countCharOccurrences(lexValue, 'a'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'b'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'c'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'd'); + assertThat(occ).isEqualTo(1); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testGroupConcatNonDistinct() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(?l) AS ?concat)" - + "WHERE { ex:groupconcat-test ?p ?l . }"; + private void testGroupConcatNonDistinct(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = getNamespaceDeclarations() + + "SELECT (GROUP_CONCAT(?l) AS ?concat)" + + "WHERE { ex:groupconcat-test ?p ?l . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); - while (result.hasNext()) { - BindingSet bs = result.next(); - assertThat(bs).isNotNull(); + while (result.hasNext()) { + BindingSet bs = result.next(); + assertThat(bs).isNotNull(); - Value concat = bs.getValue("concat"); + Value concat = bs.getValue("concat"); - assertThat(concat).isInstanceOf(Literal.class); + assertThat(concat).isInstanceOf(Literal.class); - String lexValue = ((Literal) concat).getLabel(); + String lexValue = ((Literal) concat).getLabel(); - int occ = countCharOccurrences(lexValue, 'a'); - assertThat(occ).isEqualTo(1); - occ = countCharOccurrences(lexValue, 'b'); - assertThat(occ).isEqualTo(2); - occ = countCharOccurrences(lexValue, 'c'); - assertThat(occ).isEqualTo(2); - occ = countCharOccurrences(lexValue, 'd'); - assertThat(occ).isEqualTo(1); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + int occ = countCharOccurrences(lexValue, 'a'); + assertThat(occ).isEqualTo(1); + occ = countCharOccurrences(lexValue, 'b'); + assertThat(occ).isEqualTo(2); + occ = countCharOccurrences(lexValue, 'c'); + assertThat(occ).isEqualTo(2); + occ = countCharOccurrences(lexValue, 'd'); + assertThat(occ).isEqualTo(1); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSES1970CountDistinctWildcard() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1970.trig", conn); + private void testSES1970CountDistinctWildcard(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1970.trig", conn); - String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; + String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertThat((Iterable) result).isNotNull(); + try (TupleQueryResult result = tq.evaluate()) { + assertThat((Iterable) result).isNotNull(); - assertThat(result.hasNext()).isTrue(); - BindingSet s = result.next(); - assertThat(getIntValue(s.getValue("c"), 0)).isEqualTo(3); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); + assertThat(result.hasNext()).isTrue(); + BindingSet s = result.next(); + assertThat(getIntValue(s.getValue("c"), 0)).isEqualTo(3); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testCountHaving() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - BNode bnode1 = bnode(); - BNode bnode2 = bnode(); - BNode bnode3 = bnode(); - - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - conn.add(bnode2, FOAF.KNOWS, bnode()); - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode3, FOAF.KNOWS, bnode()); - conn.add(bnode1, FOAF.KNOWS, bnode()); - - String query = "SELECT ?a WHERE { ?a ?b ?c } GROUP BY ?a HAVING( (COUNT(?c) > 1 ) && ( COUNT(?c) != 0 ) ) "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - assertThat(collect).hasSize(2); - } - } finally { - closeRepository(repo); + private void testCountHaving(RepositoryConnection conn) { + BNode bnode1 = bnode(); + BNode bnode2 = bnode(); + BNode bnode3 = bnode(); + + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + conn.add(bnode2, FOAF.KNOWS, bnode()); + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode3, FOAF.KNOWS, bnode()); + conn.add(bnode1, FOAF.KNOWS, bnode()); + + String query = "SELECT ?a WHERE { ?a ?b ?c } GROUP BY ?a HAVING( (COUNT(?c) > 1 ) && ( COUNT(?c) != 0 ) ) "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + assertThat(collect).hasSize(2); } } - private void testSum() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - String query = "SELECT ?a (SUM(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("89.4786576482391284723864721567342354783275234"))); + private void testSum(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); - } + String query = "SELECT ?a (SUM(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("89.4786576482391284723864721567342354783275234"))); - } finally { - closeRepository(repo); } } - private void testDistinctSum() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - - String query = "SELECT ?a (SUM(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("55.4786576482391284723864721567342354783275234"))); - } - } finally { - closeRepository(repo); + private void testDistinctSum(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (SUM(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(30.11)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("55.4786576482391284723864721567342354783275234"))); } - } - private void testAvg() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - - String query = "SELECT ?a (AVG(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("17.89573152964782569447729443134684709566550468"))); - } - } finally { - closeRepository(repo); + private void testAvg(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (AVG(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("17.89573152964782569447729443134684709566550468"))); } } - private void testDistinctAvg() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - - String query = "SELECT ?a (AVG(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - assertThat(collect.get(i++).getValue("aggregate")).isNull(); - - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("18.492885882746376157462157"))); - } - } finally { - closeRepository(repo); + private void testDistinctAvg(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (AVG(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + assertThat(collect.get(i++).getValue("aggregate")).isNull(); + + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(15.055)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("18.492885882746376157462157"))); } } - private void testMax() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - - String query = "SELECT ?a (MAX(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); - } - } finally { - closeRepository(repo); + private void testMax(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (MAX(?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); } } - private void testDistinctMax() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); - - String query = "SELECT ?a (MAX(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - List collect = QueryResults.asList(result); - int i = 0; - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); - assertThat(collect.get(i++).getValue("aggregate")) - .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); - assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); - } - } finally { - closeRepository(repo); + private void testDistinctMax(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); + + String query = "SELECT ?a (MAX(DISTINCT ?c) as ?aggregate) WHERE { ?a ?b ?c } GROUP BY ?a ORDER BY ?aggregate "; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + List collect = QueryResults.asList(result); + int i = 0; + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal(new BigDecimal("19.4786576482391284723864721567342354783275234"))); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal(23)); + assertThat(collect.get(i++).getValue("aggregate")) + .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); + assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); } } /** - * @see https://github.com/eclipse/rdf4j/issues/4290 + * @see https://github.com/eclipse/rdf4j/issues/4290 */ - private void testCountOrderBy_ImplicitGroup() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - mixedDataForNumericAggregates(conn); + private void testCountOrderBy_ImplicitGroup(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); - String query = "select (count(*) as ?c) where { \n" + " ?s ?p ?o .\n" + "} \n" + "order by (?s)"; + String query = "select (count(*) as ?c) where { \n" + + " ?s ?p ?o .\n" + + "} \n" + + "order by (?s)"; - TupleQuery preparedQuery = conn.prepareTupleQuery(query); + TupleQuery preparedQuery = conn.prepareTupleQuery(query); - List result = QueryResults.asList(preparedQuery.evaluate()); - assertThat(result).hasSize(1); + List result = QueryResults.asList(preparedQuery.evaluate()); + assertThat(result).hasSize(1); - BindingSet bs = result.get(0); - assertThat(bs.size()).isEqualTo(1); - assertThat(getIntValue(bs.getValue("c"), 0)).isEqualTo(19); - } finally { - closeRepository(repo); - } + BindingSet bs = result.get(0); + assertThat(bs.size()).isEqualTo(1); + assertThat(getIntValue(bs.getValue("c"), 0)).isEqualTo(19); } // private methods @@ -601,5 +508,4 @@ private int countCharOccurrences(String string, char ch) { } return count; } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java index b8da5ce7734..657cb334b65 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ArbitraryLengthPathTest.java @@ -64,50 +64,47 @@ public Stream tests() { * @throws Exception */ - private void testArbitraryLengthPathWithBinding1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; + private void testArbitraryLengthPathWithBinding1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + // execute again, but this time setting a binding + tq.setBinding("parent", OWL.THING); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); - int count = 0; - while (result.hasNext()) { + count = 0; + while (result2.hasNext()) { count++; - BindingSet bs = result.next(); + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(4, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -115,52 +112,49 @@ private void testArbitraryLengthPathWithBinding1() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding2() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); + private void testArbitraryLengthPathWithBinding2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + + // query without initializing ?child first. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - // query without initializing ?child first. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("parent", OWL.THING); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); - int count = 0; - while (result.hasNext()) { + count = 0; + while (result2.hasNext()) { count++; - BindingSet bs = result.next(); + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("parent", OWL.THING); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(4, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -168,52 +162,49 @@ private void testArbitraryLengthPathWithBinding2() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding3() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); + private void testArbitraryLengthPathWithBinding3(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); - int count = 0; - while (result.hasNext()) { + count = 0; + while (result2.hasNext()) { count++; - BindingSet bs = result.next(); + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -221,52 +212,49 @@ private void testArbitraryLengthPathWithBinding3() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding4() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE); + private void testArbitraryLengthPathWithBinding4(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE); + + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); - int count = 0; - while (result.hasNext()) { + count = 0; + while (result2.hasNext()) { count++; - BindingSet bs = result.next(); + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -274,58 +262,55 @@ private void testArbitraryLengthPathWithBinding4() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding5() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB); + private void testArbitraryLengthPathWithBinding5(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding5 - // ---"); + // System.out.println("--- testArbitraryLengthPathWithBinding5 + // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + + // System.out.println(bs); + + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); - // System.out.println(bs); + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -333,58 +318,55 @@ private void testArbitraryLengthPathWithBinding5() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding6() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); + private void testArbitraryLengthPathWithBinding6(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding6 - // ---"); + // System.out.println("--- testArbitraryLengthPathWithBinding6 + // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); - // System.out.println(bs); + // System.out.println(bs); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -392,61 +374,58 @@ private void testArbitraryLengthPathWithBinding6() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding7() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); + private void testArbitraryLengthPathWithBinding7(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(EX.ALICE); - tq.setDataset(dt); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + SimpleDataset dt = new SimpleDataset(); + dt.addDefaultGraph(EX.ALICE); + tq.setDataset(dt); - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding7 - // ---"); + // System.out.println("--- testArbitraryLengthPathWithBinding7 + // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + + // System.out.println(bs); - // System.out.println(bs); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); + + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -454,60 +433,57 @@ private void testArbitraryLengthPathWithBinding7() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithBinding8() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); - - // binding on child instead of parent. - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - SimpleDataset dt = new SimpleDataset(); - dt.addDefaultGraph(EX.ALICE); - dt.addDefaultGraph(EX.BOB); - tq.setDataset(dt); - - try (TupleQueryResult result = tq.evaluate()) { - // first execute without binding - assertNotNull(result); - // System.out.println("--- testArbitraryLengthPathWithBinding8 - // ---"); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); + private void testArbitraryLengthPathWithBinding8(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn, EX.ALICE, EX.BOB, EX.MARY); + + // binding on child instead of parent. + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . }"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + SimpleDataset dt = new SimpleDataset(); + dt.addDefaultGraph(EX.ALICE); + dt.addDefaultGraph(EX.BOB); + tq.setDataset(dt); + + try (TupleQueryResult result = tq.evaluate()) { + // first execute without binding + assertNotNull(result); + // System.out.println("--- testArbitraryLengthPathWithBinding8 + // ---"); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + + // System.out.println(bs); + + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); + } + assertEquals(7, count); + + // execute again, but this time setting a binding + tq.setBinding("child", EX.C); - // System.out.println(bs); + try (TupleQueryResult result2 = tq.evaluate()) { + assertNotNull(result2); + count = 0; + while (result2.hasNext()) { + count++; + BindingSet bs = result2.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } - assertEquals(7, count); - - // execute again, but this time setting a binding - tq.setBinding("child", EX.C); - - try (TupleQueryResult result2 = tq.evaluate()) { - assertNotNull(result2); - - count = 0; - while (result2.hasNext()) { - count++; - BindingSet bs = result2.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertEquals(2, count); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -515,33 +491,30 @@ private void testArbitraryLengthPathWithBinding8() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithFilter1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + private void testArbitraryLengthPathWithFilter1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); } - } finally { - closeRepository(repo); + assertEquals(4, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -549,33 +522,30 @@ private void testArbitraryLengthPathWithFilter1() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithFilter2() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; + private void testArbitraryLengthPathWithFilter2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(4, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); } - } finally { - closeRepository(repo); + assertEquals(4, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** @@ -583,61 +553,54 @@ private void testArbitraryLengthPathWithFilter2() throws Exception { * @throws Exception */ - private void testArbitraryLengthPathWithFilter3() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/alp-testdata.ttl", conn); - String query = getNamespaceDeclarations() + "SELECT ?parent ?child " - + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; + private void testArbitraryLengthPathWithFilter3(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); + String query = getNamespaceDeclarations() + + "SELECT ?parent ?child " + + "WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = ) }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - assertTrue(bs.hasBinding("child")); - assertTrue(bs.hasBinding("parent")); - } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + assertTrue(bs.hasBinding("child")); + assertTrue(bs.hasBinding("parent")); } - } finally { - closeRepository(repo); + assertEquals(2, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } - private void testPropertyPathInTree() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); + private void testPropertyPathInTree(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + " SELECT ?node ?name " + " FROM ex:tree-graph " - + " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; + String query = getNamespaceDeclarations() + + " SELECT ?node ?name " + + " FROM ex:tree-graph " + + " WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); - // System.out.println(bs); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + // System.out.println(bs); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java index f558459abf4..0e1580c9f51 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BasicTest.java @@ -30,7 +30,6 @@ import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.eclipse.rdf4j.testsuite.sparql.vocabulary.EX; import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.Test; /** * Basic SPARQL functionality tests @@ -44,52 +43,50 @@ public BasicTest(Supplier repo) { super(repo); } - private void testIdenticalVariablesInStatementPattern() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); + private void testIdenticalVariablesInStatementPattern(RepositoryConnection conn) { + conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); - String queryBuilder = "SELECT ?publisher " - + "{ ?publisher ?publisher }"; + String queryBuilder = "SELECT ?publisher " + + "{ ?publisher ?publisher }"; - conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder).evaluate(new AbstractTupleQueryResultHandler() { + conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) + .evaluate(new AbstractTupleQueryResultHandler() { - @Override - public void handleSolution(BindingSet bindingSet) { - fail("nobody is self published"); - } - }); - } - closeRepository(repo); + @Override + public void handleSolution(BindingSet bindingSet) { + fail("nobody is self published"); + } + }); } public Stream tests() { return Stream.of( - makeTest("testIdenticalVariablesInStatementPattern", this::testIdenticalVariablesInStatementPattern)); + makeTest("testIdenticalVariablesInStatementPattern", this::testIdenticalVariablesInStatementPattern), + makeTest("testIdenticalVariablesInStatementPattern", + this::testIdenticalVariablesSubjectContextInStatementPattern)); } - @Test - public void testIdenticalVariablesSubjectContextInStatementPattern() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(EX.ALICE, FOAF.KNOWS, EX.BOB, EX.ALICE); - conn.add(EX.ALICE, RDF.TYPE, FOAF.PERSON, EX.ALICE); - conn.add(EX.ALICE, FOAF.KNOWS, EX.A, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.B, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.C, EX.BOB); - conn.add(EX.ALICE, FOAF.KNOWS, EX.MARY, EX.BOB); + private void testIdenticalVariablesSubjectContextInStatementPattern(RepositoryConnection conn) { + conn.add(EX.ALICE, FOAF.KNOWS, EX.BOB, EX.ALICE); + conn.add(EX.ALICE, RDF.TYPE, FOAF.PERSON, EX.ALICE); + conn.add(EX.ALICE, FOAF.KNOWS, EX.A, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.B, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.C, EX.BOB); + conn.add(EX.ALICE, FOAF.KNOWS, EX.MARY, EX.BOB); - String queryBuilder = "SELECT ?knows { " + " graph ?alice {" + " ?alice a <" + FOAF.PERSON + ">; " - + " <" + FOAF.KNOWS + "> ?knows ." + " }" + "}"; + String queryBuilder = "SELECT ?knows { " + + " graph ?alice {" + + " ?alice a <" + FOAF.PERSON + ">; " + + " <" + FOAF.KNOWS + "> ?knows ." + + " }" + + "}"; - try (Stream stream = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) - .evaluate() - .stream()) { - List knows = stream.map(b -> b.getValue("knows")).collect(Collectors.toList()); - assertEquals(List.of(EX.BOB), knows); - } + try (Stream stream = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder) + .evaluate() + .stream()) { + List knows = stream.map(b -> b.getValue("knows")).collect(Collectors.toList()); + assertEquals(List.of(EX.BOB), knows); } - closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java index 2d37d2067fd..84023599e7d 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BindTest.java @@ -54,223 +54,220 @@ public BindTest(Supplier repo) { * See https://github.com/eclipse/rdf4j/issues/1018 */ - private void testBindError() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") - .execute(); + private void testBindError(RepositoryConnection conn) { - String qb = "SELECT * \n" + "WHERE { \n" + " VALUES (?NAValue) { () } \n " - + " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " - + " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + "}\n"; + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); - List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); + String qb = "SELECT * \n" + + "WHERE { \n" + + " VALUES (?NAValue) { () } \n " + + " BIND(IF(?NAValue != , ?NAValue, ?notBoundVar) as ?ValidNAValue) \n " + + " { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n" + + "}\n"; - assertEquals(2, result.size(), "query should return 2 solutions"); - } finally { - closeRepository(repo); - } + List result = QueryResults.asList(conn.prepareTupleQuery(qb).evaluate()); + + assertEquals(2, result.size(), "query should return 2 solutions"); } /** * See https://github.com/eclipse/rdf4j/issues/1405 */ - private void testBindScope() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT * {\n" + " { BIND (\"a\" AS ?a) }\n" + " { BIND (?a AS ?b) } \n" + "}"; + private void testBindScope(RepositoryConnection conn) { + String query = "SELECT * {\n" + + " { BIND (\"a\" AS ?a) }\n" + + " { BIND (?a AS ?b) } \n" + + "}"; - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); + TupleQuery q = conn.prepareTupleQuery(query); + List result = QueryResults.asList(q.evaluate()); - assertEquals(1, result.size()); + assertEquals(1, result.size()); - assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a")); - assertNull(result.get(0).getValue("b")); - } finally { - closeRepository(repo); - } + assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a")); + assertNull(result.get(0).getValue("b")); } /** * See https://github.com/eclipse/rdf4j/issues/1642 */ - private void testBindScopeUnion() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - ValueFactory f = conn.getValueFactory(); - String query = "prefix ex: \n" + "select * {\n" + " bind(ex:v1 as ?v)\n" - + " bind(strafter(str(?v),str(ex:)) as ?b)\n" + " {\n" + " bind(?b as ?b1)\n" + " } union {\n" - + " bind(?b as ?b2)\n" + " }\n" + "}"; - - TupleQuery q = conn.prepareTupleQuery(query); - List result = QueryResults.asList(q.evaluate()); - - assertEquals(2, result.size()); - - IRI v1 = f.createIRI("http://example.org/v1"); - Literal b = f.createLiteral("v1"); - for (BindingSet bs : result) { - assertThat(bs.getValue("v")).isEqualTo(v1); - assertThat(bs.getValue("b1")).isNull(); - assertThat(bs.getValue("b2")).isNull(); - } - } finally { - closeRepository(repo); + private void testBindScopeUnion(RepositoryConnection conn) { + + ValueFactory f = conn.getValueFactory(); + String query = "prefix ex: \n" + + "select * {\n" + + " bind(ex:v1 as ?v)\n" + + " bind(strafter(str(?v),str(ex:)) as ?b)\n" + + " {\n" + + " bind(?b as ?b1)\n" + + " } union {\n" + + " bind(?b as ?b2)\n" + + " }\n" + + "}"; + + TupleQuery q = conn.prepareTupleQuery(query); + List result = QueryResults.asList(q.evaluate()); + + assertEquals(2, result.size()); + + IRI v1 = f.createIRI("http://example.org/v1"); + Literal b = f.createLiteral("v1"); + for (BindingSet bs : result) { + assertThat(bs.getValue("v")).isEqualTo(v1); + assertThat(bs.getValue("b1")).isNull(); + assertThat(bs.getValue("b2")).isNull(); } } - private void testSES2250BindErrors() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") - .execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri ?p2 ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse(evaluate.hasNext(), "The query should not return a result"); - } - } finally { - closeRepository(repo); + private void testSES2250BindErrors(RepositoryConnection conn) { + + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); + + String qb = "SELECT * {\n" + + " ?s1 ?p1 ?blank . " + + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + + " ?biri ?p2 ?o2 ." + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertFalse(evaluate.hasNext(), "The query should not return a result"); } } - private void testSES2250BindErrorsInPath() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }") - .execute(); - - String qb = "SELECT * {\n" + " ?s1 ?p1 ?blank . " + " FILTER(isBlank(?blank))" - + " BIND (iri(?blank) as ?biri)" + " ?biri * ?o2 ." + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertFalse(evaluate.hasNext(), "The query should not return a result"); - } - } finally { - closeRepository(repo); + private void testSES2250BindErrorsInPath(RepositoryConnection conn) { + + conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); + + String qb = "SELECT * {\n" + + " ?s1 ?p1 ?blank . " + + " FILTER(isBlank(?blank))" + + " BIND (iri(?blank) as ?biri)" + + " ?biri * ?o2 ." + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertFalse(evaluate.hasNext(), "The query should not return a result"); } + } - private void testSelectBindOnly() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "select ?b1 ?b2 ?b3\n" + "where {\n" + " bind(1 as ?b1)\n" + "}"; + public void testSelectBindOnly(RepositoryConnection conn) { + String query = "select ?b1 ?b2 ?b3\n" + + "where {\n" + + " bind(1 as ?b1)\n" + + "}"; - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - assertThat(result.size()).isEqualTo(1); - BindingSet solution = result.get(0); + assertThat(result.size()).isEqualTo(1); + BindingSet solution = result.get(0); - assertThat(solution.getValue("b1")).isEqualTo(literal("1", CoreDatatype.XSD.INTEGER)); - assertThat(solution.getValue("b2")).isNull(); - assertThat(solution.getValue("b3")).isNull(); - } finally { - closeRepository(repo); - } + assertThat(solution.getValue("b1")).isEqualTo(literal("1", CoreDatatype.XSD.INTEGER)); + assertThat(solution.getValue("b2")).isNull(); + assertThat(solution.getValue("b3")).isNull(); } - private void testGH3696Bind() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:unit1") - .add(RDF.TYPE, "ex:Unit") - .add(RDFS.LABEL, "Unit1") - .add("ex:has", "Unit1") - .subject("ex:unit2") - .add(RDF.TYPE, "ex:Unit") - .add(RDFS.LABEL, "Unit2") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT * {\n" + " ?bind rdfs:label ?b1 ;\n" - + " a ex:Unit .\n" + " FILTER (?b1 = 'Unit2') .\n" + " BIND(?bind AS ?n0)\n" - + " ?n0 ex:has ?n1 \n" + " }"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).isEmpty(); - } finally { - closeRepository(repo); - } + private void testGH3696Bind(RepositoryConnection conn) { + + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:unit1") + .add(RDF.TYPE, "ex:Unit") + .add(RDFS.LABEL, "Unit1") + .add("ex:has", "Unit1") + .subject("ex:unit2") + .add(RDF.TYPE, "ex:Unit") + .add(RDFS.LABEL, "Unit2") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + + "SELECT * {\n" + + " ?bind rdfs:label ?b1 ;\n" + + " a ex:Unit .\n" + + " FILTER (?b1 = 'Unit2') .\n" + + " BIND(?bind AS ?n0)\n" + + " ?n0 ex:has ?n1 \n" + + " }"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).isEmpty(); } - private void testGH4499BindFilterNotExist1() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:a") - .add("ex:p", "ex:c1") - .add("ex:p", "ex:c2") - .add("ex:p", "ex:c3") - .subject("ex:c1") - .add(RDF.TYPE, "ex:T") - .add("ex:q", "something") - .subject("ex:c2") - .add(RDF.TYPE, "ex:T") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" - + " BIND ( ex:a AS ?a )\n" + " BIND ( ex:b AS ?b )\n" - + " ?a ex:p* ?c .\n" + " FILTER EXISTS { ?c rdf:type ex:T }\n" - + " FILTER NOT EXISTS { ?c ex:q ?d}\n" + "}"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).hasSize(1); - - var bs = result.get(0); - - assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); - assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); - assertThat(bs.getValue("d")).isNull(); - } finally { - closeRepository(repo); - } + private void testGH4499BindFilterNotExist1(RepositoryConnection conn) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:a") + .add("ex:p", "ex:c1") + .add("ex:p", "ex:c2") + .add("ex:p", "ex:c3") + .subject("ex:c1") + .add(RDF.TYPE, "ex:T") + .add("ex:q", "something") + .subject("ex:c2") + .add(RDF.TYPE, "ex:T") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + + "SELECT *\n" + + " WHERE {\n" + + " BIND ( ex:a AS ?a )\n" + + " BIND ( ex:b AS ?b )\n" + + " ?a ex:p* ?c .\n" + + " FILTER EXISTS { ?c rdf:type ex:T }\n" + + " FILTER NOT EXISTS { ?c ex:q ?d}\n" + + "}"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).hasSize(1); + + var bs = result.get(0); + + assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); + assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); + assertThat(bs.getValue("d")).isNull(); } - private void testGH4499BindFilterNotExist2() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") - .subject("ex:a") - .add("ex:p", "ex:c1") - .add("ex:p", "ex:c2") - .add("ex:p", "ex:c3") - .subject("ex:c1") - .add(RDF.TYPE, "ex:T") - .add("ex:q", "something") - .subject("ex:c2") - .add(RDF.TYPE, "ex:T") - .build(); - conn.add(testData); - - String query = "PREFIX ex: \n" + "SELECT *\n" + " WHERE {\n" - + " FILTER EXISTS { ?c rdf:type ex:T }\n" - + " FILTER NOT EXISTS { ?c ex:q ?d }\n" + " BIND ( ex:a AS ?a )\n" - + " BIND ( ex:b AS ?b )\n" + " ?a ex:p* ?c .\n" + "}"; - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - - assertThat(result).hasSize(1); - - var bs = result.get(0); - - assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); - assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); - assertThat(bs.getValue("d")).isNull(); - } finally { - closeRepository(repo); - } + private void testGH4499BindFilterNotExist2(RepositoryConnection conn) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") + .subject("ex:a") + .add("ex:p", "ex:c1") + .add("ex:p", "ex:c2") + .add("ex:p", "ex:c3") + .subject("ex:c1") + .add(RDF.TYPE, "ex:T") + .add("ex:q", "something") + .subject("ex:c2") + .add(RDF.TYPE, "ex:T") + .build(); + conn.add(testData); + + String query = "PREFIX ex: \n" + + "SELECT *\n" + + " WHERE {\n" + + " FILTER EXISTS { ?c rdf:type ex:T }\n" + + " FILTER NOT EXISTS { ?c ex:q ?d }\n" + + " BIND ( ex:a AS ?a )\n" + + " BIND ( ex:b AS ?b )\n" + + " ?a ex:p* ?c .\n" + + "}"; + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + + assertThat(result).hasSize(1); + + var bs = result.get(0); + + assertThat(bs.getValue("a").stringValue()).isEqualTo("http://example.org/a"); + assertThat(bs.getValue("c").stringValue()).isEqualTo("http://example.org/c2"); + assertThat(bs.getValue("d")).isNull(); } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java index 01dfe7b0831..900406b225c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/BuiltinFunctionTest.java @@ -52,364 +52,308 @@ public BuiltinFunctionTest(Supplier repo) { * See https://github.com/eclipse/rdf4j/issues/1267 */ - private void testSeconds() { + private void testSeconds(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13\"^^xsd:dateTime) AS ?sec) { }"; - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); - } + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("13", result.next().getValue("sec").stringValue()); + assertFalse(result.hasNext()); } - closeRepository(repo); } /** * See https://github.com/eclipse/rdf4j/issues/1267 */ - private void testSecondsMilliseconds() { + private void testSecondsMilliseconds(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13.815-05:00\"^^xsd:dateTime) AS ?sec) { }"; - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("13.815", result.next().getValue("sec").stringValue()); - assertFalse(result.hasNext()); - } + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("13.815", result.next().getValue("sec").stringValue()); + assertFalse(result.hasNext()); } - closeRepository(repo); } - private void testSES1991NOWEvaluation() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/defaultgraph.ttl", conn); - String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - Literal d1 = (Literal) result.next().getValue("d"); - assertTrue(result.hasNext()); - Literal d2 = (Literal) result.next().getValue("d"); - assertFalse(result.hasNext()); - assertNotNull(d1); - assertEquals(d1, d2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } + private void testSES1991NOWEvaluation(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?d WHERE {?s ?p ?o . BIND(NOW() as ?d) } LIMIT 2"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + Literal d1 = (Literal) result.next().getValue("d"); + assertTrue(result.hasNext()); + Literal d2 = (Literal) result.next().getValue("d"); + assertFalse(result.hasNext()); + assertNotNull(d1); + assertEquals(d1, d2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testSES869ValueOfNow() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, - "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); + private void testSES869ValueOfNow(RepositoryConnection conn) { + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, + "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); - BindingSet bs = result.next(); - Value p = bs.getValue("p"); - Value n = bs.getValue("n"); + BindingSet bs = result.next(); + Value p = bs.getValue("p"); + Value n = bs.getValue("n"); - assertNotNull(p); - assertNotNull(n); - assertEquals(p, n); - assertTrue(p == n); - } + assertNotNull(p); + assertNotNull(n); + assertEquals(p, n); + assertTrue(p == n); } - closeRepository(repo); } - private void testSES1991UUIDEvaluation() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/defaultgraph.ttl", conn); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; + private void testSES1991UUIDEvaluation(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - IRI uuid1 = (IRI) result.next().getValue("uid"); - IRI uuid2 = (IRI) result.next().getValue("uid"); + IRI uuid1 = (IRI) result.next().getValue("uid"); + IRI uuid2 = (IRI) result.next().getValue("uid"); - assertNotNull(uuid1); - assertNotNull(uuid2); - assertNotEquals(uuid1, uuid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } + assertNotNull(uuid1); + assertNotNull(uuid2); + assertNotEquals(uuid1, uuid2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testSES1991STRUUIDEvaluation() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/defaultgraph.ttl", conn); - String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; + private void testSES1991STRUUIDEvaluation(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - Literal uid1 = (Literal) result.next().getValue("uid"); - Literal uid2 = (Literal) result.next().getValue("uid"); + Literal uid1 = (Literal) result.next().getValue("uid"); + Literal uid2 = (Literal) result.next().getValue("uid"); - assertNotNull(uid1); - assertNotEquals(uid1, uid2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } + assertNotNull(uid1); + assertNotEquals(uid1, uid2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testSES1991RANDEvaluation() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/defaultgraph.ttl", conn); - String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; + private void testSES1991RANDEvaluation(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/defaultgraph.ttl", conn); + String query = "SELECT ?r WHERE {?s ?p ?o . BIND(RAND() as ?r) } LIMIT 3"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - Literal r1 = (Literal) result.next().getValue("r"); - Literal r2 = (Literal) result.next().getValue("r"); - Literal r3 = (Literal) result.next().getValue("r"); + Literal r1 = (Literal) result.next().getValue("r"); + Literal r2 = (Literal) result.next().getValue("r"); + Literal r3 = (Literal) result.next().getValue("r"); - assertNotNull(r1); + assertNotNull(r1); - // there is a small chance that two successive calls to the random - // number generator will generate the exact same value, so we check - // for - // three successive calls (still theoretically possible to be - // identical, but phenomenally unlikely). - assertFalse(r1.equals(r2) && r1.equals(r3)); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } + // there is a small chance that two successive calls to the random + // number generator will generate the exact same value, so we check + // for + // three successive calls (still theoretically possible to be + // identical, but phenomenally unlikely). + assertFalse(r1.equals(r2) && r1.equals(r3)); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testSES2121URIFunction() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNull(uri, "uri result for invalid URI should be unbound"); - } + private void testSES2121URIFunction(RepositoryConnection conn) { + String query = "SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI uri = (IRI) bs.getValue("uri"); + assertNull(uri, "uri result for invalid URI should be unbound"); + } - query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; - tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI uri = (IRI) bs.getValue("uri"); - assertNotNull(uri, "uri result for valid URI reference should be bound"); - } + query = "BASE SELECT (URI(\"foo bar\") as ?uri) WHERE {}"; + tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI uri = (IRI) bs.getValue("uri"); + assertNotNull(uri, "uri result for valid URI reference should be bound"); } - closeRepository(repo); } - private void test27NormalizeIRIFunction() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - IRI actual = (IRI) bs.getValue("Iri"); - IRI expected = iri("http://example.com/bar"); - assertEquals(expected, actual, "IRI result for relative IRI should be normalized"); - } + private void test27NormalizeIRIFunction(RepositoryConnection conn) { + + String query = "SELECT (IRI(\"../bar\") as ?Iri) WHERE {}"; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query, "http://example.com/foo/"); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + IRI actual = (IRI) bs.getValue("Iri"); + IRI expected = iri("http://example.com/bar"); + assertEquals(expected, actual, "IRI result for relative IRI should be normalized"); } - closeRepository(repo); } - private void testSES2052If1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" - + " FILTER(IF(BOUND(?p), ?p = , false)) \n" - + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); - } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testSES2052If1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "SELECT ?p \n" + + "WHERE { \n" + + " ?s ?p ?o . \n" + + " FILTER(IF(BOUND(?p), ?p = , false)) \n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + while (result.hasNext()) { + BindingSet bs = result.next(); + + IRI p = (IRI) bs.getValue("p"); + assertNotNull(p); + assertEquals(RDF.TYPE, p); } + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); - } - private void testSES2052If2() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = "SELECT ?p \n" + "WHERE { \n" + " ?s ?p ?o . \n" - + " FILTER(IF(!BOUND(?p), false , ?p = )) \n" - + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - while (result.hasNext()) { - BindingSet bs = result.next(); - - IRI p = (IRI) bs.getValue("p"); - assertNotNull(p); - assertEquals(RDF.TYPE, p); - } - } catch (Exception e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testSES2052If2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "SELECT ?p \n" + + "WHERE { \n" + + " ?s ?p ?o . \n" + + " FILTER(IF(!BOUND(?p), false , ?p = )) \n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + while (result.hasNext()) { + BindingSet bs = result.next(); + + IRI p = (IRI) bs.getValue("p"); + assertNotNull(p); + assertEquals(RDF.TYPE, p); } + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testRegexCaseNonAscii() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; + private void testRegexCaseNonAscii(RepositoryConnection conn) { - assertTrue(conn.prepareBooleanQuery(query).evaluate(), "case-insensitive match on Cyrillic should succeed"); + String query = "ask {filter (regex(\"Валовой\", \"валовой\", \"i\")) }"; - query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; + assertTrue(conn.prepareBooleanQuery(query).evaluate(), "case-insensitive match on Cyrillic should succeed"); - assertFalse(conn.prepareBooleanQuery(query).evaluate(), "case-sensitive match on Cyrillic should fail"); - } - closeRepository(repo); + query = "ask {filter (regex(\"Валовой\", \"валовой\")) }"; + + assertFalse(conn.prepareBooleanQuery(query).evaluate(), "case-sensitive match on Cyrillic should fail"); } - private void testFilterRegexBoolean() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); + private void testFilterRegexBoolean(RepositoryConnection conn) throws Exception { - // test case for issue SES-1050 - String query = getNamespaceDeclarations() + " SELECT *" + " WHERE { " + " ?x foaf:name ?name ; " - + " foaf:mbox ?mbox . " + " FILTER(EXISTS { " - + " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + - // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); - " } )" + " } "; + loadTestData("/testdata-query/dataset-query.trig", conn); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + // test case for issue SES-1050 + String query = getNamespaceDeclarations() + + " SELECT *" + + " WHERE { " + + " ?x foaf:name ?name ; " + + " foaf:mbox ?mbox . " + + " FILTER(EXISTS { " + + " FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) " + + // query.append(" FILTER(REGEX(?mbox, \"bob\")) "); + " } )" + + " } "; - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(1, count); - } + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(1, count); } - closeRepository(repo); } - private void testDateCastFunction_date() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); - } + private void testDateCastFunction_date(RepositoryConnection conn) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); } - closeRepository(repo); } - private void testDateCastFunction_date_withTimeZone_utc() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09Z", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); - } + private void testDateCastFunction_date_withTimeZone_utc(RepositoryConnection conn) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09Z", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); } - closeRepository(repo); } - private void testDateCastFunction_dateTime_withTimeZone_offset() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertEquals("2022-09-09+03:00", result.next().getValue("date").stringValue()); - assertFalse(result.hasNext()); - } + private void testDateCastFunction_dateTime_withTimeZone_offset(RepositoryConnection conn) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertEquals("2022-09-09+03:00", result.next().getValue("date").stringValue()); + assertFalse(result.hasNext()); } - closeRepository(repo); } - private void testDateCastFunction_invalidInput() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String qry = "PREFIX xsd: " - + "SELECT (xsd:date(\"2022-09-xx\") AS ?date) { }"; - - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - assertFalse(result.next().hasBinding("date"), - "There should be no binding because the cast should have failed."); - assertFalse(result.hasNext()); - } + private void testDateCastFunction_invalidInput(RepositoryConnection conn) { + String qry = "PREFIX xsd: " + + "SELECT (xsd:date(\"2022-09-xx\") AS ?date) { }"; + + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, qry).evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + assertFalse(result.next().hasBinding("date"), + "There should be no binding because the cast should have failed."); + assertFalse(result.hasNext()); } - closeRepository(repo); } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java index d7476c0e8ef..6f941a033cd 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ConstructTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; import java.io.StringReader; import java.util.function.Supplier; import java.util.stream.Stream; @@ -34,7 +35,9 @@ import org.eclipse.rdf4j.query.QueryResults; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.rio.RDFFormat; +import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; import org.junit.jupiter.api.DynamicTest; @@ -50,82 +53,87 @@ public ConstructTest(Supplier repo) { super(repo); } - private void testConstructModifiers() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-construct-modifiers.ttl", conn); - String qry = "PREFIX foaf: \n" + "PREFIX site: \n" - + "CONSTRUCT { \n" + " ?iri foaf:name ?name . \n" + " ?iri foaf:nick ?nick . \n" + "} \n" - + "WHERE { \n" + " ?iri foaf:name ?name ; \n" + " site:hits ?hits ; \n" - + " foaf:nick ?nick . \n" + "} \n" + "ORDER BY desc(?hits) \n" + "LIMIT 3"; - Statement[] correctResult = { - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), - statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), - - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/name"), literal("Eve"), null), - statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), - - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), - statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), }; - GraphQuery gq = conn.prepareGraphQuery(qry); - try (GraphQueryResult result = gq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - int resultNo = 0; - while (result.hasNext()) { - Statement st = result.next(); - assertThat(resultNo).isLessThan(correctResult.length); - assertEquals(correctResult[resultNo], st); - resultNo++; - } - assertEquals(correctResult.length, resultNo); + private void testConstructModifiers(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-construct-modifiers.ttl", conn); + String qry = "PREFIX foaf: \n" + + "PREFIX site: \n" + + "CONSTRUCT { \n" + + " ?iri foaf:name ?name . \n" + + " ?iri foaf:nick ?nick . \n" + + "} \n" + + "WHERE { \n" + + " ?iri foaf:name ?name ; \n" + + " site:hits ?hits ; \n" + + " foaf:nick ?nick . \n" + + "} \n" + + "ORDER BY desc(?hits) \n" + + "LIMIT 3"; + Statement[] correctResult = { + statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/name"), literal("Alice"), null), + statement(iri("urn:1"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Al"), null), + + statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/name"), literal("Eve"), null), + statement(iri("urn:3"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Ev"), null), + + statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/name"), literal("Bob"), null), + statement(iri("urn:2"), iri("http://xmlns.com/foaf/0.1/nick"), literal("Bo"), null), + }; + GraphQuery gq = conn.prepareGraphQuery(qry); + try (GraphQueryResult result = gq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + int resultNo = 0; + while (result.hasNext()) { + Statement st = result.next(); + assertThat(resultNo).isLessThan(correctResult.length); + assertEquals(correctResult[resultNo], st); + resultNo++; } + assertEquals(correctResult.length, resultNo); } - closeRepository(repo); } /** * See https://github.com/eclipse/rdf4j/issues/3011 */ - private void testConstruct_CyclicPathWithJoin() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); - conn.add(test, RDF.TYPE, DCAT.CATALOG); + private void testConstruct_CyclicPathWithJoin(RepositoryConnection conn) { + IRI test = iri("urn:test"), a = iri("urn:a"), b = iri("urn:b"), c = iri("urn:c"); + conn.add(test, RDF.TYPE, DCAT.CATALOG); - String query = "PREFIX dcat: \n" + "\n" + "CONSTRUCT {\n" - + " ?x .\n" + " ?x ?x .\n" + "}\n" + "WHERE {\n" + " ?x a dcat:Catalog .\n" - + "}"; + String query = "PREFIX dcat: \n" + + "\n" + + "CONSTRUCT {\n" + + " ?x .\n" + + " ?x ?x .\n" + + "}\n" + + "WHERE {\n" + + " ?x a dcat:Catalog .\n" + + "}"; - Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); + Model result = QueryResults.asModel(conn.prepareGraphQuery(query).evaluate()); - assertThat(result.contains(a, b, test)).isTrue(); - assertThat(result.contains(test, c, test)).isTrue(); - } - closeRepository(repo); + assertThat(result.contains(a, b, test)).isTrue(); + assertThat(result.contains(test, c, test)).isTrue(); } - private void testSES2104ConstructBGPSameURI() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; + private void testSES2104ConstructBGPSameURI(RepositoryConnection conn) + throws RDFParseException, RepositoryException, IOException { + final String queryStr = "PREFIX : CONSTRUCT {:x :p :x } WHERE {} "; - conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); + conn.add(new StringReader("@prefix : . :a :p :b . "), "", RDFFormat.TURTLE); - final IRI x = conn.getValueFactory().createIRI("urn:x"); - final IRI p = conn.getValueFactory().createIRI("urn:p"); + final IRI x = conn.getValueFactory().createIRI("urn:x"); + final IRI p = conn.getValueFactory().createIRI("urn:p"); - GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr); - try (GraphQueryResult evaluate = query.evaluate()) { - Model result = QueryResults.asModel(evaluate); + GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr); + try (GraphQueryResult evaluate = query.evaluate()) { + Model result = QueryResults.asModel(evaluate); - assertNotNull(result); - assertFalse(result.isEmpty()); - assertTrue(result.contains(x, p, x)); - } + assertNotNull(result); + assertFalse(result.isEmpty()); + assertTrue(result.contains(x, p, x)); } - closeRepository(repo); } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java index 20e86934b89..784f57f0988 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DefaultGraphTest.java @@ -44,100 +44,90 @@ public DefaultGraphTest(Supplier repo) { super(repo); } - private void testNullContext1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = " SELECT * " + " FROM DEFAULT " + " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(EX.BOB, s); // should not be present in default - // graph - assertNotEquals(EX.ALICE, s); // should not be present in - // default - // graph - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testNullContext1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + + " FROM DEFAULT " + + " WHERE { ?s ?p ?o } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); + + Resource s = (Resource) bs.getValue("s"); + + assertNotNull(s); + assertNotEquals(EX.BOB, s); // should not be present in default + // graph + assertNotEquals(EX.ALICE, s); // should not be present in + // default + // graph } + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } - closeRepository(repo); } - private void testNullContext2() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = " SELECT * " + " FROM rdf4j:nil " + " WHERE { ?s ?p ?o } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - while (result.hasNext()) { - BindingSet bs = result.next(); - assertNotNull(bs); - - Resource s = (Resource) bs.getValue("s"); - - assertNotNull(s); - assertNotEquals(EX.BOB, s); // should not be present in default - // graph - assertNotEquals(EX.ALICE, s); // should not be present in - // default - // graph - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testNullContext2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + + " FROM rdf4j:nil " + + " WHERE { ?s ?p ?o } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + while (result.hasNext()) { + BindingSet bs = result.next(); + assertNotNull(bs); + + Resource s = (Resource) bs.getValue("s"); + + assertNotNull(s); + assertNotEquals(EX.BOB, s); // should not be present in default + // graph + assertNotEquals(EX.ALICE, s); // should not be present in + // default + // graph } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSesameNilAsGraph() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = " SELECT * " + " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; + private void testSesameNilAsGraph(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = " SELECT * " + + " WHERE { GRAPH rdf4j:nil { ?s ?p ?o } } "; // query.append(" WHERE { ?s ?p ?o } "); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try { - List result = QueryResults.asList(tq.evaluate()); + try { + List result = QueryResults.asList(tq.evaluate()); - // nil graph should not be empty - assertThat(result.size()).isGreaterThan(1); + // nil graph should not be empty + assertThat(result.size()).isGreaterThan(1); - for (BindingSet bs : result) { - Resource s = (Resource) bs.getValue("s"); + for (BindingSet bs : result) { + Resource s = (Resource) bs.getValue("s"); - assertNotNull(s); - assertThat(s).withFailMessage("%s should not be present in nil graph", EX.BOB).isNotEqualTo(EX.BOB); - assertThat(s).withFailMessage("%s should not be present in nil graph", EX.ALICE) - .isNotEqualTo(EX.ALICE); - } - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + assertNotNull(s); + assertThat(s).withFailMessage("%s should not be present in nil graph", EX.BOB).isNotEqualTo(EX.BOB); + assertThat(s).withFailMessage("%s should not be present in nil graph", EX.ALICE).isNotEqualTo(EX.ALICE); } - } finally { - closeRepository(repo); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java index 0812d301fdb..c9e547ff287 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/DescribeTest.java @@ -44,309 +44,262 @@ public DescribeTest(Supplier repo) { super(repo); } - private void testDescribeA() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ex:a"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); - } + private void testDescribeA(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + + "DESCRIBE ex:a"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI a = f.createIRI("http://example.org/a"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); } } - } finally { - closeRepository(repo); } } - private void testDescribeAWhere() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI a = f.createIRI("http://example.org/a"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); - } + private void testDescribeAWhere(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI a = f.createIRI("http://example.org/a"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); } } - } finally { - closeRepository(repo); } } - private void testDescribeWhere() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI a = vf.createIRI("http://example.org/a"); - IRI b = vf.createIRI("http://example.org/b"); - IRI c = vf.createIRI("http://example.org/c"); - IRI e = vf.createIRI("http://example.org/e"); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertThat(result.contains(a, p, null)).isTrue(); - assertThat(result.contains(b, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(c, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(null, p, b)).isTrue(); - assertThat(result.contains(e, RDFS.LABEL, null)).isTrue(); - assertThat(result.contains(null, p, e)).isTrue(); - assertThat(result.contains(f, null, null)).isFalse(); - Set objects = result.filter(a, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - assertThat(result.contains((Resource) object, null, null)).isTrue(); - assertThat(result.filter((Resource) object, null, null)).hasSize(2); - } + private void testDescribeWhere(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI a = vf.createIRI("http://example.org/a"); + IRI b = vf.createIRI("http://example.org/b"); + IRI c = vf.createIRI("http://example.org/c"); + IRI e = vf.createIRI("http://example.org/e"); + IRI f = vf.createIRI("http://example.org/f"); + IRI p = vf.createIRI("http://example.org/p"); + + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + assertThat(result.contains(a, p, null)).isTrue(); + assertThat(result.contains(b, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(c, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(null, p, b)).isTrue(); + assertThat(result.contains(e, RDFS.LABEL, null)).isTrue(); + assertThat(result.contains(null, p, e)).isTrue(); + assertThat(result.contains(f, null, null)).isFalse(); + Set objects = result.filter(a, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + assertThat(result.contains((Resource) object, null, null)).isTrue(); + assertThat(result.filter((Resource) object, null, null)).hasSize(2); } } - } finally { - closeRepository(repo); } } - private void testDescribeB() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ex:b"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI b = f.createIRI("http://example.org/b"); - IRI p = f.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - Set subjects = result.filter(null, p, b).subjects(); - assertThat(subjects).isNotNull(); - for (Value subject : subjects) { - if (subject instanceof BNode) { - assertThat(result.contains(null, null, subject)).isTrue(); - } + private void testDescribeB(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:b"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI b = f.createIRI("http://example.org/b"); + IRI p = f.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + Set subjects = result.filter(null, p, b).subjects(); + assertThat(subjects).isNotNull(); + for (Value subject : subjects) { + if (subject instanceof BNode) { + assertThat(result.contains(null, null, subject)).isTrue(); } } - } finally { - closeRepository(repo); } } - private void testDescribeD() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ex:d"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory f = conn.getValueFactory(); - IRI d = f.createIRI("http://example.org/d"); - IRI p = f.createIRI("http://example.org/p"); - IRI e = f.createIRI("http://example.org/e"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(null, p, e)).isTrue(); - assertThat(result.contains(e, null, null)).isFalse(); - - Set objects = result.filter(d, p, null).objects(); - assertThat(objects).isNotNull(); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertThat(childObjects).isNotEmpty(); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertThat(result.contains((BNode) childObject, null, null)).isTrue(); - } + private void testDescribeD(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + "DESCRIBE ex:d"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory f = conn.getValueFactory(); + IRI d = f.createIRI("http://example.org/d"); + IRI p = f.createIRI("http://example.org/p"); + IRI e = f.createIRI("http://example.org/e"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(null, p, e)).isTrue(); + assertThat(result.contains(e, null, null)).isFalse(); + + Set objects = result.filter(d, p, null).objects(); + assertThat(objects).isNotNull(); + for (Value object : objects) { + if (object instanceof BNode) { + Set childObjects = result.filter((BNode) object, null, null).objects(); + assertThat(childObjects).isNotEmpty(); + for (Value childObject : childObjects) { + if (childObject instanceof BNode) { + assertThat(result.contains((BNode) childObject, null, null)).isTrue(); } } } } - } finally { - closeRepository(repo); } } - private void testDescribeF() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-describe.trig", conn); - String query = getNamespaceDeclarations() + "DESCRIBE ex:f"; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI f = vf.createIRI("http://example.org/f"); - IRI p = vf.createIRI("http://example.org/p"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result).isNotNull().hasSize(4); - - Set objects = result.filter(f, p, null).objects(); - for (Value object : objects) { - if (object instanceof BNode) { - Set childObjects = result.filter((BNode) object, null, null).objects(); - assertThat(childObjects).isNotEmpty(); - for (Value childObject : childObjects) { - if (childObject instanceof BNode) { - assertThat(result.contains((BNode) childObject, null, null)).isTrue(); - } + private void testDescribeF(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); + String query = getNamespaceDeclarations() + + "DESCRIBE ex:f"; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI f = vf.createIRI("http://example.org/f"); + IRI p = vf.createIRI("http://example.org/p"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result).isNotNull().hasSize(4); + + Set objects = result.filter(f, p, null).objects(); + for (Value object : objects) { + if (object instanceof BNode) { + Set childObjects = result.filter((BNode) object, null, null).objects(); + assertThat(childObjects).isNotEmpty(); + for (Value childObject : childObjects) { + if (childObject instanceof BNode) { + assertThat(result.contains((BNode) childObject, null, null)).isTrue(); } } } } - } finally { - closeRepository(repo); } } - private void testDescribeMultipleA() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + private void testDescribeMultipleA(RepositoryConnection conn) { + String update = "insert data { . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); - } - } finally { - closeRepository(repo); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); } } - private void testDescribeMultipleB() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String update = "insert data { . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + private void testDescribeMultipleB(RepositoryConnection conn) { + String update = "insert data { . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - String query = getNamespaceDeclarations() + "DESCRIBE "; + String query = getNamespaceDeclarations() + "DESCRIBE "; - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(urn1, blank, null)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); - } - } finally { - closeRepository(repo); + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(urn1, blank, null)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); } } - private void testDescribeMultipleC() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String update = "insert data { . [] . [] . . } "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(urn1, blank, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); - } - } finally { - closeRepository(repo); + private void testDescribeMultipleC(RepositoryConnection conn) { + String update = "insert data { . [] . [] . . } "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(urn1, blank, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); } } - private void testDescribeMultipleD() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String update = "insert data { . [] . . [] . . [] .} "; - conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); - - String query = getNamespaceDeclarations() + "DESCRIBE "; - - GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); - - ValueFactory vf = conn.getValueFactory(); - IRI urn1 = vf.createIRI("urn:1"); - IRI p1 = vf.createIRI("urn:p1"); - IRI p2 = vf.createIRI("urn:p2"); - IRI urn2 = vf.createIRI("urn:2"); - IRI urn4 = vf.createIRI("urn:4"); - IRI blank = vf.createIRI("urn:blank"); - try (GraphQueryResult evaluate = gq.evaluate()) { - Model result = QueryResults.asModel(evaluate); - - assertThat(result.contains(urn1, p1, null)).isTrue(); - assertThat(result.contains(null, blank, urn1)).isTrue(); - assertThat(result.contains(urn2, p2, null)).isTrue(); - assertThat(result.contains(urn4, p2, null)).isTrue(); - assertThat(result.contains(urn4, blank, null)).isTrue(); - } - } finally { - closeRepository(repo); + private void testDescribeMultipleD(RepositoryConnection conn) { + String update = "insert data { . [] . . [] . . [] .} "; + conn.prepareUpdate(QueryLanguage.SPARQL, update).execute(); + + String query = getNamespaceDeclarations() + "DESCRIBE "; + + GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); + + ValueFactory vf = conn.getValueFactory(); + IRI urn1 = vf.createIRI("urn:1"); + IRI p1 = vf.createIRI("urn:p1"); + IRI p2 = vf.createIRI("urn:p2"); + IRI urn2 = vf.createIRI("urn:2"); + IRI urn4 = vf.createIRI("urn:4"); + IRI blank = vf.createIRI("urn:blank"); + try (GraphQueryResult evaluate = gq.evaluate()) { + Model result = QueryResults.asModel(evaluate); + + assertThat(result.contains(urn1, p1, null)).isTrue(); + assertThat(result.contains(null, blank, urn1)).isTrue(); + assertThat(result.contains(urn2, p2, null)).isTrue(); + assertThat(result.contains(urn4, p2, null)).isTrue(); + assertThat(result.contains(urn4, blank, null)).isTrue(); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java index dc0808f7b06..f17a57e9b4f 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ExistsTest.java @@ -37,36 +37,39 @@ public ExistsTest(Supplier repo) { super(repo); } - private void testFilterNotExistsBindingToCurrentSolutionMapping() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String ex = "http://example/"; - IRI a1 = Values.iri(ex, "a1"); - IRI a2 = Values.iri(ex, "a2"); - - IRI both = Values.iri(ex, "both"); - - IRI predicate1 = Values.iri(ex, "predicate1"); - IRI predicate2 = Values.iri(ex, "predicate2"); - - conn.add(a1, predicate1, both); - conn.add(a1, predicate2, both); - - conn.add(a2, predicate1, both); - conn.add(a2, predicate2, Values.bnode()); - - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX : \n" + "SELECT * WHERE {\n" - + " ?a :predicate1 ?p1\n" + " FILTER NOT EXISTS {\n" + " ?a :predicate2 ?p2 .\n" - + " FILTER(?p2 = ?p1)\n" + " }\n" + "}\n"); - - try (Stream stream = tupleQuery.evaluate().stream()) { - List collect = stream.collect(Collectors.toList()); - assertEquals(1, collect.size()); - assertEquals(a2, collect.get(0).getValue("a")); - } - } finally { - closeRepository(repo); + private void testFilterNotExistsBindingToCurrentSolutionMapping(RepositoryConnection conn) { + + String ex = "http://example/"; + IRI a1 = Values.iri(ex, "a1"); + IRI a2 = Values.iri(ex, "a2"); + + IRI both = Values.iri(ex, "both"); + + IRI predicate1 = Values.iri(ex, "predicate1"); + IRI predicate2 = Values.iri(ex, "predicate2"); + + conn.add(a1, predicate1, both); + conn.add(a1, predicate2, both); + + conn.add(a2, predicate1, both); + conn.add(a2, predicate2, Values.bnode()); + + TupleQuery tupleQuery = conn.prepareTupleQuery( + "PREFIX : \n" + + "SELECT * WHERE {\n" + + " ?a :predicate1 ?p1\n" + + " FILTER NOT EXISTS {\n" + + " ?a :predicate2 ?p2 .\n" + + " FILTER(?p2 = ?p1)\n" + + " }\n" + + "}\n"); + + try (Stream stream = tupleQuery.evaluate().stream()) { + List collect = stream.collect(Collectors.toList()); + assertEquals(1, collect.size()); + assertEquals(a2, collect.get(0).getValue("a")); } + } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java index c5913728458..365ed6044a6 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/GroupByTest.java @@ -34,19 +34,14 @@ public GroupByTest(Supplier repo) { super(repo); } - private void testGroupByEmpty() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - // see issue https://github.com/eclipse/rdf4j/issues/573 - String query = "select ?x where {?x ?p ?o} group by ?x"; - - TupleQuery tq = conn.prepareTupleQuery(query); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } finally { - closeRepository(repo); + private void testGroupByEmpty(RepositoryConnection conn) { + // see issue https://github.com/eclipse/rdf4j/issues/573 + String query = "select ?x where {?x ?p ?o} group by ?x"; + + TupleQuery tq = conn.prepareTupleQuery(query); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java index e139d5f869f..724cc943bc0 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/InTest.java @@ -44,69 +44,54 @@ public InTest(Supplier repo) { super(repo); } - private void testInComparison1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1913.trig", conn); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(literal("1", CoreDatatype.XSD.INTEGER), y); - } - } finally { - closeRepository(repo); + private void testInComparison1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + BindingSet bs = result.next(); + Value y = bs.getValue("y"); + assertNotNull(y); + assertTrue(y instanceof Literal); + assertEquals(literal("1", CoreDatatype.XSD.INTEGER), y); } } - private void testInComparison2() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1913.trig", conn); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } finally { - closeRepository(repo); + private void testInComparison2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); } } - private void testInComparison3() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1913.trig", conn); - String query = " PREFIX : \n" - + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - BindingSet bs = result.next(); - Value y = bs.getValue("y"); - assertNotNull(y); - assertTrue(y instanceof Literal); - assertEquals(literal("1", XSD.INTEGER), y); - } - } finally { - closeRepository(repo); + private void testInComparison3(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1913.trig", conn); + String query = " PREFIX : \n" + + " SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + BindingSet bs = result.next(); + Value y = bs.getValue("y"); + assertNotNull(y); + assertTrue(y instanceof Literal); + assertEquals(literal("1", XSD.INTEGER), y); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java index 58c8ebf1b25..dc83e80f8da 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/MinusTest.java @@ -38,44 +38,50 @@ public MinusTest(Supplier repo) { super(repo); } - private void testScopingOfFilterInMinus() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String ex = "http://example/"; - IRI a1 = Values.iri(ex, "a1"); - IRI a2 = Values.iri(ex, "a2"); + private void testScopingOfFilterInMinus(RepositoryConnection conn) { - IRI both = Values.iri(ex, "both"); + String ex = "http://example/"; + IRI a1 = Values.iri(ex, "a1"); + IRI a2 = Values.iri(ex, "a2"); - IRI predicate1 = Values.iri(ex, "predicate1"); - IRI predicate2 = Values.iri(ex, "predicate2"); + IRI both = Values.iri(ex, "both"); - conn.add(a1, predicate1, both); - conn.add(a1, predicate2, both); + IRI predicate1 = Values.iri(ex, "predicate1"); + IRI predicate2 = Values.iri(ex, "predicate2"); - conn.add(a2, predicate1, both); - conn.add(a2, predicate2, Values.bnode()); + conn.add(a1, predicate1, both); + conn.add(a1, predicate2, both); - TupleQuery tupleQuery = conn.prepareTupleQuery( - "PREFIX : \n" + "SELECT * WHERE {\n" + " ?a :predicate1 ?p1\n" + " MINUS {\n" - + " ?a :predicate2 ?p2 .\n" + " FILTER(?p2 = ?p1)\n" + " }\n" + "} ORDER BY ?a\n"); + conn.add(a2, predicate1, both); + conn.add(a2, predicate2, Values.bnode()); - try (Stream stream = tupleQuery.evaluate().stream()) { - List collect = stream.collect(Collectors.toList()); - assertEquals(2, collect.size()); + TupleQuery tupleQuery = conn.prepareTupleQuery( + "PREFIX : \n" + + "SELECT * WHERE {\n" + + " ?a :predicate1 ?p1\n" + + " MINUS {\n" + + " ?a :predicate2 ?p2 .\n" + + " FILTER(?p2 = ?p1)\n" + + " }\n" + + "} ORDER BY ?a\n" + ); - List expectedValues = List.of(a1, a2); - List actualValues = collect.stream().map(b -> b.getValue("a")).collect(Collectors.toList()); + try (Stream stream = tupleQuery.evaluate().stream()) { + List collect = stream.collect(Collectors.toList()); + assertEquals(2, collect.size()); - assertEquals(expectedValues, actualValues); - } - } finally { - closeRepository(repo); + List expectedValues = List.of(a1, a2); + List actualValues = collect + .stream() + .map(b -> b.getValue("a")) + .collect(Collectors.toList()); + + assertEquals(expectedValues, actualValues); } + } public Stream tests() { return Stream.of(makeTest("ScopingOfFilterInMinus", this::testScopingOfFilterInMinus)); } - } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java index 9d0e4a57da8..46dfad6b607 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OptionalTest.java @@ -48,131 +48,146 @@ public OptionalTest(Supplier repo) { super(repo); } - private void testSES1898LeftJoinSemantics1() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1898.trig", conn); - String query = " PREFIX : " + " SELECT * WHERE { " + " ?s :p1 ?v1 . " - + " OPTIONAL {?s :p2 ?v2 } ." + " ?s :p3 ?v2 . " + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(0, count); - } - } finally { - closeRepository(repo); + private void testSES1898LeftJoinSemantics1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1898.trig", conn); + String query = " PREFIX : " + + " SELECT * WHERE { " + + " ?s :p1 ?v1 . " + + " OPTIONAL {?s :p2 ?v2 } ." + + " ?s :p3 ?v2 . " + + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(0, count); } } - private void testSES1121VarNamesInOptionals() throws Exception { + private void testSES1121VarNamesInOptionals(RepositoryConnection conn) throws Exception { // Verifying that variable names have no influence on order of optionals // in query. See SES-1121. - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1121.trig", conn); - String query1 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" - + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?c . } \n " - + " } \n" + " } \n"; + loadTestData("/testdata-query/dataset-ses1121.trig", conn); - String query2 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + " WHERE { GRAPH ?g { \n" - + " OPTIONAL { ?var35 ex:p ?b . } \n " + " OPTIONAL { ?b ex:q ?var2 . } \n " - + " } \n" + " } \n"; + String query1 = getNamespaceDeclarations() + + " SELECT DISTINCT *\n" + + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + + " OPTIONAL { ?b ex:q ?c . } \n " + + " } \n" + + " } \n"; - TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); - TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); + String query2 = getNamespaceDeclarations() + + " SELECT DISTINCT *\n" + + " WHERE { GRAPH ?g { \n" + + " OPTIONAL { ?var35 ex:p ?b . } \n " + + " OPTIONAL { ?b ex:q ?var2 . } \n " + + " } \n" + + " } \n"; - try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate()) { - assertNotNull(result1); - assertNotNull(result2); + TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1); + TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2); - List qr1 = QueryResults.asList(result1); - List qr2 = QueryResults.asList(result2); + try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate()) { + assertNotNull(result1); + assertNotNull(result2); - // System.out.println(qr1); - // System.out.println(qr2); + List qr1 = QueryResults.asList(result1); + List qr2 = QueryResults.asList(result2); - // if optionals are not kept in same order, query results will be - // different size. - assertEquals(qr1.size(), qr2.size()); + // System.out.println(qr1); + // System.out.println(qr2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); + // if optionals are not kept in same order, query results will be + // different size. + assertEquals(qr1.size(), qr2.size()); + + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSameTermRepeatInOptional() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = getNamespaceDeclarations() + " SELECT ?l ?opt1 ?opt2 " + " FROM ex:optional-sameterm-graph " - + " WHERE { " + " ?s ex:p ex:A ; " + " { " + " { " - + " ?s ?p ?l ." + " FILTER(?p = rdfs:label) " + " } " - + " OPTIONAL { " + " ?s ?p ?opt1 . " - + " FILTER (?p = ex:prop1) " + " } " + " OPTIONAL { " - + " ?s ?p ?opt2 . " + " FILTER (?p = ex:prop2) " - + " } " + " }" + " } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value l = bs.getValue("l"); - assertTrue(l instanceof Literal); - assertEquals("label", ((Literal) l).getLabel()); - - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); - } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testSameTermRepeatInOptional(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = getNamespaceDeclarations() + + " SELECT ?l ?opt1 ?opt2 " + + " FROM ex:optional-sameterm-graph " + + " WHERE { " + + " ?s ex:p ex:A ; " + + " { " + + " { " + + " ?s ?p ?l ." + + " FILTER(?p = rdfs:label) " + + " } " + + " OPTIONAL { " + + " ?s ?p ?opt1 . " + + " FILTER (?p = ex:prop1) " + + " } " + + " OPTIONAL { " + + " ?s ?p ?opt2 . " + + " FILTER (?p = ex:prop2) " + + " } " + + " }" + + " } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + // System.out.println(bs); + + Value l = bs.getValue("l"); + assertTrue(l instanceof Literal); + assertEquals("label", ((Literal) l).getLabel()); + + Value opt1 = bs.getValue("opt1"); + assertNull(opt1); + + Value opt2 = bs.getValue("opt2"); + assertNull(opt2); } - } finally { - closeRepository(repo); + assertEquals(1, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } /** * See https://github.com/eclipse/rdf4j/issues/3072 * */ - private void testValuesAfterOptional() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String data = "@prefix rdfs: . \n" + "@prefix : . \n" - + ":r1 a rdfs:Resource . \n" + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; - - String query = "" + "prefix rdfs: \n" + "prefix : \n" - + "\n" + "select ?resource ?label where { \n" + " ?resource a rdfs:Resource . \n" - + " optional { ?resource rdfs:label ?label } \n" + " values ?label { undef } \n" + "}"; - - conn.add(new StringReader(data), RDFFormat.TURTLE); - - List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); - assertThat(result).hasSize(2); - } finally { - closeRepository(repo); - } + private void testValuesAfterOptional(RepositoryConnection conn) throws Exception { + String data = "@prefix rdfs: . \n" + + "@prefix : . \n" + + ":r1 a rdfs:Resource . \n" + + ":r2 a rdfs:Resource ; rdfs:label \"a label\" . \n"; + + String query = "" + + "prefix rdfs: \n" + + "prefix : \n" + + "\n" + + "select ?resource ?label where { \n" + + " ?resource a rdfs:Resource . \n" + + " optional { ?resource rdfs:label ?label } \n" + + " values ?label { undef } \n" + + "}"; + + conn.add(new StringReader(data), RDFFormat.TURTLE); + + List result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate()); + assertThat(result).hasSize(2); } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java index 771501f54bc..c9e863f21cc 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/OrderByTest.java @@ -31,58 +31,46 @@ public OrderByTest(Supplier repo) { super(repo); } - private void testDistinctOptionalOrderBy() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", - RDFFormat.TURTLE); - - String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by ?nr"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); - } - } finally { - closeRepository(repo); + private void testDistinctOptionalOrderBy(RepositoryConnection conn) throws Exception { + + conn.add(new StringReader("[] a .\n" + + "[] a ; 123 ."), "", RDFFormat.TURTLE); + + String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by ?nr"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); } } - private void testOrderByVariableNotInUse() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(new StringReader("_:bob1 a ; rdfs:label \"Bob1\" .\n" - + "_:bob2 a ; rdfs:label \"Bob2\" ."), "", RDFFormat.TURTLE); - - String query = "SELECT * WHERE { ?person a } ORDER BY ?score\n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - // use distinct because the issue is that the query produces duplicates - long count = result.distinct().count(); - assertEquals(2, count); - } - } finally { - closeRepository(repo); + private void testOrderByVariableNotInUse(RepositoryConnection conn) throws Exception { + + conn.add(new StringReader("_:bob1 a ; rdfs:label \"Bob1\" .\n" + + "_:bob2 a ; rdfs:label \"Bob2\" ."), "", RDFFormat.TURTLE); + + String query = "SELECT * WHERE { ?person a } ORDER BY ?score\n"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + // use distinct because the issue is that the query produces duplicates + long count = result.distinct().count(); + assertEquals(2, count); } } - private void testDistinctOptionalOrderByMath() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", - RDFFormat.TURTLE); - - String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by (?nr + STRLEN(?o))"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); - } - } finally { - closeRepository(repo); + private void testDistinctOptionalOrderByMath(RepositoryConnection conn) throws Exception { + + conn.add(new StringReader("[] a .\n" + + "[] a ; 123 ."), "", RDFFormat.TURTLE); + + String query = "select distinct ?o ?nr { ?o a optional { ?o ?nr } } order by (?nr + STRLEN(?o))"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java index 70e44098537..a01d7bcebca 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/PropertyPathTest.java @@ -62,172 +62,147 @@ public PropertyPathTest(Supplier repo) { super(repo); } - private void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { - - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String data = " .\n" + " .\n" - + " .\n" + " .\n" - + " .\n"; - - conn.begin(); - conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); - conn.commit(); - - String query = getNamespaceDeclarations() + "SELECT ?x \n" + "WHERE { ?x */ . \n" - + " ?x */ . \n" + "} \n"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - - assertNotNull(result); - assertTrue(result.hasNext()); - - Value x = result.next().getValue("x"); - assertNotNull(x); - assertTrue(x instanceof IRI); - assertEquals("urn:s1", x.stringValue()); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); + private void testSES2147PropertyPathsWithIdenticalSubsPreds(RepositoryConnection conn) throws Exception { + + String data = " .\n" + + " .\n" + + " .\n" + + " .\n" + + " .\n"; + + conn.begin(); + conn.add(new StringReader(data), "", RDFFormat.NTRIPLES); + conn.commit(); + + String query = getNamespaceDeclarations() + + "SELECT ?x \n" + + "WHERE { ?x */ . \n" + + " ?x */ . \n" + + "} \n"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + + assertNotNull(result); + assertTrue(result.hasNext()); + + Value x = result.next().getValue("x"); + assertNotNull(x); + assertTrue(x instanceof IRI); + assertEquals("urn:s1", x.stringValue()); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSES2024PropertyPathAnonVarSharing() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses2024.trig", conn); - String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - BindingSet bs = result.next(); - Literal l1 = (Literal) bs.getValue("l1"); - Literal l2 = (Literal) bs.getValue("l2"); - - assertNotNull(l1); - assertNotEquals(l1, l2); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); - } - } - - private void testPropertyPathNegationInversion() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String data = "@prefix : .\n" + ":Mary :parentOf :Jim.\n" + ":Jim :knows :Jane.\n" - + ":Jane :worksFor :IBM."; + private void testSES2024PropertyPathAnonVarSharing(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses2024.trig", conn); + String query = "PREFIX : SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }"; - conn.add(new StringReader(data), "", RDFFormat.TURTLE); - String query1 = "prefix : ASK WHERE { :IBM ^(:|!:) :Jane } "; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - assertTrue(conn.prepareBooleanQuery(query1).evaluate()); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - String query2 = "prefix : ASK WHERE { :IBM ^(:|!:) ?a } "; - assertTrue(conn.prepareBooleanQuery(query2).evaluate()); + BindingSet bs = result.next(); + Literal l1 = (Literal) bs.getValue("l1"); + Literal l2 = (Literal) bs.getValue("l2"); - String query3 = "prefix : ASK WHERE { :IBM (^(:|!:))* :Mary } "; - assertTrue(conn.prepareBooleanQuery(query3).evaluate()); - } finally { - closeRepository(repo); + assertNotNull(l1); + assertNotEquals(l1, l2); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSES2336NegatedPropertyPathMod() throws Exception { + private void testPropertyPathNegationInversion(RepositoryConnection conn) throws Exception { + String data = "@prefix : .\n" + ":Mary :parentOf :Jim.\n" + ":Jim :knows :Jane.\n" + + ":Jane :worksFor :IBM."; - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { + conn.add(new StringReader(data), "", RDFFormat.TURTLE); + String query1 = "prefix : ASK WHERE { :IBM ^(:|!:) :Jane } "; - loadTestData("/testdata-query/dataset-ses2336.trig", conn); - String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; + assertTrue(conn.prepareBooleanQuery(query1).evaluate()); - ValueFactory vf = conn.getValueFactory(); - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + String query2 = "prefix : ASK WHERE { :IBM ^(:|!:) ?a } "; + assertTrue(conn.prepareBooleanQuery(query2).evaluate()); - try (TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertNotNull(result); + String query3 = "prefix : ASK WHERE { :IBM (^(:|!:))* :Mary } "; + assertTrue(conn.prepareBooleanQuery(query3).evaluate()); + + } - IRI a = vf.createIRI(EX.NAMESPACE, "a"); - IRI b = vf.createIRI(EX.NAMESPACE, "b"); - IRI c = vf.createIRI(EX.NAMESPACE, "c"); - IRI d = vf.createIRI(EX.NAMESPACE, "d"); - IRI e = vf.createIRI(EX.NAMESPACE, "e"); - IRI test = vf.createIRI(EX.NAMESPACE, "Test"); + private void testSES2336NegatedPropertyPathMod(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses2336.trig", conn); + String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", a))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", test))); - assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", c))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", d))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", e))); - assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", test))); + ValueFactory vf = conn.getValueFactory(); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - assertFalse(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", b))); + try (TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertNotNull(result); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } finally { - closeRepository(repo); + IRI a = vf.createIRI(EX.NAMESPACE, "a"); + IRI b = vf.createIRI(EX.NAMESPACE, "b"); + IRI c = vf.createIRI(EX.NAMESPACE, "c"); + IRI d = vf.createIRI(EX.NAMESPACE, "d"); + IRI e = vf.createIRI(EX.NAMESPACE, "e"); + IRI test = vf.createIRI(EX.NAMESPACE, "Test"); + + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", a))); + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", test))); + assertTrue(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", c))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", d))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", e))); + assertTrue(containsSolution(result, new SimpleBinding("s", d), new SimpleBinding("o", test))); + + assertFalse(containsSolution(result, new SimpleBinding("s", a), new SimpleBinding("o", b))); + + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } - private void testSES1685propPathSameVar() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; + private void testSES1685propPathSameVar(RepositoryConnection conn) throws Exception { + final String queryStr = "PREFIX : SELECT ?x WHERE {?x :p+ ?x}"; - conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); + conn.add(new StringReader("@prefix : . :a :p :b . :b :p :a ."), "", RDFFormat.TURTLE); - TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); + TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); - try (Stream result = query.evaluate().stream()) { - long count = result.count(); - assertEquals(2, count); - } - } finally { - closeRepository(repo); + try (Stream result = query.evaluate().stream()) { + long count = result.count(); + assertEquals(2, count); } } - private void testSES1073InverseSymmetricPattern() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - IRI a = iri("http://example.org/a"); - IRI b1 = iri("http://example.org/b1"); - IRI b2 = iri("http://example.org/b2"); - IRI c1 = iri("http://example.org/c1"); - IRI c2 = iri("http://example.org/c2"); - IRI a2b = iri("http://example.org/a2b"); - IRI b2c = iri("http://example.org/b2c"); - conn.add(a, a2b, b1); - conn.add(a, a2b, b2); - conn.add(b1, b2c, c1); - conn.add(b2, b2c, c2); - String query = "select * "; - query += "where{ "; - query += "?c1 ^/^// ?c2 . "; - query += " } "; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (Stream result = tq.evaluate().stream()) { - long count = result.count(); - assertEquals(4, count); - } - } finally { - closeRepository(repo); + private void testSES1073InverseSymmetricPattern(RepositoryConnection conn) { + IRI a = iri("http://example.org/a"); + IRI b1 = iri("http://example.org/b1"); + IRI b2 = iri("http://example.org/b2"); + IRI c1 = iri("http://example.org/c1"); + IRI c2 = iri("http://example.org/c2"); + IRI a2b = iri("http://example.org/a2b"); + IRI b2c = iri("http://example.org/b2c"); + conn.add(a, a2b, b1); + conn.add(a, a2b, b2); + conn.add(b1, b2c, c1); + conn.add(b2, b2c, c2); + String query = "select * "; + query += "where{ "; + query += "?c1 ^/^// ?c2 . "; + query += " } "; + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (Stream result = tq.evaluate().stream()) { + long count = result.count(); + assertEquals(4, count); } } @@ -235,64 +210,60 @@ private void testSES1073InverseSymmetricPattern() { * @see GH-2727 */ - private void testNestedInversePropertyPathWithZeroLength() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String insert = "insert data {\n" + " .\n" - + " .\n" + " .\n" - + " .\n" + " .\n" - + " .\n" + "}"; + private void testNestedInversePropertyPathWithZeroLength(RepositoryConnection conn) { + String insert = "insert data {\n" + + " .\n" + + " .\n" + + " .\n" + + " .\n" + + " .\n" + + " .\n" + + "}"; - String query = "select * where { \n" + " (^)? ?o .\n" + "}"; + String query = "select * where { \n" + + " (^)? ?o .\n" + + "}"; - conn.prepareUpdate(insert).execute(); + conn.prepareUpdate(insert).execute(); - TupleQuery tq = conn.prepareTupleQuery(query); + TupleQuery tq = conn.prepareTupleQuery(query); - try (final TupleQueryResult evaluate = tq.evaluate()) { - List result = QueryResults.asList(evaluate); - assertThat(result).hasSize(4); - } - } finally { - closeRepository(repo); + try (final TupleQueryResult evaluate = tq.evaluate()) { + List result = QueryResults.asList(evaluate); + assertThat(result).hasSize(4); } } - private void testComplexPath() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); - conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); - - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX skos: \r\n" - + " SELECT * " + " WHERE {\r\n" - + " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + " }"); - try (TupleQueryResult evaluate = tupleQuery.evaluate()) { - List collect = evaluate.stream().collect(Collectors.toList()); - assertEquals(2, collect.size()); - } - } finally { - closeRepository(repo); + private void testComplexPath(RepositoryConnection conn) { + conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); + conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); + + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX skos: \r\n" + + " SELECT * " + + " WHERE {\r\n" + + " ?s (skos:broader|^skos:narrower|skos:topConceptOf|^skos:hasTopConcept) ?o.\r\n" + + " }"); + try (TupleQueryResult evaluate = tupleQuery.evaluate()) { + List collect = evaluate.stream().collect(Collectors.toList()); + assertEquals(2, collect.size()); } } - private void testInversePath() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - BNode bnode1 = Values.bnode("bnode1"); + private void testInversePath(RepositoryConnection conn) { + BNode bnode1 = Values.bnode("bnode1"); - conn.add(Values.bnode(), FOAF.KNOWS, bnode1); - conn.add(Values.bnode(), FOAF.KNOWS, bnode1); + conn.add(Values.bnode(), FOAF.KNOWS, bnode1); + conn.add(Values.bnode(), FOAF.KNOWS, bnode1); - TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" - + "SELECT * WHERE {\n" + " ?x foaf:knows/^foaf:knows ?y . \n" + " FILTER(?x != ?y)\n" + "}"); + TupleQuery tupleQuery = conn.prepareTupleQuery("PREFIX foaf: <" + FOAF.NAMESPACE + ">\n" + + "SELECT * WHERE {\n" + + " ?x foaf:knows/^foaf:knows ?y . \n" + + " FILTER(?x != ?y)\n" + + "}"); - try (TupleQueryResult evaluate = tupleQuery.evaluate()) { - List collect = evaluate.stream().collect(Collectors.toList()); - assertEquals(2, collect.size()); - } - } finally { - closeRepository(repo); + try (TupleQueryResult evaluate = tupleQuery.evaluate()) { + List collect = evaluate.stream().collect(Collectors.toList()); + assertEquals(2, collect.size()); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java index c835192e332..087ce8344c0 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/SubselectTest.java @@ -39,66 +39,83 @@ public SubselectTest(Supplier repo) { super(repo); } - private void testSES2373SubselectOptional() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - conn.prepareUpdate(QueryLanguage.SPARQL, - "insert data {" + " ." + " 1 ." + " ." - + " ." + " 2 ." + " ." - + " ." + " 3 ." + " ." - + " ." + " 4 ." + " ." - + " ." + " 5 ." + " ." + "}") - .execute(); + private void testSES2373SubselectOptional(RepositoryConnection conn) { + conn.prepareUpdate(QueryLanguage.SPARQL, + "insert data {" + " ." + " 1 ." + " ." + + " ." + " 2 ." + " ." + + " ." + " 3 ." + " ." + + " ." + " 4 ." + " ." + + " ." + " 5 ." + " ." + "}") + .execute(); - String qb = "select ?x { \n" + " { select ?v { ?v filter (?v = ) } }.\n" - + " optional { select ?val { ?v ?val .} }\n" + " ?v ?x \n" + "}\n"; + String qb = "select ?x { \n" + + " { select ?v { ?v filter (?v = ) } }.\n" + + " optional { select ?val { ?v ?val .} }\n" + + " ?v ?x \n" + + "}\n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult result = tq.evaluate()) { - assertTrue(result.hasNext(), "The query should return a result"); - BindingSet b = result.next(); - assertTrue(b.hasBinding("x"), "?x is from the mandatory part of the query and should be bound"); - } - } finally { - closeRepository(repo); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult result = tq.evaluate()) { + assertTrue(result.hasNext(), "The query should return a result"); + BindingSet b = result.next(); + assertTrue(b.hasBinding("x"), "?x is from the mandatory part of the query and should be bound"); } } - private void testSES2154SubselectOptional() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String ub = "insert data { \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " a . \n" + " a . \n" - + " a . \n" + " \"01\" . \n" + " \"02\" . \n" - + " \"03\" . \n" + " \"04\" . \n" - + " \"05\" . \n" + " \"06\" . \n" - + " \"07\" . \n" + " \"08\" . \n" - + " \"09\" . \n" + " \"10\" . \n" - + " \"11\" . \n" + " \"12\" . \n" + "} \n"; + private void testSES2154SubselectOptional(RepositoryConnection conn) { + + String ub = "insert data { \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " a . \n" + + " \"01\" . \n" + + " \"02\" . \n" + + " \"03\" . \n" + + " \"04\" . \n" + + " \"05\" . \n" + + " \"06\" . \n" + + " \"07\" . \n" + + " \"08\" . \n" + + " \"09\" . \n" + + " \"10\" . \n" + + " \"11\" . \n" + + " \"12\" . \n" + + "} \n"; - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); + conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - String qb = "SELECT ?s ?label\n" + "WHERE { \n" + " ?s a \n .\n" - + " OPTIONAL { {SELECT ?label WHERE { \n" + " ?s ?label . \n" - + " } ORDER BY ?label LIMIT 2 \n" + " }\n" + " }\n" + "}\n" - + "ORDER BY ?s\n" + "LIMIT 10 \n"; + String qb = "SELECT ?s ?label\n" + + "WHERE { \n" + + " ?s a \n .\n" + + " OPTIONAL { {SELECT ?label WHERE { \n" + + " ?s ?label . \n" + + " } ORDER BY ?label LIMIT 2 \n" + + " }\n" + + " }\n" + + "}\n" + + "ORDER BY ?s\n" + + "LIMIT 10 \n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); - try (TupleQueryResult evaluate = tq.evaluate()) { - assertTrue(evaluate.hasNext(), "The query should return a result"); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb); + try (TupleQueryResult evaluate = tq.evaluate()) { + assertTrue(evaluate.hasNext(), "The query should return a result"); - List result = QueryResults.asList(evaluate); - assertEquals(10, result.size()); - for (BindingSet bs : result) { - Literal label = (Literal) bs.getValue("label"); - assertTrue(label.stringValue().equals("01") || label.stringValue().equals("02"), - "wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')"); - } + List result = QueryResults.asList(evaluate); + assertEquals(10, result.size()); + for (BindingSet bs : result) { + Literal label = (Literal) bs.getValue("label"); + assertTrue(label.stringValue().equals("01") || label.stringValue().equals("02"), + "wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')"); } - } finally { - closeRepository(repo); } } diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java index 804a7123676..aa929294d0c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/UnionTest.java @@ -45,105 +45,115 @@ public UnionTest(Supplier repo) { super(repo); } - private void testEmptyUnion() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String query = "PREFIX : " + "SELECT ?visibility WHERE {" - + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." - + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + "}"; - try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { - assertNotNull(result); - assertFalse(result.hasNext()); - } - } finally { - closeRepository(repo); + private void testEmptyUnion(RepositoryConnection conn) { + String query = "PREFIX : " + + "SELECT ?visibility WHERE {" + + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." + + "BIND (IF(BOUND(?var), 'VISIBLE', 'HIDDEN') as ?visibility)" + + "}"; + try (TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) { + assertNotNull(result); + assertFalse(result.hasNext()); } } - private void testSameTermRepeatInUnion() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - String query = "PREFIX foaf:\n" + "SELECT * {\n" + " {\n" - + " ?sameTerm foaf:mbox ?mbox\n" + " FILTER sameTerm(?sameTerm,$william)\n" - + " } UNION {\n" + " ?x foaf:knows ?sameTerm\n" - + " FILTER sameTerm(?sameTerm,$william)\n" + " }\n" + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value mbox = bs.getValue("mbox"); - Value x = bs.getValue("x"); - - assertTrue(mbox instanceof Literal || x instanceof IRI); - } - assertEquals(3, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + private void testSameTermRepeatInUnion(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + String query = "PREFIX foaf:\n" + + "SELECT * {\n" + + " {\n" + + " ?sameTerm foaf:mbox ?mbox\n" + + " FILTER sameTerm(?sameTerm,$william)\n" + + " } UNION {\n" + + " ?x foaf:knows ?sameTerm\n" + + " FILTER sameTerm(?sameTerm,$william)\n" + + " }\n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william")); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + // System.out.println(bs); + + Value mbox = bs.getValue("mbox"); + Value x = bs.getValue("x"); + + assertTrue(mbox instanceof Literal || x instanceof IRI); } - } finally { - closeRepository(repo); + assertEquals(3, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } } - private void testSameTermRepeatInUnionAndOptional() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-query.trig", conn); - - String query = getNamespaceDeclarations() + "SELECT * {\n" + " {\n" + " ex:a ?p ?prop1\n" - + " FILTER (?p = ex:prop1)\n" + " } UNION {\n" + " ?s ex:p ex:A ; " - + " { " + " { " + " ?s ?p ?l ." - + " FILTER(?p = rdfs:label) " + " } " + " OPTIONAL { " - + " ?s ?p ?opt1 . " + " FILTER (?p = ex:prop1) " - + " } " + " OPTIONAL { " + " ?s ?p ?opt2 . " - + " FILTER (?p = ex:prop2) " + " } " + " }" + " }\n" + "}"; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); - - // System.out.println(bs); - - Value prop1 = bs.getValue("prop1"); - Value l = bs.getValue("l"); - - assertTrue(prop1 instanceof Literal || l instanceof Literal); - if (l instanceof Literal) { - Value opt1 = bs.getValue("opt1"); - assertNull(opt1); - - Value opt2 = bs.getValue("opt2"); - assertNull(opt2); - } + private void testSameTermRepeatInUnionAndOptional(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); + + String query = getNamespaceDeclarations() + + "SELECT * {\n" + + " {\n" + + " ex:a ?p ?prop1\n" + + " FILTER (?p = ex:prop1)\n" + + " } UNION {\n" + + " ?s ex:p ex:A ; " + + " { " + + " { " + + " ?s ?p ?l ." + + " FILTER(?p = rdfs:label) " + + " } " + + " OPTIONAL { " + + " ?s ?p ?opt1 . " + + " FILTER (?p = ex:prop1) " + + " } " + + " OPTIONAL { " + + " ?s ?p ?opt2 . " + + " FILTER (?p = ex:prop2) " + + " } " + + " }" + + " }\n" + + "}"; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); + + // System.out.println(bs); + + Value prop1 = bs.getValue("prop1"); + Value l = bs.getValue("l"); + + assertTrue(prop1 instanceof Literal || l instanceof Literal); + if (l instanceof Literal) { + Value opt1 = bs.getValue("opt1"); + assertNull(opt1); + + Value opt2 = bs.getValue("opt2"); + assertNull(opt2); } - assertEquals(2, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); } - } finally { - closeRepository(repo); + assertEquals(2, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } public Stream tests() { diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java index dc4bf759f77..fc76ddd62c4 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/sparql/tests/ValuesTest.java @@ -53,183 +53,179 @@ public ValuesTest(Supplier repo) { super(repo); } - private void testValuesInOptional() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1692.trig", conn); - String query = " PREFIX : \n" - + " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; - - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - - int count = 0; - while (result.hasNext()) { - count++; - BindingSet bs = result.next(); - // System.out.println(bs); - IRI a = (IRI) bs.getValue("a"); - assertNotNull(a); - Value isX = bs.getValue("isX"); - Literal name = (Literal) bs.getValue("name"); - assertNotNull(name); - if (a.stringValue().endsWith("a1")) { - assertNotNull(isX); - } else if (a.stringValue().endsWith(("a2"))) { - assertNull(isX); - } + private void testValuesInOptional(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1692.trig", conn); + String query = " PREFIX : \n" + + " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "; + + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + + int count = 0; + while (result.hasNext()) { + count++; + BindingSet bs = result.next(); + // System.out.println(bs); + IRI a = (IRI) bs.getValue("a"); + assertNotNull(a); + Value isX = bs.getValue("isX"); + Literal name = (Literal) bs.getValue("name"); + assertNotNull(name); + if (a.stringValue().endsWith("a1")) { + assertNotNull(isX); + } else if (a.stringValue().endsWith(("a2"))) { + assertNull(isX); } - assertEquals(2, count); } - } finally { - closeRepository(repo); + assertEquals(2, count); } + } - private void testValuesClauseNamedGraph() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String ex = "http://example.org/"; - String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + "@prefix ex: <" + ex + "> .\n" - + "ex:graph1 {\n" + " ex:Person1 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" - + " foaf:name \"Person 3\" .\n" + "}"; - - conn.add(new StringReader(data), "", RDFFormat.TRIG); - - String query = "SELECT ?person ?name ?__index \n" + "WHERE { " - + " VALUES (?person ?name ?__index) { \n" - + " ( UNDEF \"0\") \n" - + " ( UNDEF \"2\") } \n" - + " GRAPH { ?person ?name . } }"; - - TupleQuery q = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(q.evaluate()); - assertThat(result).hasSize(2); - } finally { - closeRepository(repo); - } + private void testValuesClauseNamedGraph(RepositoryConnection conn) throws Exception { + + String ex = "http://example.org/"; + String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + + "@prefix ex: <" + ex + "> .\n" + + "ex:graph1 {\n" + + " ex:Person1 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 1\" . ex:Person2 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 2\" . ex:Person3 rdf:type foaf:Person ;\n" + + " foaf:name \"Person 3\" .\n" + + "}"; + + conn.add(new StringReader(data), "", RDFFormat.TRIG); + + String query = "SELECT ?person ?name ?__index \n" + + "WHERE { " + + " VALUES (?person ?name ?__index) { \n" + + " ( UNDEF \"0\") \n" + + " ( UNDEF \"2\") } \n" + + " GRAPH { ?person ?name . } }"; + + TupleQuery q = conn.prepareTupleQuery(query); + + List result = QueryResults.asList(q.evaluate()); + assertThat(result).hasSize(2); } - private void testValuesCartesianProduct() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - final String queryString = "" + "select ?x ?y where { " + " values ?x { undef 67 } " - + " values ?y { undef 42 } " + "}"; - final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); - - List bindingSets = QueryResults.asList(tupleQuery.evaluate()); - assertThat(bindingSets).hasSize(4); - } finally { - closeRepository(repo); - } + private void testValuesCartesianProduct(RepositoryConnection conn) { + final String queryString = "" + + "select ?x ?y where { " + + " values ?x { undef 67 } " + + " values ?y { undef 42 } " + + "}"; + final TupleQuery tupleQuery = conn.prepareTupleQuery(queryString); + + List bindingSets = QueryResults.asList(tupleQuery.evaluate()); + assertThat(bindingSets).hasSize(4); } - private void testSES1081SameTermWithValues() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testdata-query/dataset-ses1081.trig", conn); - String query = "PREFIX ex: \n" + " SELECT * \n" + " WHERE { \n " - + " ?s ex:p ?a . \n" + " FILTER sameTerm(?a, ?e) \n " - + " VALUES ?e { ex:b } \n " + " } "; + private void testSES1081SameTermWithValues(RepositoryConnection conn) throws Exception { - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + loadTestData("/testdata-query/dataset-ses1081.trig", conn); + String query = "PREFIX ex: \n" + + " SELECT * \n" + + " WHERE { \n " + + " ?s ex:p ?a . \n" + + " FILTER sameTerm(?a, ?e) \n " + + " VALUES ?e { ex:b } \n " + + " } "; - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); - int count = 0; - while (result.hasNext()) { - BindingSet bs = result.next(); - count++; - assertNotNull(bs); + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); - Value s = bs.getValue("s"); - Value a = bs.getValue("a"); + int count = 0; + while (result.hasNext()) { + BindingSet bs = result.next(); + count++; + assertNotNull(bs); - assertNotNull(s); - assertNotNull(a); - assertEquals(iri("http://example.org/a"), s); - assertEquals(iri("http://example.org/b"), a); - } - assertEquals(1, count); - } catch (QueryEvaluationException e) { - e.printStackTrace(); - fail(e.getMessage()); + Value s = bs.getValue("s"); + Value a = bs.getValue("a"); + + assertNotNull(s); + assertNotNull(a); + assertEquals(iri("http://example.org/a"), s); + assertEquals(iri("http://example.org/b"), a); } - } finally { - closeRepository(repo); + assertEquals(1, count); + } catch (QueryEvaluationException e) { + e.printStackTrace(); + fail(e.getMessage()); } + } - private void testSES2136() throws Exception { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl", conn); - String query = "PREFIX : \n" + "SELECT ?s ?o { \n" - + " { SELECT * WHERE { ?s ?p ?o . } }\n" + " VALUES (?o) { (:b) }\n" + "}\n"; + private void testSES2136(RepositoryConnection conn) throws Exception { - ValueFactory vf = conn.getValueFactory(); - final IRI a = vf.createIRI("http://example.org/a"); - final IRI b = vf.createIRI("http://example.org/b"); + loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl", conn); + String query = "PREFIX : \n" + + "SELECT ?s ?o { \n" + + " { SELECT * WHERE { ?s ?p ?o . } }\n" + + " VALUES (?o) { (:b) }\n" + + "}\n"; - TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + ValueFactory vf = conn.getValueFactory(); + final IRI a = vf.createIRI("http://example.org/a"); + final IRI b = vf.createIRI("http://example.org/b"); - try (TupleQueryResult result = tq.evaluate()) { - assertNotNull(result); - assertTrue(result.hasNext()); - BindingSet bs = result.next(); - assertFalse(result.hasNext(), "only one result expected"); - assertEquals(a, bs.getValue("s")); - assertEquals(b, bs.getValue("o")); - } - } finally { - closeRepository(repo); + TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); + + try (TupleQueryResult result = tq.evaluate()) { + assertNotNull(result); + assertTrue(result.hasNext()); + BindingSet bs = result.next(); + assertFalse(result.hasNext(), "only one result expected"); + assertEquals(a, bs.getValue("s")); + assertEquals(b, bs.getValue("o")); } + } /** * https://github.com/eclipse/rdf4j/issues/1026 */ - private void testFilterExistsExternalValuesClause() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - String ub = "insert data {\n" + " a .\n" - + " a .\n" + " .\n" - + " .\n" + "}"; - conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); - - String query = "select ?s {\n" + " ?s a* .\n" - + " FILTER EXISTS {?s ?o}\n" + "} limit 100 values ?o {}"; - - TupleQuery tq = conn.prepareTupleQuery(query); - - List result = QueryResults.asList(tq.evaluate()); - assertEquals(1, result.size(), "single result expected"); - assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); - } finally { - closeRepository(repo); - } + private void testFilterExistsExternalValuesClause(RepositoryConnection conn) { + String ub = "insert data {\n" + + " a .\n" + + " a .\n" + + " .\n" + + " .\n" + + "}"; + conn.prepareUpdate(QueryLanguage.SPARQL, ub).execute(); + + String query = "select ?s {\n" + + " ?s a* .\n" + + " FILTER EXISTS {?s ?o}\n" + + "} limit 100 values ?o {}"; + + TupleQuery tq = conn.prepareTupleQuery(query); + + List result = QueryResults.asList(tq.evaluate()); + assertEquals(1, result.size(), "single result expected"); + assertEquals("http://subj1", result.get(0).getValue("s").stringValue()); } - public void testMultipleValuesClauses() { - Repository repo = openRepository(); - try (RepositoryConnection conn = repo.getConnection()) { - Update update = conn.prepareUpdate("PREFIX ex: \n" + "\n" - + "INSERT DATA { ex:sub ex:somePred \"value\" . };\n" + "\n" + "INSERT { ?s ?newPred ?newObj }\n" - + "WHERE {\n" + " # If one combines these into a single VALUES clause then it also works\n" - + " VALUES ?newPred { ex:somePred2 }\n" + " VALUES ?newObj { \"value2\" }\n" - + " ?s ex:somePred [] .\n" + "}"); - update.execute(); - } finally { - closeRepository(repo); - } + public void testMultipleValuesClauses(RepositoryConnection conn) { + Update update = conn.prepareUpdate("PREFIX ex: \n" + + "\n" + + "INSERT DATA { ex:sub ex:somePred \"value\" . };\n" + + "\n" + + "INSERT { ?s ?newPred ?newObj }\n" + + "WHERE {\n" + + " # If one combines these into a single VALUES clause then it also works\n" + + " VALUES ?newPred { ex:somePred2 }\n" + + " VALUES ?newObj { \"value2\" }\n" + + " ?s ex:somePred [] .\n" + + "}"); + update.execute(); } public Stream tests() { From da3e01eadfad0854fac15a7f7c335b0355b50694 Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Fri, 10 Nov 2023 14:28:57 +0100 Subject: [PATCH 5/6] GH-4592 Reenable geosparql junit testing. Allow for non DAWG approved tests to run. Adds a manifest-all.ttl file for geosparql like sparql 1.1. compliance. Also remove some unused imports. Signed-off-by: Jerven Bolleman --- .../algebra/geosparql/GeoSPARQLManifestTest.java | 4 +++- .../resources/testcases-geosparql/manifest-all.ttl | 10 ++++++++++ .../sparql/manifest/SPARQLQueryComplianceTest.java | 12 ++++++------ 3 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 testsuites/geosparql/src/main/resources/testcases-geosparql/manifest-all.ttl diff --git a/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java b/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java index 4afe05485b4..9733719e6b8 100644 --- a/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java +++ b/testsuites/geosparql/src/main/java/org/eclipse/rdf4j/testsuite/query/algebra/geosparql/GeoSPARQLManifestTest.java @@ -14,10 +14,12 @@ import org.eclipse.rdf4j.testsuite.query.parser.sparql.manifest.SPARQLQueryComplianceTest; import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; public abstract class GeoSPARQLManifestTest extends SPARQLQueryComplianceTest { + @TestFactory public Collection tests() { - return getTestData("testcases-geosparql/functions/manifest.ttl"); + return getTestData("testcases-geosparql/manifest-all.ttl", false); } } diff --git a/testsuites/geosparql/src/main/resources/testcases-geosparql/manifest-all.ttl b/testsuites/geosparql/src/main/resources/testcases-geosparql/manifest-all.ttl new file mode 100644 index 00000000000..0a241a503e9 --- /dev/null +++ b/testsuites/geosparql/src/main/resources/testcases-geosparql/manifest-all.ttl @@ -0,0 +1,10 @@ +@prefix rdf: . +@prefix rdfs: . +@prefix mf: . +@prefix qt: . + +<> rdf:type mf:Manifest ; + rdfs:label "GeoSPARQL Evaluation tests" ; + mf:include ( + + ). diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java index 0082777e594..d13deef7a8e 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQLQueryComplianceTest.java @@ -17,7 +17,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.StringWriter; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; @@ -28,7 +27,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.eclipse.rdf4j.common.io.IOUtil; @@ -57,7 +55,6 @@ import org.eclipse.rdf4j.query.resultio.TupleQueryResultParser; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryResult; import org.eclipse.rdf4j.repository.sail.SailRepository; import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; @@ -518,14 +515,17 @@ public List getSubManifests() { public abstract Collection tests(); public Collection getTestData(String manifestResource) { + return getTestData(manifestResource, true); + } + + public Collection getTestData(String manifestResource, boolean approvedOnly) { List tests = new ArrayList<>(); Deque manifests = new ArrayDeque<>(); - manifests.add( - SPARQL11UpdateComplianceTest.class.getClassLoader().getResource(manifestResource).toExternalForm()); + manifests.add(this.getClass().getClassLoader().getResource(manifestResource).toExternalForm()); while (!manifests.isEmpty()) { String pop = manifests.pop(); - SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs); + SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs, approvedOnly); tests.addAll(manifest.tests); manifests.addAll(manifest.subManifests); } From 04143fbee5de98ed539b5f7d39b7e53f18efd218 Mon Sep 17 00:00:00 2001 From: Jerven Bolleman Date: Fri, 10 Nov 2023 20:01:19 +0100 Subject: [PATCH 6/6] GH-4592 Fix missing @TestFactory --- .../parser/sparql/manifest/SPARQL10QueryComplianceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java index 662996c185e..065a5c8b02c 100644 --- a/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java +++ b/testsuites/sparql/src/main/java/org/eclipse/rdf4j/testsuite/query/parser/sparql/manifest/SPARQL10QueryComplianceTest.java @@ -15,6 +15,7 @@ import java.util.List; import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; /** * A test suite that runs the W3C Approved SPARQL 1.0 query tests. @@ -51,6 +52,7 @@ public SPARQL10QueryComplianceTest() { } } + @TestFactory public Collection tests() { return getTestData("testcases-sparql-1.0-w3c/data-r2/manifest-evaluation.ttl"); }