"""Tests for Ownership cache model.""" import time from typing import Any import pytest from assets.connectors import redis_connector from assets.exceptions import InvalidEntityType from assets.models.cache import ownership @pytest.fixture def ownership_data(freezer: Any) -> dict[str, Any]: """Fixture for ownership data.""" freezer.move_to("2025-10-24 12:00:00") return { "ownership": True, "created": time.strftime("%Y%m%d%H%M%S", time.localtime()), } @pytest.mark.parametrize( "account_type,entity_type,expected_key", [ ("vendor", "product", "ownership:product:vendor:100:200"), ("subaccount", "product", "ownership:product:subaccount:100:200"), ("vendor", "track", "ownership:track:vendor:100:200"), ], ) def test_get_key( account_type: str, entity_type: str, expected_key: str, ownership_data: dict[str, Any], ) -> None: """Test key generation for saving ownership data.""" ownership.save(entity_type, 200, account_type, 100, ownership_data["ownership"]) def test_save(ownership_data: dict[str, Any]) -> None: """Test saving ownership data to cache.""" ownership.save("product", 215, "vendor", 100, ownership_data["ownership"]) def test_save_wrong_entity_type(ownership_data: dict[str, Any]) -> None: """Test saving ownership data with wrong entity type.""" with pytest.raises(InvalidEntityType) as exc: ownership.save("wrong_type", 215, "vendor", 100, ownership_data["ownership"]) assert exc.value.description == "Invalid entity type" def test_save_failure_ignored() -> None: """Test ownership data saving failure is ignored.""" ownership.save("product", 215, "vendor", 100, True) def test_get(ownership_data: dict[str, Any]) -> None: """Test getting ownership data from cache.""" test_account_type = "vendor" test_account_id = 100 test_entity_type = "product" test_entity_id = 200 ownership.save( test_entity_type, test_entity_id, test_account_type, test_account_id, ownership_data["ownership"], ) response = ownership.get( test_entity_type, test_entity_id, test_account_type, test_account_id ) assert response == ownership_data def test_get_not_found() -> None: """Test getting ownership data which doesn't exist in the cache.""" response = ownership.get("product", 111, "vendor", 999) assert not response def test_get_expired(ownership_data: dict[str, Any]) -> None: """Test getting expired ownership data.""" test_account_type = "vendor" test_account_id = 100 test_entity_type = "product" test_entity_id = 200 ownership.save( test_entity_type, test_entity_id, test_account_type, test_account_id, ownership_data["ownership"], ) key = ownership._get_key( test_entity_type, test_entity_id, test_account_type, test_account_id ) redis_connector.client.pexpire(key, 1) response = ownership.get( test_entity_type, test_entity_id, test_account_type, test_account_id ) assert not response def test_get_failure_ignored() -> None: """Test ownership data get failure is ignored.""" response = ownership.get("product", 111, "vendor", 999) assert not response