Coverage for src/kwai/core/domain/value_objects/period.py: 96%

23 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2024-01-01 00:00 +0000

1"""Module that defines the value object Period.""" 

2 

3from dataclasses import dataclass, field 

4from datetime import timedelta 

5 

6from kwai.core.domain.value_objects.timestamp import Timestamp 

7 

8 

9@dataclass(frozen=True, kw_only=True, slots=True) 

10class Period: 

11 """Value object for handling a period between dates.""" 

12 

13 start_date: Timestamp = field(default_factory=Timestamp.create_now) 

14 end_date: Timestamp = field(default_factory=Timestamp) 

15 

16 def __post_init__(self): 

17 """Perform post initialization. 

18 

19 Raises: 

20 ValueError: when the start date is before the end date. 

21 """ 

22 if not self.end_date.empty: 

23 if self.start_date.timestamp > self.end_date.timestamp: 

24 raise ValueError("start_date should be before end_date") 

25 

26 @property 

27 def delta(self) -> timedelta | None: 

28 """Return the delta between end and start time.""" 

29 if not self.end_date.empty: 

30 return self.end_date.timestamp - self.start_date.timestamp 

31 return None 

32 

33 @property 

34 def endless(self) -> bool: 

35 """Return True when end date is not set.""" 

36 return self.end_date.empty 

37 

38 @classmethod 

39 def create_from_delta(cls, start_date: Timestamp = None, **kwargs) -> "Period": 

40 """Create a period from a delta.""" 

41 date = start_date or Timestamp.create_now() 

42 return Period(start_date=date, end_date=date.add_delta(**kwargs))