Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

Fix three defects found by dogfooding the validator on a 21.6M-statement graph

FABIOTESS9f4ad67cf11d
diff --git a/src/batch.rs b/src/batch.rs
index 6e4cdcd9..7a1895ed 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -167,7 +167,11 @@ impl BatchRunner {
None => return json!({"error": "validate requires a file path"}),
};
match GraphStore::validate_file(input) {
- Ok(count) => json!({"ok": true, "triples": count}),
+ Ok(counts) => json!({
+ "ok": true,
+ "triples": counts.triples,
+ "statements": counts.statements,
+ }),
Err(e) => json!({"error": e.to_string()}),
}
}
diff --git a/src/graph.rs b/src/graph.rs
index 758404bb..34189702 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -7,6 +7,15 @@ use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;
+/// What a parse produced. `statements` counts parser events; `triples` counts
+/// distinct triples, which is the size of the resulting graph. They differ
+/// whenever the source repeats a statement.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ValidationCounts {
+ pub statements: usize,
+ pub triples: usize,
+}
+
/// Optional HTTP authentication for remote SPARQL endpoints.
///
/// Enterprise triple stores gate their SPARQL Protocol endpoints behind auth:
@@ -110,10 +119,14 @@ impl GraphStore {
let quads: Vec<_> = parser
.for_reader(reader)
.collect::<Result<_, _>>()?;
+ // Report triples actually added, not parse events. The store is a set, so
+ // re-inserting a statement it already holds changes nothing and must not be
+ // counted as a load.
+ let before = store.len().unwrap_or(0);
for quad in &quads {
store.insert(quad)?;
}
- Ok(quads.len())
+ Ok(store.len().unwrap_or(before).saturating_sub(before))
}
/// Load RDF content in a specified format (Turtle, RDF/XML, etc.)
@@ -133,10 +146,14 @@ impl GraphStore {
let quads: Vec<_> = parser
.for_reader(reader)
.collect::<Result<_, _>>()?;
+ // Report triples actually added, not parse events. The store is a set, so
+ // re-inserting a statement it already holds changes nothing and must not be
+ // counted as a load.
+ let before = store.len().unwrap_or(0);
for quad in &quads {
store.insert(quad)?;
}
- Ok(quads.len())
+ Ok(store.len().unwrap_or(before).saturating_sub(before))
}
pub fn load_file(&self, path: &str) -> anyhow::Result<usize> {
@@ -160,10 +177,14 @@ impl GraphStore {
let quads: Vec<_> = parser
.for_reader(reader)
.collect::<Result<_, _>>()?;
+ // Report triples actually added, not parse events. The store is a set, so
+ // re-inserting a statement it already holds changes nothing and must not be
+ // counted as a load.
+ let before = store.len().unwrap_or(0);
for quad in &quads {
store.insert(quad)?;
}
- Ok(quads.len())
+ Ok(store.len().unwrap_or(before).saturating_sub(before))
}
pub fn save_file(&self, path: &str, format: &str) -> anyhow::Result<()> {
@@ -172,28 +193,42 @@ impl GraphStore {
Ok(())
}
- pub fn validate_turtle(ttl: &str) -> anyhow::Result<usize> {
+ pub fn validate_turtle(ttl: &str) -> anyhow::Result<ValidationCounts> {
let reader = Cursor::new(ttl.as_bytes());
let parser = RdfParser::from_format(RdfFormat::Turtle).for_reader(reader);
- let mut count = 0;
- for quad in parser {
- quad?;
- count += 1;
- }
- Ok(count)
+ Self::count_parsed(parser)
}
- pub fn validate_file(path: &str) -> anyhow::Result<usize> {
+ pub fn validate_file(path: &str) -> anyhow::Result<ValidationCounts> {
let content = std::fs::read_to_string(path)?;
let format = Self::detect_format_sniffed(path, &content);
let reader = Cursor::new(content.as_bytes());
let parser = RdfParser::from_format(format).for_reader(reader);
- let mut count = 0;
+ Self::count_parsed(parser)
+ }
+
+ /// Count what a parser produced, distinguishing statements from triples.
+ ///
+ /// An RDF graph is a set, so a statement repeated in the source contributes
+ /// one triple and not two. Reporting the parse-event count as a triple count
+ /// overstates any generated document that repeats a statement, which real
+ /// serialisers do constantly: emitting `?lib a :Library` once per record is
+ /// ordinary practice and inflated one 16.7 MB file by 6.7 per cent.
+ fn count_parsed<I>(parser: I) -> anyhow::Result<ValidationCounts>
+ where
+ I: IntoIterator<Item = Result<Quad, oxigraph::io::RdfParseError>>,
+ {
+ let mut statements = 0usize;
+ let mut seen = std::collections::HashSet::new();
for quad in parser {
- quad?;
- count += 1;
+ let quad = quad?;
+ statements += 1;
+ seen.insert(quad);
}
- Ok(count)
+ Ok(ValidationCounts {
+ statements,
+ triples: seen.len(),
+ })
}
pub fn sparql_select(&self, query: &str) -> anyhow::Result<String> {
diff --git a/src/main.rs b/src/main.rs
index e752be2a..bc37a80b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1436,8 +1436,12 @@ async fn async_main() -> anyhow::Result<()> {
GraphStore::validate_file(&input)
};
match result {
- Ok(count) => output_json(
- &serde_json::json!({"ok": true, "triples": count}),
+ Ok(counts) => output_json(
+ &serde_json::json!({
+ "ok": true,
+ "triples": counts.triples,
+ "statements": counts.statements,
+ }),
cli.pretty,
),
Err(e) => {
diff --git a/src/ontology.rs b/src/ontology.rs
index 247dcc8e..e1f33ee9 100644
--- a/src/ontology.rs
+++ b/src/ontology.rs
@@ -15,9 +15,10 @@ impl OntologyService {
/// Validate RDF syntax. Returns a JSON report (never errors on bad input).
pub fn validate_string(content: &str) -> anyhow::Result<String> {
match GraphStore::validate_turtle(content) {
- Ok(count) => Ok(serde_json::json!({
+ Ok(counts) => Ok(serde_json::json!({
"valid": true,
- "triple_count": count,
+ "triple_count": counts.triples,
+ "statement_count": counts.statements,
"errors": []
})
.to_string()),
@@ -33,10 +34,11 @@ impl OntologyService {
/// Validate an RDF file.
pub fn validate_file(path: &str) -> anyhow::Result<String> {
match GraphStore::validate_file(path) {
- Ok(count) => Ok(serde_json::json!({
+ Ok(counts) => Ok(serde_json::json!({
"valid": true,
"path": path,
- "triple_count": count,
+ "triple_count": counts.triples,
+ "statement_count": counts.statements,
"errors": []
})
.to_string()),
diff --git a/src/shacl.rs b/src/shacl.rs
index 2ac37749..3a5eb980 100644
--- a/src/shacl.rs
+++ b/src/shacl.rs
@@ -48,6 +48,12 @@ impl ShaclValidator {
"#,
)?;
+ // sh:targetClass selects SHACL instances, which the specification defines as
+ // reachable by rdf:type followed by zero or more rdfs:subClassOf steps, not by a
+ // direct rdf:type alone. Matching the direct type only made every shape targeting
+ // a superclass silently select nothing: a shapes graph targeting an abstract
+ // Assertion class over data typed with its concrete subclasses reported
+ // `conforms: true` having evaluated no focus nodes at all.
let mut violations: Vec<serde_json::Value> = Vec::new();
let mut skipped: Vec<serde_json::Value> = Vec::new();
@@ -113,10 +119,11 @@ impl ShaclValidator {
&format!(
r#"
PREFIX sh: <http://www.w3.org/ns/shacl#>
- SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?pattern ?hasValue ?message ?severity WHERE {{
+ SELECT ?prop ?path ?invPath ?minCount ?maxCount ?datatype ?class ?pattern ?hasValue ?message ?severity WHERE {{
{} sh:property ?prop .
?prop sh:path ?path .
OPTIONAL {{ ?path sh:inversePath ?invPath }}
+ OPTIONAL {{ ?prop sh:class ?class }}
OPTIONAL {{ ?prop sh:minCount ?minCount }}
OPTIONAL {{ ?prop sh:maxCount ?maxCount }}
OPTIONAL {{ ?prop sh:datatype ?datatype }}
@@ -145,7 +152,7 @@ impl ShaclValidator {
?prop ?pred ?o .
FILTER(?pred NOT IN (
sh:path, sh:minCount, sh:maxCount, sh:datatype,
- sh:pattern, sh:hasValue, sh:message, sh:severity,
+ sh:class, sh:pattern, sh:hasValue, sh:message, sh:severity,
sh:name, sh:description, sh:order, sh:group,
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
))
@@ -213,7 +220,7 @@ impl ShaclValidator {
if min_count > 0 {
let query = format!(
r#"SELECT ?focus (COUNT(?val) AS ?cnt) WHERE {{
- ?focus a <{target_class}> .
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
OPTIONAL {{ ?focus {path_expr} ?val }}
}} GROUP BY ?focus HAVING (COUNT(?val) < {min_count})"#
);
@@ -247,7 +254,7 @@ impl ShaclValidator {
.unwrap_or(u64::MAX);
let query = format!(
r#"SELECT ?focus (COUNT(?val) AS ?cnt) WHERE {{
- ?focus a <{target_class}> .
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
?focus {path_expr} ?val .
}} GROUP BY ?focus HAVING (COUNT(?val) > {max_count})"#
);
@@ -273,12 +280,47 @@ impl ShaclValidator {
}
}
+ // sh:class. Every value node must be a SHACL instance of the class,
+ // which the specification defines as reachable by rdf:type followed by
+ // zero or more rdfs:subClassOf steps. A literal is never a SHACL
+ // instance of anything, and the anti-join below excludes literals for
+ // free because a literal cannot appear in subject position.
+ if let Some(cls_str) = prop.get("class") {
+ let cls = strip_angle_brackets(cls_str);
+ let query = format!(
+ r#"SELECT ?focus ?val WHERE {{
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
+ ?focus {path_expr} ?val .
+ FILTER NOT EXISTS {{
+ ?val <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{cls}> .
+ }}
+ }}"#
+ );
+ let results = graph_sparql_select(graph, &query)?;
+ for row in &results {
+ if let Some(focus) = row.get("focus") {
+ let msg = if message.is_empty() {
+ format!("Value is not a SHACL instance of <{}>", cls)
+ } else {
+ message.clone()
+ };
+ violations.push(serde_json::json!({
+ "severity": severity,
+ "focus_node": strip_angle_brackets(focus),
+ "path": path,
+ "constraint": "class",
+ "message": msg,
+ }));
+ }
+ }
+ }
+
// sh:datatype
if let Some(dt_str) = prop.get("datatype") {
let dt = strip_angle_brackets(dt_str);
let query = format!(
r#"SELECT ?focus ?val WHERE {{
- ?focus a <{target_class}> .
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
?focus {path_expr} ?val .
FILTER(DATATYPE(?val) != <{dt}>)
}}"#
@@ -313,7 +355,7 @@ impl ShaclValidator {
let escaped = pattern.replace('\\', "\\\\").replace('"', "\\\"");
let query = format!(
r#"SELECT ?focus ?val WHERE {{
- ?focus a <{target_class}> .
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
?focus {path_expr} ?val .
FILTER(!REGEX(STR(?val), "{escaped}"))
}}"#
@@ -345,7 +387,7 @@ impl ShaclValidator {
let term = has_value_term.trim();
let query = format!(
r#"SELECT ?focus WHERE {{
- ?focus a <{target_class}> .
+ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> .
FILTER NOT EXISTS {{ ?focus {path_expr} {term} }}
}}"#
);
@@ -411,7 +453,7 @@ impl ShaclValidator {
// rather than assumed harmless.
let focus_rows = graph_sparql_select(
graph,
- &format!("SELECT ?this WHERE {{ ?this a <{target_class}> }}"),
+ &format!("SELECT ?this WHERE {{ ?this <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> }}"),
)?;
let focus_nodes: Vec<String> = focus_rows
.iter()
@@ -812,7 +854,7 @@ fn is_recognised_xsd_datatype(iri: &str) -> bool {
/// target class has no instances passes every constraint vacuously.
fn count_focus_nodes(graph: &Arc<GraphStore>, target_class: &str) -> anyhow::Result<u64> {
let query = format!(
- r#"SELECT (COUNT(DISTINCT ?focus) AS ?cnt) WHERE {{ ?focus a <{target_class}> }}"#
+ r#"SELECT (COUNT(DISTINCT ?focus) AS ?cnt) WHERE {{ ?focus <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>/<http://www.w3.org/2000/01/rdf-schema#subClassOf>* <{target_class}> }}"#
);
let rows = graph_sparql_select(graph, &query)?;
Ok(rows
diff --git a/tests/graph_jsonld_test.rs b/tests/graph_jsonld_test.rs
index 05bf1d44..0a47af76 100644
--- a/tests/graph_jsonld_test.rs
+++ b/tests/graph_jsonld_test.rs
@@ -18,9 +18,10 @@ fn validate_file_reads_a_jsonld_document() {
let path = dir.path().join("doc.jsonld");
std::fs::write(&path, JSONLD_DOC).unwrap();
- let count = GraphStore::validate_file(path.to_str().unwrap())
+ let counts = GraphStore::validate_file(path.to_str().unwrap())
.expect("a .jsonld file must validate as JSON-LD, not as Turtle");
- assert_eq!(count, 2);
+ assert_eq!(counts.triples, 2);
+ assert_eq!(counts.statements, 2, "this document repeats no statement");
}
#[test]
@@ -109,7 +110,7 @@ fn a_jsonld_body_in_a_misnamed_file_is_still_read_as_jsonld() {
let path = dir.path().join("doc.owl");
std::fs::write(&path, JSONLD_DOC).unwrap();
- let count = GraphStore::validate_file(path.to_str().unwrap())
+ let counts = GraphStore::validate_file(path.to_str().unwrap())
.expect("a JSON-LD body must be detected from its content");
- assert_eq!(count, 2);
+ assert_eq!(counts.triples, 2);
}
diff --git a/tests/shacl_class_constraint_test.rs b/tests/shacl_class_constraint_test.rs
new file mode 100644
index 00000000..c1b3fa04
--- /dev/null
+++ b/tests/shacl_class_constraint_test.rs
@@ -0,0 +1,67 @@
+//! `sh:class` must be evaluated, not skipped.
+//!
+//! Until this test was written the constraint was collected by no query, evaluated by no
+//! code, and reported only as "constraint not implemented", which suppressed the verdict
+//! to null. A caller checking the verdict got neither a pass nor a fail.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+const DATA: &str = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ex: <http://example.org/> .
+
+ ex:Person a owl:Class .
+ ex:Address a owl:Class .
+ ex:UkAddress a owl:Class ; rdfs:subClassOf ex:Address .
+
+ ex:good a ex:Person ; ex:addr ex:addr1 .
+ ex:sub a ex:Person ; ex:addr ex:addr2 .
+ ex:wrong a ex:Person ; ex:addr ex:notAnAddress .
+ ex:lit a ex:Person ; ex:addr "12 High Street" .
+
+ ex:addr1 a ex:Address .
+ ex:addr2 a ex:UkAddress .
+ ex:notAnAddress a ex:Person .
+"#;
+
+const SHAPES: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:PersonShape a sh:NodeShape ;
+ sh:targetClass ex:Person ;
+ sh:property [ sh:path ex:addr ; sh:class ex:Address ] .
+"#;
+
+#[test]
+fn class_constraint_is_evaluated_and_the_verdict_is_a_boolean() {
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(DATA, None).expect("load");
+ let json = ShaclValidator::validate(&graph, SHAPES).expect("validate");
+ let r: serde_json::Value = serde_json::from_str(&json).expect("parse");
+
+ assert!(r["conforms"].is_boolean(), "verdict must not be null: {r}");
+ assert_eq!(r["conforms"], serde_json::json!(false), "report: {r}");
+
+ let skipped = r["skipped_constraints"].as_array().cloned().unwrap_or_default();
+ assert!(
+ !skipped.iter().any(|s| s["constraint"].as_str().unwrap_or_default().ends_with("#class")),
+ "sh:class must no longer be reported as unimplemented: {r}"
+ );
+
+ let focus: Vec<String> = r["violations"].as_array().expect("violations")
+ .iter()
+ .filter(|v| v["constraint"] == serde_json::json!("class"))
+ .map(|v| v["focus_node"].as_str().unwrap_or_default().to_string())
+ .collect();
+
+ // ex:wrong points at a Person, and ex:lit points at a literal, which is never a
+ // SHACL instance of anything. ex:sub points at a UkAddress, which is an Address by
+ // subclass closure and must pass.
+ assert!(focus.iter().any(|f| f.ends_with("wrong")), "ex:wrong should fail: {focus:?}");
+ assert!(focus.iter().any(|f| f.ends_with("lit")), "a literal is never a SHACL instance: {focus:?}");
+ assert!(!focus.iter().any(|f| f.ends_with("sub")), "a subclass instance must pass: {focus:?}");
+ assert!(!focus.iter().any(|f| f.ends_with("good")), "a direct instance must pass: {focus:?}");
+}
diff --git a/tests/shacl_subclass_target_test.rs b/tests/shacl_subclass_target_test.rs
new file mode 100644
index 00000000..b852bf8a
--- /dev/null
+++ b/tests/shacl_subclass_target_test.rs
@@ -0,0 +1,83 @@
+//! `sh:targetClass` must select SHACL instances, not only direct `rdf:type` matches.
+//!
+//! SHACL defines a SHACL instance as a node reachable by `rdf:type` followed by zero or
+//! more `rdfs:subClassOf` steps. Matching the direct type alone makes every shape that
+//! targets a superclass select nothing, and the validator then reports `conforms: true`
+//! having evaluated no focus nodes at all. That is the one failure mode this validator
+//! is not allowed to have, and it was present until this test was written.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::shacl::ShaclValidator;
+use std::sync::Arc;
+
+const ONTOLOGY_AND_DATA: &str = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ex: <http://example.org/> .
+
+ ex:Assertion a owl:Class .
+ ex:IdentifierAssertion a owl:Class ; rdfs:subClassOf ex:Assertion .
+ ex:StructureAssertion a owl:Class ; rdfs:subClassOf ex:IdentifierAssertion .
+
+ # Typed with the concrete leaf class only, which is how generated data looks.
+ ex:a1 a ex:StructureAssertion ; ex:value "ok" .
+ ex:a2 a ex:StructureAssertion .
+"#;
+
+const SHAPES: &str = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+
+ ex:AssertionShape a sh:NodeShape ;
+ sh:targetClass ex:Assertion ;
+ sh:property [ sh:path ex:value ; sh:minCount 1 ] .
+"#;
+
+fn report(data: &str, shapes: &str) -> serde_json::Value {
+ let graph = Arc::new(GraphStore::new());
+ graph.load_turtle(data, None).expect("load data");
+ let json = ShaclValidator::validate(&graph, shapes).expect("validate");
+ serde_json::from_str(&json).expect("parse report")
+}
+
+#[test]
+fn target_class_reaches_instances_of_a_transitive_subclass() {
+ let r = report(ONTOLOGY_AND_DATA, SHAPES);
+ // ex:a2 is a StructureAssertion, therefore an IdentifierAssertion, therefore an
+ // Assertion, and it has no ex:value. The shape must fire.
+ assert_eq!(
+ r["conforms"], serde_json::json!(false),
+ "a shape targeting a superclass must evaluate instances of its subclasses: {r}"
+ );
+ let violations = r["violations"].as_array().expect("violations array");
+ assert_eq!(violations.len(), 1, "expected exactly one violation: {r}");
+ assert!(
+ violations[0]["focus_node"].as_str().unwrap_or_default().ends_with("a2"),
+ "the violation should be on ex:a2: {r}"
+ );
+}
+
+#[test]
+fn a_superclass_shape_is_not_reported_as_unmatched() {
+ let r = report(ONTOLOGY_AND_DATA, SHAPES);
+ let unmatched = r["unmatched_shapes"].as_array().cloned().unwrap_or_default();
+ assert!(
+ unmatched.is_empty(),
+ "the shape has two focus nodes via subclass closure, so it is not unmatched: {r}"
+ );
+ assert_eq!(r["focus_nodes"], serde_json::json!(2), "report: {r}");
+}
+
+#[test]
+fn direct_type_targeting_still_works() {
+ let shapes = r#"
+ @prefix sh: <http://www.w3.org/ns/shacl#> .
+ @prefix ex: <http://example.org/> .
+ ex:LeafShape a sh:NodeShape ;
+ sh:targetClass ex:StructureAssertion ;
+ sh:property [ sh:path ex:value ; sh:minCount 1 ] .
+ "#;
+ let r = report(ONTOLOGY_AND_DATA, shapes);
+ assert_eq!(r["conforms"], serde_json::json!(false), "report: {r}");
+ assert_eq!(r["focus_nodes"], serde_json::json!(2), "report: {r}");
+}
diff --git a/tests/validate_counts_distinct_triples_test.rs b/tests/validate_counts_distinct_triples_test.rs
new file mode 100644
index 00000000..04ef4752
--- /dev/null
+++ b/tests/validate_counts_distinct_triples_test.rs
@@ -0,0 +1,46 @@
+//! `validate` must not report parse events as triples.
+//!
+//! An RDF graph is a set, so a statement repeated in the source contributes one triple
+//! and not two. Counting parser events and labelling the result `triples` overstates any
+//! generated document that repeats a statement, which real serialisers do constantly:
+//! emitting a shared node's rdf:type once per record inflated one 16.7 MB file by 6.7
+//! per cent against rdflib.
+
+use open_ontologies::graph::GraphStore;
+
+const DUPLICATED: &str = r#"
+ @prefix ex: <http://example.org/> .
+ ex:a ex:p ex:b .
+ ex:a ex:p ex:b .
+ ex:a ex:p ex:c .
+"#;
+
+#[test]
+fn statements_and_triples_are_reported_separately() {
+ let counts = GraphStore::validate_turtle(DUPLICATED).expect("validate");
+ assert_eq!(counts.statements, 3, "three statements were parsed");
+ assert_eq!(counts.triples, 2, "the graph holds two distinct triples");
+}
+
+#[test]
+fn a_document_with_no_duplicates_reports_equal_counts() {
+ let counts = GraphStore::validate_turtle(
+ "@prefix ex: <http://example.org/> .\nex:a ex:p ex:b .\nex:a ex:p ex:c .\n",
+ )
+ .expect("validate");
+ assert_eq!(counts.statements, counts.triples);
+ assert_eq!(counts.triples, 2);
+}
+
+#[test]
+fn load_reports_triples_added_not_statements_parsed() {
+ let graph = GraphStore::new();
+ let added = graph.load_turtle(DUPLICATED, None).expect("load");
+ assert_eq!(added, 2, "the store deduplicates, so only two triples were added");
+ assert_eq!(graph.triple_count(), 2);
+
+ // Loading the same content again adds nothing at all.
+ let again = graph.load_turtle(DUPLICATED, None).expect("reload");
+ assert_eq!(again, 0, "re-loading identical content adds no triples");
+ assert_eq!(graph.triple_count(), 2);
+}