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
45 changes: 43 additions & 2 deletions src/linkml_reference_validator/field_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,34 @@
full URIs before matching.
"""

import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional, Protocol

if TYPE_CHECKING:
from curies import Converter


def _uri_tokens(uri: str) -> set[str]:
"""Split a URI/CURIE into lowercased word tokens.

Splits on camelCase boundaries and any run of non-alphanumeric characters,
so a generic term can be matched as a whole word rather than as a bare
substring (which would flag ``user_preference`` or ``dereference`` as
containing "reference").

Examples:
>>> sorted(_uri_tokens("http://example.org/myReferenceField"))
['example', 'field', 'http', 'my', 'org', 'reference']
>>> sorted(_uri_tokens("test:user_preference"))
['preference', 'test', 'user']
>>> sorted(_uri_tokens("dcterms:references"))
['dcterms', 'references']
"""
spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", uri)
return {tok.lower() for tok in re.split(r"[^A-Za-z0-9]+", spaced) if tok}


# =============================================================================
# URI Constants
# =============================================================================
Expand Down Expand Up @@ -126,20 +147,32 @@ class ReferenceURIs:
LEGACY_LINKML: str = "https://w3id.org/linkml/authoritative_reference"
LEGACY_LINKML_PREFIXED: str = "linkml:authoritative_reference"

# Additional patterns to match (substrings)
# Unambiguous patterns matched as substrings (e.g. dcterms:source has no
# generic single-word form to confuse).
MATCH_PATTERNS: tuple[str, ...] = (
"dcterms:references",
"dc/terms/references",
"dcterms:source",
"dc/terms/source",
"authoritative_reference",
)

# Generic terms matched as whole word tokens, NOT bare substrings, so that
# "user_preference" / "dereference" are not mistaken for references.
TOKEN_TERMS: tuple[str, ...] = (
"reference",
"references",
)

@classmethod
def is_reference_uri(cls, uri: str) -> bool:
"""Check if a URI identifies a reference field.

Specific Dublin Core / legacy URIs are matched as substrings. The
generic word "reference(s)" is matched only as a whole token, so URIs
that merely contain those letters (``user_preference``, ``dereference``)
are not misclassified.

Args:
uri: URI string to check (can be full or prefixed)

Expand All @@ -155,11 +188,19 @@ def is_reference_uri(cls, uri: str) -> bool:
True
>>> ReferenceURIs.is_reference_uri("https://w3id.org/linkml/authoritative_reference")
True
>>> ReferenceURIs.is_reference_uri("http://example.org/myReferenceField")
True
>>> ReferenceURIs.is_reference_uri("oa:exact")
False
>>> ReferenceURIs.is_reference_uri("test:user_preference")
False
>>> ReferenceURIs.is_reference_uri("ex:dereference")
False
"""
uri_lower = uri.lower()
return any(pattern in uri_lower for pattern in cls.MATCH_PATTERNS)
if any(pattern in uri_lower for pattern in cls.MATCH_PATTERNS):
return True
return bool(_uri_tokens(uri) & set(cls.TOKEN_TERMS))


@dataclass(frozen=True)
Expand Down
47 changes: 47 additions & 0 deletions tests/test_field_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,53 @@ def test_multiple_implements(self):
assert is_excerpt_slot(slot) is True


class TestReferenceURITokenBoundaries:
"""The generic 'reference' term must match as a token, not a bare substring.

A bare substring match flags unrelated URIs like ``user_preference`` or
``dereference`` (both contain the letters 'reference'), which would cause
the plugin to treat those slots as authoritative references. Matching the
word as a camelCase / separator-delimited token avoids the false positives
while still recognising real reference fields.
"""

@pytest.mark.parametrize(
"uri",
[
"test:user_preference",
"ex:dereference",
"http://example.org/userPreference",
"schema:preferenceOrder",
],
)
def test_non_reference_terms_rejected(self, uri: str):
"""URIs where 'reference' is only a substring of another word."""
assert ReferenceURIs.is_reference_uri(uri) is False

@pytest.mark.parametrize(
"uri",
[
# Specific canonical / legacy forms must keep matching
"dcterms:references",
"http://purl.org/dc/terms/references",
"dcterms:source",
"linkml:authoritative_reference",
# Generic 'reference' token in various shapes
"http://example.org/myReferenceField",
"test:reference",
"ex:cross_reference",
],
)
def test_real_reference_terms_accepted(self, uri: str):
"""Genuine reference fields must still be detected."""
assert ReferenceURIs.is_reference_uri(uri) is True

def test_slot_with_preference_uri_not_a_reference(self):
"""A slot whose URI merely contains 'preference' is not a reference."""
slot = Mock(implements=["test:user_preference"], slot_uri=None)
assert is_reference_slot(slot) is False


class TestIsReferenceSlot:
"""Tests for is_reference_slot function."""

Expand Down
2 changes: 2 additions & 0 deletions tests/test_title_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,12 @@ def test_validate_with_title_field(self, plugin, mocker):
# Setup schema view
mock_slot_ref = mocker.MagicMock()
mock_slot_ref.implements = ["linkml:authoritative_reference"]
mock_slot_ref.slot_uri = None
mock_slot_ref.range = None

mock_slot_excerpt = mocker.MagicMock()
mock_slot_excerpt.implements = ["linkml:excerpt"]
mock_slot_excerpt.slot_uri = None
mock_slot_excerpt.range = None

mock_slot_title = mocker.MagicMock()
Expand Down
Loading