How to use __instancecheck__ method in freezegun

Best Python code snippet using freezegun

_typecheck.py

Source:_typecheck.py Github

copy

Full Screen

...58class Union(Type):59 """A sum type.60 A correct type is any of the types provided.61 """62 def __instancecheck__(self, instance):63 return isinstance(instance, self._types)64class Optional(_SingleArgumentType):65 """An optional type.66 A correct type is either the provided type or NoneType.67 """68 def __instancecheck__(self, instance):69 # types.NoneType does not exist in Python 370 return isinstance(instance, (self._type, type(None)))71class List(_SingleArgumentType):72 """A typed list.73 A correct type is a list where each element has the single provided type.74 """75 def __instancecheck__(self, instance):76 return (isinstance(instance, list) and77 all(isinstance(x, self._type) for x in instance))78class Sequence(_SingleArgumentType):79 """A typed sequence.80 A correct type is a sequence where each element has the single provided type.81 """82 def __instancecheck__(self, instance):83 return (isinstance(instance, collections.Sequence) and84 all(isinstance(x, self._type) for x in instance))85class Collection(_SingleArgumentType):86 """A sized, iterable container.87 A correct type is an iterable and container with known size where each element88 has the single provided type.89 We use this in preference to Iterable because we check each instance of the90 iterable at runtime, and hence need to avoid iterables that could be91 exhausted.92 """93 def __instancecheck__(self, instance):94 return (isinstance(instance, collections.Iterable) and95 isinstance(instance, collections.Sized) and96 isinstance(instance, collections.Container) and97 all(isinstance(x, self._type) for x in instance))98class Tuple(Type):99 """A typed tuple.100 A correct type is a tuple with the correct length where each element has101 the correct type.102 """103 def __instancecheck__(self, instance):104 return (isinstance(instance, tuple) and105 len(instance) == len(self._types) and106 all(isinstance(x, t) for x, t in zip(instance, self._types)))107class Mapping(_TwoArgumentType):108 """A typed mapping.109 A correct type has the correct parametric types for keys and values.110 """111 def __instancecheck__(self, instance):112 key_type, value_type = self._types # pylint: disable=unbalanced-tuple-unpacking113 return (isinstance(instance, collections.Mapping) and114 all(isinstance(k, key_type) for k in instance.keys()) and115 all(isinstance(k, value_type) for k in instance.values()))116class Dict(Mapping):117 """A typed dict.118 A correct type has the correct parametric types for keys and values.119 """120 def __instancecheck__(self, instance):121 return (isinstance(instance, dict) and122 super(Dict, self).__instancecheck__(instance))123def _replace_forward_references(t, context):124 """Replace forward references in the given type."""125 if isinstance(t, str):126 return context[t]127 elif isinstance(t, Type):128 return type(t)(*[_replace_forward_references(t, context) for t in t._types]) # pylint: disable=protected-access129 else:130 return t131def register_type_abbreviation(name, alias):132 """Register an abbreviation for a type in typecheck tracebacks.133 This makes otherwise very long typecheck errors much more readable.134 Example:135 typecheck.register_type_abbreviation(tf.compat.v1.Dimension,136 'tf.compat.v1.Dimension')...

Full Screen

Full Screen

validator.py

Source:validator.py Github

copy

Full Screen

