mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-08-29 04:26:20 +00:00
* refactor(export): centralize graph-payload key normalization
Graph payloads circulate under two vocabularies, entities/relationships and nodes/edges, and consumers each reconciled them locally with competing idioms. The same payload could be exported, silently dropped, or rejected depending on which consumer read it.
Add normalize_graph_payload() to utils.helpers as the single place that decision is made. Both spellings present with one empty resolves to the populated one, which is the shape JSONExporter emits; both non-empty and different is refused, since there is no basis to prefer either and picking one would silently discard the other; a non-empty mapping with no recognized key raises rather than returning empty collections, with require_recognized=False for callers that should degrade.
Adopt it in the three exporters that genuinely alias. LPGExporter read nodes with entities as the default, so it dropped every entity when nodes was present but empty, losing everything on a JSON round-trip. ArangoAQLExporter had the same idiom plus a manual fallback. Neo4jCSVExporter routes its mapping branch through the shared resolver so the reference implementation cannot drift; its attribute branch stays local, since objects are not mappings.
Also feed LPGExporter._generate_indexes the resolved entities. It read entities directly, so a nodes/edges payload produced no indexes even once node generation was fixed.
CSVExporter and JSONExporter are deliberately excluded: they write entities, relationships, nodes and edges as separate outputs by design rather than reconciling two spellings of one collection, so normalizing there would rename output files.
* fix(export): reject non-mapping input to the YAML exporters
export_yaml declared Union[Dict[str, Any], List[Dict[str, Any]]], but both
YAML exporters read their payload by key, so a list reached .get() and
surfaced as a bare AttributeError from inside the exporter, naming neither
the offending argument nor the shape expected.
Reject rather than wrap. These formats distinguish entities from
relationships from triplets, so inferring which collection a bare list
represents would silently mislabel the records, and wrapping it under an
unrecognised key would write a structurally valid file with every
collection empty - trading a loud failure for silent data loss.
Validate in the exporters, matching the existing precedent in
Neo4jCSVExporter._normalize_graph, so direct users of the classes get the
same contract as callers of the convenience wrapper. Narrow the wrapper
type hint to Dict[str, Any] to match.
* fix(export): address YAML exporter review findings
- semantica/export/yaml_exporter.py — import Sequence from typing
instead of collections.abc. `Sequence[str]` in _require_mapping's
annotation is evaluated at function-definition time; collections.abc.Sequence
only became subscriptable in Python 3.9, so on the 3.8 this project
declares support for, importing this module raised TypeError.
typing.Sequence has supported subscripting since 3.5.3. Mapping stays
imported from collections.abc since it's only used for isinstance.
- tests/export/test_yaml_exporter_input_validation.py — clean up each
test's tempfile.mkdtemp() dir via addCleanup instead of leaking it,
and read exported YAML through a context manager instead of an
unclosed yaml.safe_load(open(...)).
* fix(export): reject YAML export payloads with no recognized key
Both YAML exporters built their output from a fixed set of `.get(key, [])`
lookups, so a mapping keyed by anything else serialized to a structurally
valid file with every collection empty. Nothing signalled the loss: no
exception, no warning, and the progress log reported a completed export.
The only way to notice was to open the file. The realistic trigger is
re-exporting an `export_json` payload, whose `{"data", "count", "metadata"}`
envelope drops every record.
- SemanticNetworkYAMLExporter.export_semantic_network now resolves its
collections through normalize_graph_payload(), which raises rather than
returning empty collections for an unrecognized mapping. Adopting the
shared resolver rather than repeating the check locally also brings the
'nodes'/'edges' aliases, so ContextGraph.to_dict() — the most direct path
from this library's own graph type to YAML, used in
examples/capability_gap_context_graphs_example.py — exports its records
instead of an empty file.
- export_for_pipeline built its nested semantic network from the same
defaulted lookups and had the same defect; it goes through the resolver
too.
- YAMLSchemaExporter.export_ontology_schema gets the equivalent check over
its own key set. Schemas are a separate vocabulary with no aliasing, so
_require_recognized_keys lives in this module rather than in the shared
graph resolver.
- 'metadata' is deliberately not sufficient to make a payload recognized.
An export_json envelope carries one, so accepting it would readmit the
case this fix is most likely to be needed for.
- An empty mapping is still exported: an empty graph is legitimate and has
no records to lose.
- SemanticNetworkYAMLExporter.export() serializes before creating the
output directory, so a rejected export leaves nothing behind.
The two rejections keep distinct exception types, following what the
codebase already does: a payload of the wrong *type* cannot be exported at
all and raises ProcessingError, matching Neo4jCSVExporter._normalize_graph;
a mapping whose *contents* are unusable raises ValidationError, matching
normalize_graph_payload. _require_mapping therefore runs first at every
entry point, so a non-mapping never reaches the resolver.
Docstring Raises sections, export_usage.md and docs/reference/export.md
record the accepted input shapes and both failures.
Closes #953.
* fix(export): reject payloads whose records resolve to nothing
Addresses the Qodo findings on #958.
Presence-only recognition (finding 1): checking that a recognized key is
present answered "did the caller use our vocabulary" when the question that
matters is "did anything the caller supplied survive". A payload like
{"entities": [], "data": [...records...]} cleared the check, resolved to
empty, and dropped every record under 'data' -- the silent-empty export by a
narrower route.
- utils/helpers.py — split the check in two. _require_recognized_keys keeps
the presence rule; _require_nothing_dropped runs after resolution and
refuses a payload that resolved to nothing while an unread key still holds
records. Only a non-empty list counts as evidence: ContextGraph.to_dict()
always carries a populated 'statistics' dict, and an empty graph must stay
exportable, so 'metadata', 'statistics' and 'count' are named as context
rather than records.
- export/yaml_exporter.py — the schema path had the same hole and now runs
both checks through the shared helpers rather than its own copy, so the
two vocabularies cannot drift apart in what counts as a silent-empty
export.
Progress reported success on a failed write (finding 3): export_semantic_
network stops its tracking as completed once serialization returns, but
export() then creates the directory and writes the file. A failure there
left the tracker showing a completed export with no output.
- export/yaml_exporter.py — the serialization span now says it serialized,
not that it exported, and export() opens its own span around the
filesystem work that stops as failed on error. Nothing reports a completed
export until the bytes are on disk.
Finding 2 (export_yaml no longer accepts List[Dict]) is the intended
resolution of #952 rather than a regression: wrapping a bare list under a
guessed key is what would mislabel the records. The signature, docstring and
PR description already record the narrowed contract.
Tests cover both directions of each fix, including that an empty
ContextGraph still exports and that a failing write is not reported as
completed.
* fix(export): validate collection values and make Neo4j mappings strict
Two gaps at the boundary the shared normalizer is supposed to own.
_resolve_collection() resolved on truthiness alone, so a recognized key
could still hold something that is not a collection of records:
{"entities": "abc"} normalized to three single-character "records", and
{"entities": 42} surfaced as a raw TypeError from list() inside whichever
exporter happened to read it, naming the exporter rather than the payload
key at fault. Collection values are now validated before conversion --
strings, bytes, mappings, and non-iterable scalars are rejected by key
name, and each element must be a mapping or an attribute-carrying object,
the two record shapes the exporters actually read. None stays legal as an
absent collection, the spelling a JSON round-trip produces for []; it
cannot hide dropped records, since _require_nothing_dropped() still runs.
Every spelling present is validated, not just the one that wins, so a
malformed alias is not excused by a well-formed canonical key.
Neo4jCSVExporter._normalize_graph() opted out of the recognized-key check
for mappings, which left it able to turn {"data": [...]} into header-only
CSVs indistinguishable from a genuinely empty graph -- the exact failure
the rest of the change exists to prevent. Mapping payloads now go through
normalize_graph_payload() on its default terms. The attribute path for
graph objects is untouched. With no caller left opting out, the
require_recognized flag is removed rather than kept as a way back into
the silent-empty export.
Regression tests cover the malformed values end to end through every
export path that reads the normalizer, and assert the rejected Neo4j
export writes no CSV files.
* fix(export): close YAML schema and record validation gaps
Fix 1 -- _require_usable_schema silent data loss (P1):
_require_usable_schema() passed all values from _SCHEMA_KEYS into
_require_nothing_dropped() as evidence that records survived. Scalar
metadata fields such as version='1.0' and uri='http://...' are truthy
strings, so any one of them caused _require_nothing_dropped() to return
early and silently discard records stored under an unread key alongside
them (e.g. {'version': '1.0', 'nodes': [{'id': 'c1'}]}). Fixed by
building the resolved list from only non-empty list/tuple values of
recognised schema keys.
Fix 2 -- _is_record accepts modules and type objects (P2):
_is_record() accepted any object with __dict__, which includes Python
modules and class objects. Elements that passed _coerce_records then
reached exporters and raised AttributeError (e.g. module 'math' has no
attribute 'get') rather than a ValidationError at the validation
boundary. Fixed by excluding types.ModuleType and type from the
__dict__ branch while preserving support for all user-defined
attribute-bearing record objects.
Tests: 101 tests pass across
tests/utils/test_normalize_graph_payload.py
tests/export/test_yaml_exporter_key_recognition.py
tests/export/test_yaml_exporter_input_validation.py
tests/export/test_neo4j_csv_exporter.py
* fix(export): close exception-type and record-shape gaps in normalize_graph_payload
LPGExporter and ArangoAQLExporter called normalize_graph_payload() with no
type guard, so non-mapping input raised ValidationError from inside the
resolver while the YAML and Neo4j exporters raised ProcessingError for the
identical mistake -- inconsistent with the exception-type contract this PR
establishes. Both now use the shared _require_mapping() guard (moved from
yaml_exporter.py into utils/helpers.py so all three can use it).
Neo4jCSVExporter._normalize_graph checked isinstance(graph, dict), so a
non-dict Mapping (MappingProxyType, ChainMap) fell through to the
object-attribute branch and was rejected, even though the identical payload
exported fine via the other three exporters. Now checks isinstance(graph,
Mapping).
normalize_graph_payload() accepts dataclass/attribute-bearing object
records, but LPGExporter/ArangoAQLExporter call .get(...) directly on
resolved entities -- an object-shaped record passed validation only to
crash with a raw AttributeError once used, the exact failure this
boundary exists to prevent. Records are now converted to plain dicts at
the boundary (_coerce_records -> new _record_to_dict), so every consumer
gets a uniform shape regardless of which reading the caller used.
Two non-empty spellings of the same collection holding identical records
in a different order were rejected as conflicting, since the check used
plain list equality. Comparison is now an order-independent multiset of
each record's canonical JSON form.
* docs(changelog): add entry for #958 YAML export input hardening
Documents the full arc of #958 -- the normalize_graph_payload()
centralization, YAML input validation, both review rounds from
@Sameer6305, and the exception-type/record-shape follow-up fixes -- plus
closes #956, #952, #953.
---------
Co-authored-by: Pravit Ampapathini <pravitampapathini@Pravits-MacBook-Air-3.local>
Co-authored-by: Sameer Kadam <sskadam6305@gmail.com>
Co-authored-by: KaifAhmad1 <kaifahmad087@gmail.com>
435 lines
17 KiB
Python
435 lines
17 KiB
Python
"""Tests for YAML export key recognition (issue #953).
|
|
|
|
``SemanticNetworkYAMLExporter`` built its output from ``.get(key, [])``
|
|
lookups, so a mapping keyed by anything it did not read -- an ``export_json``
|
|
envelope, a typo'd 'entitys', ``ContextGraph.to_dict()``'s 'nodes'/'edges' --
|
|
serialized to a structurally valid file with every collection empty. Nothing
|
|
signalled the loss: no exception, no warning, and the progress log reported a
|
|
completed export. ``YAMLSchemaExporter`` had the same defect over a different
|
|
key set.
|
|
|
|
The exporters are run for real rather than mocked, and the written files are
|
|
parsed back, since the behaviour under test is what actually lands on disk.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
from semantica.context.context_graph import ContextGraph
|
|
from semantica.export.methods import export_json, export_yaml
|
|
from semantica.export.yaml_exporter import (
|
|
SemanticNetworkYAMLExporter,
|
|
YAMLSchemaExporter,
|
|
)
|
|
from semantica.utils.exceptions import ProcessingError, ValidationError
|
|
|
|
ENTITIES = [{"id": "e1", "name": "Acme"}, {"id": "e2", "name": "Beta"}]
|
|
RELATIONSHIPS = [{"id": "r1", "source": "e1", "target": "e2", "type": "PARTNER"}]
|
|
TRIPLETS = [{"subject": "e1", "predicate": "partner_of", "object": "e2"}]
|
|
|
|
|
|
def _load(path):
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
return yaml.safe_load(handle)
|
|
|
|
|
|
class TestSemanticNetworkKeyRecognition:
|
|
"""An unrecognized mapping is refused instead of silently emptied."""
|
|
|
|
def test_export_json_envelope_is_rejected(self, tmp_path):
|
|
"""The realistic trigger: re-exporting an export_json payload.
|
|
|
|
``export_json`` wraps records as ``{"data": [...], "count": N,
|
|
"metadata": {...}}``. Feeding that straight to ``export_yaml`` used to
|
|
write a file with every record gone. Note the envelope's 'metadata'
|
|
key is deliberately not enough to make the payload recognized --
|
|
treating it as sufficient would readmit exactly this case.
|
|
"""
|
|
json_path = tmp_path / "records.json"
|
|
export_json(ENTITIES, json_path)
|
|
envelope = yaml.safe_load(json_path.read_text(encoding="utf-8"))
|
|
assert "data" in envelope and "metadata" in envelope
|
|
|
|
yaml_path = tmp_path / "records.yaml"
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
export_yaml(envelope, yaml_path)
|
|
|
|
message = str(excinfo.value)
|
|
assert "'data'" in message, "error should name the supplied keys"
|
|
assert "'entities'" in message, "error should name the expected keys"
|
|
assert not yaml_path.exists(), "a rejected export must write nothing"
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[
|
|
{"records": ENTITIES},
|
|
{"entitys": ENTITIES},
|
|
{"data": ENTITIES},
|
|
{"metadata": {"source": "test"}},
|
|
],
|
|
ids=["records", "typo", "data", "metadata-only"],
|
|
)
|
|
def test_unrecognized_mappings_are_rejected(self, payload):
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ValidationError):
|
|
exporter.export_semantic_network(payload)
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[
|
|
{"entities": [], "data": ENTITIES},
|
|
{"nodes": [], "edges": [], "records": ENTITIES},
|
|
{"triplets": [], "data": ENTITIES, "metadata": {"source": "test"}},
|
|
],
|
|
ids=["entities-empty", "nodes-edges-empty", "triplets-empty"],
|
|
)
|
|
def test_recognized_but_empty_with_records_elsewhere_is_rejected(self, payload):
|
|
"""Presence of a recognized key is not proof the records survived.
|
|
|
|
``{"entities": [], "data": [...]}`` clears a presence-only check and
|
|
still resolves to empty, dropping everything under 'data' -- the same
|
|
silent-empty export by a narrower route.
|
|
"""
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
exporter.export_semantic_network(payload)
|
|
|
|
message = str(excinfo.value)
|
|
assert "holds records" in message
|
|
assert "'entities'" in message, "error should name where records belong"
|
|
|
|
def test_empty_graph_with_non_record_keys_still_exports(self, tmp_path):
|
|
"""The rejection must key on dropped *records*, not on unread keys.
|
|
|
|
``ContextGraph.to_dict()`` always carries a populated 'statistics'
|
|
dict, so an empty graph would be refused if any unread key counted.
|
|
"""
|
|
graph = ContextGraph()
|
|
path = tmp_path / "empty_graph.yaml"
|
|
export_yaml(graph.to_dict(), path)
|
|
|
|
written = _load(path)
|
|
assert written["entities"] == []
|
|
assert written["relationships"] == []
|
|
|
|
def test_empty_mapping_still_exports(self, tmp_path):
|
|
"""An empty graph is legitimate and carries nothing that could be lost."""
|
|
path = tmp_path / "empty.yaml"
|
|
export_yaml({}, path)
|
|
|
|
written = _load(path)
|
|
assert written["entities"] == []
|
|
assert written["relationships"] == []
|
|
assert written["triplets"] == []
|
|
|
|
def test_recognized_keys_still_export(self, tmp_path):
|
|
path = tmp_path / "network.yaml"
|
|
export_yaml(
|
|
{
|
|
"entities": ENTITIES,
|
|
"relationships": RELATIONSHIPS,
|
|
"triplets": TRIPLETS,
|
|
"metadata": {"source": "test"},
|
|
},
|
|
path,
|
|
)
|
|
|
|
written = _load(path)
|
|
assert written["entities"] == ENTITIES
|
|
assert written["relationships"] == RELATIONSHIPS
|
|
assert written["triplets"] == TRIPLETS
|
|
assert written["metadata"]["source"] == "test"
|
|
|
|
def test_nodes_edges_alias_exports_records(self, tmp_path):
|
|
path = tmp_path / "aliased.yaml"
|
|
export_yaml({"nodes": ENTITIES, "edges": RELATIONSHIPS}, path)
|
|
|
|
written = _load(path)
|
|
assert written["entities"] == ENTITIES
|
|
assert written["relationships"] == RELATIONSHIPS
|
|
|
|
def test_context_graph_to_dict_round_trips(self, tmp_path):
|
|
"""The most direct path from this library's own graph type to YAML.
|
|
|
|
Built from a real ``ContextGraph`` rather than a hand-written
|
|
'nodes'/'edges' dict, so the test breaks if ``to_dict()`` changes
|
|
vocabulary.
|
|
"""
|
|
graph = ContextGraph()
|
|
graph.add_node("n1", node_type="Person", content="Alice")
|
|
graph.add_node("n2", node_type="Org", content="Acme")
|
|
graph.add_edge("n1", "n2", "WORKS_FOR")
|
|
|
|
path = tmp_path / "context.yaml"
|
|
export_yaml(graph.to_dict(), path)
|
|
|
|
written = _load(path)
|
|
assert len(written["entities"]) == 2
|
|
assert len(written["relationships"]) == 1
|
|
|
|
def test_conflicting_spellings_are_refused(self):
|
|
"""Two populated spellings of one collection: no basis to pick either."""
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ValidationError):
|
|
exporter.export_semantic_network(
|
|
{"entities": ENTITIES, "nodes": [{"id": "other"}]}
|
|
)
|
|
|
|
def test_non_mapping_raises_processing_error(self):
|
|
"""A wrong type is a different failure from a wrong-keyed mapping.
|
|
|
|
ProcessingError says the object cannot be exported at all;
|
|
ValidationError says the mapping's contents are unusable. Pinned here
|
|
so the two do not quietly converge.
|
|
"""
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ProcessingError):
|
|
exporter.export_semantic_network(ENTITIES)
|
|
|
|
def test_rejected_export_creates_no_output_directory(self, tmp_path):
|
|
"""Validation runs before the output directory is created."""
|
|
target = tmp_path / "nested" / "out.yaml"
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
|
|
with pytest.raises(ValidationError):
|
|
exporter.export({"data": ENTITIES}, target)
|
|
|
|
assert not target.parent.exists()
|
|
|
|
|
|
class TestPipelineExportKeyRecognition:
|
|
"""export_for_pipeline read the same defaulted lookups, so it had the bug too."""
|
|
|
|
def test_unrecognized_mapping_is_rejected(self):
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ValidationError):
|
|
exporter.export_for_pipeline({"data": ENTITIES})
|
|
|
|
def test_non_mapping_raises_processing_error(self):
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
with pytest.raises(ProcessingError):
|
|
exporter.export_for_pipeline(ENTITIES)
|
|
|
|
def test_aliases_resolve_into_the_semantic_network(self):
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
written = yaml.safe_load(
|
|
exporter.export_for_pipeline({"nodes": ENTITIES, "edges": RELATIONSHIPS})
|
|
)
|
|
|
|
assert written["semantic_network"]["entities"] == ENTITIES
|
|
assert written["semantic_network"]["relationships"] == RELATIONSHIPS
|
|
|
|
def test_metadata_is_preserved(self):
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
written = yaml.safe_load(
|
|
exporter.export_for_pipeline(
|
|
{"entities": ENTITIES, "metadata": {"source": "test"}}
|
|
)
|
|
)
|
|
|
|
assert written["metadata"]["source"] == "test"
|
|
assert written["semantic_network"]["entities"] == ENTITIES
|
|
|
|
|
|
class TestSchemaKeyRecognition:
|
|
"""method="schema" emitted empty classes/properties/namespaces the same way."""
|
|
|
|
def test_unrecognized_mapping_is_rejected(self, tmp_path):
|
|
path = tmp_path / "schema.yaml"
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
export_yaml({"nodes": [{"id": "1"}]}, path, method="schema")
|
|
|
|
message = str(excinfo.value)
|
|
assert "'nodes'" in message
|
|
assert "'classes'" in message
|
|
assert not path.exists()
|
|
|
|
def test_non_mapping_raises_processing_error(self):
|
|
exporter = YAMLSchemaExporter()
|
|
with pytest.raises(ProcessingError):
|
|
exporter.export_ontology_schema([{"id": "1"}])
|
|
|
|
def test_recognized_but_empty_with_records_elsewhere_is_rejected(self):
|
|
"""The schema path had the same presence-only hole."""
|
|
exporter = YAMLSchemaExporter()
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
exporter.export_ontology_schema({"classes": [], "nodes": [{"id": "1"}]})
|
|
|
|
assert "holds records" in str(excinfo.value)
|
|
|
|
def test_ontology_metadata_without_records_still_exports(self):
|
|
"""A schema described only by its identity is not a dropped export."""
|
|
exporter = YAMLSchemaExporter()
|
|
written = yaml.safe_load(
|
|
exporter.export_ontology_schema(
|
|
{"uri": "http://example.org/o", "classes": []}
|
|
)
|
|
)
|
|
|
|
assert written["ontology"]["uri"] == "http://example.org/o"
|
|
assert written["classes"] == []
|
|
|
|
def test_empty_mapping_still_exports(self, tmp_path):
|
|
path = tmp_path / "schema.yaml"
|
|
export_yaml({}, path, method="schema")
|
|
|
|
written = _load(path)
|
|
assert written["classes"] == []
|
|
assert written["properties"] == []
|
|
assert written["namespaces"] == {}
|
|
|
|
@pytest.mark.parametrize(
|
|
"payload",
|
|
[
|
|
{"classes": ["Person"], "properties": ["WORKS_FOR"]},
|
|
{"namespaces": {"ex": "http://example.org/"}},
|
|
{"uri": "http://example.org/ontology"},
|
|
],
|
|
ids=["classes-properties", "namespaces-only", "uri-only"],
|
|
)
|
|
def test_recognized_keys_still_export(self, payload, tmp_path):
|
|
path = tmp_path / "schema.yaml"
|
|
export_yaml(payload, path, method="schema")
|
|
|
|
written = _load(path)
|
|
assert written["classes"] == payload.get("classes", [])
|
|
assert written["properties"] == payload.get("properties", [])
|
|
assert written["ontology"]["uri"] == payload.get("uri", "")
|
|
|
|
# ── Fix regression: scalar recognized keys must not short-circuit the ──
|
|
# ── dropped-records check (version, uri, title, description). ──────────
|
|
|
|
@pytest.mark.parametrize(
|
|
"scalar_key, scalar_value",
|
|
[
|
|
("version", "1.0"),
|
|
("uri", "http://example.org/ontology"),
|
|
("title", "My Ontology"),
|
|
("description", "A test ontology"),
|
|
],
|
|
ids=["version", "uri", "title", "description"],
|
|
)
|
|
def test_scalar_recognized_key_does_not_excuse_records_under_unread_key(
|
|
self, scalar_key, scalar_value
|
|
):
|
|
"""A truthy scalar such as version='1.0' must not silence the dropped-
|
|
records check. Before the fix, any truthy value from _SCHEMA_KEYS
|
|
would make _require_nothing_dropped believe something resolved and
|
|
return early, silently discarding a list under an unread key.
|
|
"""
|
|
exporter = YAMLSchemaExporter()
|
|
with pytest.raises(ValidationError) as excinfo:
|
|
exporter.export_ontology_schema(
|
|
{scalar_key: scalar_value, "nodes": [{"id": "c1"}]}
|
|
)
|
|
assert "holds records" in str(excinfo.value), str(excinfo.value)
|
|
|
|
def test_valid_classes_with_scalar_metadata_is_accepted(self):
|
|
"""classes/properties populated alongside version/uri must still work."""
|
|
exporter = YAMLSchemaExporter()
|
|
written = yaml.safe_load(
|
|
exporter.export_ontology_schema(
|
|
{
|
|
"classes": [{"id": "Person"}],
|
|
"properties": [{"id": "name"}],
|
|
"version": "2.0",
|
|
"uri": "http://example.org/o",
|
|
}
|
|
)
|
|
)
|
|
assert written["classes"] == [{"id": "Person"}]
|
|
assert written["properties"] == [{"id": "name"}]
|
|
assert written["ontology"]["version"] == "2.0"
|
|
assert written["ontology"]["uri"] == "http://example.org/o"
|
|
|
|
|
|
class TestFailureIsObservable:
|
|
"""The complaint in #953 was that the logs affirmatively reported success."""
|
|
|
|
def test_no_success_is_logged_for_a_rejected_export(self, tmp_path, caplog):
|
|
path = tmp_path / "out.yaml"
|
|
|
|
with caplog.at_level("DEBUG"):
|
|
with pytest.raises(ValidationError):
|
|
export_yaml({"data": ENTITIES}, path)
|
|
|
|
assert "Exported YAML to" not in caplog.text
|
|
assert any(
|
|
record.levelname in ("WARNING", "ERROR", "CRITICAL")
|
|
for record in caplog.records
|
|
), "a rejected export should leave something at warning or above"
|
|
|
|
|
|
class _RecordingTracker:
|
|
"""Records the exporter's own progress calls, which are what is under test."""
|
|
|
|
def __init__(self):
|
|
self.stopped = []
|
|
self._next_id = 0
|
|
|
|
def start_tracking(self, **kwargs):
|
|
self._next_id += 1
|
|
return str(self._next_id)
|
|
|
|
def update_tracking(self, tracking_id, **kwargs):
|
|
pass
|
|
|
|
def stop_tracking(self, tracking_id, status=None, message=None):
|
|
self.stopped.append((status, message))
|
|
|
|
|
|
class TestProgressReflectsTheWrite:
|
|
"""Serialization completing is not the same as the file landing on disk."""
|
|
|
|
def test_failed_write_is_not_reported_as_completed(self, tmp_path):
|
|
"""A write failure after serialization must not leave a clean tracker.
|
|
|
|
The path's parent is an existing *file*, so directory creation fails
|
|
after `export_semantic_network` has already reported its own
|
|
completion.
|
|
"""
|
|
blocker = tmp_path / "blocker"
|
|
blocker.write_text("not a directory", encoding="utf-8")
|
|
target = blocker / "nested" / "out.yaml"
|
|
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
tracker = _RecordingTracker()
|
|
exporter.progress_tracker = tracker
|
|
|
|
with pytest.raises(OSError):
|
|
exporter.export({"entities": ENTITIES}, target)
|
|
|
|
assert not target.exists()
|
|
statuses = [status for status, _ in tracker.stopped]
|
|
assert "failed" in statuses, f"write failure went unreported: {tracker.stopped}"
|
|
assert not any(
|
|
status == "completed" and "Exported YAML" in (message or "")
|
|
for status, message in tracker.stopped
|
|
), "no span may claim a completed export when nothing was written"
|
|
|
|
def test_successful_write_is_reported_as_completed(self, tmp_path):
|
|
target = tmp_path / "out.yaml"
|
|
exporter = SemanticNetworkYAMLExporter()
|
|
tracker = _RecordingTracker()
|
|
exporter.progress_tracker = tracker
|
|
|
|
exporter.export({"entities": ENTITIES}, target)
|
|
|
|
assert target.exists()
|
|
assert all(status == "completed" for status, _ in tracker.stopped)
|
|
assert any(
|
|
"Exported YAML" in (message or "") for _, message in tracker.stopped
|
|
), "the write should report its own completion, not just serialization"
|
|
|
|
|
|
class TestUnaffectedExporters:
|
|
"""export_json's own behaviour is untouched -- only the YAML path changed."""
|
|
|
|
def test_export_json_still_accepts_a_bare_list(self, tmp_path):
|
|
path = tmp_path / "records.json"
|
|
export_json(ENTITIES, path)
|
|
|
|
assert Path(path).exists()
|