Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ Each record is a `GedcomStructure` with a `tag`, an optional `xref` and `pointer

`loads` and `dumps` are the string equivalents. Non-conforming input raises `GedcomParseError`, a `ValueError` carrying `line_number`. A pointer to a record that does not exist is kept rather than rejected; `gedcom7.validate(records)` lists each one as a `dangling-pointer` error.

`validate` returns a list of `Error`, each with a `category`, a `message` and the `path` to the structure, such as `@I1@ INDI > BIRT > DATE`. An `Error` whose `severity` is `"recommendation"` breaks only a recommendation of the specification, so the dataset still conforms; `dumps(records, validate=True)` raises only for the others. An empty list does not prove a dataset conforms: cardinality and enumeration values are not checked, and substructures of extensions are left to the extension's own definition.

### GEDZIP

```python
Expand Down
7 changes: 4 additions & 3 deletions gedcom7/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,9 @@ def dumps(
cannot be encoded as conforming lines. Pass ``validate=True`` to check the
dataset first and raise
:class:`~gedcom7.exceptions.GedcomValidationError`, whose ``errors`` holds
every problem :func:`~gedcom7.validator.validate` found, rather than only the
first one that stops a line being written.
every error :func:`~gedcom7.validator.validate` found, rather than only the
first one that stops a line being written. Findings that are only
recommendations do not stop the write.
"""
if line_terminator not in ("\n", "\r\n", "\r"):
raise GedcomSerializeError(
Expand All @@ -233,7 +234,7 @@ def dumps(

records = list(records)
if validate:
errors = _validate(records)
errors = [e for e in _validate(records) if e.severity == "error"]
if errors:
raise GedcomValidationError(errors)
uris = _schema(records)
Expand Down
47 changes: 27 additions & 20 deletions gedcom7/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import re
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Literal

from . import cast, const, grammar, types

Expand All @@ -34,14 +34,20 @@

@dataclass
class Error:
"""One problem, and the path through the tree to where it was found."""
"""One problem, and the path through the tree to where it was found.

``severity`` is ``"error"`` when the specification requires what was broken,
and ``"recommendation"`` when it only recommends it: a dataset whose problems
are all recommendations still conforms.
"""

category: str
message: str
path: str
structure: types.GedcomStructure | None = field(
default=None, repr=False, compare=False
)
severity: Literal["error", "recommendation"] = "error"


def validate(records: Iterable[types.GedcomStructure]) -> list[Error]:
Expand All @@ -54,7 +60,8 @@ def validate(records: Iterable[types.GedcomStructure]) -> list[Error]:

An empty list means the dataset passes the checks this can make; it does not
mean the dataset conforms, since cardinality and enumeration values are not
checked. See :mod:`gedcom7.validator` for what that leaves out.
checked. See :mod:`gedcom7.validator` for what that leaves out. Entries whose
``severity`` is ``"recommendation"`` do not make the dataset non-conforming.
"""
records = list(records)
errors: list[Error] = []
Expand All @@ -77,9 +84,13 @@ def _path(structure: types.GedcomStructure) -> str:


def _report(
errors: list[Error], category: str, message: str, structure: types.GedcomStructure
errors: list[Error],
category: str,
message: str,
structure: types.GedcomStructure,
severity: Literal["error", "recommendation"] = "error",
) -> None:
errors.append(Error(category, message, _path(structure), structure))
errors.append(Error(category, message, _path(structure), structure, severity))


def _check_dataset(records: list[types.GedcomStructure], errors: list[Error]) -> None:
Expand Down Expand Up @@ -135,9 +146,15 @@ def _check_dataset(records: list[types.GedcomStructure], errors: list[Error]) ->
def _check_schema(
records: list[types.GedcomStructure], errors: list[Error]
) -> set[str]:
"""Check that the header maps each tag to one URI and back, and list the URIs."""
"""Report header tag definitions that share a URI, and list the declared URIs.

One tag defined with several URIs is not reported. The specification allows
it where those URIs' concepts cannot appear in the same place, which only the
extensions' own documentation can tell, while also listing a unique extension
tag per tag definition among its requirements; the specific permission, which
comes with a worked example, is taken to govern.
"""
by_uri: dict[str, set[str]] = {}
by_tag: dict[str, set[str]] = {}
origin: dict[str, types.GedcomStructure] = {}
for record in records:
if record.tag != const.HEAD:
Expand All @@ -159,27 +176,17 @@ def _check_schema(
continue
tag, uri = match.group("exttag"), match.group("uri")
by_uri.setdefault(uri, set()).add(tag)
by_tag.setdefault(tag, set()).add(uri)
origin.setdefault(uri, definition)
origin.setdefault(tag, definition)

for uri, tags in by_uri.items():
if len(tags) > 1:
_report(
errors,
"schema-conflict",
f"{uri} is abbreviated by {' and '.join(sorted(tags))}, so "
"which one is written is arbitrary",
f"{uri} is abbreviated by {' and '.join(sorted(tags))}; these "
"tags mean the same thing, and a schema should give a URI only one",
origin[uri],
)
for tag, uris in by_tag.items():
if len(uris) > 1:
_report(
errors,
"schema-conflict",
f"{tag} stands for {' and '.join(sorted(uris))}, so it resolves "
"to neither when read back",
origin[tag],
severity="recommendation",
)
return set(by_uri)

Expand Down
14 changes: 14 additions & 0 deletions test/test_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,20 @@ def test_error_reports_line_number() -> None:
assert excinfo.value.line == "1 NOTE @invalid"


@pytest.mark.parametrize(
("body", "line_number"),
[
("0 @i1@ INDI\n", 4), # as a record's identifier
("0 @I1@ INDI\n1 FAMC @f1@\n", 5), # as a pointer
],
)
def test_lower_case_xref_rejected_at_its_line(body: str, line_number: int) -> None:
"""Xref = atsign 1*tagchar atsign, and tagchar admits no lower-case letter."""
with pytest.raises(GedcomParseError, match="malformed line") as excinfo:
parse(body)
assert excinfo.value.line_number == line_number


def test_two_spaces_after_tag_is_payload() -> None:
"""If the tag is followed by 2 spaces, the second is part of the payload."""
records = parse("0 @I1@ INDI\n1 NOTE leading space kept\n")
Expand Down
37 changes: 31 additions & 6 deletions test/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,16 @@ def test_malformed_payload() -> None:
assert categories(dataset(individual(birth))) == ["malformed-payload"]


def test_file_format_must_be_a_media_type() -> None:
"""A bare extension such as ``png`` is not a media type."""
records = gedcom7.loads(
"0 HEAD\n1 GEDC\n2 VERS 7.0\n0 @O1@ OBJE\n1 FILE a.png\n2 FORM png\n0 TRLR\n"
)
(error,) = gedcom7.validate(records)
assert error.category == "malformed-payload"
assert error.path == "@O1@ OBJE > FILE > FORM"


@pytest.mark.parametrize("text", ["32 JAN 2000", "0 JAN 2000", "30 FEB 2000"])
def test_day_outside_the_month(text: str) -> None:
"""The grammar allows any digits for a day, so the range is checked here."""
Expand Down Expand Up @@ -289,16 +299,31 @@ def schema_dataset(*definitions: str) -> list[types.GedcomStructure]:
return records


def test_two_tags_for_one_uri() -> None:
"""dumps would pick between them arbitrarily."""
def test_two_tags_for_one_uri_is_a_recommendation() -> None:
"""The specification says a schema should, not must, give a URI one tag."""
records = schema_dataset(f"_ONE {FOAF}", f"_TWO {FOAF}")
(error,) = gedcom7.validate(records)
assert error.category == "schema-conflict"
assert error.severity == "recommendation"
assert error.path == "HEAD > SCHMA > TAG"


def test_dumps_validate_writes_past_a_recommendation() -> None:
"""A dataset whose only findings are recommendations still conforms."""
records = schema_dataset(f"_ONE {FOAF}", f"_TWO {FOAF}")
assert categories(records) == ["schema-conflict"]
assert "1 _ONE x" in gedcom7.dumps(records, validate=True)


def test_two_uris_for_one_tag() -> None:
"""The parser refuses to resolve such a tag at all."""
def test_two_uris_for_one_tag_is_not_reported() -> None:
"""The specification permits reusing a tag for concepts that never meet."""
records = schema_dataset(f"_SAME {FOAF}", "_SAME http://example.com/other")
assert "schema-conflict" in categories(records)
assert gedcom7.validate(records) == []


def test_findings_are_errors_by_default() -> None:
records = dataset(individual(types.GedcomStructure(tag="FAMS", pointer="@F9@")))
(error,) = gedcom7.validate(records)
assert error.severity == "error"


def test_undeclared_extension_tag() -> None:
Expand Down
Loading