Coverage for src/kwai/modules/identity/create_user.py: 96%

24 statements  

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

1"""Use case: create a user.""" 

2 

3from dataclasses import dataclass 

4 

5from kwai.core.domain.exceptions import UnprocessableException 

6from kwai.core.domain.value_objects.email_address import EmailAddress 

7from kwai.core.domain.value_objects.name import Name 

8from kwai.core.domain.value_objects.password import Password 

9from kwai.modules.identity.users.user import UserEntity 

10from kwai.modules.identity.users.user_account import UserAccountEntity 

11from kwai.modules.identity.users.user_account_repository import UserAccountRepository 

12 

13 

14@dataclass(kw_only=True, frozen=True, slots=False) 

15class CreateUserCommand: 

16 """Input for the CreateUser use case. 

17 

18 See: [CreateUser][kwai.modules.identity.create_user.CreateUser] 

19 

20 Attributes: 

21 email: The email address for the new user. 

22 first_name: The first name of the new user. 

23 last_name: The last name of the new user. 

24 password: The password for the new user. 

25 remark: A remark about the new user. 

26 """ 

27 

28 email: str 

29 first_name: str 

30 last_name: str 

31 password: str 

32 remark: str 

33 

34 

35class CreateUser: 

36 """Use case for creating a new user.""" 

37 

38 def __init__(self, user_account_repo: UserAccountRepository): 

39 """Create the use case. 

40 

41 Args: 

42 user_account_repo: Repository that creates a new user account. 

43 """ 

44 self._user_account_repo = user_account_repo 

45 

46 async def execute(self, command: CreateUserCommand) -> UserAccountEntity: 

47 """Execute the use case. 

48 

49 Args: 

50 command: The input for this use case. 

51 

52 Returns: 

53 An entity for a user account. 

54 

55 Raises: 

56 UnprocessableException: when the email address is already used by another 

57 user. 

58 """ 

59 email = EmailAddress(command.email) 

60 if await self._user_account_repo.exists_with_email(email): 

61 raise UnprocessableException( 

62 f"A user with email {command.email} already exists." 

63 ) 

64 

65 user_account = UserAccountEntity( 

66 user=UserEntity( 

67 email=email, 

68 remark=command.remark, 

69 name=Name(first_name=command.first_name, last_name=command.last_name), 

70 ), 

71 password=Password.create_from_string(command.password), 

72 ) 

73 return await self._user_account_repo.create(user_account)