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
16 changes: 8 additions & 8 deletions python/src/ossie/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class OssieField(BaseModel):

model_config = ConfigDict(frozen=True)

name: str
name: str = Field(..., min_length=1)
expression: OssieExpression
dimension: Optional[OssieDimension] = None
label: Optional[str] = None
Expand Down Expand Up @@ -157,8 +157,8 @@ class OssieDataset(BaseModel):

model_config = ConfigDict(frozen=True)

name: str
source: str
name: str = Field(..., min_length=1)
source: str = Field(..., min_length=1)
primary_key: Optional[list[str]] = None
unique_keys: Optional[list[list[str]]] = None
description: Optional[str] = None
Expand All @@ -172,9 +172,9 @@ class OssieRelationship(BaseModel):

model_config = ConfigDict(frozen=True, populate_by_name=True)

name: str
from_dataset: str = Field(..., alias="from")
to: str
name: str = Field(..., min_length=1)
from_dataset: str = Field(..., alias="from", min_length=1)
to: str = Field(..., min_length=1)
from_columns: list[str] = Field(..., min_length=1)
to_columns: list[str] = Field(..., min_length=1)
ai_context: Optional[OssieAIContext] = None
Expand All @@ -186,7 +186,7 @@ class OssieMetric(BaseModel):

model_config = ConfigDict(frozen=True)

name: str
name: str = Field(..., min_length=1)
expression: OssieExpression
description: Optional[str] = None
datatype: Optional[OssieDataType] = None
Expand All @@ -199,7 +199,7 @@ class OssieSemanticModel(BaseModel):

model_config = ConfigDict(frozen=True)

name: str
name: str = Field(..., min_length=1)
description: Optional[str] = None
ai_context: Optional[OssieAIContext] = None
datasets: list[OssieDataset] = Field(..., min_length=1)
Expand Down
99 changes: 98 additions & 1 deletion python/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@

import pytest
import yaml
from pydantic import ValidationError
from pydantic import BaseModel, ValidationError

from ossie import (
OssieAIContextObject,
OssieDataset,
OssieDataType,
OssieDialect,
OssieDialectExpression,
OssieDimension,
OssieDocument,
OssieExpression,
OssieField,
OssieMetric,
OssieRelationship,
OssieSemanticModel,
)
Expand Down Expand Up @@ -324,6 +327,100 @@ def test_effective_time_dimension_role(
assert field.is_time_dimension() is expected


# ---------------------------------------------------------------------------
# Identifier constraints
# ---------------------------------------------------------------------------


# Every schema node whose properties the models mirror, so a `minLength` added to
# the schema without a matching model constraint fails the parity test below.
_CONSTRAINED_NODES = {
"SemanticModel": OssieSemanticModel,
"Dataset": OssieDataset,
"Field": OssieField,
"Metric": OssieMetric,
"Relationship": OssieRelationship,
}


def _model_min_length(model: type[BaseModel], prop: str) -> int | None:
"""Return the `min_length` the model enforces for the field exposed as *prop*."""
field = next(
(f for name, f in model.model_fields.items() if (f.alias or name) == prop),
None,
)
assert field is not None, f"{model.__name__} has no field exposed as {prop!r}"
for meta in field.metadata:
if getattr(meta, "min_length", None) is not None:
return meta.min_length
return None


def test_identifier_min_length_matches_core_schema() -> None:
"""The models must not accept identifiers the schema rejects as empty.

`to_ossie_yaml()` output is validated against this schema, so a model that
permits an empty name serializes a document the schema refuses.
"""
schema_path = Path(__file__).parents[2] / "core-spec" / "ossie-schema.json"
schema = json.loads(schema_path.read_text())

checked = 0
for node, model in _CONSTRAINED_NODES.items():
for prop, prop_schema in schema["$defs"][node]["properties"].items():
expected = prop_schema.get("minLength")
if expected is None:
continue
assert _model_min_length(model, prop) == expected, (
f"{node}.{prop} requires minLength {expected} in the schema"
)
checked += 1

# Guards against the loop silently checking nothing if the schema moves.
assert checked == 8


@pytest.mark.parametrize(
("build", "label"),
[
(lambda: OssieSemanticModel(name="", datasets=[_dataset()]), "semantic_model.name"),
(lambda: OssieDataset(name="", source="db.s.t"), "dataset.name"),
(lambda: OssieDataset(name="orders", source=""), "dataset.source"),
(lambda: OssieField(name="", expression=_expression()), "field.name"),
(lambda: OssieMetric(name="", expression=_expression()), "metric.name"),
(lambda: _relationship(name=""), "relationship.name"),
(lambda: _relationship(**{"from": ""}), "relationship.from"),
(lambda: _relationship(to=""), "relationship.to"),
],
ids=lambda value: value if isinstance(value, str) else "",
)
def test_empty_identifiers_are_rejected(build, label: str) -> None:
with pytest.raises(ValidationError):
build()


def _expression() -> OssieExpression:
return OssieExpression(
dialects=[OssieDialectExpression(dialect=OssieDialect.ANSI_SQL, expression="x")]
)


def _dataset() -> OssieDataset:
return OssieDataset(name="orders", source="db.s.orders")


def _relationship(**overrides) -> OssieRelationship:
kwargs = {
"name": "orders_to_customers",
"from": "orders",
"to": "customers",
"from_columns": ["customer_id"],
"to_columns": ["id"],
}
kwargs.update(overrides)
return OssieRelationship.model_validate(kwargs)


# ---------------------------------------------------------------------------
# Model behavior
# ---------------------------------------------------------------------------
Expand Down
Loading