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

23 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-05 17:55 +0000

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

2from dataclasses import dataclass, field 

3from datetime import timedelta 

4 

5from kwai.core.domain.value_objects.local_timestamp import LocalTimestamp 

6 

7 

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

9class Period: 

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

11 

12 start_date: LocalTimestamp = field(default_factory=LocalTimestamp.create_now) 

13 end_date: LocalTimestamp = field(default_factory=LocalTimestamp) 

14 

15 def __post_init__(self): 

16 """Perform post initialization. 

17 

18 Raises: 

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

20 """ 

21 if not self.end_date.empty: 

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

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

24 

25 @property 

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

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

28 if not self.end_date.empty: 

29 return self.end_date.timestamp - self.start_date.timestamp 

30 return None 

31 

32 @property 

33 def endless(self) -> bool: 

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

35 return self.end_date.empty 

36 

37 @classmethod 

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

39 """Create a period from a delta.""" 

40 date = start_date or LocalTimestamp.create_now() 

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