Coverage for bc/kwai-bc-identity/src/kwai_bc_identity/create_user.py: 95%

19 statements  

« prev     ^ index     » next       coverage.py v7.11.0, 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 

9 

10from kwai_bc_identity.users.user import UserEntity 

11from kwai_bc_identity.users.user_account import UserAccountEntity 

12from kwai_bc_identity.users.user_account_repository import UserAccountRepository 

13 

14 

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

16class CreateUserCommand: 

17 """Input for the CreateUser use case. 

18 

19 See: [CreateUser][kwai_bc_identity.create_user.CreateUser] 

20 

21 Attributes: 

22 email: The email address for the new user. 

23 first_name: The first name of the new user. 

24 last_name: The last name of the new user. 

25 password: The password for the new user. 

26 remark: A remark about the new user. 

27 """ 

28 

29 email: str 

30 first_name: str 

31 last_name: str 

32 password: str 

33 remark: str 

34 

35 

36class CreateUser: 

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

38 

39 def __init__(self, user_account_repo: UserAccountRepository): 

40 """Create the use case. 

41 

42 Args: 

43 user_account_repo: Repository that creates a new user account. 

44 """ 

45 self._user_account_repo = user_account_repo 

46 

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

48 """Execute the use case. 

49 

50 Args: 

51 command: The input for this use case. 

52 

53 Returns: 

54 An entity for a user account. 

55 

56 Raises: 

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

58 user. 

59 """ 

60 email = EmailAddress(command.email) 

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

62 raise UnprocessableException( 

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

64 ) 

65 

66 user_account = UserAccountEntity( 

67 user=UserEntity( 

68 email=email, 

69 remark=command.remark, 

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

71 ), 

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

73 ) 

74 return await self._user_account_repo.create(user_account)