...10 self.base_class = base_class11 self.__name__ = self.__class__.__name__ # Emulate a `type`.12 def __call__(self, *args, **kwargs) -> None:13 return None # Fool runtime checks in typing module.14 def __instancecheck__(self, instance: Any) -> bool:15 return isinstance(instance, self.base_class)16 def __repr__(self) -> str:17 return '%s(%s)' % (self.__class__.__name__, self._args())18 def _args(self) -> str:19 return ''20class Color(Validator):21 def __init__(self, n_channels: int = 1, flat: bool = True) -> None:22 if flat and n_channels != 1:23 raise NotImplementedError('Unable to flatten %d channels' % n_channels)24 super().__init__(int)25 self._n_channels = n_channels26 self._flat = flat27 def coerce(28 self, value: Any, flat: Optional[bool] = None) -> Union[int, List[int]]:29 if flat is None:30 flat = self._flat31 result = []32 if isinstance(value, (tuple, list)):33 result = value34 elif isinstance(value, ColorChannel):35 value = int(value)36 result = [value] * self._n_channels37 elif isinstance(value, str):38 matched = _COLOR_REGEX.match(value)39 if matched:40 value = matched.group(1)41 if not matched or not value:42 pass # Error handling below.43 elif len(value) in (3, 4): # Double before reading each channel.44 result = [int(v * 2, 16) for v in value]45 elif len(value) in (1, 2, 4, 6, 8):46 result = [47 int(value[start:start+2], 16) for start in range(0, len(value), 2)48 ]49 if not result:50 pass51 elif flat:52 if len(result) == 1:53 return result[0]54 elif all(value == result[0] for value in result): # Monochrome: #9f9f9f.55 return result[0]56 elif len(result) == 1: # Monochrome.57 return result * self._n_channels58 elif len(result) == self._n_channels:59 return result60 elif self._n_channels == 1 and all(value == result[0] for value in result):61 return [result[0]]62 raise ValueError(63 '"%s" is not a %d-channel color' % (value, self._n_channels))64 def to_rgb_hex(self, value: Any) -> Optional[str]:65 if value is None:66 return '#000000'67 coerced = self.coerce(value, flat=False)68 if len(coerced) == 1:69 return '#%0.2x%0.2x%0.2x' % (coerced[0], coerced[0], coerced[0])70 elif len(coerced) in (3, 4):71 return '#%0.2x%0.2x%0.2x' % tuple(coerced[:3])72 raise ValueError('Cannot hex encode "%s"' % str(coerced))73 def __instancecheck__(self, instance: Any) -> bool:74 if isinstance(instance, (tuple, list)):75 values = instance76 else:77 values = [instance]78 return all(isinstance(value, int) for value in values)79class NumberInRange(Validator):80 min_value: numbers.Number = float('-inf')81 max_value: numbers.Number = float('inf')82 def __init__(83 self,84 min_value: Optional[numbers.Number] = None,85 max_value: Optional[numbers.Number] = None):86 if min_value is None and max_value is None:87 raise ValueError('min_value and max_value are both None')88 if min_value is not None:89 self.min_value = min_value90 if max_value is not None:91 self.max_value = max_value92 super().__init__(numbers.Number)93 def __instancecheck__(self, instance: Any) -> bool:94 if not super().__instancecheck__(instance):95 return False96 return self.min_value <= instance <= self.max_value97 def _args(self) -> str:98 return 'min_value=%s, max_value=%s' % (self.min_value, self.max_value)99ColorChannel = NumberInRange(min_value=0, max_value=255)100class Option(Validator):101 def __init__(self, options: List[T]) -> None:102 if not options:103 raise ValueError('No valid options')104 self._options = options105 super().__init__(type(options[0]))106 def __instancecheck__(self, instance: Any) -> bool:107 if not super().__instancecheck__(instance):108 return False109 return instance in self._options110 def __iter__(self) -> Iterable[T]:111 yield from self._options112class Point(Validator):113 _limits: Tuple[numbers.Number]114 def __init__(self, *limits: numbers.Number) -> None:115 if not limits:116 raise ValueError('1+ limits are required for Point validation')117 self._limits = limits118 super().__init__(tuple)119 def __instancecheck__(self, instance: Any) -> bool:120 if (not super().__instancecheck__(instance) or121 len(instance) != len(self._limits)):122 return False123 return all(0 <= v <= limit for v, limit in zip(instance, self._limits))124 def from_str(self, value: str) -> Tuple[numbers.Number]:125 coerce = type(self._limits[0])126 segments = value.strip('()[] ').split(',')127 return tuple(coerce(segment.strip()) for segment in segments)128class RangeInRange(Validator):129 min_value: numbers.Number130 max_value: numbers.Number131 def __init__(132 self, min_value: numbers.Number, max_value: numbers.Number) -> None:133 self.min_value = min_value134 self.max_value = max_value135 super().__init__(tuple)136 def __instancecheck__(self, instance: Any) -> bool:137 if not super().__instancecheck__(instance) or len(instance) != 2:138 return False139 min_value, max_value = instance140 return self.min_value <= min_value <= max_value <= self.max_value141 def _args(self) -> str:...

Full Screen

Full Screen

_typecheck.pyi

Source:_typecheck.pyi Github

copy

Full Screen

...9 def __init__(self, tpe: Any) -> None: ...10class _TwoArgumentType(Type):11 def __init__(self, first_type: Any, second_type: Any) -> None: ...12class Union(Type):13 def __instancecheck__(self, instance: Any): ...14class Optional(_SingleArgumentType):15 def __instancecheck__(self, instance: Any): ...16class List(_SingleArgumentType):17 def __instancecheck__(self, instance: Any): ...18class Sequence(_SingleArgumentType):19 def __instancecheck__(self, instance: Any): ...20class Collection(_SingleArgumentType):21 def __instancecheck__(self, instance: Any): ...22class Tuple(Type):23 def __instancecheck__(self, instance: Any): ...24class Mapping(_TwoArgumentType):25 def __instancecheck__(self, instance: Any): ...26class Dict(Mapping):27 def __instancecheck__(self, instance: Any): ...28def register_type_abbreviation(name: Any, alias: Any) -> None: ...29class Error(TypeError): ...30def accepts(*types: Any): ......

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run freezegun automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful