Skip to content

Commit 89e0cc4

Browse files
committed
Improve base entity
1 parent 3d494b4 commit 89e0cc4

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/app/domain/entities/base.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from abc import ABC
21
from dataclasses import dataclass
32
from typing import Any, TypeVar
43

@@ -9,7 +8,7 @@
98

109

1110
@dataclass(eq=False)
12-
class Entity[T: ValueObject](ABC):
11+
class Entity[T: ValueObject]:
1312
"""
1413
raises DomainError
1514
@@ -22,6 +21,21 @@ class Entity[T: ValueObject](ABC):
2221

2322
id_: T
2423

24+
def __post_init__(self) -> None:
25+
"""
26+
:raises DomainError:
27+
28+
Hook for additional initialization and ensuring invariants.
29+
Subclasses can override this method to implement custom logic, while
30+
still calling `super().__post_init__()` to preserve base checks.
31+
"""
32+
self.__forbid_base_class_instantiation()
33+
34+
def __forbid_base_class_instantiation(self) -> None:
35+
""":raises DomainError:"""
36+
if type(self) is Entity:
37+
raise DomainError("Base Entity cannot be instantiated directly.")
38+
2539
def __setattr__(self, name: str, value: Any) -> None:
2640
"""
2741
:raises DomainError:

tests/app/unit/domain/entities/test_base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
import pytest
22

3+
from app.domain.entities.base import Entity
34
from app.domain.exceptions.base import DomainError
45
from tests.app.unit.factories.named_entity import (
56
create_named_entity,
67
create_named_entity_id,
78
create_named_entity_subclass,
89
)
910
from tests.app.unit.factories.tagged_entity import create_tagged_entity
11+
from tests.app.unit.factories.value_objects import create_single_field_vo
12+
13+
14+
def test_cannot_init() -> None:
15+
vo = create_single_field_vo()
16+
17+
with pytest.raises(DomainError):
18+
Entity(id_=vo)
1019

1120

1221
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)