diff --git a/api/src/database/models/companies.py b/api/src/database/models/companies.py index 1eab06681..940712d03 100644 --- a/api/src/database/models/companies.py +++ b/api/src/database/models/companies.py @@ -1,3 +1,3 @@ -from longlink import Company +from longlink import CompanyDB -__all__ = ["Company"] +__all__ = ["CompanyDB"] diff --git a/api/src/database/services/companies.py b/api/src/database/services/companies.py index 46573cce3..2ef6e2514 100644 --- a/api/src/database/services/companies.py +++ b/api/src/database/services/companies.py @@ -6,44 +6,44 @@ from src.database.types import attr from src.models.pagination import Pagination from sqlalchemy.ext.asyncio import AsyncSession -from src.database.models.companies import Company +from src.database.models.companies import CompanyDB -async def fetch(session: AsyncSession, pagination: Pagination, query: str | None) -> tuple[Sequence[Company], int]: +async def fetch(session: AsyncSession, pagination: Pagination, query: str | None) -> tuple[Sequence[CompanyDB], int]: """List public companies using a stable name and identity ordering.""" # Search literal text rather than interpreting SQL wildcard input. - statement = select(Company).options(defer(attr(Company.logo), raiseload=True)) + statement = select(CompanyDB).options(defer(attr(CompanyDB.logo), raiseload=True)) if query: statement = statement.where( or_( - col(Company.name).icontains(query, autoescape=True), - col(Company.uid).icontains(query, autoescape=True), - col(Company.sector).icontains(query, autoescape=True), + col(CompanyDB.name).icontains(query, autoescape=True), + col(CompanyDB.uid).icontains(query, autoescape=True), + col(CompanyDB.sector).icontains(query, autoescape=True), ) ) # Count before applying deterministic pagination. total = await session.scalar(select(func.count()).select_from(statement.subquery())) result = await session.scalars( - statement.order_by(func.lower(col(Company.name)), col(Company.id)).offset(pagination.offset).limit(pagination.page_size) + statement.order_by(func.lower(col(CompanyDB.name)), col(CompanyDB.id)).offset(pagination.offset).limit(pagination.page_size) ) return result.all(), total or 0 -async def detail(session: AsyncSession, slug: str) -> Company: +async def detail(session: AsyncSession, slug: str) -> CompanyDB: """Find an exact slug, EHRA identity, or unambiguous Swiss UID alias.""" # Canonical slugs take precedence over every alias. - statement = select(Company).options(defer(attr(Company.logo), raiseload=True)) - result = await session.scalars(statement.where(col(Company.slug) == slug)) + statement = select(CompanyDB).options(defer(attr(CompanyDB.logo), raiseload=True)) + result = await session.scalars(statement.where(col(CompanyDB.slug) == slug)) company = result.one_or_none() if company is not None: return company # EHRA is unique, while historical UID aliases may identify multiple companies. uid = slug.upper().replace("-", "").replace(".", "") - condition = col(Company.ehra) == slug if slug.isascii() and slug.isdecimal() else col(Company.uid) == uid + condition = col(CompanyDB.ehra) == slug if slug.isascii() and slug.isdecimal() else col(CompanyDB.uid) == uid result = await session.scalars(statement.where(condition).limit(2)) matches = result.all() if len(matches) > 1: @@ -58,7 +58,7 @@ async def logo(session: AsyncSession, slug: str) -> bytes: """Read imported WebP image bytes.""" # Missing companies and companies without a logo share one response. - result = await session.scalars(select(col(Company.logo)).where(col(Company.slug) == slug)) + result = await session.scalars(select(col(CompanyDB.logo)).where(col(CompanyDB.slug) == slug)) data = result.one_or_none() if data is None: raise HTTPException(status_code=404, detail="Company logo not found") diff --git a/api/src/routes/v1/companies.py b/api/src/routes/v1/companies.py index 9064e9e7d..80b8eb7b3 100644 --- a/api/src/routes/v1/companies.py +++ b/api/src/routes/v1/companies.py @@ -4,7 +4,7 @@ from src.models.companies import CompanyPage, CompanyProfile from src.database.services import companies from src.models.pagination import Pagination -from src.database.models.companies import Company +from src.database.models.companies import CompanyDB router = APIRouter(prefix="/companies") @@ -21,7 +21,7 @@ async def list_companies( @router.get("/{slug}", response_model=CompanyProfile) -async def get_company(slug: Annotated[str, Path(max_length=255)], session: auth.Session) -> Company: +async def get_company(slug: Annotated[str, Path(max_length=255)], session: auth.Session) -> CompanyDB: """Return a public profile and its canonical name-based slug.""" return await companies.detail(session, slug) diff --git a/api/tests/database/models/test_init.py b/api/tests/database/models/test_init.py index d8340148d..a1a4bce9f 100644 --- a/api/tests/database/models/test_init.py +++ b/api/tests/database/models/test_init.py @@ -1,5 +1,5 @@ import pytest -from longlink import Company, PlatformModel +from longlink import CompanyDB, PlatformModel from sqlmodel import SQLModel from src.database import models from src.database.models import base, companies @@ -14,8 +14,8 @@ def test_platform_metadata_is_isolated_from_solution_metadata() -> None: assert models.metadata is not SQLModel.metadata assert base.PlatformModel is PlatformModel assert models.metadata is PlatformModel.metadata - assert Company.__table__.metadata is PlatformModel.metadata - assert issubclass(Company, PlatformModel) - assert companies.Company is Company - assert models.metadata.tables["companies"] is Company.__table__ + assert CompanyDB.__table__.metadata is PlatformModel.metadata + assert issubclass(CompanyDB, PlatformModel) + assert companies.CompanyDB is CompanyDB + assert models.metadata.tables["companies"] is CompanyDB.__table__ assert "companies" not in SQLModel.metadata.tables diff --git a/api/tests/database/services/test_companies.py b/api/tests/database/services/test_companies.py index 6adc17fe5..f6f42619b 100644 --- a/api/tests/database/services/test_companies.py +++ b/api/tests/database/services/test_companies.py @@ -7,14 +7,14 @@ from src.models.companies import CompanyProfile, CompanySummary from src.database.services import companies from src.models.pagination import Pagination -from src.database.models.companies import Company +from src.database.models.companies import CompanyDB async def test_company_profiles_serialize_detached_without_loading_logos_or_references() -> None: """Read public profiles with bounded queries and no implicit serialization I/O.""" # Arrange - company = Company( + company = CompanyDB( uid="CHE123456789", name="Retained company", slug="retained-company-123", @@ -33,7 +33,7 @@ async def test_company_profiles_serialize_detached_without_loading_logos_or_refe ) async with session_scope() as session: session.add_all( - [company, Company(uid="CHE987654321", name="Retained second company", slug="retained-second-company", locations=[])] + [company, CompanyDB(uid="CHE987654321", name="Retained second company", slug="retained-second-company", locations=[])] ) await session.commit() statements: list[str] = [] @@ -100,12 +100,12 @@ async def test_company_search_matches_literal_text_across_paginated_fields(query # Arrange matches = [ - Company(name=f"Alpha {query} Company", uid="CHE100", slug="alpha"), - Company(name="Bravo Company", uid=f"CHE{query}200", slug="bravo"), - Company(name="Charlie Company", uid="CHE300", sector=f"Sector {query} services", slug="charlie"), + CompanyDB(name=f"Alpha {query} Company", uid="CHE100", slug="alpha"), + CompanyDB(name="Bravo Company", uid=f"CHE{query}200", slug="bravo"), + CompanyDB(name="Charlie Company", uid="CHE300", sector=f"Sector {query} services", slug="charlie"), ] async with session_scope() as session: - session.add_all([*matches, Company(name="Delta Company", uid="CHE400", sector="Other services", slug="delta")]) + session.add_all([*matches, CompanyDB(name="Delta Company", uid="CHE400", sector="Other services", slug="delta")]) await session.commit() # Act diff --git a/api/tests/routes/v1/test_companies.py b/api/tests/routes/v1/test_companies.py index 7c5930811..8ae9cd304 100644 --- a/api/tests/routes/v1/test_companies.py +++ b/api/tests/routes/v1/test_companies.py @@ -1,7 +1,7 @@ import pytest from httpx2 import AsyncClient from src.database.session import session_scope -from src.database.models.companies import Company +from src.database.models.companies import CompanyDB async def test_company_logo_serves_stored_webp_from_public_profile(client: AsyncClient) -> None: @@ -9,7 +9,7 @@ async def test_company_logo_serves_stored_webp_from_public_profile(client: Async # Arrange image = bytes.fromhex("52494646220000005745425056503820160000003001009d012a010001000ec0fe25a400037000000000") - company = Company(uid="CHE123456789", name="Company", slug="company-123", ehra="123", logo=image) + company = CompanyDB(uid="CHE123456789", name="Company", slug="company-123", ehra="123", logo=image) async with session_scope() as session: session.add(company) await session.commit() @@ -34,7 +34,7 @@ async def test_company_logo_returns_not_found_for_absent_images(client: AsyncCli """Give the same not-found response for absent companies and absent logos.""" # Arrange - company = Company(uid="CHE123456789", name="Without logo", slug="without-logo") + company = CompanyDB(uid="CHE123456789", name="Without logo", slug="without-logo") async with session_scope() as session: session.add(company) await session.commit() diff --git a/sdk/README.md b/sdk/README.md index f958a0625..80b1e072f 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -42,6 +42,19 @@ longlink docs build "approval queue" Search runs locally with keyword ranking and typo-tolerant matching. Build returns authored implementation guidance and relevant APIs, not code or templates. +### Company model migration + +```python +from longlink import Company, CompanyDB + +profile = Company.model_validate({"uid": "CHE123456789", "name": "Example", "slug": "example"}) +``` + +`Company` is now a plain Pydantic `BaseModel` for `Company.model_validate`. +Replace imports and uses of the former ORM `Company` with `CompanyDB` for database +persistence, queries, sessions, and SQLModel metadata. No compatibility aliases +are provided. No database schema migration is required. +
## Development diff --git a/sdk/longlink/__init__.py b/sdk/longlink/__init__.py index ab762433b..4727e4bd5 100644 --- a/sdk/longlink/__init__.py +++ b/sdk/longlink/__init__.py @@ -5,7 +5,7 @@ from .database.base import Audit from .database.users import User from .database.platform import PlatformModel -from .database.companies import Company +from .database.companies import Company, CompanyDB from .database.relations import Model, UserRelationship from .utils.environments import Environments from .database.legalforms import LegalForm @@ -14,6 +14,7 @@ "APIRouter", "Audit", "Company", + "CompanyDB", "Context", "Environments", "LongLink", diff --git a/sdk/longlink/database/companies.py b/sdk/longlink/database/companies.py index 2147061dc..f5d5660c3 100644 --- a/sdk/longlink/database/companies.py +++ b/sdk/longlink/database/companies.py @@ -2,7 +2,7 @@ import unicodedata from uuid import UUID, uuid4 from typing import ClassVar -from pydantic import HttpUrl, field_validator, model_validator +from pydantic import HttpUrl, BaseModel, field_validator, model_validator from sqlmodel import Field, col from sqlalchemy import JSON, Enum, Text, Column, LargeBinary from sqlalchemy.orm import Mapped, column_property, add_mapped_attribute @@ -16,11 +16,9 @@ def normalize_website(value: str | None) -> str | None: return str(HttpUrl(value)) if value is not None else None -class Company(PlatformModel, table=True): - """Persist public company profiles independently of collection systems.""" +class Company(BaseModel): + """Validate public company profiles without creating ORM objects.""" - __tablename__: ClassVar[str] = "companies" - has_logo: ClassVar[Mapped[bool]] MAX_LOGO_BYTES: ClassVar[int] = 65535 MAX_SLUG_LENGTH: ClassVar[int] = 255 @@ -118,11 +116,9 @@ def validate_logo(cls, value: object) -> bytes | None: @property def logo_url(self) -> str | None: - """Derive the public image endpoint without loading image bytes.""" + """Derive the public image endpoint from validated image bytes.""" - # New collector objects already hold bytes; deferred profiles use the SQL expression. - present = self.__dict__["logo"] is not None if "logo" in self.__dict__ else self.has_logo - return f"/api/v1/companies/{self.slug}/logo" if present else None + return f"/api/v1/companies/{self.slug}/logo" if self.logo is not None else None @property def registry_url(self) -> str | None: @@ -137,5 +133,20 @@ def resolved_legal_form(self) -> str | None: return LegalForm(self.legal_form).label if self.legal_form is not None else None +class CompanyDB(Company, PlatformModel, table=True): + """Persist public company profiles independently of collection systems.""" + + __tablename__: ClassVar[str] = "companies" + has_logo: ClassVar[Mapped[bool]] + + @property + def logo_url(self) -> str | None: + """Derive the public image endpoint without loading image bytes.""" + + # New collector objects already hold bytes; deferred profiles use the SQL expression. + present = self.__dict__["logo"] is not None if "logo" in self.__dict__ else self.has_logo + return f"/api/v1/companies/{self.slug}/logo" if present else None + + # Project image presence without selecting the deferred binary payload. -add_mapped_attribute(Company, "has_logo", column_property(col(Company.logo).is_not(None))) +add_mapped_attribute(CompanyDB, "has_logo", column_property(col(CompanyDB.logo).is_not(None))) diff --git a/sdk/tests/database/test_base.py b/sdk/tests/database/test_base.py index 6970e1c3e..30a093fac 100644 --- a/sdk/tests/database/test_base.py +++ b/sdk/tests/database/test_base.py @@ -4,8 +4,8 @@ import sqlite3 from typing import Literal from pathlib import Path -from longlink import Company, LegalForm, PlatformModel -from pydantic import ValidationError +from longlink import Company, CompanyDB, LegalForm, PlatformModel +from pydantic import BaseModel, ValidationError from sqlmodel import SQLModel, select from sqlalchemy import text, event, literal from sqlalchemy.exc import OperationalError @@ -16,13 +16,55 @@ from sqlmodel.ext.asyncio.session import AsyncSession +@pytest.fixture(params=[Company, CompanyDB]) +def company_model(request: pytest.FixtureRequest) -> type[Company]: + """Exercise company rules with and without ORM instrumentation.""" + + return request.param + + +def test_company_profile_has_no_orm_state() -> None: + """Validate collector data without acquiring SQLModel or SQLAlchemy state.""" + + # Arrange + data = {"uid": "CHE123456789", "name": "Company", "ehra": "123"} + + # Act + profile = Company.model_validate(data) + + # Assert + assert isinstance(profile, BaseModel) + assert not isinstance(profile, SQLModel) + assert not hasattr(profile, "_sa_instance_state") + assert not hasattr(Company, "metadata") + assert profile.slug == "company-123" + assert profile.logo_url is None + assert profile.registry_url == "https://www.zefix.admin.ch/en/search/entity/list/firm/123" + assert profile.resolved_legal_form is None + assert profile.locations == [] + assert profile.model_fields_set == {"uid", "name", "ehra", "slug"} + + +def test_company_constructor_retains_sqlmodel_validation_semantics() -> None: + """Keep direct table construction distinct from explicit profile validation.""" + + # Arrange and act + company = CompanyDB(uid="CHE123456789", name="", ehra="123", slug="company", website="not a URL") + + # Assert + assert company.name == "" + assert company.website == "not a URL" + with pytest.raises(ValidationError): + CompanyDB.model_validate(company.model_dump()) + + async def test_company_collector_persists_profile_outside_solution_metadata() -> None: """Use the shared model with a collector-owned session without changing Solution tables.""" # Arrange engine = create_async_engine("sqlite+aiosqlite:///:memory:") image = bytes.fromhex("52494646220000005745425056503820160000003001009d012a010001000ec0fe25a400037000000000") - company = Company.model_validate( + company = CompanyDB.model_validate( { "uid": "CHE123456789", "name": "Collected company", @@ -49,9 +91,9 @@ async def test_company_collector_persists_profile_outside_solution_metadata() -> session.add(company) await session.commit() async with AsyncSession(engine) as session: - result = await session.exec(select(Company).where(Company.legal_form == LegalForm.CORPORATION)) + result = await session.exec(select(CompanyDB).where(CompanyDB.legal_form == LegalForm.CORPORATION)) persisted = result.one() - result = await session.exec(select(Company).where(Company.legal_form == "0106")) + result = await session.exec(select(CompanyDB).where(CompanyDB.legal_form == "0106")) assert result.one() is persisted assert await session.scalar(text("SELECT legal_form FROM companies")) == "0106" @@ -71,31 +113,18 @@ async def test_company_collector_persists_profile_outside_solution_metadata() -> assert "legal_seat" not in persisted.model_dump() assert "legal_seat" not in PlatformModel.metadata.tables["companies"].columns assert persisted.resolved_legal_form == "Corporation (Ltd)" - assert issubclass(Company, PlatformModel) - assert Company.metadata is PlatformModel.metadata + assert issubclass(CompanyDB, PlatformModel) + assert CompanyDB.metadata is PlatformModel.metadata assert PlatformModel.metadata is not SQLModel.metadata assert set(PlatformModel.metadata.tables) == {"companies"} assert not {"companies", "legal_forms", "municipalities"} & SQLModel.metadata.tables.keys() - assert Company.model_validate({"uid": "CHE123456789", "name": "x" * 255, "slug": "boundary-company"}).name == "x" * 255 - assert Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "x" * 255}).slug == "x" * 255 - for slug in ("", "x" * 256): - with pytest.raises(ValidationError, match="slug"): - Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": slug}) - website = "https://example.com/" + "x" * 235 - assert Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": website}).website == website - assert Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": None}).website is None - for invalid_website in ("", "ftp://example.com", website + "x", "https://" + ".".join(["a" * 60] * 4) + ".com"): - with pytest.raises(ValidationError, match="website"): - Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": invalid_website}) - with pytest.raises(ValidationError): - Company.model_validate({"uid": "x" * 13, "name": "Invalid company", "slug": "invalid-company"}) finally: # Release the collector-owned engine. await engine.dispose() @pytest.mark.parametrize("name", ["", "x" * 256]) -def test_company_collector_rejects_invalid_name_lengths(name: str) -> None: +def test_company_collector_rejects_invalid_name_lengths(company_model: type[Company], name: str) -> None: """Reject company names outside the eCH-0108 unitNameType range.""" # Arrange @@ -103,7 +132,56 @@ def test_company_collector_rejects_invalid_name_lengths(name: str) -> None: # Act and assert with pytest.raises(ValidationError, match="name"): - Company.model_validate(profile) + company_model.model_validate(profile) + + +@pytest.mark.parametrize( + ("field", "value", "expected"), + [ + ("name", "x" * 255, "x" * 255), + ("slug", "x" * 255, "x" * 255), + ("website", "https://example.com/" + "x" * 235, "https://example.com/" + "x" * 235), + ("website", "https://example.com", "https://example.com/"), + ("website", None, None), + ("locations", [{"address": None, "kind": "office"}], [{"address": None, "kind": "office"}]), + ], +) +def test_company_profile_preserves_valid_fields(company_model: type[Company], field: str, value: object, expected: object) -> None: + """Retain boundary values, explicit nulls, and normalized public data.""" + + # Arrange + profile = {"uid": "CHE123456789", "name": "Company", "slug": "company", field: value} + + # Act + company = company_model.model_validate(profile) + + # Assert + assert getattr(company, field) == expected + assert field in company.model_fields_set + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("uid", "x" * 13), + ("website", ""), + ("website", "ftp://example.com"), + ("website", "https://example.com/" + "x" * 236), + ("website", "https://" + ".".join(["a" * 60] * 4) + ".com"), + ("locations", None), + ("locations", [{"address": 123}]), + ], +) +def test_company_profile_rejects_invalid_fields(company_model: type[Company], field: str, value: object) -> None: + """Reject malformed public data through both validation entry points.""" + + # Arrange + profile = {"uid": "CHE123456789", "name": "Company", "slug": "company", field: value} + + # Act and assert + with pytest.raises(ValidationError) as error: + company_model.model_validate(profile) + assert field in {issue["loc"][0] for issue in error.value.errors()} @pytest.mark.parametrize( @@ -116,29 +194,29 @@ def test_company_collector_rejects_invalid_name_lengths(name: str) -> None: ("x" * 233 + " & Company", "12345678901234567890", "x" * 233 + "-12345678901234567890"), ], ) -def test_company_generates_omitted_slug(name: str, ehra: str, expected: str) -> None: +def test_company_generates_omitted_slug(company_model: type[Company], name: str, ehra: str, expected: str) -> None: """Generate bounded ASCII slugs without changing caller-owned profiles.""" # Arrange profile = {"uid": "CHE123456789", "name": name, "ehra": ehra} # Act - company = Company.model_validate(profile) + company = company_model.model_validate(profile) # Assert assert company.slug == expected assert "slug" not in profile -def test_company_preserves_existing_identity_and_slug() -> None: +def test_company_preserves_existing_identity_and_slug(company_model: type[Company]) -> None: """Retain row identity and a supplied slug when the company name changes.""" # Arrange - original = Company.model_validate({"uid": "CHE123456789", "name": "Original Company", "ehra": "123"}) + original = company_model.model_validate({"uid": "CHE123456789", "name": "Original Company", "ehra": "123"}) profile = original.model_dump() | {"name": "Renamed Company"} # Act - company = Company.model_validate(profile) + company = company_model.model_validate(profile) # Assert assert company.id == original.id @@ -146,7 +224,7 @@ def test_company_preserves_existing_identity_and_slug() -> None: @pytest.mark.parametrize("slug", ["", None, "x" * 256]) -def test_company_rejects_invalid_supplied_slug(slug: str | None) -> None: +def test_company_rejects_invalid_supplied_slug(company_model: type[Company], slug: str | None) -> None: """Validate supplied slugs instead of replacing invalid values.""" # Arrange @@ -154,7 +232,7 @@ def test_company_rejects_invalid_supplied_slug(slug: str | None) -> None: # Act and assert with pytest.raises(ValidationError, match="slug"): - Company.model_validate(profile) + company_model.model_validate(profile) @pytest.mark.parametrize( @@ -174,7 +252,7 @@ def test_company_rejects_invalid_supplied_slug(slug: str | None) -> None: ({"name": "Company", "ehra": "1" * 21}, "ehra"), ], ) -def test_company_rejects_invalid_slug_sources(source: dict[str, object], field: str) -> None: +def test_company_rejects_invalid_slug_sources(company_model: type[Company], source: dict[str, object], field: str) -> None: """Report field validation errors for missing or invalid slug source data.""" # Arrange @@ -182,7 +260,7 @@ def test_company_rejects_invalid_slug_sources(source: dict[str, object], field: # Act and assert with pytest.raises(ValidationError) as error: - Company.model_validate(profile) + company_model.model_validate(profile) assert field in {issue["loc"][0] for issue in error.value.errors()} @@ -195,19 +273,20 @@ def test_company_rejects_invalid_slug_sources(source: dict[str, object], field: (None, None), ], ) -def test_company_collector_resolves_legal_forms(value: str | None, expected: LegalForm | None) -> None: +def test_company_collector_resolves_legal_forms(company_model: type[Company], value: str | None, expected: LegalForm | None) -> None: """Resolve supported input forms and preserve explicit null overrides.""" # Arrange profile = {"uid": "CHE123456789", "name": "Company", "slug": "company", "legal_form": value} # Act - company = Company.model_validate(profile) + company = company_model.model_validate(profile) # Assert assert company.legal_form is expected assert "legal_form" in company.model_fields_set assert company.model_dump()["legal_form"] is expected + assert company.resolved_legal_form == ("Corporation (Ltd)" if expected is not None else None) @pytest.mark.parametrize( @@ -231,7 +310,7 @@ def test_company_collector_resolves_legal_forms(value: str | None, expected: Leg {"code": "0106"}, ], ) -def test_company_collector_rejects_invalid_legal_forms(value: object) -> None: +def test_company_collector_rejects_invalid_legal_forms(company_model: type[Company], value: object) -> None: """Reject unknown codes, legacy labels, and values that require coercion.""" # Arrange @@ -239,7 +318,7 @@ def test_company_collector_rejects_invalid_legal_forms(value: object) -> None: # Act and assert with pytest.raises(ValidationError, match="Unknown legal form"): - Company.model_validate(profile) + company_model.model_validate(profile) @pytest.mark.parametrize( @@ -251,14 +330,14 @@ def test_company_collector_rejects_invalid_legal_forms(value: object) -> None: pytest.param("😀" * 16383 + "éx", id="multibyte-boundary"), ], ) -def test_company_collector_preserves_descriptions_within_byte_capacity(description: str | None) -> None: +def test_company_collector_preserves_descriptions_within_byte_capacity(company_model: type[Company], description: str | None) -> None: """Preserve optional descriptions and exact UTF-8 storage boundaries.""" # Arrange profile = {"uid": "CHE123456789", "name": "Company", "slug": "company", "description": description} # Act - company = Company.model_validate(profile) + company = company_model.model_validate(profile) # Assert assert company.description == description @@ -267,7 +346,7 @@ def test_company_collector_preserves_descriptions_within_byte_capacity(descripti @pytest.mark.parametrize( "description", [pytest.param("a" * 65536, id="ascii-overflow"), pytest.param("😀" * 16383 + "éxx", id="multibyte-overflow")] ) -def test_company_collector_rejects_descriptions_exceeding_byte_capacity(description: str) -> None: +def test_company_collector_rejects_descriptions_exceeding_byte_capacity(company_model: type[Company], description: str) -> None: """Reject UTF-8 byte overflow even when the character count fits.""" # Arrange @@ -275,11 +354,11 @@ def test_company_collector_rejects_descriptions_exceeding_byte_capacity(descript # Act and assert with pytest.raises(ValidationError, match="description exceeds database byte capacity 65535"): - Company.model_validate(profile) + company_model.model_validate(profile) @pytest.mark.parametrize("size", [None, 12, 65534, 65535]) -def test_company_collector_preserves_logos_within_byte_capacity(size: int | None) -> None: +def test_company_collector_preserves_logos_within_byte_capacity(company_model: type[Company], size: int | None) -> None: """Preserve nulls and signature-correct bytes at the storage boundary.""" # Arrange @@ -287,15 +366,16 @@ def test_company_collector_preserves_logos_within_byte_capacity(size: int | None profile = {"uid": "CHE123456789", "name": "Company", "slug": "company", "logo": image} # Act - company = Company.model_validate(profile) - validated = Company.validate_logo(image) + company = company_model.model_validate(profile) + validated = company_model.validate_logo(image) # Assert assert company.logo is image assert validated is image + assert company.logo_url == ("/api/v1/companies/company/logo" if image is not None else None) -def test_company_collector_rejects_logo_byte_overflow() -> None: +def test_company_collector_rejects_logo_byte_overflow(company_model: type[Company]) -> None: """Reject oversized images through model and direct boundary validation.""" # Arrange @@ -304,9 +384,9 @@ def test_company_collector_rejects_logo_byte_overflow() -> None: # Act and assert with pytest.raises(ValidationError, match="Logo must contain at most 65535 bytes of image data"): - Company.model_validate(profile) + company_model.model_validate(profile) with pytest.raises(ValueError, match="Logo must contain at most 65535 bytes of image data"): - Company.validate_logo(image) + company_model.validate_logo(image) @pytest.mark.parametrize( @@ -322,7 +402,7 @@ def test_company_collector_rejects_logo_byte_overflow() -> None: pytest.param(b"RIFF\x04\x00\x00\x00WEBPjunk", id="trailing-junk"), ], ) -def test_company_collector_rejects_non_webp_images(image: bytes) -> None: +def test_company_collector_rejects_non_webp_images(company_model: type[Company], image: bytes) -> None: """Reject other formats and inconsistent WebP container lengths.""" # Arrange @@ -330,9 +410,9 @@ def test_company_collector_rejects_non_webp_images(image: bytes) -> None: # Act and assert with pytest.raises(ValidationError, match="WebP"): - Company.model_validate(profile) + company_model.model_validate(profile) with pytest.raises(ValueError, match="WebP"): - Company.validate_logo(image) + company_model.validate_logo(image) @pytest.mark.parametrize( @@ -344,7 +424,7 @@ def test_company_collector_rejects_non_webp_images(image: bytes) -> None: pytest.param(42, id="integer"), ], ) -def test_company_rejects_logo_type_coercion(image: object) -> None: +def test_company_rejects_logo_type_coercion(company_model: type[Company], image: object) -> None: """Require bytes before Pydantic can coerce strings or mutable buffers.""" # Arrange @@ -352,9 +432,9 @@ def test_company_rejects_logo_type_coercion(image: object) -> None: # Act and assert with pytest.raises(ValidationError): - Company.model_validate(profile) + company_model.model_validate(profile) with pytest.raises(ValueError, match="Logo"): - Company.validate_logo(image) + company_model.validate_logo(image) @pytest.mark.parametrize(