Coverage for src/somesy/julia/models.py: 86%

44 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-07-29 07:50 +0000

1"""Julia model.""" 

2 

3import uuid 

4from logging import getLogger 

5from typing import Optional, Set 

6 

7from packaging.version import parse as parse_version 

8from pydantic import ( 

9 BaseModel, 

10 EmailStr, 

11 Field, 

12 TypeAdapter, 

13 ValidationError, 

14 field_validator, 

15) 

16from typing_extensions import Annotated 

17 

18EMailAddress = TypeAdapter(EmailStr) 

19logger = getLogger("somesy") 

20 

21 

22class JuliaConfig(BaseModel): 

23 """Julia configuration model.""" 

24 

25 model_config = dict(use_enum_values=True) 

26 

27 name: Annotated[ 

28 str, 

29 Field(description="Package name"), 

30 ] 

31 version: Annotated[ 

32 str, 

33 Field( 

34 pattern=r"^\d+(\.\d+)*((a|b|rc)\d+)?(post\d+)?(dev\d+)?$", 

35 description="Package version", 

36 ), 

37 ] 

38 uuid: Annotated[str, Field(description="Package UUID")] 

39 authors: Annotated[Optional[Set[str]], Field(description="Package authors")] = None 

40 

41 @field_validator("version") 

42 @classmethod 

43 def validate_version(cls, v): 

44 """Validate version using PEP 440.""" 

45 try: 

46 _ = parse_version(v) 

47 except ValueError as err: 

48 raise ValueError("Invalid version") from err 

49 return v 

50 

51 @field_validator("authors") 

52 @classmethod 

53 def validate_email_format(cls, v): 

54 """Validate person format, omit person that is not in correct format, don't raise an error.""" 

55 if v is None: 

56 return [] 

57 validated = [] 

58 for author in v: 

59 try: 

60 if not ( 

61 not isinstance(author, str) 

62 or " " not in author 

63 or not EMailAddress.validate_python(author.split(" ")[-1][1:-1]) 

64 ): 

65 validated.append(author) 

66 else: 

67 logger.warning( 

68 f"Invalid email format for author {author}, omitting." 

69 ) 

70 except ValidationError: 

71 logger.warning(f"Invalid format for author {author}, omitting.") 

72 return validated 

73 

74 @field_validator("uuid") 

75 @classmethod 

76 def validate_uuid(cls, v): 

77 """Validate uuid field.""" 

78 try: 

79 _ = uuid.UUID(v) 

80 except ValueError as err: 

81 raise ValueError("Invalid UUID") from err 

82 return v