Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/cryptography/utils.py: 63%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

81 statements  

1# This file is dual licensed under the terms of the Apache License, Version 

2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 

3# for complete details. 

4 

5from __future__ import annotations 

6 

7import enum 

8import sys 

9import types 

10import typing 

11import warnings 

12from collections.abc import Callable, Sequence 

13 

14 

15# We use a UserWarning subclass, instead of DeprecationWarning, because CPython 

16# decided deprecation warnings should be invisible by default. 

17class CryptographyDeprecationWarning(UserWarning): 

18 pass 

19 

20 

21# Several APIs were deprecated with no specific end-of-life date because of the 

22# ubiquity of their use. They should not be removed until we agree on when that 

23# cycle ends. 

24DeprecatedIn36 = CryptographyDeprecationWarning 

25DeprecatedIn40 = CryptographyDeprecationWarning 

26DeprecatedIn41 = CryptographyDeprecationWarning 

27DeprecatedIn42 = CryptographyDeprecationWarning 

28DeprecatedIn43 = CryptographyDeprecationWarning 

29DeprecatedIn46 = CryptographyDeprecationWarning 

30 

31 

32# If you're wondering why we don't use `Buffer`, it's because `Buffer` would 

33# be more accurately named: Bufferable. It means something which has an 

34# `__buffer__`. Which means you can't actually treat the result as a buffer 

35# (and do things like take a `len()`). 

36if sys.version_info >= (3, 9): 

37 Buffer = typing.Union[bytes, bytearray, memoryview] 

38else: 

39 Buffer = typing.ByteString 

40 

41 

42def _check_bytes(name: str, value: bytes) -> None: 

43 if not isinstance(value, bytes): 

44 raise TypeError(f"{name} must be bytes") 

45 

46 

47def _check_byteslike(name: str, value: Buffer) -> None: 

48 try: 

49 memoryview(value) 

50 except TypeError: 

51 raise TypeError(f"{name} must be bytes-like") 

52 

53 

54def int_to_bytes(integer: int, length: int | None = None) -> bytes: 

55 if length == 0: 

56 raise ValueError("length argument can't be 0") 

57 return integer.to_bytes( 

58 length or (integer.bit_length() + 7) // 8 or 1, "big" 

59 ) 

60 

61 

62class InterfaceNotImplemented(Exception): 

63 pass 

64 

65 

66class _DeprecatedValue: 

67 def __init__(self, value: object, message: str, warning_class): 

68 self.value = value 

69 self.message = message 

70 self.warning_class = warning_class 

71 

72 

73class _ModuleWithDeprecations(types.ModuleType): 

74 def __init__(self, module: types.ModuleType): 

75 super().__init__(module.__name__) 

76 self.__dict__["_module"] = module 

77 

78 def __getattr__(self, attr: str) -> object: 

79 obj = getattr(self._module, attr) 

80 if isinstance(obj, _DeprecatedValue): 

81 warnings.warn(obj.message, obj.warning_class, stacklevel=2) 

82 obj = obj.value 

83 return obj 

84 

85 def __setattr__(self, attr: str, value: object) -> None: 

86 setattr(self._module, attr, value) 

87 

88 def __delattr__(self, attr: str) -> None: 

89 obj = getattr(self._module, attr) 

90 if isinstance(obj, _DeprecatedValue): 

91 warnings.warn(obj.message, obj.warning_class, stacklevel=2) 

92 

93 delattr(self._module, attr) 

94 

95 def __dir__(self) -> Sequence[str]: 

96 return ["_module", *dir(self._module)] 

97 

98 

99def deprecated( 

100 value: object, 

101 module_name: str, 

102 message: str, 

103 warning_class: type[Warning], 

104 name: str | None = None, 

105) -> _DeprecatedValue: 

106 module = sys.modules[module_name] 

107 if not isinstance(module, _ModuleWithDeprecations): 

108 sys.modules[module_name] = module = _ModuleWithDeprecations(module) 

109 dv = _DeprecatedValue(value, message, warning_class) 

110 # Maintain backwards compatibility with `name is None` for pyOpenSSL. 

111 if name is not None: 

112 setattr(module, name, dv) 

113 return dv 

114 

115 

116def cached_property(func: Callable) -> property: 

117 cached_name = f"_cached_{func}" 

118 sentinel = object() 

119 

120 def inner(instance: object): 

121 cache = getattr(instance, cached_name, sentinel) 

122 if cache is not sentinel: 

123 return cache 

124 result = func(instance) 

125 setattr(instance, cached_name, result) 

126 return result 

127 

128 return property(inner) 

129 

130 

131# Python 3.10 changed representation of enums. We use well-defined object 

132# representation and string representation from Python 3.9. 

133class Enum(enum.Enum): 

134 def __repr__(self) -> str: 

135 return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>" 

136 

137 def __str__(self) -> str: 

138 return f"{self.__class__.__name__}.{self._name_}"