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/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/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/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/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/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/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..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 @@ -10,50 +10,16 @@ *******************************************************************************/ 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; +import org.junit.jupiter.api.TestFactory; -@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; + @TestFactory + public Collection tests() { + 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/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..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 @@ -10,17 +10,12 @@ *******************************************************************************/ 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; +import org.junit.jupiter.api.TestFactory; /** * A test suite that runs the W3C Approved SPARQL 1.0 query tests. @@ -29,74 +24,36 @@ * * @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; + @TestFactory + 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..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,15 +17,16 @@ 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; import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; import java.util.LinkedHashSet; 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; @@ -54,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; @@ -63,8 +63,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 +74,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 +97,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 +490,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 +510,26 @@ public List getSubManifests() { } } + + @TestFactory + 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(this.getClass().getClassLoader().getResource(manifestResource).toExternalForm()); + while (!manifests.isEmpty()) { + String pop = manifests.pop(); + SPARQLQueryTestManifest manifest = new SPARQLQueryTestManifest(pop, excludedSubdirs, approvedOnly); + 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); - } -} 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..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 @@ -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; @@ -46,8 +47,9 @@ 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.junit.jupiter.api.function.ThrowingConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,27 +60,45 @@ */ public abstract class AbstractComplianceTest { - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + 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 repo; - protected RepositoryConnection conn; + } - @Before - public void setUp() throws Exception { - repo = RepositorySPARQLComplianceTestSuite.getEmptyInitializedRepository(this.getClass()); - conn = new RepositoryConnectionWrapper(repo.getConnection()); + protected Repository openRepository() { + Repository r = repo.get(); + r.init(); + return r; } - @After - public void tearDown() { - try { - conn.close(); - } finally { - repo.shutDown(); + protected RepositoryConnection openConnection(Repository r) { + return new RepositoryConnectionWrapper(r.getConnection()); + } + + protected void closeRepository(Repository r) { + try (RepositoryConnection conn = r.getConnection()) { + conn.clear(); } + 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 bc3ea5f971c..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,13 +10,15 @@ *******************************************************************************/ package org.eclipse.rdf4j.testsuite.sparql; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.IOException; -import java.nio.file.Files; +import java.util.concurrent.atomic.AtomicInteger; +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,83 +40,153 @@ 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(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream arbitraryLengthPath() throws RDF4JException, IOException { + return new ArbitraryLengthPathTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream basic() throws RDF4JException, IOException { + return new BasicTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream bind() throws RDF4JException, IOException { + return new BindTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream builtinFunction() throws RDF4JException, IOException { + return new BuiltinFunctionTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream construct() throws RDF4JException, IOException { + return new ConstructTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream defaultGraph() throws RDF4JException, IOException { + return new DefaultGraphTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream describe() throws RDF4JException, IOException { + return new DescribeTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream groupBy() throws RDF4JException, IOException { + return new GroupByTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream in() throws RDF4JException, IOException { + return new InTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream optional() throws RDF4JException, IOException { + return new OptionalTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream propertyPath() throws RDF4JException, IOException { + return new PropertyPathTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream subselect() throws RDF4JException, IOException { + return new SubselectTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream union() throws RDF4JException, IOException { + return new UnionTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream values() throws RDF4JException, IOException { + return new ValuesTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream orderBy() throws RDF4JException, IOException { + return new OrderByTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream exists() throws RDF4JException, IOException { + return new ExistsTest(this::getEmptyInitializedRepository).tests(); + } + + @TestFactory + Stream minus() throws RDF4JException, IOException { + return new MinusTest(this::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; + private static final AtomicInteger tempDirNameForRepoCounter = new AtomicInteger(); - public static void setRepositoryFactory(RepositoryFactory factory) throws IOException { - if (dataDir != null && dataDir.isDirectory()) { - FileUtil.deleteDir(dataDir); - dataDir = null; - } - RepositorySPARQLComplianceTestSuite.factory = factory; + protected final RepositoryFactory 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(); - 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 0a25c45a38b..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 @@ -21,6 +21,8 @@ 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; import org.eclipse.rdf4j.model.IRI; @@ -34,8 +36,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL aggregate function compliance. @@ -44,11 +48,43 @@ */ public class AggregateTest extends AbstractComplianceTest { + public AggregateTest(Supplier 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() { + public void testMaxAggregateWithGroupEmptyResult(RepositoryConnection conn) { String query = "select ?s (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n" + @@ -62,8 +98,7 @@ public void testMaxAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMaxAggregateWithoutGroupEmptySolution() { + private void testMaxAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { String query = "select (max(?o) as ?omax) {\n" + " ?s ?p ?o .\n" + " }\n"; @@ -76,8 +111,8 @@ public void testMaxAggregateWithoutGroupEmptySolution() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMinAggregateWithGroupEmptyResult() { + + private void testMinAggregateWithGroupEmptyResult(RepositoryConnection conn) { String query = "select ?s (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n" + @@ -91,8 +126,7 @@ public void testMinAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testMinAggregateWithoutGroupEmptySolution() { + private void testMinAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { String query = "select (min(?o) as ?omin) {\n" + " ?s ?p ?o .\n" + " }\n"; @@ -105,12 +139,9 @@ 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(RepositoryConnection conn) { + + 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,8 +151,7 @@ public void testSampleAggregateWithGroupEmptyResult() { /** * See https://github.com/eclipse/rdf4j/issues/1978 */ - @Test - public void testSampleAggregateWithoutGroupEmptySolution() { + private void testSampleAggregateWithoutGroupEmptySolution(RepositoryConnection conn) { String query = "select (sample(?o) as ?osample) {\n" + " ?s ?p ?o .\n" + " }\n"; @@ -131,8 +161,7 @@ public void testSampleAggregateWithoutGroupEmptySolution() { } } - @Test - public void testSES2361UndefMin() { + 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(); @@ -142,8 +171,7 @@ public void testSES2361UndefMin() { } } - @Test - public void testSES2361UndefMax() { + 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(); @@ -153,8 +181,7 @@ public void testSES2361UndefMax() { } } - @Test - public void testSES2361UndefCount() { + private void testSES2361UndefCount(RepositoryConnection conn) { 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 +191,7 @@ public void testSES2361UndefCount() { } } - @Test - public void testSES2361UndefCountWildcard() { + private void testSES2361UndefCountWildcard(RepositoryConnection conn) { 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 +201,7 @@ public void testSES2361UndefCountWildcard() { } } - @Test - public void testSES2361UndefSum() { + 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(); @@ -186,9 +211,8 @@ public void testSES2361UndefSum() { } } - @Test - public void testSES1979MinMaxInf() throws Exception { - loadTestData("/testdata-query/dataset-ses1979.trig"); + 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); @@ -205,9 +229,8 @@ public void testSES1979MinMaxInf() throws Exception { } - @Test - public void testGroupConcatDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + private void testGroupConcatDistinct(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = getNamespaceDeclarations() + "SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)" + @@ -244,9 +267,8 @@ public void testGroupConcatDistinct() throws Exception { } - @Test - public void testGroupConcatNonDistinct() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + 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 . }"; @@ -282,9 +304,8 @@ public void testGroupConcatNonDistinct() throws Exception { } - @Test - public void testSES1970CountDistinctWildcard() throws Exception { - loadTestData("/testdata-query/dataset-ses1970.trig"); + private void testSES1970CountDistinctWildcard(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1970.trig", conn); String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; @@ -302,8 +323,7 @@ public void testSES1970CountDistinctWildcard() throws Exception { } } - @Test - public void testCountHaving() { + private void testCountHaving(RepositoryConnection conn) { BNode bnode1 = bnode(); BNode bnode2 = bnode(); BNode bnode3 = bnode(); @@ -323,9 +343,8 @@ public void testCountHaving() { } } - @Test - public void testSum() { - mixedDataForNumericAggregates(); + 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()) { @@ -339,12 +358,10 @@ public void testSum() { .isEqualTo(literal(new BigDecimal("89.4786576482391284723864721567342354783275234"))); } - } - @Test - public void testDistinctSum() { - mixedDataForNumericAggregates(); + 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()) { @@ -357,12 +374,10 @@ public void testDistinctSum() { assertThat(collect.get(i++).getValue("aggregate")) .isEqualTo(literal(new BigDecimal("55.4786576482391284723864721567342354783275234"))); } - } - @Test - public void testAvg() { - mixedDataForNumericAggregates(); + 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()) { @@ -377,9 +392,8 @@ public void testAvg() { } } - @Test - public void testDistinctAvg() { - mixedDataForNumericAggregates(); + 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()) { @@ -395,9 +409,8 @@ public void testDistinctAvg() { } } - @Test - public void testMax() { - mixedDataForNumericAggregates(); + 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()) { @@ -411,12 +424,10 @@ public void testMax() { .isEqualTo(literal("2022-01-01T01:01:01.000000001Z", CoreDatatype.XSD.DATETIME)); assertThat(collect.get(i++).getValue("aggregate")).isEqualTo(literal("3")); } - } - @Test - public void testDistinctMax() { - mixedDataForNumericAggregates(); + 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()) { @@ -435,9 +446,8 @@ public void testDistinctMax() { /** * @see https://github.com/eclipse/rdf4j/issues/4290 */ - @Test - public void testCountOrderBy_ImplicitGroup() { - mixedDataForNumericAggregates(); + private void testCountOrderBy_ImplicitGroup(RepositoryConnection conn) { + mixedDataForNumericAggregates(conn); String query = "select (count(*) as ?c) where { \n" + " ?s ?p ?o .\n" @@ -456,7 +466,7 @@ public void testCountOrderBy_ImplicitGroup() { // 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 2bd728762f7..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 @@ -10,10 +10,13 @@ *******************************************************************************/ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.vocabulary.OWL; import org.eclipse.rdf4j.query.BindingSet; @@ -22,9 +25,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.repository.RepositoryConnection; 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; /** * Tests on SPARQL property paths involving * or + operators (arbitrary length paths). @@ -35,13 +40,32 @@ */ public class ArbitraryLengthPathTest extends AbstractComplianceTest { + public ArbitraryLengthPathTest(Supplier 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 { - loadTestData("/testdata-query/alp-testdata.ttl"); + + 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 . }"; @@ -87,9 +111,9 @@ public void testArbitraryLengthPathWithBinding1() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); + + private void testArbitraryLengthPathWithBinding2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); // query without initializing ?child first. String query = getNamespaceDeclarations() + @@ -137,9 +161,9 @@ public void testArbitraryLengthPathWithBinding2() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); + + private void testArbitraryLengthPathWithBinding3(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/alp-testdata.ttl", conn); // binding on child instead of parent. String query = getNamespaceDeclarations() + @@ -187,9 +211,9 @@ public void testArbitraryLengthPathWithBinding3() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding4() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", 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() + @@ -237,9 +261,9 @@ public void testArbitraryLengthPathWithBinding4() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding5() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", 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() + @@ -293,9 +317,9 @@ public void testArbitraryLengthPathWithBinding5() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding6() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", 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() + @@ -349,9 +373,9 @@ public void testArbitraryLengthPathWithBinding6() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding7() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", 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() + @@ -408,9 +432,9 @@ public void testArbitraryLengthPathWithBinding7() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithBinding8() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl", EX.ALICE, EX.BOB, EX.MARY); + + 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() + @@ -466,9 +490,9 @@ public void testArbitraryLengthPathWithBinding8() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter1() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); + + 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) }"; @@ -497,9 +521,9 @@ public void testArbitraryLengthPathWithFilter1() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter2() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); + + 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) }"; @@ -528,9 +552,9 @@ public void testArbitraryLengthPathWithFilter2() throws Exception { * @see SES-1091 * @throws Exception */ - @Test - public void testArbitraryLengthPathWithFilter3() throws Exception { - loadTestData("/testdata-query/alp-testdata.ttl"); + + 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 = ) }"; @@ -555,9 +579,8 @@ public void testArbitraryLengthPathWithFilter3() throws Exception { } - @Test - public void testPropertyPathInTree() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + private void testPropertyPathInTree(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = getNamespaceDeclarations() + " SELECT ?node ?name " + @@ -579,6 +602,5 @@ public void testPropertyPathInTree() throws Exception { 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 d588360a5ac..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 @@ -10,10 +10,11 @@ *******************************************************************************/ 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.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -24,9 +25,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.repository.RepositoryConnection; 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; /** * Basic SPARQL functionality tests @@ -36,8 +39,11 @@ */ public class BasicTest extends AbstractComplianceTest { - @Test - public void testIdenticalVariablesInStatementPattern() { + public BasicTest(Supplier repo) { + super(repo); + } + + private void testIdenticalVariablesInStatementPattern(RepositoryConnection conn) { conn.add(EX.ALICE, DC.PUBLISHER, EX.BOB); String queryBuilder = "SELECT ?publisher " + @@ -53,8 +59,14 @@ public void handleSolution(BindingSet bindingSet) { }); } - @Test - public void testIdenticalVariablesSubjectContextInStatementPattern() { + public Stream tests() { + return Stream.of( + makeTest("testIdenticalVariablesInStatementPattern", this::testIdenticalVariablesInStatementPattern), + makeTest("testIdenticalVariablesInStatementPattern", + this::testIdenticalVariablesSubjectContextInStatementPattern)); + } + + 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); 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..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 @@ -12,11 +12,13 @@ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -31,8 +33,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Test on SPARQL BIND function. @@ -42,11 +46,15 @@ */ public class BindTest extends AbstractComplianceTest { + public BindTest(Supplier repo) { + super(repo); + } + /** * See https://github.com/eclipse/rdf4j/issues/1018 */ - @Test - public void testBindError() { + + private void testBindError(RepositoryConnection conn) { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); @@ -59,14 +67,14 @@ public void testBindError() { 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() { + + private void testBindScope(RepositoryConnection conn) { String query = "SELECT * {\n" + " { BIND (\"a\" AS ?a) }\n" + " { BIND (?a AS ?b) } \n" + @@ -84,8 +92,8 @@ public void testBindScope() { /** * See https://github.com/eclipse/rdf4j/issues/1642 */ - @Test - public void testBindScopeUnion() { + + private void testBindScopeUnion(RepositoryConnection conn) { ValueFactory f = conn.getValueFactory(); String query = "prefix ex: \n" + @@ -114,8 +122,7 @@ public void testBindScopeUnion() { } - @Test - public void testSES2250BindErrors() { + private void testSES2250BindErrors(RepositoryConnection conn) { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); @@ -128,12 +135,11 @@ public void testSES2250BindErrors() { 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(RepositoryConnection conn) { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data { _:blank }").execute(); @@ -146,12 +152,12 @@ public void testSES2250BindErrorsInPath() { 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() { + public void testSelectBindOnly(RepositoryConnection conn) { String query = "select ?b1 ?b2 ?b3\n" + "where {\n" + " bind(1 as ?b1)\n" @@ -167,8 +173,8 @@ public void testSelectBindOnly() { assertThat(solution.getValue("b3")).isNull(); } - @Test - public void testGH3696Bind() { + private void testGH3696Bind(RepositoryConnection conn) { + Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:unit1") .add(RDF.TYPE, "ex:Unit") @@ -194,8 +200,7 @@ public void testGH3696Bind() { assertThat(result).isEmpty(); } - @Test - public void testGH4499BindFilterNotExist1() { + private void testGH4499BindFilterNotExist1(RepositoryConnection conn) { Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:a") .add("ex:p", "ex:c1") @@ -230,8 +235,7 @@ public void testGH4499BindFilterNotExist1() { assertThat(bs.getValue("d")).isNull(); } - @Test - public void testGH4499BindFilterNotExist2() { + private void testGH4499BindFilterNotExist2(RepositoryConnection conn) { Model testData = new ModelBuilder().setNamespace("ex", "http://example.org/") .subject("ex:a") .add("ex:p", "ex:c1") @@ -266,4 +270,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..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 @@ -11,14 +11,15 @@ 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.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; @@ -30,8 +31,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.repository.RepositoryConnection; 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 +44,15 @@ */ public class BuiltinFunctionTest extends AbstractComplianceTest { + public BuiltinFunctionTest(Supplier repo) { + super(repo); + } + /** * See https://github.com/eclipse/rdf4j/issues/1267 */ - @Test - public void testSeconds() { + + private void testSeconds(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (SECONDS(\"2011-01-10T14:45:13\"^^xsd:dateTime) AS ?sec) { }"; @@ -60,8 +67,8 @@ public void testSeconds() { /** * See https://github.com/eclipse/rdf4j/issues/1267 */ - @Test - public 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) { }"; @@ -73,9 +80,8 @@ public void testSecondsMilliseconds() { } } - @Test - public void testSES1991NOWEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); + 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); @@ -95,8 +101,7 @@ public void testSES1991NOWEvaluation() throws Exception { } } - @Test - public void testSES869ValueOfNow() { + private void testSES869ValueOfNow(RepositoryConnection conn) { TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?p ( NOW() as ?n ) { BIND (NOW() as ?p ) }"); @@ -115,9 +120,8 @@ public void testSES869ValueOfNow() { } } - @Test - public void testSES1991UUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); + 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); @@ -137,9 +141,8 @@ public void testSES1991UUIDEvaluation() throws Exception { } } - @Test - public void testSES1991STRUUIDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); + 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); @@ -158,9 +161,8 @@ public void testSES1991STRUUIDEvaluation() throws Exception { } } - @Test - public void testSES1991RANDEvaluation() throws Exception { - loadTestData("/testdata-query/defaultgraph.ttl"); + 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); @@ -186,8 +188,7 @@ public void testSES1991RANDEvaluation() throws Exception { } } - @Test - public void testSES2121URIFunction() { + 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()) { @@ -195,7 +196,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 +206,12 @@ 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(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()) { @@ -219,13 +220,12 @@ 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 { - loadTestData("/testdata-query/dataset-query.trig"); + 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" + @@ -246,12 +246,10 @@ public void testSES2052If1() throws Exception { e.printStackTrace(); fail(e.getMessage()); } - } - @Test - public void testSES2052If2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + 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" + @@ -272,23 +270,22 @@ public void testSES2052If2() throws Exception { e.printStackTrace(); fail(e.getMessage()); } - } - @Test - public void testRegexCaseNonAscii() { + private void testRegexCaseNonAscii(RepositoryConnection conn) { + 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 { - loadTestData("/testdata-query/dataset-query.trig"); + private void testFilterRegexBoolean(RepositoryConnection conn) throws Exception { + + loadTestData("/testdata-query/dataset-query.trig", conn); // test case for issue SES-1050 String query = getNamespaceDeclarations() + @@ -310,8 +307,7 @@ public void testFilterRegexBoolean() throws Exception { } } - @Test - public void testDateCastFunction_date() { + private void testDateCastFunction_date(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09\") AS ?date) { }"; @@ -323,8 +319,7 @@ public void testDateCastFunction_date() { } } - @Test - public void testDateCastFunction_date_withTimeZone_utc() { + private void testDateCastFunction_date_withTimeZone_utc(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09Z\") AS ?date) { }"; @@ -336,8 +331,7 @@ public void testDateCastFunction_date_withTimeZone_utc() { } } - @Test - public void testDateCastFunction_dateTime_withTimeZone_offset() { + private void testDateCastFunction_dateTime_withTimeZone_offset(RepositoryConnection conn) { String qry = "PREFIX xsd: " + "SELECT (xsd:date(\"2022-09-09T14:45:13+03:00\") AS ?date) { }"; @@ -349,17 +343,36 @@ public void testDateCastFunction_dateTime_withTimeZone_offset() { } } - @Test - public void testDateCastFunction_invalidInput() { + 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("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..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 @@ -14,12 +14,15 @@ 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.IOException; import java.io.StringReader; +import java.util.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; @@ -30,9 +33,13 @@ 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.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.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL CONSTRUCT queries. @@ -42,9 +49,12 @@ */ public class ConstructTest extends AbstractComplianceTest { - @Test - public void testConstructModifiers() throws Exception { - loadTestData("/testdata-query/dataset-construct-modifiers.ttl"); + public ConstructTest(Supplier repo) { + super(repo); + } + + 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" @@ -86,8 +96,8 @@ public void testConstructModifiers() throws Exception { /** * See https://github.com/eclipse/rdf4j/issues/3011 */ - @Test - public void testConstruct_CyclicPathWithJoin() { + + 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); @@ -107,8 +117,8 @@ public void testConstruct_CyclicPathWithJoin() { assertThat(result.contains(test, c, test)).isTrue(); } - @Test - public void testSES2104ConstructBGPSameURI() throws Exception { + 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); @@ -125,4 +135,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..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 @@ -11,11 +11,13 @@ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.query.BindingSet; @@ -24,9 +26,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.repository.RepositoryConnection; 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; /** * Tests on handling default graph identification (DEFAULT keyword, rf4j:nil). @@ -36,9 +40,12 @@ */ public class DefaultGraphTest extends AbstractComplianceTest { - @Test - public void testNullContext1() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + public DefaultGraphTest(Supplier repo) { + super(repo); + } + + private void testNullContext1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = " SELECT * " + " FROM DEFAULT " + " WHERE { ?s ?p ?o } "; @@ -67,9 +74,8 @@ public void testNullContext1() throws Exception { } } - @Test - public void testNullContext2() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + private void testNullContext2(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = " SELECT * " + " FROM rdf4j:nil " + " WHERE { ?s ?p ?o } "; @@ -98,9 +104,8 @@ public void testNullContext2() throws Exception { } } - @Test - public void testSesameNilAsGraph() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + 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 } "); @@ -125,4 +130,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..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 @@ -14,6 +14,8 @@ 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; import org.eclipse.rdf4j.model.IRI; @@ -26,8 +28,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL DESCRIBE queries @@ -36,9 +40,12 @@ */ public class DescribeTest extends AbstractComplianceTest { - @Test - public void testDescribeA() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); + public DescribeTest(Supplier repo) { + super(repo); + } + + private void testDescribeA(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); String query = getNamespaceDeclarations() + "DESCRIBE ex:a"; @@ -60,9 +67,8 @@ public void testDescribeA() throws Exception { } } - @Test - public void testDescribeAWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); + private void testDescribeAWhere(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); String query = getNamespaceDeclarations() + "DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "; @@ -84,11 +90,9 @@ public void testDescribeAWhere() throws Exception { } } - @Test - public void testDescribeWhere() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ?x WHERE {?x rdfs:label ?y . } "; + 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); @@ -120,11 +124,9 @@ public void testDescribeWhere() throws Exception { } } - @Test - public void testDescribeB() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:b"; + 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); @@ -143,11 +145,9 @@ public void testDescribeB() throws Exception { } } - @Test - public void testDescribeD() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); - String query = getNamespaceDeclarations() + - "DESCRIBE ex:d"; + 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); @@ -177,9 +177,8 @@ public void testDescribeD() throws Exception { } } - @Test - public void testDescribeF() throws Exception { - loadTestData("/testdata-query/dataset-describe.trig"); + private void testDescribeF(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-describe.trig", conn); String query = getNamespaceDeclarations() + "DESCRIBE ex:f"; @@ -208,13 +207,11 @@ public void testDescribeF() throws Exception { } } - @Test - public void testDescribeMultipleA() { + 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); @@ -233,13 +230,11 @@ public void testDescribeMultipleA() { } } - @Test - public void testDescribeMultipleB() { + 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); @@ -258,13 +253,11 @@ public void testDescribeMultipleB() { } } - @Test - public void testDescribeMultipleC() { + private void testDescribeMultipleC(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); @@ -284,13 +277,11 @@ public void testDescribeMultipleC() { } } - @Test - public void testDescribeMultipleD() { + private void testDescribeMultipleD(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); @@ -312,4 +303,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..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 @@ -10,9 +10,10 @@ *******************************************************************************/ 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.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,8 +21,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Test for queries using EXISTS @@ -30,8 +33,11 @@ */ public class ExistsTest extends AbstractComplianceTest { - @Test - public void testFilterNotExistsBindingToCurrentSolutionMapping() { + public ExistsTest(Supplier repo) { + super(repo); + } + + private void testFilterNotExistsBindingToCurrentSolutionMapping(RepositoryConnection conn) { String ex = "http://example/"; IRI a1 = Values.iri(ex, "a1"); @@ -66,4 +72,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..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 @@ -10,13 +10,18 @@ *******************************************************************************/ 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.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.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL GROUP BY @@ -25,8 +30,11 @@ */ public class GroupByTest extends AbstractComplianceTest { - @Test - public void testGroupByEmpty() { + public GroupByTest(Supplier repo) { + super(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"; @@ -37,4 +45,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..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 @@ -11,10 +11,13 @@ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; @@ -24,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on the IN operator. @@ -35,9 +40,12 @@ */ public class InTest extends AbstractComplianceTest { - @Test - public void testInComparison1() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); + public InTest(Supplier repo) { + super(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)) } "; @@ -55,9 +63,8 @@ public void testInComparison1() throws Exception { } } - @Test - public void testInComparison2() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); + 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)) } "; @@ -69,9 +76,8 @@ public void testInComparison2() throws Exception { } } - @Test - public void testInComparison3() throws Exception { - loadTestData("/testdata-query/dataset-ses1913.trig"); + 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)) } "; @@ -89,4 +95,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..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 @@ -10,9 +10,10 @@ *******************************************************************************/ 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.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -21,8 +22,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Test for queries using MINUS @@ -31,8 +34,11 @@ */ public class MinusTest extends AbstractComplianceTest { - @Test - public void testScopingOfFilterInMinus() { + public MinusTest(Supplier repo) { + super(repo); + } + + private void testScopingOfFilterInMinus(RepositoryConnection conn) { String ex = "http://example/"; IRI a1 = Values.iri(ex, "a1"); @@ -75,4 +81,7 @@ public void testScopingOfFilterInMinus() { } + 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..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 @@ -11,14 +11,15 @@ 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; +import java.util.function.Supplier; import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; @@ -29,9 +30,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.repository.RepositoryConnection; 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 OPTIONAL clause behavior. @@ -41,9 +44,12 @@ */ public class OptionalTest extends AbstractComplianceTest { - @Test - public void testSES1898LeftJoinSemantics1() throws Exception { - loadTestData("/testdata-query/dataset-ses1898.trig"); + public OptionalTest(Supplier repo) { + super(repo); + } + + private void testSES1898LeftJoinSemantics1(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses1898.trig", conn); String query = " PREFIX : " + " SELECT * WHERE { " + " ?s :p1 ?v1 . " + @@ -58,12 +64,11 @@ public void testSES1898LeftJoinSemantics1() throws Exception { } } - @Test - public 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. - loadTestData("/testdata-query/dataset-ses1121.trig"); + loadTestData("/testdata-query/dataset-ses1121.trig", conn); String query1 = getNamespaceDeclarations() + " SELECT DISTINCT *\n" + @@ -105,9 +110,8 @@ public void testSES1121VarNamesInOptionals() throws Exception { } - @Test - public void testSameTermRepeatInOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + 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 " + @@ -164,8 +168,7 @@ public void testSameTermRepeatInOptional() throws Exception { * See https://github.com/eclipse/rdf4j/issues/3072 * */ - @Test - public void testValuesAfterOptional() throws Exception { + private void testValuesAfterOptional(RepositoryConnection conn) throws Exception { String data = "@prefix rdfs: . \n" + "@prefix : . \n" + ":r1 a rdfs:Resource . \n" @@ -186,4 +189,11 @@ public void testValuesAfterOptional() throws Exception { 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..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 @@ -10,22 +10,28 @@ *******************************************************************************/ 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.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.Test; +import org.junit.jupiter.api.DynamicTest; public class OrderByTest extends AbstractComplianceTest { - @Test - public void testDistinctOptionalOrderBy() throws Exception { + public OrderByTest(Supplier repo) { + super(repo); + } + + private void testDistinctOptionalOrderBy(RepositoryConnection conn) throws Exception { conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); @@ -39,8 +45,7 @@ public void testDistinctOptionalOrderBy() throws Exception { } } - @Test - public void testOrderByVariableNotInUse() throws Exception { + private void testOrderByVariableNotInUse(RepositoryConnection conn) throws Exception { conn.add(new StringReader("_:bob1 a ; rdfs:label \"Bob1\" .\n" + "_:bob2 a ; rdfs:label \"Bob2\" ."), "", RDFFormat.TURTLE); @@ -55,8 +60,7 @@ public void testOrderByVariableNotInUse() throws Exception { } } - @Test - public void testDistinctOptionalOrderByMath() throws Exception { + private void testDistinctOptionalOrderByMath(RepositoryConnection conn) throws Exception { conn.add(new StringReader("[] a .\n" + "[] a ; 123 ."), "", RDFFormat.TURTLE); @@ -70,4 +74,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..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 @@ -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.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; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -41,10 +42,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.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.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL property paths. @@ -55,8 +58,11 @@ */ public class PropertyPathTest extends AbstractComplianceTest { - @Test - public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { + public PropertyPathTest(Supplier repo) { + super(repo); + } + + private void testSES2147PropertyPathsWithIdenticalSubsPreds(RepositoryConnection conn) throws Exception { String data = " .\n" + " .\n" + @@ -91,9 +97,8 @@ public void testSES2147PropertyPathsWithIdenticalSubsPreds() throws Exception { } } - @Test - public void testSES2024PropertyPathAnonVarSharing() throws Exception { - loadTestData("/testdata-query/dataset-ses2024.trig"); + 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 . }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); @@ -113,11 +118,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(RepositoryConnection conn) 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,9 +135,8 @@ public void testPropertyPathNegationInversion() throws Exception { } - @Test - public void testSES2336NegatedPropertyPathMod() throws Exception { - loadTestData("/testdata-query/dataset-ses2336.trig"); + private void testSES2336NegatedPropertyPathMod(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-ses2336.trig", conn); String query = "prefix : select * where { ?s a :Test ; !:p? ?o . }"; ValueFactory vf = conn.getValueFactory(); @@ -168,8 +169,7 @@ public void testSES2336NegatedPropertyPathMod() throws Exception { } - @Test - public void testSES1685propPathSameVar() throws Exception { + 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); @@ -182,8 +182,7 @@ public void testSES1685propPathSameVar() throws Exception { } } - @Test - public void testSES1073InverseSymmetricPattern() { + 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"); @@ -210,8 +209,8 @@ public void testSES1073InverseSymmetricPattern() { /** * @see GH-2727 */ - @Test - public void testNestedInversePropertyPathWithZeroLength() { + + private void testNestedInversePropertyPathWithZeroLength(RepositoryConnection conn) { String insert = "insert data {\n" + " .\n" + " .\n" @@ -229,12 +228,13 @@ public void testNestedInversePropertyPathWithZeroLength() { 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); + } } - @Test - public void testComplexPath() { + private void testComplexPath(RepositoryConnection conn) { conn.add(Values.bnode(), SKOS.BROADER, Values.bnode()); conn.add(Values.bnode(), SKOS.TOP_CONCEPT_OF, Values.bnode()); @@ -249,8 +249,7 @@ public void testComplexPath() { } } - @Test - public void testInversePath() { + private void testInversePath(RepositoryConnection conn) { BNode bnode1 = Values.bnode("bnode1"); conn.add(Values.bnode(), FOAF.KNOWS, bnode1); @@ -275,4 +274,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..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 @@ -10,10 +10,12 @@ *******************************************************************************/ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.query.BindingSet; @@ -21,8 +23,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPARQL nested SELECT query handling. @@ -31,8 +35,11 @@ */ public class SubselectTest extends AbstractComplianceTest { - @Test - public void testSES2373SubselectOptional() { + public SubselectTest(Supplier repo) { + super(repo); + } + + private void testSES2373SubselectOptional(RepositoryConnection conn) { conn.prepareUpdate(QueryLanguage.SPARQL, "insert data {" + " ." + " 1 ." + " ." + " ." + " 2 ." + " ." @@ -49,14 +56,13 @@ public void testSES2373SubselectOptional() { 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(RepositoryConnection conn) { String ub = "insert data { \n" + " a . \n" + @@ -101,15 +107,20 @@ public void testSES2154SubselectOptional() { 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..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 @@ -10,12 +10,15 @@ *******************************************************************************/ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -25,8 +28,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.repository.RepositoryConnection; import org.eclipse.rdf4j.testsuite.sparql.AbstractComplianceTest; -import org.junit.Test; +import org.junit.jupiter.api.DynamicTest; /** * Tests on SPRQL UNION clauses. @@ -36,8 +41,11 @@ */ public class UnionTest extends AbstractComplianceTest { - @Test - public void testEmptyUnion() { + public UnionTest(Supplier repo) { + super(repo); + } + + private void testEmptyUnion(RepositoryConnection conn) { String query = "PREFIX : " + "SELECT ?visibility WHERE {" + "OPTIONAL { SELECT ?var WHERE { :s a :MyType . BIND (:s as ?var ) .} } ." @@ -49,9 +57,8 @@ public void testEmptyUnion() { } } - @Test - public void testSameTermRepeatInUnion() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + private void testSameTermRepeatInUnion(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = "PREFIX foaf:\n" + "SELECT * {\n" + " {\n" + @@ -87,12 +94,10 @@ public void testSameTermRepeatInUnion() throws Exception { e.printStackTrace(); fail(e.getMessage()); } - } - @Test - public void testSameTermRepeatInUnionAndOptional() throws Exception { - loadTestData("/testdata-query/dataset-query.trig"); + private void testSameTermRepeatInUnionAndOptional(RepositoryConnection conn) throws Exception { + loadTestData("/testdata-query/dataset-query.trig", conn); String query = getNamespaceDeclarations() + "SELECT * {\n" + @@ -151,4 +156,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..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 @@ -12,15 +12,17 @@ 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.function.Supplier; +import java.util.stream.Stream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -34,9 +36,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.repository.RepositoryConnection; 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 VALUES clauses. @@ -45,9 +49,12 @@ */ public class ValuesTest extends AbstractComplianceTest { - @Test - public void testValuesInOptional() throws Exception { - loadTestData("/testdata-query/dataset-ses1692.trig"); + public ValuesTest(Supplier repo) { + super(repo); + } + + 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) } } } "; @@ -75,10 +82,11 @@ public void testValuesInOptional() throws Exception { } assertEquals(2, count); } + } - @Test - public void testValuesClauseNamedGraph() throws Exception { + private void testValuesClauseNamedGraph(RepositoryConnection conn) throws Exception { + String ex = "http://example.org/"; String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n" + "@prefix ex: <" + ex + "> .\n" @@ -104,8 +112,7 @@ public void testValuesClauseNamedGraph() throws Exception { assertThat(result).hasSize(2); } - @Test - public void testValuesCartesianProduct() { + private void testValuesCartesianProduct(RepositoryConnection conn) { final String queryString = "" + "select ?x ?y where { " + " values ?x { undef 67 } " @@ -117,9 +124,9 @@ public void testValuesCartesianProduct() { assertThat(bindingSets).hasSize(4); } - @Test - public void testSES1081SameTermWithValues() throws Exception { - loadTestData("/testdata-query/dataset-ses1081.trig"); + private void testSES1081SameTermWithValues(RepositoryConnection conn) throws Exception { + + loadTestData("/testdata-query/dataset-ses1081.trig", conn); String query = "PREFIX ex: \n" + " SELECT * \n" + " WHERE { \n " + @@ -155,9 +162,9 @@ public void testSES1081SameTermWithValues() throws Exception { } - @Test - public void testSES2136() throws Exception { - loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl"); + private void testSES2136(RepositoryConnection conn) throws Exception { + + loadTestData("/testcases-sparql-1.1-w3c/bindings/data02.ttl", conn); String query = "PREFIX : \n" + "SELECT ?s ?o { \n" + " { SELECT * WHERE { ?s ?p ?o . } }\n" + @@ -174,17 +181,18 @@ 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")); } + } /** * https://github.com/eclipse/rdf4j/issues/1026 */ - @Test - public void testFilterExistsExternalValuesClause() { + + private void testFilterExistsExternalValuesClause(RepositoryConnection conn) { String ub = "insert data {\n" + " a .\n" + " a .\n" + @@ -201,12 +209,11 @@ public void testFilterExistsExternalValuesClause() { 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() { + public void testMultipleValuesClauses(RepositoryConnection conn) { Update update = conn.prepareUpdate("PREFIX ex: \n" + "\n" + "INSERT DATA { ex:sub ex:somePred \"value\" . };\n" + @@ -221,4 +228,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)); + } }