Coverage for bioimageio/spec/_internal/field_validation.py: 38%

42 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-02-05 13:53 +0000

1from __future__ import annotations 

2 

3from datetime import date, datetime 

4from typing import ( 

5 Any, 

6 Hashable, 

7 Mapping, 

8 Sequence, 

9 Union, 

10) 

11 

12import requests 

13 

14from ._settings import settings 

15from .constants import KNOWN_GH_USERS, KNOWN_INVALID_GH_USERS 

16from .field_warning import issue_warning 

17from .type_guards import is_mapping, is_sequence, is_tuple 

18from .validation_context import validation_context_var 

19 

20 

21def is_valid_yaml_leaf_value(value: Any) -> bool: 

22 return value is None or isinstance(value, (bool, date, datetime, int, float, str)) 

23 

24 

25def is_valid_yaml_key(value: Union[Any, Sequence[Any]]) -> bool: 

26 return ( 

27 is_valid_yaml_leaf_value(value) 

28 or is_tuple(value) 

29 and all(is_valid_yaml_leaf_value(v) for v in value) 

30 ) 

31 

32 

33def is_valid_yaml_mapping(value: Union[Any, Mapping[Any, Any]]) -> bool: 

34 return is_mapping(value) and all( 

35 is_valid_yaml_key(k) and is_valid_yaml_value(v) for k, v in value.items() 

36 ) 

37 

38 

39def is_valid_yaml_sequence(value: Union[Any, Sequence[Any]]) -> bool: 

40 return is_sequence(value) and all(is_valid_yaml_value(v) for v in value) 

41 

42 

43def is_valid_yaml_value(value: Any) -> bool: 

44 return any( 

45 is_valid(value) 

46 for is_valid in ( 

47 is_valid_yaml_key, 

48 is_valid_yaml_mapping, 

49 is_valid_yaml_sequence, 

50 ) 

51 ) 

52 

53 

54def validate_unique_entries(seq: Sequence[Hashable]): 

55 if len(seq) != len(set(seq)): 

56 raise ValueError("Entries are not unique.") 

57 return seq 

58 

59 

60def validate_gh_user(username: str, hotfix_known_errorenous_names: bool = True) -> str: 

61 if hotfix_known_errorenous_names: 

62 if username == "Constantin Pape": 

63 return "constantinpape" 

64 

65 if ( 

66 username.lower() in KNOWN_GH_USERS 

67 or not validation_context_var.get().perform_io_checks 

68 ): 

69 return username 

70 

71 if username.lower() in KNOWN_INVALID_GH_USERS: 

72 raise ValueError(f"Known invalid GitHub user '{username}'") 

73 

74 try: 

75 r = requests.get( 

76 f"https://api.github.com/users/{username}", 

77 auth=settings.github_auth, 

78 timeout=3, 

79 ) 

80 except requests.exceptions.Timeout: 

81 issue_warning( 

82 "Could not verify GitHub user '{value}' due to connection timeout", 

83 value=username, 

84 ) 

85 else: 

86 if r.status_code == 403 and r.reason == "rate limit exceeded": 

87 issue_warning( 

88 "Could not verify GitHub user '{value}' due to GitHub API rate limit", 

89 value=username, 

90 ) 

91 elif r.status_code != 200: 

92 KNOWN_INVALID_GH_USERS.add(username.lower()) 

93 raise ValueError(f"Could not find GitHub user '{username}'") 

94 

95 KNOWN_GH_USERS.add(username.lower()) 

96 

97 return username