python_code
stringlengths
0
108k
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype Decidedly Object-Oriented Runtime-checking (DOOR) data** (i.e., global constants internally required throughout the :mod:`beartype.door` subpackage). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsub import ( _TypeHintOriginIsinstanceableArgs1, _TypeHintOriginIsinstanceableArgs2, _TypeHintOriginIsinstanceableArgs3, _TypeHintSubscripted, ) from beartype.door._cls.doorsuper import TypeHint from beartype.door._cls.pep.pep484.doorpep484class import ClassTypeHint from beartype.door._cls.pep.doorpep484604 import UnionTypeHint from beartype.door._cls.pep.doorpep586 import LiteralTypeHint from beartype.door._cls.pep.doorpep593 import AnnotatedTypeHint from beartype.door._cls.pep.pep484.doorpep484newtype import NewTypeTypeHint from beartype.door._cls.pep.pep484.doorpep484typevar import TypeVarTypeHint from beartype.door._cls.pep.pep484585.doorpep484585callable import ( CallableTypeHint) from beartype.door._cls.pep.pep484585.doorpep484585tuple import _TupleTypeHint from beartype.roar import ( BeartypeDoorNonpepException, # BeartypeDoorPepUnsupportedException, ) from beartype.typing import ( Dict, Type, ) from beartype._data.hint.pep.sign.datapepsigncls import HintSign from beartype._data.hint.pep.sign.datapepsigns import ( HintSignAnnotated, HintSignCallable, HintSignGeneric, HintSignLiteral, HintSignNewType, HintSignTuple, HintSignTypeVar, ) from beartype._util.hint.pep.utilpepget import ( get_hint_pep_args, # get_hint_pep_origin_or_none, get_hint_pep_sign_or_none, ) from beartype._util.hint.pep.utilpeptest import is_hint_pep_typing # ....................{ GETTERS }.................... def get_typehint_subclass(hint: object) -> Type[TypeHint]: ''' Concrete :class:`TypeHint` subclass handling the passed low-level unwrapped PEP-compliant type hint if any *or* raise an exception otherwise. Parameters ---------- hint : object Low-level type hint to be inspected. Returns ---------- Type[TypeHint] Concrete subclass of the abstract :mod:`TypeHint` superclass handling this hint. Raises ---------- beartype.roar.BeartypeDoorNonpepException If this API does *not* currently support the passed hint. beartype.roar.BeartypeDecorHintPepSignException If the passed hint is *not* actually a PEP-compliant type hint. ''' # ..................{ SUBCLASS }.................. # Sign uniquely identifying this hint if any *OR* "None" otherwise (i.e., if # this hint is a PEP-noncompliant class). hint_sign = get_hint_pep_sign_or_none(hint) # Private concrete subclass of this ABC handling this hint if any *OR* # "None" otherwise (i.e., if no such subclass has been authored yet). wrapper_subclass = _HINT_SIGN_TO_TYPEHINT_CLS.get(hint_sign) # type: ignore[arg-type] # If this hint appears to be currently unsupported... if wrapper_subclass is None: # FIXME: This condition is kinda intense. Should we really be conflating # typing attributes that aren't types with objects that are types? Let's # investigate exactly which kinds of type hints require this and # contemplate something considerably more elegant. # If either... if ( # This hint is a PEP-noncompliant class *OR*... isinstance(hint, type) or # An unsupported kind of PEP-compliant type hint (e.g., # "typing.TypedDict" instance)... is_hint_pep_typing(hint) # Return the concrete "TypeHint" subclass handling all such classes. ): wrapper_subclass = ClassTypeHint # Else, raise an exception. else: raise BeartypeDoorNonpepException( f'Type hint {repr(hint)} invalid ' f'(i.e., either PEP-noncompliant or PEP-compliant but ' f'currently unsupported by "beartype.door.TypeHint").' ) # Else, this hint is supported. #FIXME: Alternately, it might be preferable to refactor this to resemble: # if ( # not get_hint_pep_args(hint) and # get_hint_pep_origin_or_none(hint) is None # ): # wrapper_subclass = ClassTypeHint # #That's possibly simpler and cleaner, as it seamlessly conveys the exact #condition we're going for -- assuming it works, of course. *sigh* #FIXME: While sensible, the above approach induces non-trivial test #failures. Let's investigate this further at a later time, please. # If a subscriptable type has no args, all we care about is the origin. elif ( not get_hint_pep_args(hint) and hint_sign not in _HINT_SIGNS_ORIGINLESS # get_hint_pep_origin_or_none(hint) is None ): wrapper_subclass = ClassTypeHint # In any case, this hint is supported by this concrete subclass. # Return this subclass. return wrapper_subclass # ....................{ PRIVATE ~ globals }.................... # Further initialized below by the _init() function. _HINT_SIGN_TO_TYPEHINT_CLS: Dict[HintSign, Type[TypeHint]] = { HintSignAnnotated: AnnotatedTypeHint, HintSignCallable: CallableTypeHint, HintSignGeneric: _TypeHintSubscripted, HintSignLiteral: LiteralTypeHint, HintSignNewType: NewTypeTypeHint, HintSignTuple: _TupleTypeHint, HintSignTypeVar: TypeVarTypeHint, } ''' Dictionary mapping from each sign uniquely identifying PEP-compliant type hints to the :class:`TypeHint` subclass handling those hints. ''' #FIXME: Consider shifting into "datapepsignset" if still required. _HINT_SIGNS_ORIGINLESS = frozenset(( HintSignNewType, HintSignTypeVar, )) ''' Frozen set of all **origin-less signs.** ''' # ....................{ PRIVATE ~ initializers }.................... def _init() -> None: ''' Initialize this submodule. ''' # Isolate function-specific imports. from beartype._data.hint.pep.sign.datapepsignset import ( HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_1, HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_2, HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_3, HINT_SIGNS_UNION, ) # Fully initialize the "HINT_SIGN_TO_TYPEHINT" dictionary declared above. for sign in HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_1: _HINT_SIGN_TO_TYPEHINT_CLS[sign] = _TypeHintOriginIsinstanceableArgs1 for sign in HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_2: _HINT_SIGN_TO_TYPEHINT_CLS[sign] = _TypeHintOriginIsinstanceableArgs2 for sign in HINT_SIGNS_ORIGIN_ISINSTANCEABLE_ARGS_3: _HINT_SIGN_TO_TYPEHINT_CLS[sign] = _TypeHintOriginIsinstanceableArgs3 for sign in HINT_SIGNS_UNION: _HINT_SIGN_TO_TYPEHINT_CLS[sign] = UnionTypeHint # For each concrete "TypeHint" subclass registered with this dictionary # (*AFTER* initializing this dictionary)... for typehint_cls in _HINT_SIGN_TO_TYPEHINT_CLS.values(): # If the unqualified basename of this subclass is prefixed by an # underscare, this subclass is private rather than public. In this case, # silently ignore this private subclass and continue to the next. if typehint_cls.__name__.startswith('_'): continue # Else, this subclass is public. # Sanitize the fully-qualified module name of this public subclass from # the private submodule declaring this subclass (e.g., # "beartype.door._cls.pep.doorpep484604.UnionTypeHintbeartype") to the # public "beartype.door" subpackage to both improve the readability of # exception messages and discourage end users from accessing that # private submodule. typehint_cls.__class__.__module__ = 'beartype.door' # Initialize this submodule. _init()
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype Decidedly Object-Oriented Runtime-checking (DOOR) metaclass hierarchy** (i.e., metaclass hierarchy driving our object-oriented type hint class hierarchy, especially with respect to instantiation, mapping, and memoization). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from abc import ABCMeta from beartype.typing import Any from beartype._cave._cavefast import NoneType from beartype._util.cache.map.utilmapbig import CacheUnboundedStrong from beartype._util.hint.utilhinttest import is_hint_uncached from threading import RLock # ....................{ METACLASSES }.................... #FIXME: Unit test us up, please. class _TypeHintMeta(ABCMeta): # class SingletonMeta(type): ''' **Singleton abstract base class (ABC) metaclass** (i.e., the standard :class:`abc.ABCMeta` metaclass augmented with caching to implement the singleton design pattern). This metaclass is superior to the usual approach of implementing the singleton design pattern: overriding the :meth:`__new__` method of a singleton class to conditionally create a new instance of that class only if an instance has *not* already been created. Why? Because that approach unavoidably re-calls the :meth:`__init__` method of a previously initialized singleton instance on each instantiation of that class. Doing so is generally considered harmful. This metaclass instead guarantees that the :meth:`__init__` method of a singleton instance is only called exactly once on the first instantiation of that class. Attributes ---------- __singleton : Optional[type] Either: * If the current singleton abstract base class (ABC) has been initialized (i.e., if the :meth:`__init__` method of this metaclass initializing that class with metaclass-specific logic) but a singleton instance of that class has *not* yet been instantiated (i.e., if the :meth:`__call__` method of this metaclass calling the :meth:`__new__` and :meth:`__init__` methods of that class (in that order) has been called), ``None``. * Else, the current singleton ABC has been initialized and a singleton instance of that class has been instantiated. In this case, that instance. For forward compatibility with future :class:`ABCMeta` changes, the name of this instance variable is prefixed by ``"__"`` and thus implicitly obfuscated by Python to be externally inaccessible. See Also ---------- https://stackoverflow.com/a/8665179/2809027 StackOverflow answers strongly inspiring this implementation. ''' # ..................{ INSTANTIATORS }.................. def __call__(cls: '_TypeHintMeta', hint: object) -> Any: # type: ignore[override] ''' Factory constructor magically instantiating and returning a singleton instance of the concrete subclass of the :class:`beartype.door.TypeHint` abstract base class (ABC) appropriate for handling the passed low-level type hint. Parameters ---------- cls : _TypeHintMeta The :class:`beartype.door.TypeHint` ABC. hint : object Low-level type hint to be wrapped by a singleton :class:`beartype.door.TypeHint` instance. Raises ---------- BeartypeDoorNonpepException If this class does *not* currently support the passed hint. BeartypeDecorHintPepSignException If the passed hint is *not* actually a PEP-compliant type hint. ''' # print(f'!!!!!!!!!!!!! [ in _TypeHintMeta.__call__(cls={repr(cls)}, hint={repr(hint)}) ] !!!!!!!!!!!!!!!') # ................{ IMPORTS }................ # Avoid circular import dependencies. from beartype.door._cls.doorsuper import TypeHint # ................{ TRIVIALITIES }................ # If this class is a concrete subclass of the "TypeHint" abstract base # class (ABC) rather than ABC itself, instantiate that subclass in the # standard way. if cls is not TypeHint: # print('!!!!!!!!!!!!! [ _TypeHintMeta.__call__ ] instantiating subclass... !!!!!!!!!!!!!!!') return super().__call__(hint) # Else, this class is that ABC. In this case, instantiate that ABC in a # non-standard way. # # If this low-level type hint is already a high-level type hint wrapper, # return this wrapper as is. This guarantees the following constraint: # >>> TypeHint(TypeHint(hint)) is TypeHint(hint) # True elif isinstance(hint, TypeHint): # print('!!!!!!!!!!!!! [ _TypeHintMeta.__call__ ] reducing to noop... !!!!!!!!!!!!!!!') return hint # Else, this hint is *NOT* already a wrapper. # ................{ CACHING }................ # Key uniquely identifying this hint, defined as either... hint_key = ( # If this hint is *NOT* self-caching (i.e., *NOT* already internally # cached by its parent class or module), the machine-readable # representation of this hint. Computing this string consumes more # time and space and is thus performed *ONLY* where required, which # is for hints that are *NOT* already reduced to singleton objects. # # Note that this is *NOT* merely an optimization concern. Some # PEP-compliant type hints have arbitrary caller-defined and thus # possibly ambiguous representations. Ergo, the machine-readable # representation of an arbitrary hint does *NOT* uniquely identify # that hint in general and thus *CANNOT* be used to cache that hint. # Class factories producing hints with such names include: # * "typing.ParamSpec". # * "typing.TypeVar". repr(hint) if is_hint_uncached(hint) else # Else, this hint is self-caching and thus already reduced to a # singleton object. In this case, the identifier identifying this # singleton object. id(hint) ) #FIXME: Revise commentary, please. # Previously cached type hint wrapper wrapping this hint if this hint # has already been wrapped at least once by an instance of the # "TypeHint" class under the active Python interpreter *OR* "None" # otherwise (i.e., if this hist has yet to be wrapped such an instance). wrapper = ( _HINT_KEY_TO_WRAPPER.cache_or_get_cached_func_return_passed_arg( # Cache this wrapper singleton under this key. key=hint_key, # If a wrapper singleton has yet to be instantiated for this # hint, do so by calling this private factory method passed... value_factory=cls._make_wrapper, # ...this hint. arg=hint, )) # Return this wrapper. return wrapper # ..................{ PRIVATE }.................. def _make_wrapper(cls: '_TypeHintMeta', hint: object) -> object: ''' **Type hint wrapper factory** (i.e., low-level private method creating and returning a new :class:`beartype.door.TypeHint` instance wrapping the passed type hint), intended to be called by the :meth:`CacheUnboundedStrong.cache_or_get_cached_func_return_passed_arg` method to create a new type hint wrapper singleton for the passed hint. Parameters ---------- cls : _TypeHintMeta The :class:`beartype.door.TypeHint` ABC. hint : object Low-level type hint to be wrapped by a singleton :class:`beartype.door.TypeHint` instance. Raises ---------- BeartypeDoorNonpepException If this class does *not* currently support the passed hint. BeartypeDecorHintPepSignException If the passed hint is *not* actually a PEP-compliant type hint. ''' # ................{ IMPORTS }................ # Avoid circular import dependencies. from beartype.door._doordata import get_typehint_subclass # ................{ REDUCTION }................ # Reduce this hint to a more amenable form suitable for mapping to a # concrete "TypeHint" subclass if desired. # # Note that this reduction intentionally ignores the entire # "beartype._check.conv" subpackage. Although submodules of that # subpackage do perform various coercions, reductions, and sanitizations # of low-level PEP-compliant type hints, they do so only for the express # purpose of dynamic code generation. That subpackage is *NOT* # general-purpose and is, in fact, harmful in this context. Why? Because # that subpackage erodes the semantic meaning from numerous type hints # that this subpackage necessarily preserves. # # ................{ REDUCTION ~ pep 484 : none }................ # If this is the PEP 484-compliant "None" singleton, reduce this hint to # the type of that singleton. While *NOT* explicitly defined by the # "typing" module, PEP 484 explicitly supports this singleton: # When used in a type hint, the expression None is considered # equivalent to type(None). # # The "None" singleton is used to type callables lacking an explicit # "return" statement and thus absurdly common. Ergo, detect this early. if hint is None: hint = NoneType # pyright: ignore[reportGeneralTypeIssues] # Else, this is *NOT* the PEP 484-compliant "None" singleton. # ................{ INSTANTIATION }................ # Concrete "TypeHint" subclass handling this hint if this hint is # supported by an existing "TypeHint" subclass *OR* raise an exception # otherwise (i.e., if this hint is currently unsupported). wrapper_subclass = get_typehint_subclass(hint) # print(f'!!!!!!!!!!!!! [ in {repr(cls)}.__new__() ] !!!!!!!!!!!!!!!') # Type hint wrapper wrapping this hint as a new singleton instance of # this subclass. wrapper = wrapper_subclass(hint) # wrapper = super(_TypeHintMeta, wrapper_subclass).__call__(hint) # print('!!!!!!!!!!!!! [ _TypeHintMeta.__call__ ] caching and returning singleton... !!!!!!!!!!!!!!!') # Return this wrapper. return wrapper # ....................{ PRIVATE ~ mappings }.................... _HINT_KEY_TO_WRAPPER = CacheUnboundedStrong( # Prefer the slower reentrant lock type for safety. As the subpackage name # implies, the DOOR API is fundamentally recursive and requires reentrancy. lock_type=RLock, ) ''' **Type hint wrapper cache** (i.e., non-thread-safe cache mapping from the machine-readable representations of all type hints to cached singleton instances of concrete subclasses of the :class:`beartype.door.TypeHint` abstract base class (ABC) wrapping those hints).** Design -------------- **This dictionary is intentionally thread-safe.** Why? Because this dictionary is used to ensure that :class:`beartype.door.TypeHint` instances are singletons, enabling callers to reliably implement higher-level abstractions memoized (i.e., cached) against these singletons. Those abstractions could be module-scoped and thus effectively global. To prevent race conditions between competing threads contending over those globals, this dictionary *must* be thread-safe. **This dictionary is intentionally designed as a naive dictionary rather than a robust LRU cache,** for the same reasons that callables accepting hints are memoized by the :func:`beartype._util.cache.utilcachecall.callable_cached` rather than the :func:`functools.lru_cache` decorator. Why? Because: * The number of different type hints instantiated across even worst-case codebases is negligible in comparison to the space consumed by those hints. * The :attr:`sys.modules` dictionary persists strong references to all callables declared by previously imported modules. In turn, the ``func.__annotations__`` dunder dictionary of each such callable persists strong references to all type hints annotating that callable. In turn, these two statements imply that type hints are *never* garbage collected but instead persisted for the lifetime of the active Python process. Ergo, temporarily caching hints in an LRU cache is pointless, as there are *no* space savings in dropping stale references to unused hints. **This dictionary intentionally caches machine-readable representation strings hashes rather than alternative keys** (e.g., actual hashes). Why? Disambiguity. Although comparatively less efficient in both space and time to construct than hashes, the :func:`repr` strings produced for two dissimilar type hints *never* ambiguously collide unless an external caller maliciously modified one or more identifying dunder attributes of those hints (e.g., the ``__module__``, ``__qualname__``, and/or ``__name__`` dunder attributes). That should *never* occur in production code. Meanwhile, the :func:`hash` values produced for two dissimilar type hints *commonly* ambiguously collide. This is why hashable containers (e.g., :class:`dict`, :class:`set`) explicitly handle hash table collisions and why we are *not* going to do so. Likewise, this dictionary intentionally caches machine-readable representations of low-level type hints rather than those hints themselves. Since increasingly many hints are no longer self-caching (e.g., PEP 585-compliant type hints like "list[str]"), the latter *CANNOT* be guaranteed to be singletons and thus safely used as cache keys. Also: '''
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype Decidedly Object-Oriented Runtime-checking (DOOR) superclass** (i.e., root of the object-oriented type hint class hierarchy encapsulating the non-object-oriented type hint API standardized by the :mod:`typing` module). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ TODO }.................... #FIXME: Slot "TypeHint" attributes for lookup efficiency, please. #FIXME: Privatize most (...or perhaps all) public instance variables, please. # ....................{ IMPORTS }.................... from beartype.door._doorcheck import ( die_if_unbearable, is_bearable, ) from beartype.door._doormeta import _TypeHintMeta from beartype.door._doortest import die_unless_typehint from beartype.door._doortyping import T from beartype.typing import ( TYPE_CHECKING, Any, FrozenSet, Generic, Iterable, Tuple, Union, overload, ) from beartype._conf.confcls import ( BEARTYPE_CONF_DEFAULT, BeartypeConf, ) from beartype._data.datatyping import CallableMethodGetitemArg from beartype._util.cache.utilcachecall import ( method_cached_arg_by_id, property_cached, ) from beartype._util.hint.pep.utilpepget import ( get_hint_pep_args, get_hint_pep_origin_or_none, get_hint_pep_sign_or_none, ) from beartype._util.hint.utilhintfactory import TypeHintTypeFactory from beartype._util.hint.utilhinttest import is_hint_ignorable from beartype._util.mod.lib.utiltyping import import_typing_attr_or_fallback # ....................{ HINTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # CAUTION: Synchronize with similar logic in "beartype.door._doorcheck". See # the head of that submodule for detailed commentary. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if TYPE_CHECKING: from typing_extensions import TypeGuard else: TypeGuard = import_typing_attr_or_fallback( 'TypeGuard', TypeHintTypeFactory(bool)) # ....................{ SUPERCLASSES }.................... #FIXME: Subclass all applicable "collections.abc" ABCs for explicitness, please. #FIXME: Document all public and private attributes of this class, please. class TypeHint(Generic[T], metaclass=_TypeHintMeta): # class TypeHint(Generic[T], metaclass=ABCMeta): ''' Abstract base class (ABC) of all **type hint wrapper** (i.e., high-level object encapsulating a low-level type hint augmented with a magically object-oriented Pythonic API, including equality and rich comparison testing) subclasses. Sorting -------- **Type hint wrappers are partially ordered** with respect to one another. Type hints wrappers support all binary comparators (i.e., ``==``, ``!=``, ``<``, ``<=``, ``>``, and ``>=``) such that for any three type hint wrappers ``a``, ``b`, and ``c``: * ``a ≤ a`` (i.e., **reflexivity**). * If ``a ≤ b`` and ``b ≤ c``, then ``a ≤ c`` (i.e., **transitivity**). * If ``a ≤ b`` and ``b ≤ a``, then ``a == b`` (i.e., **antisymmetry**). **Type hint wrappers are not totally ordered,** however. Like unordered sets, type hint wrappers do *not* satisfy **totality** (i.e., either ``a ≤ b`` or ``b ≤ a``, which is *not* necessarily the case for incommensurable type hint wrappers). Type hint wrappers are thus usable in algorithms and data structures requiring at most a partial ordering over their input. Examples -------- >>> from beartype.door import TypeHint >>> hint_a = TypeHint(Callable[[str], list]) >>> hint_b = TypeHint(Callable[Union[int, str], Sequence[Any]]) >>> hint_a <= hint_b True >>> hint_a > hint_b False >>> hint_a.is_subhint(hint_b) True >>> list(hint_b) [TypeHint(typing.Union[int, str]), TypeHint(typing.Sequence[typing.Any])] Attributes (Private) -------- _args : Tuple[object, ...] Tuple of the zero or more low-level child type hints subscripting (indexing) the low-level parent type hint wrapped by this wrapper. _hint : T Low-level type hint wrapped by this wrapper. _hint_sign : Optional[beartype._data.hint.pep.sign.datapepsigncls.HintSign] Either: * If this hint is PEP-compliant and thus uniquely identified by a :mod:`beartype`-specific sign, that sign. * If this hint is a simple class, ``None``. ''' # ..................{ INITIALIZERS }.................. def __init__(self, hint: T) -> None: ''' Initialize this type hint wrapper from the passed low-level type hint. Parameters ---------- hint : object Low-level type hint to be wrapped by this wrapper. ''' # Classify all passed parameters. Note that this type hint is guaranteed # to be a type hint by validation performed by this metaclass __init__() # method. self._hint = hint # Sign uniquely identifying this and that hint if any *OR* "None" self._hint_sign = get_hint_pep_sign_or_none(hint) # FIXME: This... is pretty wierd. I mean, I definitely get this part: # self._origin: type = get_hint_pep_origin_or_none(hint) # # Sure. That makes sense and is thus great. But the trailing " or hint" # confounds me a bit. For one thing, arbitrary type hints are definitely # *NOT* types and thus really *NOT* origin types. We probably just want # to reduce this to simply: # self._origin = get_hint_pep_origin_or_none(hint) # Origin class, that may or may not be subscripted. self._origin: type = get_hint_pep_origin_or_none(hint) or hint # type: ignore # Tuple of all low-level child type hints of this hint. self._args = self._make_args() # ..................{ DUNDERS }.................. def __hash__(self) -> int: ''' Hash of the low-level immutable type hint wrapped by this immutable wrapper. Defining this method satisfies the :class:`collections.abc.Hashable` abstract base class (ABC), enabling this wrapper to be used as in hashable containers (e.g., dictionaries, sets). ''' return hash(self._hint) def __repr__(self) -> str: ''' Machine-readable representation of this type hint wrapper. ''' return f'TypeHint({repr(self._hint)})' # ..................{ DUNDERS ~ compare : equals }.................. # Note that we intentionally avoid typing this method as returning # "Union[bool, NotImplementedType]". Why? Because mypy in particular has # epileptic fits about "NotImplementedType". This is *NOT* worth the agony! @method_cached_arg_by_id def __eq__(self, other: object) -> bool: ''' ``True`` only if the low-level type hint wrapped by this wrapper is semantically equivalent to the other low-level type hint wrapped by the passed wrapper. This tester is memoized for efficiency, as Python implicitly calls this dunder method on hashable-based container lookups (e.g., :meth:`dict.get`) expected to be ``O(1)`` fast. Parameters ---------- other : object Other type hint to be tested against this type hint. Returns ---------- bool ``True`` only if this type hint is equal to that other hint. ''' # If that object is *NOT* a type hint wrapper, defer to either: # * If the class of that object defines a similar __eq__() method # supporting the "TypeHint" API, that method. # * Else, Python's builtin C-based fallback equality comparator that # merely compares whether two objects are identical (i.e., share the # same object ID). if not isinstance(other, TypeHint): return NotImplemented # Else, that object is also a type hint wrapper. # Defer to the subclass-specific implementation of this test. return self._is_equal(other) def __ne__(self, other: object) -> bool: return not (self == other) # ..................{ DUNDERS ~ compare : rich }.................. def __le__(self, other: object) -> bool: '''Return true if self is a subhint of other.''' if not isinstance(other, TypeHint): return NotImplemented return self.is_subhint(other) def __lt__(self, other: object) -> bool: '''Return true if self is a strict subhint of other.''' if not isinstance(other, TypeHint): return NotImplemented return self.is_subhint(other) and self != other def __ge__(self, other: object) -> bool: '''Return true if self is a superhint of other.''' if not isinstance(other, TypeHint): return NotImplemented return self.is_superhint(other) def __gt__(self, other: object) -> bool: '''Return true if self is a strict superhint of other.''' if not isinstance(other, TypeHint): return NotImplemented return self.is_superhint(other) and self != other # ..................{ DUNDERS ~ iterable }.................. def __contains__(self, hint_child: 'TypeHint') -> bool: ''' ``True`` only if the low-level type hint wrapped by the passed **type hint wrapper** (i.e., :class:`TypeHint` instance) is a child type hint originally subscripting the low-level parent type hint wrapped by this :class:`TypeHint` instance. ''' # Sgt. Pepper's One-liners GitHub Club Band. return hint_child in self._args_wrapped_frozenset def __iter__(self) -> Iterable['TypeHint']: ''' Generator iteratively yielding all **children type hint wrappers** (i.e., :class:`TypeHint` instances wrapping all low-level child type hints originally subscripting the low-level parent type hint wrapped by this :class:`TypeHint` instance). Defining this method satisfies the :class:`collections.abc.Iterable` abstract base class (ABC). ''' # For those who are about to one-liner, we salute you. yield from self._args_wrapped_tuple # ..................{ DUNDERS ~ iterable : item }.................. # Inform static type-checkers of the one-to-one correspondence between the # type of the object subscripting an instance of this class with the type of # the object returned by that subscription. Note this constraint is strongly # inspired by this erudite StackOverflow answer: # https://stackoverflow.com/a/71183076/2809027 @overload def __getitem__(self, index: int) -> 'TypeHint': ... @overload def __getitem__(self, index: slice) -> Tuple['TypeHint', ...]: ... def __getitem__(self, index: CallableMethodGetitemArg) -> ( Union['TypeHint', Tuple['TypeHint', ...]]): ''' Either: * If the passed object is an integer, then this type hint wrapper was subscripted by either a positive 0-based absolute index or a negative -1-based relative index. In either case, this dunder method returns the **child type hint wrapper** (i.e., :class:`TypeHint` instance wrapping a low-level child type hint originally subscripting the low-level parent type hint wrapped by this :class:`TypeHint` instance) with the same index. * If the passed object is a slice, then this type hint wrapper was subscripted by a range of such indices. In this case, this dunder method returns a tuple of the zero or more child type hint wrappers with the same indices. Parameters ---------- index : Union[int, slice] Either: * Positive 0-based absolute index or negative -1-based relative index of the child type hint originally subscripting the parent type hint wrapped by this :class:`TypeHint` instance to be returned wrapped by a new :class:`TypeHint` instance. * Slice of such indices of the zero or more child type hints originally subscripting the parent type hint wrapped by this :class:`TypeHint` instance to be returned in a tuple of these child type hints wrapped by new :class:`TypeHint` instances. Returns ---------- Union['TypeHint', Tuple['TypeHint', ...]] Child type hint wrapper(s) at these ind(ex|ices), as detailed above. ''' # Defer validation of the correctness of the passed index or slice to # the low-level tuple.__getitem__() dunder method. Though we could (and # possibly should) perform that validation here, doing so is non-trivial # in the case of both a negative relative index *AND* a passed slice. # This trivial approach suffices for now. return self._args_wrapped_tuple[index] # ..................{ DUNDERS ~ iterable : sized }.................. #FIXME: Unit test us up, please. def __bool__(self) -> bool: ''' ``True`` only if the low-level parent type hint wrapped by this wrapper was subscripted by at least one child type hint. ''' # See __len__() for further commentary. return bool(self._args_wrapped_tuple) #FIXME: Unit test us up, please. def __len__(self) -> int: ''' Number of low-level child type hints subscripting the low-level parent type hint wrapped by this wrapper. Defining this method satisfies the :class:`collections.abc.Sized` abstract base class (ABC). ''' # Return the exact length of the same iterable returned by the # __iter__() dunder method rather than the possibly differing length of # the "self._args" tuple, for safety. Theoretically, these two iterables # should exactly coincide in length. Pragmatically, it's best to assume # nothing in the murky waters we swim in. return len(self._args_wrapped_tuple) # ..................{ PROPERTIES ~ read-only }.................. # Read-only properties intentionally defining *NO* corresponding setter. @property def hint(self) -> T: ''' **Original type hint** (i.e., low-level PEP-compliant type hint wrapped by this wrapper at :meth:`TypeHint.__init__` instantiation time). ''' # Q: Can one-liners solve all possible problems? A: Yes. return self._hint @property def is_ignorable(self) -> bool: ''' ``True`` only if this type hint is **ignorable** (i.e., conveys *no* meaningful semantics despite superficially appearing to do so). While one might expect the set of all ignorable type hints to be both finite and small, this set is actually **countably infinite** in size. Countably infinitely many type hints are ignorable. This includes: * :attr:`typing.Any`, by design. * :class:`object`, the root superclass of all types. Ergo, parameters and return values annotated as :class:`object` unconditionally match *all* objects under :func:`isinstance`-based type covariance and thus semantically reduce to unannotated parameters and return values. * The unsubscripted :attr:`typing.Optional` singleton, which semantically expands to the implicit ``Optional[Any]`` type hint under :pep:`484`. Since :pep:`484` also stipulates that all ``Optional[t]`` type hints semantically expand to ``Union[t, type(None)]`` type hints for arbitrary arguments ``t``, ``Optional[Any]`` semantically expands to merely ``Union[Any, type(None)]``. Since all unions subscripted by :attr:`typing.Any` semantically reduce to merely :attr:`typing.Any`, the unsubscripted :attr:`typing.Optional` singleton also reduces to merely :attr:`typing.Any`. This intentionally excludes the ``Optional[type(None)]`` type hint, which the :mod:`typing` module reduces to merely ``type(None)``. * The unsubscripted :attr:`typing.Union` singleton, which semantically reduces to :attr:`typing.Any` by the same argument. * Any subscription of :attr:`typing.Union` by one or more ignorable type hints. There exists a countably infinite number of such subscriptions, many of which are non-trivial to find by manual inspection. The ignorability of a union is a transitive property propagated "virally" from child to parent type hints. Consider: * ``Union[Any, bool, str]``. Since :attr:`typing.Any` is ignorable, this hint is trivially ignorable by manual inspection. * ``Union[str, List[int], NewType('MetaType', Annotated[object, 53])]``. Although several child type hints of this union are non-ignorable, the deeply nested :class:`object` child type hint is ignorable by the argument above. It transitively follows that the ``Annotated[object, 53]`` parent type hint subscripted by :class:`object`, the :attr:`typing.NewType` parent type hint aliased to ``Annotated[object, 53]``, *and* the entire union subscripted by that :attr:`typing.NewType` are themselves all ignorable as well. * Any subscription of :attr:`typing.Annotated` by one or more ignorable type hints. As with :attr:`typing.Union`, there exists a countably infinite number of such subscriptions. (See the prior item.) * The :class:`typing.Generic` and :class:`typing.Protocol` superclasses, both of which impose no constraints *in and of themselves.* Since all possible objects satisfy both superclasses. both superclasses are synonymous to the ignorable :class:`object` root superclass: e.g., .. code-block:: python >>> from typing as Protocol >>> isinstance(object(), Protocol) True >>> isinstance('wtfbro', Protocol) True >>> isinstance(0x696969, Protocol) True * Any subscription of either the :class:`typing.Generic` or :class:`typing.Protocol` superclasses, regardless of whether the child type hints subscripting those superclasses are ignorable or not. Subscripting a type that conveys no meaningful semantics continues to convey no meaningful semantics. For example, the type hints ``typing.Generic[typing.Any]`` and ``typing.Generic[str]`` are both equally ignorable – despite the :class:`str` class being otherwise unignorable in most type hinting contexts. * And frankly many more. And... *now we know why this tester exists.* This tester method is memoized for efficiency. Returns ---------- bool ``True`` only if this type hint is ignorable. ''' # Mechanic: Somebody set up us the bomb. return is_hint_ignorable(self._hint) # ..................{ CHECKERS }.................. def die_if_unbearable( self, # Mandatory flexible parameters. obj: object, # Optional keyword-only parameters. *, conf: BeartypeConf = BEARTYPE_CONF_DEFAULT, ) -> None: ''' Raise an exception if the passed arbitrary object violates this type hint under the passed beartype configuration. Parameters ---------- obj : object Arbitrary object to be tested against this hint. conf : BeartypeConf, optional **Beartype configuration** (i.e., self-caching dataclass encapsulating all settings configuring type-checking for the passed object). Defaults to ``BeartypeConf()``, the default ``O(1)`` constant-time configuration. Raises ---------- BeartypeDoorHintViolation If this object violates this hint. Examples ---------- >>> from beartype.door import TypeHint >>> TypeHint(list[str]).die_if_unbearable( ... ['And', 'what', 'rough', 'beast,'], ) >>> TypeHint(list[str]).die_if_unbearable( ... ['its', 'hour', 'come', 'round'], list[int]) beartype.roar.BeartypeDoorHintViolation: Object ['its', 'hour', 'come', 'round'] violates type hint list[int], as list index 0 item 'its' not instance of int. ''' # One-liner, one love, one heart. Let's get together and code alright. die_if_unbearable(obj=obj, hint=self._hint, conf=conf) #FIXME: Submit an upstream mypy issue. Since mypy correctly accepts our #comparable beartype.door.is_bearable() function, mypy should also #accept this equivalent method. mypy currently fails to do so with this #false positive: # error: Variable "beartype.door._cls.doorsuper.TypeHint.TypeGuard" is not # valid as a type # #Clearly, mypy fails to percolate the type variable "T" from our #pseudo-superclass "Generic[T]" onto this return annotation. *sigh* def is_bearable( self, # Mandatory flexible parameters. obj: object, # Optional keyword-only parameters. *, conf: BeartypeConf = BEARTYPE_CONF_DEFAULT, ) -> TypeGuard[T]: ''' ``True`` only if the passed arbitrary object satisfies this type hint under the passed beartype configuration. Parameters ---------- obj : object Arbitrary object to be tested against this hint. conf : BeartypeConf, optional **Beartype configuration** (i.e., self-caching dataclass encapsulating all settings configuring type-checking for the passed object). Defaults to ``BeartypeConf()``, the default ``O(1)`` constant-time configuration. Returns ---------- bool ``True`` only if this object satisfies this hint. Raises ---------- beartype.roar.BeartypeDecorHintForwardRefException If this hint contains one or more relative forward references, which this tester explicitly prohibits to improve both the efficiency and portability of calls to this tester. Examples ---------- >>> from beartype.door import TypeHint >>> TypeHint(list[str]).is_bearable(['Things', 'fall', 'apart;']) True >>> TypeHint(list[int]).is_bearable( ... ['the', 'centre', 'cannot', 'hold;']) False ''' # One-liners justify their own existence. return is_bearable(obj=obj, hint=self._hint, conf=conf) # ..................{ TESTERS ~ subhint }.................. # Note that the @method_cached_arg_by_id rather than @callable_cached # decorator is *ABSOLUTELY* required here. Why? Because the @callable_cached # decorator internally caches the passed "other" argument as the key of a # dictionary. Subsequent calls to this method when passed the same argument # lookup that "other" in that dictionary. Since dictionary lookups # implicitly call other.__eq__() to resolve key collisions *AND* since the # TypeHint.__eq__() method calls TypeHint.is_subhint(), infinite recursion! @method_cached_arg_by_id def is_subhint(self, other: 'TypeHint') -> bool: ''' ``True`` only if this type hint is a **subhint** of the passed type hint. This tester method is memoized for efficiency. Parameters ---------- other : TypeHint Other type hint to be tested against this type hint. Returns ---------- bool ``True`` only if this type hint is a subhint of that other hint. See Also ---------- :func:`beartype.door.is_subhint` Further details. ''' # If the passed object is *NOT* a type hint wrapper, raise an exception. die_unless_typehint(other) # Else, that object is a type hint wrapper. # If that other hint is the "typing.Any" catch-all (which, by # definition, is the superhint of *ALL* hints -- including "Any" # itself), this hint is necessarily a subhint of that hint. In this # case, return true. if other._hint is Any: return True # Else, that other hint is *NOT* the "typing.Any" catch-all. # Defer to the subclass-specific implementation of this test. return self._is_subhint(other) def is_superhint(self, other: 'TypeHint') -> bool: ''' ``True`` only if this type hint is a **superhint** of the passed type hint. This tester method is memoized for efficiency. Parameters ---------- other : TypeHint Other type hint to be tested against this type hint. Returns ---------- bool ``True`` only if this type hint is a superhint of that other hint. See Also ---------- :func:`beartype.door.is_subhint` Further details. ''' # If the passed object is *NOT* a type hint wrapper, raise an exception. die_unless_typehint(other) # Else, that object is a type hint wrapper. # Return true only if this hint is a superhint of the passed hint. return other.is_subhint(self) # ..................{ PRIVATE }.................. # Subclasses are encouraged to override these concrete methods defaulting to # general-purpose implementations suitable for most subclasses. # ..................{ PRIVATE ~ factories }.................. def _make_args(self) -> tuple: ''' Tuple of the zero or more low-level child type hints subscripting (indexing) the low-level parent type hint wrapped by this wrapper, which the :meth:`TypeHint.__init__` method assigns to the :attr:`_args` instance variable of this wrapper. Subclasses are advised to override this method to set the :attr:`_args` instance variable of this wrapper in a subclass-specific manner. ''' # We are the one-liner. We are the codebase. return get_hint_pep_args(self._hint) # ..................{ PRIVATE ~ testers }.................. def _is_equal(self, other: 'TypeHint') -> bool: ''' ``True`` only if the low-level type hint wrapped by this wrapper is semantically equivalent to the other low-level type hint wrapped by the passed wrapper. Subclasses are advised to override this method to implement the public :meth:`is_subhint` tester method (which internally defers to this private tester method) in a subclass-specific manner. Since the default implementation is guaranteed to suffice for *all* possible use cases, subclasses should override this method only for efficiency reasons; the default implementation calls the :meth:`is_subhint` method twice and is thus *not* necessarily the optimal implementation for subclasses. Notably, the default implementation exploits the well-known syllogism between two partially ordered items ``A`` and ``B``: * If ``A <= B`` and ``A >= B``, then ``A == B``. This private tester method is *not* memoized for efficiency, as the caller is guaranteed to be the public :meth:`__eq__` tester method, which is already memoized. Parameters ---------- other : TypeHint Other type hint to be tested against this type hint. Returns ---------- bool ``True`` only if this type hint is equal to that other hint. ''' # Return true only if both... # # Note that this conditional implements the trivial boolean syllogism # that we all know and adore: "If A <= B and B <= A, then A == B". return ( # This union is a subhint of that object. self.is_subhint(other) and # That object is a subhint of this union. other.is_subhint(self) ) def _is_subhint(self, other: 'TypeHint') -> bool: ''' ``True`` only if this type hint is a **subhint** of the passed type hint. Subclasses are advised to override this method to implement the public :meth:`is_subhint` tester method (which internally defers to this private tester method) in a subclass-specific manner. This private tester method is *not* memoized for efficiency, as the caller is guaranteed to be the public :meth:`is_subhint` tester method, which is already memoized. Parameters ---------- other : TypeHint Other type hint to be tested against this type hint. Returns ---------- bool ``True`` only if this type hint is a subhint of that other hint. See Also ---------- :func:`beartype.door.is_subhint` Further details. ''' # Return true only if this hint is a subhint of *ANY* branch of that # other hint. return any( self._is_le_branch(that_branch) for that_branch in other._branches) # ..................{ PRIVATE ~ properties : read-only }.................. # Read-only properties intentionally defining *NO* corresponding setter. @property # type: ignore @property_cached def _args_wrapped_tuple(self) -> Tuple['TypeHint', ...]: ''' Tuple of the zero or more high-level child **type hint wrappers** (i.e., :class:`TypeHint` instances) wrapping the low-level child type hints subscripting (indexing) the low-level parent type hint wrapped by this wrapper. This attribute is intentionally defined as a memoized property to minimize space and time consumption for use cases *not* accessing this attribute. ''' # One-liner, don't fail us now! return tuple(TypeHint(hint_child) for hint_child in self._args) @property # type: ignore @property_cached def _args_wrapped_frozenset(self) -> FrozenSet['TypeHint']: ''' Frozen set of the zero or more high-level child **type hint wrappers** (i.e., :class:`TypeHint` instances) wrapping the low-level child type hints subscripting (indexing) the low-level parent type hint wrapped by this wrapper. This attribute is intentionally defined as a memoized property to minimize space and time consumption for use cases *not* accessing this attribute. ''' return frozenset(self._args_wrapped_tuple) @property def _branches(self) -> Iterable['TypeHint']: """ Immutable iterable of all **branches** (i.e., high-level type hint wrappers encapsulating all low-level child type hints subscripting (indexing) the low-level parent type hint encapsulated by this high-level parent type hint wrappers if this is a union (and thus an instance of the :class:`UnionTypeHint` subclass) *or* the 1-tuple containing only this instance itself otherwise) of this type hint wrapper. This property enables the child type hints of :pep:`484`- and :pep:`604`-compliant unions (e.g., :attr:`typing.Union`, :attr:`typing.Optional`, and ``|``-delimited type objects) to be handled transparently *without* special cases in subclass implementations. """ # Default to returning the 1-tuple containing only this instance, as # *ALL* subclasses except "_HintTypeUnion" require this default. return (self,) # ..................{ PRIVATE ~ abstract }.................. # Subclasses *MUST* implement all of the following abstract methods. #FIXME: This implies our usage of "abc.ABC" above to be useless, which is #mostly fine. But let's remove all reference to "abc.ABC" above, please. # We intentionally avoid applying the @abstractmethod decorator here. Why? # Because doing so would cause static type checkers (e.g., mypy) to # incorrectly flag this class as abstract and thus *NOT* instantiable. In # fact, the magical __new__() method defined by this class enables this # otherwise abstract class to be safely instantiated as "TypeHint(hint)". def _is_le_branch(self, branch: 'TypeHint') -> bool: ''' ``True`` only if this partially ordered type hint is **compatible** with the passed branch of another partially ordered type hint passed to the parent call of the :meth:`__le__` dunder method. See Also ---------- :meth:`__le__` Further details. ''' raise NotImplementedError( # pragma: no cover 'Abstract method TypeHint._is_le_branch() undefined.') # ..................{ PRIVATE ~ abstract : property }.................. @property def _is_args_ignorable(self) -> bool: """ Flag that indicates this hint can be evaluating only using the origin. This is useful for parametrized type hints with no arguments or with :attr:`typing.Any`-type placeholder arguments (e.g., ``Tuple[Any, ...]``, ``Callable[..., Any]``). It's also useful in cases where a builtin type or abc.collection is used as a type hint (and has no sign). For example: .. code-block:: python >>> get_hint_pep_sign_or_none(tuple) None >>> get_hint_pep_sign_or_none(typing.Tuple) HintSignTuple In this case, using :attr:`_is_args_ignorable` allows us to us simplify the comparison. """ raise NotImplementedError( # pragma: no cover 'Abstract method TypeHint._is_args_ignorable() undefined.')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype Decidedly Object-Oriented Runtime-checking (DOOR) middle-men subclasses** (i.e., abstract subclasses of the object-oriented type hint class hierarchy simplifying the definition of concrete subclasses of this hierarchy). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from abc import abstractmethod from beartype.door._cls.doorsuper import TypeHint from beartype.roar import BeartypeDoorException from beartype.typing import ( Any, ) from beartype._util.cache.utilcachecall import ( property_cached, ) # ....................{ SUBCLASSES }.................... class _TypeHintSubscripted(TypeHint): ''' **Subscripted type hint wrapper** (i.e., high-level object encapsulating a low-level parent type hint subscripted (indexed) by one or more equally low-level children type hints). ''' # ..................{ PRIVATE ~ properties : concrete }.................. @property # type: ignore[misc] @property_cached def _is_args_ignorable(self) -> bool: ''' ``True`` only if all child type hints subscripting (indexing) this parent type hint are ignorable. Note that this property is *not* equivalent to the :meth:`is_ignorable` property. Although related, a non-ignorable parent type hint can trivially have ignorable child type hints (e.g., ``list[Any]``). ''' #FIXME: Kinda unsure about this. Above, we define "_origin" as: # self._origin: type = get_hint_pep_origin_or_none(hint) or hint # type: ignore # #That effectively reduces to: # self._origin: type = hint.__origin__ or hint # type: ignore #FIXME: Ideally, this should read: # return all( # hint_child.is_ignorable # for hint_child in self._args_wrapped_tuple # ) # #Sadly, that refactoring currently raises non-trivial test failures. #Let's investigate at a later time, please. return all( hint_child._origin is Any for hint_child in self._args_wrapped_tuple ) # ..................{ PRIVATE ~ testers }.................. def _is_le_branch(self, branch: TypeHint) -> bool: # If the other branch was *NOT* subscripted, we assume it was # subscripted by "Any" and simply check that the origins are compatible. if branch._is_args_ignorable: return issubclass(self._origin, branch._origin) # Else, the other branch was subscripted. return ( # That branch is also a type hint wrapper of the same concrete # subclass as this type hint wrapper *AND*... isinstance(branch, type(self)) and # The low-level unordered type hint encapsulated by this # high-level partially ordered type hint is a subclass of # The low-level unordered type hint encapsulated by the branch issubclass(self._origin, branch._origin) and # *AND* All child (argument) hints are subclasses of the # corresponding branch child hint all( self_child <= branch_child for self_child, branch_child in zip( self._args_wrapped_tuple, branch._args_wrapped_tuple ) ) ) # ....................{ SUBCLASSES ~ isinstanceable }.................... class _TypeHintOriginIsinstanceable(_TypeHintSubscripted): ''' **Isinstanceable type hint wrapper** (i.e., high-level object encapsulating a low-level parent type hint subscripted (indexed) by exactly one or more low-level child type hints originating from isinstanceable classes such that *all* objects satisfying those hints are instances of those class). ''' # ..................{ PRIVATE ~ properties }.................. @property @abstractmethod def _args_len_expected(self) -> int: ''' Number of child type hints that this instance of a concrete subclass of this abstract base class (ABC) is expected to be subscripted (indexed) by. ''' pass # ..................{ PRIVATE ~ factories }.................. def _make_args(self) -> tuple: # Tuple of the zero or more low-level child type hints subscripting # (indexing) the low-level parent type hint wrapped by this wrapper. args = super()._make_args() # If this hint was subscripted by an unexpected number of child hints... if len(args) != self._args_len_expected: #FIXME: This seems sensible, but currently provokes test failures. #Let's investigate further at a later time, please. # # If this hint was subscripted by *NO* parameters, comply with PEP # # 484 standards by silently pretending this hint was subscripted by # # the "typing.Any" fallback for all missing parameters. # if len(self._args) == 0: # return (Any,)*self._args_len_expected #FIXME: Consider raising a less ambiguous exception type, yo. #FIXME: Consider actually testing this. This *IS* technically #testable and should thus *NOT* be marked as "pragma: no cover". # In most cases it will be hard to reach this exception, since most # of the typing library's subscripted type hints will raise an # exception if constructed improperly. raise BeartypeDoorException( # pragma: no cover f'{type(self)} type must have {self._args_len_expected} ' f'argument(s), but got {len(args)}.' ) # Else, this hint was subscripted by the expected number of child hints. # Return these child hints. return args # ..................{ PRIVATE ~ testers }.................. # Note that this redefinition of the superclass _is_equal() method is # technically unnecessary, as that method is already sufficiently # general-purpose to suffice for *ALL* possible subclasses (including this # subclass). Nonetheless, we wrote this method first. More importantly, this # method is *SUBSTANTIALLY* faster than the superclass method. Although # efficiency is typically *NOT* a pressing concern for the DOOR API, # discarding faster working code would be senseless. def _is_equal(self, other: TypeHint) -> bool: # If *ALL* of the child type hints subscripting both of these parent # type hints are ignorable, return true only if these parent type hints # both originate from the same isinstanceable class. if self._is_args_ignorable and other._is_args_ignorable: return self._origin == other._origin # Else, one or more of the child type hints subscripting either of these # parent type hints are unignorable. # # If either... elif ( # These hints have differing signs *OR*... self._hint_sign is not other._hint_sign or # These hints have a differing number of child type hints... len(self._args_wrapped_tuple) != len(other._args_wrapped_tuple) ): # Then these hints are unequal. return False # Else, these hints share the same sign and number of child type hints. # Return true only if all child type hints of these hints are equal. return all( this_child == that_child #FIXME: Probably more efficient and maintainable to write this as: # for this_child in self # for that_child in other for this_child, that_child in zip( self._args_wrapped_tuple, other._args_wrapped_tuple) ) class _TypeHintOriginIsinstanceableArgs1(_TypeHintOriginIsinstanceable): ''' **1-argument isinstanceable type hint wrapper** (i.e., high-level object encapsulating a low-level parent type hint subscripted (indexed) by exactly one low-level child type hint originating from an isinstanceable class such that *all* objects satisfying that hint are instances of that class). ''' @property def _args_len_expected(self) -> int: return 1 class _TypeHintOriginIsinstanceableArgs2(_TypeHintOriginIsinstanceable): ''' **2-argument isinstanceable type hint wrapper** (i.e., high-level object encapsulating a low-level parent type hint subscripted (indexed) by exactly two low-level child type hints originating from isinstanceable classes such that *all* objects satisfying those hints are instances of those classes). ''' @property def _args_len_expected(self) -> int: return 2 class _TypeHintOriginIsinstanceableArgs3(_TypeHintOriginIsinstanceable): ''' **3-argument isinstanceable type hint wrapper** (i.e., high-level object encapsulating a low-level parent type hint subscripted (indexed) by exactly three low-level child type hints originating from isinstanceable classes such that *all* objects satisfying those hints are instances of those classes). ''' @property def _args_len_expected(self) -> int: return 3
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) union type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`-compliant :attr:`typing.Optional` and :attr:`typing.Union` type hints and :pep:`604`-compliant ``|``-delimited union type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsub import _TypeHintSubscripted from beartype.door._cls.doorsuper import TypeHint from beartype.typing import Iterable # ....................{ SUBCLASSES }.................... class UnionTypeHint(_TypeHintSubscripted): ''' **Union type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`-compliant :attr:`typing.Optional` or :attr:`typing.Union` type hint *or* :pep:`604`-compliant ``|``-delimited union type hint). ''' # ..................{ PRIVATE ~ properties }.................. @property def _branches(self) -> Iterable[TypeHint]: return self._args_wrapped_tuple # ..................{ PRIVATE ~ testers }.................. def _is_le_branch(self, branch: TypeHint) -> bool: raise NotImplementedError('UnionTypeHint._is_le_branch() unsupported.') # pragma: no cover def _is_subhint(self, other: TypeHint) -> bool: # Return true only if *EVERY* child type hint of this union is a subhint # of at least one other child type hint of the passed other union. # # Note that this test has O(n**2) time complexity. Although non-ideal, # this is also unavoidable. Thankfully, since most real-world unions are # subscripted by only a small number of child type hints, this is also # mostly ignorable in practice. return all( # For each child type hint subscripting this union... ( # If that other type hint is itself a union, true only if... any( # For at least one other child type hint subscripting that # other union, this child type hint is a subhint of that # other child type hint. this_branch.is_subhint(that_branch) for that_branch in other._branches ) if isinstance(other, UnionTypeHint) else # Else, that other type hint is *NOT* a union. In this case, # true only if this child type hint is a subhint of that other # type hint. # # Note that this is a common edge case. Examples include: # * "TypeHint(Union[...]) <= TypeHint(Any)". Although "Any" is # *NOT* a union, *ALL* unions are subhints of "Any". # * "TypeHint(Union[A, B]) <= TypeHint(Union[A])" where "A" is # the superclass of "B". Since Python reduces "Union[A]" to # just "A", this is exactly equivalent to the comparison # "TypeHint(Union[A, B]) <= TypeHint(A)". Although "A" is # *NOT* a union, this example clearly demonstrates that a # union may be a subhint of a non-union that is *NOT* "Any" -- # contrary to intuition. Examples include: # * "TypeHint(Union[int, bool]) <= TypeHint(Union[int])". this_branch.is_subhint(other) ) for this_branch in self._branches )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) literal type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`586`-compliant :attr:`typing.Literal` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsub import _TypeHintSubscripted from beartype.door._cls.doorsuper import TypeHint from beartype.typing import Tuple # ....................{ SUBCLASSES }.................... class LiteralTypeHint(_TypeHintSubscripted): ''' **Literal type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`586`-compliant :attr:`typing.Literal` type hint). ''' # ..................{ PRIVATE ~ properties }.................. @property def _args_wrapped_tuple(self) -> Tuple[TypeHint, ...]: # Return the empty tuple, thus presenting Literal type hints as having # *NO* child type hints. Why? Because the arguments subscripting a # Literal type hint are *NOT* generally PEP-compliant type hints and # thus *CANNOT* be safely wrapped by "TypeHint" instances. These # arguments are merely arbitrary values. # # Note that this property getter is intentionally *NOT* memoized with # @property_cached, as Python already efficiently guarantees the empty # tuple to be a singleton. return () @property def _is_args_ignorable(self) -> bool: return False # ..................{ PRIVATE ~ testers }.................. def _is_subhint(self, other: TypeHint) -> bool: # If the other hint is also a literal, return true only if the set of # all child hints subscripting this literal is a subset of the set of # all child hints subscripting that literal. if isinstance(other, LiteralTypeHint): return all( this_hint_child in other._args for this_hint_child in self._args ) # Else, the other hint is *NOT* also a literal. # # If the other hint is just an origin, check that *ALL* child hints # subscripting this literal are instances of that origin. elif other._is_args_ignorable: return all( isinstance(this_hint_child, other._origin) for this_hint_child in self._args ) # Else, the other hint is *NOT* just an origin. # Return true only if the type of each child hint subscripting this # literal is a subhint of the other hint. return all( TypeHint(type(this_hint_child)).is_subhint(other) for this_hint_child in self._args )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) annotated type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`593`-compliant :attr:`typing.Annotated` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsuper import TypeHint from beartype._util.cache.utilcachecall import callable_cached from beartype._util.hint.pep.proposal.utilpep593 import ( get_hint_pep593_metadata, get_hint_pep593_metahint, ) from contextlib import suppress # ....................{ SUBCLASSES }.................... class AnnotatedTypeHint(TypeHint): ''' **Annotated type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`593`-compliant :attr:`typing.Annotated` type hint). Attributes (Private) -------- _metadata : tuple[object] **Metadata** (i.e., tuple of zero or more arbitrary low-level caller-defined objects annotating this :attr:`typing.Annotated` type hint, equivalent to all remaining arguments subscripting this hint). _metahint_wrapper : TypeHint **Metahint wrapper** (i.e., :class:`TypeHint` instance wrapping the child type hint annotated by this parent :attr:`typing.Annotated` type hint, equivalent to the first argument subscripting this hint). ''' # ..................{ INITIALIZERS }.................. def __init__(self, hint: object) -> None: # Initialize our superclass. super().__init__(hint) # Tuple of the zero or more arbitrary caller-defined arguments following # the first argument subscripting this hint. self._metadata = get_hint_pep593_metadata(hint) # Wrapper wrapping the first argument subscripting this hint. self._metahint_wrapper = TypeHint(get_hint_pep593_metahint(hint)) # ..................{ PRIVATE ~ properties }.................. @property def _is_args_ignorable(self) -> bool: # since Annotated[] must be used with at least two arguments, we are # never just the origin of the metahint return False # ..................{ PRIVATE ~ testers }.................. def _is_equal(self, other: TypeHint) -> bool: return ( isinstance(other, AnnotatedTypeHint) and self._metahint_wrapper == other._metahint_wrapper and self._metadata == other._metadata ) def _is_le_branch(self, branch: TypeHint) -> bool: # If the other type is not annotated, we ignore annotations on this # one and just check that the metahint is a subhint of the other. # e.g. Annotated[t.List[int], 'meta'] <= List[int] if not isinstance(branch, AnnotatedTypeHint): return self._metahint_wrapper.is_subhint(branch) # Else, that hint is a "typing.Annotated[...]" type hint. If either... if ( # The child type hint annotated by this parent hint does not subhint # the child type hint annotated by that parent hint *OR*... self._metahint_wrapper > branch._metahint_wrapper or # These hints are annotated by a differing number of objects... len(self._metadata) != len(branch._metadata) ): # This hint *CANNOT* be a subhint of that hint. Return false. return False # Attempt to... # # Note that the following iteration performs equality comparisons on # arbitrary caller-defined objects. Since these comparisons may raise # arbitrary caller-defined exceptions, we silently squelch any such # exceptions that arise by returning false below instead. with suppress(Exception): # Return true only if these hints are annotated by equivalent # objects. We avoid testing for a subhint relation here (e.g., with # the "<=" operator), as arbitrary caller-defined objects are *MUCH* # more likely to define a relevant equality comparison than a # relevant less-than-or-equal-to comparison. return self._metadata == branch._metadata # Else, one or more objects annotating these hints are incomparable. So, # this hint *CANNOT* be a subhint of that hint. Return false. return False # pragma: no cover
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) type variable classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`-compliant :attr:`typing.TypeVar` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsuper import TypeHint from beartype.door._cls.pep.doorpep484604 import UnionTypeHint # from beartype.roar import BeartypeDoorPepUnsupportedException from beartype.typing import ( TYPE_CHECKING, Any, Tuple, TypeVar, ) from beartype._util.cache.utilcachecall import property_cached # ....................{ SUBCLASSES }.................... class TypeVarTypeHint(UnionTypeHint): ''' **Type variable wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`-compliant :attr:`typing.TypeVar` type hint). ''' # ..................{ STATIC }.................. # Squelch false negatives from static type checkers. if TYPE_CHECKING: _hint: TypeVar # ..................{ PRIVATE ~ methods }.................. @property # type: ignore[misc] @property_cached def _args_wrapped_tuple(self) -> Tuple[TypeHint, ...]: #FIXME: Support covariance and contravariance, please. We don't #particularly care about either at the moment. Moreover, runtime type #checkers were *NEVER* expected to support either -- although we #eventually intend to do so. For now, raising a fatal exception here #would seem to be extreme overkill. Doing nothing is (probably) better #than doing something reckless and wild. # # Human-readable string describing the variance of this type variable if # # any *OR* "None" otherwise (i.e., if this type variable is invariant). # variance_str = None # if self._hint.__covariant__: # variance_str = 'covariant' # elif self._hint.__contravariant__: # variance_str = 'contravariant' # # # If this type variable is variant, raise an exception. # if variance_str: # raise BeartypeDoorPepUnsupportedException( # f'Type hint {repr(self._hint)} ' # f'variance "{variance_str}" currently unsupported.' # ) # # Else, this type variable is invariant. # TypeVars may only be bound or constrained, but not both. The # difference between the two has semantic meaning for static type # checkers but relatively little meaning for us. Ultimately, we're only # concerned with the set of compatible types present in either the bound # or the constraints. So, we treat a type variable as a union of its # constraints or bound. See also: # https://docs.python.org/3/library/typing.html#typing.TypeVar # If this type variable is bounded, return the 1-tuple containing only # this wrapped bound. if self._hint.__bound__ is not None: return (TypeHint(self._hint.__bound__),) # Else, this type variable is unbounded. # # If this type variable is constrained, return the n-tuple containing # each of these wrapped constraints. elif self._hint.__constraints__: return tuple(TypeHint(t) for t in self._hint.__constraints__) # Else, this type variable is unconstrained. #FIXME: Consider globalizing this as a private constant for efficiency. # Return the 1-tuple containing only the wrapped catch-all "Any". Why? # Because an unconstrained, unbounded type variable is semantically # equivalent to a type variable bounded by "Any". return (TypeHint(Any),)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) new-type type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`-compliant :attr:`typing.NewType` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.pep.pep484.doorpep484class import ClassTypeHint from beartype._util.hint.pep.proposal.pep484.utilpep484newtype import ( get_hint_pep484_newtype_class) # ....................{ SUBCLASSES }.................... class NewTypeTypeHint(ClassTypeHint): ''' **New-type type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`-compliant :attr:`typing.NewType` type hint). ''' # ..................{ INITIALIZERS }.................. def __init__(self, hint: object) -> None: # Initialize the superclass with all passed parameters. super().__init__(hint) supertype = get_hint_pep484_newtype_class(hint) # We want to "create" an origin for this NewType that treats the newtype # as a subclass of its supertype. For example, if the hint is # "NewType("MyType", str)", then the origin should be # "class MyString(str): pass". try: # We create a literal subclass here, which would be non-ideal due to # explosive space and time consumption. Thankfully, however, # "TypeHint" wrappers are cached. Ergo, this subclass should only be # created and cached once per new-type. name = getattr(hint, '__name__', str(hint)) self._origin = type(name, (supertype,), {}) # Not all types are subclassable (e.g., "Any"). except TypeError: self._origin = supertype
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) class type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`-compliant type hints that are, in fact, simple classes). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsuper import TypeHint from beartype.typing import ( TYPE_CHECKING, Any, ) # ....................{ SUBCLASSES }.................... class ClassTypeHint(TypeHint): ''' **Class type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`-compliant type hint that is, in fact, a simple class). Caveats ---------- This wrapper also intentionally wraps :pep:`484`-compliant ``None`` type hints as the simple type of the ``None`` singleton, as :pep:`484` standardized the reduction of the former to the latter: When used in a type hint, the expression None is considered equivalent to type(None). Although a unique ``NoneTypeHint`` subclass of this class specific to the ``None`` singleton *could* be declared, doing so is substantially complicated by the fact that numerous PEP-compliant type hints internally elide ``None`` to the type of that singleton before the `beartype.door` API ever sees a distinction. Notably, this includes :pep:`484`-compliant unions subscripted by that singleton: e.g., .. code-block >>> from typing import Union >>> Union[str, None].__args__ (str, NoneType) ''' # ..................{ STATIC }.................. # Squelch false negatives from static type checkers. if TYPE_CHECKING: _hint: type # ..................{ PRIVATE ~ properties }.................. @property def _is_args_ignorable(self) -> bool: # Unconditionally return true, as simple classes are unsubscripted and # could thus be said to only have ignorable arguments. Look. Semantics. return True # ..................{ PRIVATE ~ methods }.................. def _is_le_branch(self, branch: TypeHint) -> bool: # Everything is a subclass of "Any". if branch._origin is Any: return True # "Any" is only a subclass of "Any". Furthermore, "Any" is unsuitable as # the first argument to issubclass() below. elif self._origin is Any: return False #FIXME: Actually, let's avoid the implicit numeric tower for now. #Explicit is better than implicit and we really strongly disagree with #this subsection of PEP 484, which does more real-world harm than good. # # Numeric tower: # # https://peps.python.org/pep-0484/#the-numeric-tower # if self._origin is float and branch._origin in {float, int}: # return True # if self._origin is complex and branch._origin in {complex, float, int}: # return True # Return true only if... return branch._is_args_ignorable and issubclass( self._origin, branch._origin)
#!/usr/bin/env python3 #--------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) callable type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`- and :pep:`585`-compliant ``Tuple[...]`` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsub import _TypeHintSubscripted from beartype.door._cls.doorsuper import TypeHint from beartype.typing import Any # ....................{ SUBCLASSES }.................... # FIXME: Document all public and private attributes of this class, please. class _TupleTypeHint(_TypeHintSubscripted): ''' **Tuple type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`- or :pep:`585`-compliant ``Tuple[...]`` type hint). Attributes (Private) -------- ''' # ..................{ INITIALIZERS }.................. def __init__(self, hint: object) -> None: #FIXME: Actually, it might be preferable to define two distinct #subclasses: #* "class _TypeHintTupleVariadic(_TypeHintSequence)", handling variadic # tuple type hints of the form "Tuple[T, ...]". #* "class _TypeHintTupleFixed(_TypeHintSubscripted)", handling # fixed-length tuple type hints. # #Why? Because variadic and fixed-length tuple type hints have *NOTHING* #semantically to do with one another. All they share is the common #prefix "Tuple". Aside from that, everything is dissimilar. Indeed, #most of the logic below (especially _is_le_branch(), which is kinda #cray-cray) would strongly benefit from separating this class into two #subclasses. # #Note that implementing this division will probably require generalizing #the TypeHint.__new__() method to support this division. # Initialize all subclass-specific instance variables for safety. self._is_variable_length: bool = False #FIXME: Non-ideal. The superclass __len__() method already returns 0 as #expected for "Tuple[()]" type hints. Excise us up! self._is_empty_tuple: bool = False # Initialize the superclass with all passed parameters. super().__init__(hint) def _make_args(self) -> tuple: # Tuple of the zero or more low-level child type hints subscripting # (indexing) the low-level parent type hint wrapped by this wrapper. args = super()._make_args() # Validate these child hints. Specifically, remove any # PEP-noncompliant child hints from this tuple and set associated flags. # # e.g. `Tuple` without any arguments # This may be unreachable (since a bare Tuple will go to ClassTypeHint), # but it's here for completeness and safety. if len(args) == 0: # pragma: no cover args = (Any,) self._is_variable_length = True #FIXME: This is non-portable and thus basically broken. Ideally, empty #tuples should instead be detected by explicitly calling the #is_hint_pep484585_tuple_empty() tester. elif len(args) == 1 and args[0] == (): args = () self._is_empty_tuple = True elif len(args) == 2 and args[1] is Ellipsis: args = (args[0],) self._is_variable_length = True # Return these child hints. return args # ..................{ PRIVATE ~ properties }.................. @property def _is_args_ignorable(self) -> bool: #FIXME: Actually, pretty sure this only returns true if this hint is #"Tuple[Any, ...]". *shrug* # Return true only if this hint is either "Tuple[Any, ...]" or the # unsubscripted "Tuple" type hint factory. return ( self._is_variable_length and bool(self) and self[0].is_ignorable ) # ..................{ PRIVATE ~ testers }.................. def _is_le_branch(self, branch: TypeHint) -> bool: if branch._is_args_ignorable: return issubclass(self._origin, branch._origin) elif not isinstance(branch, _TupleTypeHint): return False elif self._is_args_ignorable: return False elif branch._is_empty_tuple: return self._is_empty_tuple elif branch._is_variable_length: that_hint = branch._args_wrapped_tuple[0] if self._is_variable_length: return that_hint.is_subhint(self._args_wrapped_tuple[0]) return all( this_child.is_subhint(that_hint) for this_child in self._args_wrapped_tuple ) elif self._is_variable_length: return ( branch._is_variable_length and self._args_wrapped_tuple[0].is_subhint( branch._args_wrapped_tuple[0]) ) elif len(self._args) != len(branch._args): return False return all( this_child <= that_child for this_child, that_child in zip( self._args_wrapped_tuple, branch._args_wrapped_tuple ) )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Decidedly Object-Oriented Runtime-checking (DOOR) callable type hint classes** (i.e., :class:`beartype.door.TypeHint` subclasses implementing support for :pep:`484`- and :pep:`585`-compliant ``Callable[...]`` type hints). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype.door._cls.doorsub import _TypeHintSubscripted from beartype.door._cls.doorsuper import TypeHint from beartype.roar import BeartypeDoorPepUnsupportedException from beartype.typing import ( Any, Tuple, ) from beartype._data.hint.pep.sign.datapepsignset import ( HINT_SIGNS_CALLABLE_PARAMS) from beartype._util.cache.utilcachecall import property_cached from beartype._util.hint.pep.proposal.pep484585.utilpep484585callable import ( get_hint_pep484585_callable_params, get_hint_pep484585_callable_return, ) from beartype._util.hint.pep.utilpepget import get_hint_pep_sign_or_none # ....................{ SUBCLASSES }.................... # FIXME: Document all public and private attributes of this class, please. class CallableTypeHint(_TypeHintSubscripted): ''' **Callable type hint wrapper** (i.e., high-level object encapsulating a low-level :pep:`484`- or :pep:`585`-compliant ``Callable[...]`` type hint). Attributes (Private) -------- ''' # ..................{ INITIALIZERS }.................. def _make_args(self) -> tuple: # Tuple of the zero or more low-level child type hints subscripting # (indexing) the low-level parent type hint wrapped by this wrapper. args = super()._make_args() # Note that this branch may be literally unreachable, as an # unsubscripted "Callable" should already be implicitly handled by the # "ClassTypeHint" subclass. Nonetheless, this branch exists for safety. if len(args) == 0: # pragma: no cover args = (..., Any,) else: # Parameters type hint(s) subscripting this callable type hint. self._callable_params = get_hint_pep484585_callable_params( self._hint) #FIXME: Should we classify this hint as well? Contemplate us up. # Return type hint subscripting this callable type hint. callable_return = get_hint_pep484585_callable_return(self._hint) # If this hint was first subscripted by an ellipsis (i.e., "...") # signifying a callable accepting an arbitrary number of parameters # of arbitrary types, strip this ellipsis. The ellipsis is *NOT* a # PEP-compliant type hint in general and thus *CANNOT* be wrapped by # the "TypeHint" wrapper. if self._callable_params is Ellipsis: # e.g. `Callable[..., Any]` self._callable_params = () # Else... else: # Sign uniquely identifying this parameter list if any *OR* # "None" otherwise. hint_args_sign = get_hint_pep_sign_or_none( self._callable_params) # If this hint was first subscripted by a PEP 612-compliant # type hint, raise an exception. *sigh* if hint_args_sign in HINT_SIGNS_CALLABLE_PARAMS: raise BeartypeDoorPepUnsupportedException( f'Type hint {repr(self._hint)} ' f'PEP 612 child type hint ' f'{repr(self._callable_params)} ' f'currently unsupported.' ) # Else, this hint was *NOT* first subscripted by a PEP # 612-compliant type hint. #FIXME: Note this will fail if "self._callable_params" is a PEP #612-compliant "typing.ParamSpec(...)" or "typing.Concatenate[...]" #object, as neither are tuples and thus *NOT* addable here. #FIXME: *AFTER* resolving that issue, remove the trailing pragma #"# type: ignore[operator]" from the following line. # Recreate the tuple of child type hints subscripting this parent # callable type hint from the tuple of argument type hints # introspected above. Why? Because the latter is saner than the # former in edge cases (e.g., ellipsis, empty argument lists). args = self._callable_params + (callable_return,) # type: ignore[operator] # Return these child hints. return args # ..................{ PROPERTIES ~ bools }.................. # FIXME: Remove this by instead adding support for ignoring ignorable # callable type hints to our core is_hint_ignorable() tester. Specifically: # * Ignore "Callable[..., {hint_ignorable}]" type hints, where "..." is the # ellipsis singleton and "{hint_ignorable}" is any ignorable type hint. # This has to be handled in a deep manner by: # * Defining a new is_hint_pep484585_ignorable_or_none() tester in the # existing "utilpep484585" submodule, whose initial implementation tests # for *ONLY* ignorable callable type hints. # * Import that tester in the "utilpeptest" submodule. # * Add that tester to the "_IS_HINT_PEP_IGNORABLE_TESTERS" tuple. # * Add example ignorable callable type hints to our test suite's data. @property def is_ignorable(self) -> bool: # Callable[..., Any] (or just `Callable`) return self.is_params_ignorable and self.is_return_ignorable @property def is_params_ignorable(self) -> bool: # Callable[..., ???] return self._args[0] is Ellipsis @property def is_return_ignorable(self) -> bool: # Callable[???, Any] return self.return_hint.is_ignorable # ..................{ PROPERTIES ~ hints }.................. @property # type: ignore @property_cached def param_hints(self) -> Tuple[TypeHint, ...]: ''' Arguments portion of the callable. May be an empty tuple if the callable takes no arguments. ''' return self._args_wrapped_tuple[:-1] @property def return_hint(self) -> TypeHint: ''' Return type of the callable. ''' return self._args_wrapped_tuple[-1] # ..................{ PRIVATE ~ testers }.................. #FIXME: Internally comment us up, please. def _is_le_branch(self, branch: TypeHint) -> bool: # If the branch is not subscripted, then we assume it is subscripted # with ``Any``, and we simply check that the origins are compatible. if branch._is_args_ignorable: return issubclass(self._origin, branch._origin) if not isinstance(branch, CallableTypeHint): return False if not issubclass(self._origin, branch._origin): return False if not branch.is_params_ignorable and ( ( self.is_params_ignorable or len(self.param_hints) != len(branch.param_hints) or any( self_arg > branch_arg for self_arg, branch_arg in zip( self.param_hints, branch.param_hints) ) ) ): return False # FIXME: Insufficient, sadly. There are *MANY* different type hints that # are ignorable and thus semantically equivalent to "Any". It's likely # we should just reduce this to a one-liner resembling: # return self.return_hint <= branch.return_hint # # Are we missing something? We're probably missing something. *sigh* if not branch.is_return_ignorable: return ( False if self.is_return_ignorable else self.return_hint <= branch.return_hint ) return True
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. # # --------------------( SYNOPSIS )-------------------- # Configuration file for the Sphinx documentation builder. # # --------------------( SEE ALSO )-------------------- # * https://www.sphinx-doc.org/en/master/usage/configuration.html # List of all options supported in this file. # ....................{ TODO }.................... #FIXME: [EXTENSION] Add "sphinx-notfound-page" support to enable us to provide #a sane 404 page for non-existent pages. In fact, we already appear to have a #"404.rst" document. Well, isn't that noice. Because we can't be bothered to #configure this at the moment, note that: #* We've temporarily moved "404.rst" into the parent subdirectory, where it # has absolutely no effect (but at least does *NOT* induce fatal errors). #* We'll need to move "404.rst" back into this subdirectory first. # ....................{ IMPORTS ~ path }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # CAUTION: Avoid importing from *ANY* package or module other than those # provided by Python's standard library. Since Python's import path (i.e., # "sys.path") has yet to be properly established, imports from this project in # particular are likely to fail under common edge cases. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Preliminary imports from Python's standard library required to establish the # directory structure for this project. import sys from pathlib import Path # ....................{ PRIVATE ~ path }.................... # High-level "Path" object encapsulating the absolute dirname of the directory # containing the current Sphinx configuration file. # # Note that the comparable Path.absolute() method was neither documented nor # tested before Python 3.11. See also this relevant StackOverflow answer: # https://stackoverflow.com/a/44569249/2809027 # Dismantled, this is: # # * ".resolve(...)", creating and returning a new high-level "Path" # object canonicalizing the relative dirname with which the original "Path" # object was instantiated into an absolute dirname. # * "strict=True", raising a "FileNotFoundError" if this directory does *NOT* # exist. _DOC_SRC_DIR = Path(__file__).parent.resolve(strict=True) # High-level "Path" object encapsulating the absolute dirname of this project's # root directory, containing: # * The main directory implementing this project's Python package. # * The test directory implementing this project's pytest test suite. # * The documentation directory containing this configuration script. # * The ".git/" subdirectory if this is the live GitHub-based version. _ROOT_DIR = Path(_DOC_SRC_DIR / '../../').resolve(strict=True) # Expose this project's top-level package directory to Python and thus Sphinx. # Note that this is effectively required to avoid common edge cases. See also: # * https://samnicholls.net/2016/06/15/how-to-sphinx-readthedocs # The "Make autodoc actually work" is the canonical writeup on this kludge. sys.path.insert(0, str(_ROOT_DIR)) # print(f'sys.path (from "doc/source/conf.py"): {sys.path}') # ....................{ IMPORTS }.................... # Sphinx defaults to hardcoding version specifiers. Since this is insane, we # import our package-specific version specifier for reuse below. See also: # * https://protips.readthedocs.io/git-tag-version.html # "Inferring Release Number from Git Tags", detailing a clever one-liner # harvesting this specifier from the most recent git tag. from beartype.meta import ( AUTHORS, COPYRIGHT, NAME, SPHINX_THEME_NAME, VERSION, ) from beartype._util.mod.utilmodtest import is_module # from warnings import warn # ....................{ PRIVATE ~ path : more }.................... # High-level "Path" object encapsulating the absolute dirname of this project's # top-level package directory, raising a "FileNotFoundError" if this directory # does *NOT* exist. # # Note that this requires the "sys.path" global to be properly established above # and *MUST* thus be deferred until after that. _PACKAGE_DIR = (_ROOT_DIR / NAME).resolve(strict=True) # Relative filename of our URI repository (i.e., hidden reStructuredText (reST) # document defining common URI links in reST format, exposed to all other reST # documents via the "rst_epilog" setting below). _LINKS_FILENAME = str((_DOC_SRC_DIR / '_links.rst').resolve(strict=True)) # ....................{ CONSTANTS ~ sphinx }.................... # Sphinx-specific metadata programmatically published by this package. project = NAME author = AUTHORS copyright = COPYRIGHT release = VERSION version = VERSION # ....................{ SETTINGS }.................... # List of zero or more Sphinx-specific warning categories to be squelched (i.e., # suppressed, ignored). suppress_warnings = [ #FIXME: *THIS IS TERRIBLE.* Generally speaking, we do want Sphinx to inform #us about cross-referencing failures. Remove this hack entirely after Sphinx #resolves this open issue: # https://github.com/sphinx-doc/sphinx/issues/4961 # Squelch mostly ignorable warnings resembling: # WARNING: more than one target found for cross-reference 'TypeHint': # beartype.door._doorcls.TypeHint, beartype.door.TypeHint # # Sphinx currently emits *HUNDREDS* of these warnings against our # documentation. All of these warnings appear to be ignorable. Although we # could explicitly squelch *SOME* of these warnings by canonicalizing # relative to absolute references in docstrings, Sphinx emits still others # of these warnings when parsing PEP-compliant type hints via static # analysis. Since those hints are actual hints that *CANNOT* by definition # by canonicalized, our only recourse is to squelch warnings altogether. 'ref.python', ] # ....................{ SETTINGS ~ path }.................... # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of pathname patterns relative to this "doc/src/" subdirectory matching # all files and directories to be ignored when finding source files. Note this # list also affects the "html_static_path" and "html_extra_path" settings. exclude_patterns = [ # Ignore our URI repository, which magical logic below dynamically includes # on all pages through the classic "rst_epilog" trick. _LINKS_FILENAME, ] # ....................{ SETTINGS ~ rst }.................... # String of arbitrary reStructuredText (reST) to be implicitly appended to the # contents of *ALL* reST documents rendered by this configuration, initialized # to the empty string for safety. rst_epilog = '' # Append the contents of our URI repository file to this string, exposing the # common URI links centralized in this file to all other reST documents. # # See also this StackOverflow answer strongly inspiring this implementation: # https://stackoverflow.com/a/61694897/2809027 with open(_LINKS_FILENAME, encoding='utf-8') as links_file: rst_epilog += links_file.read() # ....................{ EXTENSIONS ~ mandatory }.................... # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ # ..................{ BUILTIN }.................. # Builtin extensions unconditionally available under *ALL* reasonably # modern versions of Sphinx uniquely prefixed by "sphinx.ext.". # Builtin extension automatically creating one explicit globally # cross-referenceable target "{/document/basename}:{section_title}" for each # section titled "{section_title}" of each document residing at # "{/document/basename}". By default, Sphinx requires targets to be manually # prepended before all sections to be cross-referenced elsewhere. *facepalm* 'sphinx.ext.autosectionlabel', # Builtin extension enabling attributes defined by the standard library # (e.g., the "typing" module, the "types.GenericAlias" type) to be # cross-referenced as a fallback when *NOT* already defined by this project. "sphinx.ext.intersphinx", # Builtin extension autogenerating reStructuredText documentation from # class, callable, and variable docstrings embedded in Python modules # formatted according to either NumPy or Google style. # # Note this effectively requires 'sphinx.ext.autodoc' to be listed as well. 'sphinx.ext.napoleon', # Builtin extension rendering "math::" directives into HTML-only JavaScript # via the third-party MathJax library. 'sphinx.ext.mathjax', # Builtin extension autogenerating reStructuredText documentation listing # each of this project's Python modules and linking external references to # those modules to these listings. 'sphinx.ext.viewcode', # ..................{ BUILTIN ~ autodoc }.................. #FIXME: We currently prefer "autoapi" (which avoids runtime imports and code #execution) to "autodoc" (which performs runtime imports and code #execution), but nonetheless preserve this for posterity. #FIXME: Almost certainly insufficient. Since this is Sphinx, the #"autodoc" extension requires additional non-trivial configuration. Note, #however, that the "autosummary" extension enabled below *SHOULD* automate #most of that configuration once its fully working. Ergo, avoid investing a #considerable amount of effort in "autodoc" itself. Try "autosummary"! # Builtin extension autogenerating reStructuredText documentation from # class, callable, and variable docstrings embedded in Python modules, # documenting this project's public (and optionally also private) API. # 'sphinx.ext.autodoc', #FIXME: How does this compare with "viewcode"? Are the two at all #comparable? Does merely one suffice? Research us up, please. #FIXME: Almost certainly insufficient. Since this is Sphinx, the #"autosummary" extension requires additional non-trivial configuration that #absolutely *SHOULD* come bundled with Sphinx but currently isn't for #nebulous reasons. See this StackOverflow answer for an exhaustive solution #requiring copying of third-party templates into our configuration: # https://stackoverflow.com/a/62613202/2809027 #Lastly, note that this issue may have been resolved by a bleeding-edge #Sphinx version by the time we finally resolve this. See also the end of: # https://github.com/sphinx-doc/sphinx/issues/7912 # # Builtin extension autosummarizing reStructuredText documentation # # autogenerated by the "autodoc" extension (listed above). By default, # # the "autodoc" extension fails to automatically structure (i.e., summarize # # with a single compact HTML markup tag) the documentation it generates. # 'sphinx.ext.autosummary', # ..................{ THIRD-PARTY }.................. # Third-party Sphinx extensions required to be externally installed. For # usability, this block should typically be empty. Third-party Sphinx # extensions should ideally be optionally enabled. See below. # Third-party "autoapi" Sphinx extension, an alternative to the builtin # "autodoc" Sphinx extension actively maintained by Read The Docs (RTD). # "autoapi" is strongly preferable to "autodoc" in the modern context, as: # * "autodoc" dynamically imports *ALL* Python modules to be documented and # thus executes *ALL* module-scoped code in those modules at documentation # time, significantly complicating documentation time in the event of # module-scoped code *NOT* expected to be executed at documentation time. # Conversely, "autoapi" simply statically parses the same modules and thus # entirely circumvents the arbitrary code execution "pain point." # * "autosummary" (another builtin Sphinx extension typically used to # conjunction with "autodoc" to generate table of contents (TOC) entries) # defaults to a silent noop; even when configured to generate non-empty # content, however, "autosummary" fails to document class- or # module-scoped attributes due to long-standing Sphinx limitations. # Conversely, "autoapi" generates usable TOC entries out-of-the-box with # *NO* configuration or kludges required. 'autoapi.extension', ] # ....................{ EXTENSIONS ~ optional }.................... # Third-party Sphinx extensions conditionally used if externally installed. # If the third-party Sphinx extension defining the custom HTML theme preferred # by this documentation is importable under the active Python interpreter, # enable this theme for substantially improved rendering. if is_module(SPHINX_THEME_NAME): # Set the HTML theme to this theme. # # Note that we intentionally do *NOT* do this, which other themes require: # Register the fully-qualified name of this extension. # extensions.append(SPHINX_THEME_NAME) # Why? Because doing so induces this exception from Furo: # Extension error (furo): # Handler <function _builder_inited at 0x7f9be7bf2040> for event # 'builder-inited' threw an exception (exception: Did you list 'furo' in # the `extensions` in conf.py? If so, please remove it. Furo does not # work with non-HTML builders and specifying it as an `html_theme` is # sufficient.) html_theme = SPHINX_THEME_NAME # Else, this theme is unavailable. In this case, fallback to Sphinx's default # HTML theme *AND*... else: #FIXME: Convert this back into a warning by calling warn() *AFTER* deciding #how to do so safely. The core issue is that we convert warnings into #failures during testing; ergo, we need to install the Python package #providing this theme during testing. We can't be bothered at the moment. # Emit a non-fatal warning informing end users of this fallback. print( ( 'WARNING: ' f'Optional Sphinx extension "{SPHINX_THEME_NAME}" not found; ' 'falling back to default Sphinx HTML theme.' ), ) # ....................{ EXTENSIONS ~ autodoc }.................... # "autoapi.extension"-specific settings. See also: # https://sphinx-autoapi.readthedocs.io/en/latest/reference/config.html # Machine-readable string identifying the software language to be documented. autoapi_type = 'python' # List of the relative or absolute dirnames of all input top-level package # directories to be recursively documented for this project. autoapi_dirs = [str(_PACKAGE_DIR)] # Relative dirname of the output subdirectory to add generated API documentation # files, relative to the subdirectory containing this file (i.e., "doc/src/"). autoapi_root = 'api' # Instruct "autoapi" to... autoapi_options = [ # Document public documented attributes of modules and classes. 'members', # Document undocumented attributes of modules and classes. *gulp* 'undoc-members', # Document dunder attributes of modules and classes. Although often # ignorable for documentation purposes, dunder attributes can be documented # with non-ignorable docstrings intended to be exposed as documentation. # This includes the public "beartype.door.TypeHint" class, whose # well-documented dunder methods benefit from exposure to users. 'special-members', # List all superclasses of classes. 'show-inheritance', # Include "autosummary" directives in generated module documentation. 'show-module-summary', # List attributes imported from the same package. 'imported-members', ] #FIXME: Uncomment as needed to debug local "autoapi" issues. # autoapi_keep_files = True #FIXME: Consider customizing "autoapi" templates at some point. For now, the #defaults suffice. See also this useful article on the subject: # https://bylr.info/articles/2022/05/10/api-doc-with-sphinx-autoapi/#setting-up-templates #See also the official How-To at: # https://sphinx-autoapi.readthedocs.io/en/latest/how_to.html#how-to-customise-layout-through-templates # ....................{ EXTENSIONS ~ autodoc }.................... # "sphinx.ext.autodoc"-specific settings. See also: # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html # Instruct "autodoc" to globally append type hints annotating callable # signatures to the parameters and returns they annotate in the content (i.e., # descriptions) of those callables. Note this requires Sphinx >= 4.1. # # Since the third-party "autoapi" extension implicitly supports this setting, we # intentionally define this setting despite *NOT* using "autodoc". autodoc_typehints = 'both' # ....................{ EXTENSIONS ~ autosectionlabel }.................... # 'sphinx.ext.autosectionlabel'-specific settings. See also: # https://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html # Instruct "autosectionlabel" to uniquify created targets by prefixing # section titles with document pathnames in these targets. By default, this # extension ambiguously creates targets as section titles; that simplistic # scheme fails when two or more documents share the same section titles, a # common use case that's effectively infeasible to prohibit. autosectionlabel_prefix_document = True # ....................{ EXTENSIONS ~ intersphinx }.................... # 'sphinx.ext.intersphinx'-specific settings. See also: # https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html # Dictionary mapping from the machine-readable name of each external project to # search for references to otherwise missing references in reStructuredText # (reST) documentation as a graceful fallback to a 2-tuple "(URI, inventory)", # where "inventory" is typically ignorable and thus "None" for our purposes. # # Note that the keys of this dictionary may be used to unambiguously reference # attributes of that external project in reST documentation: e.g., # # External link to Python's Comparison Manual. # external:python+ref:`comparison manual <comparisons>` intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), } # ....................{ EXTENSIONS ~ napoleon }.................... # 'sphinx.ext.napoleon'-specific settings. See also: # https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html # Force Napolean to *ONLY* parse docstrings in the NumPy format used by this # project. By default, Napolean attempts and often fails to permissively parse # docstrings in both Google and NumPy formats. napoleon_numpy_docstring = True napoleon_google_docstring = False # List of the names of all non-standard section headers (i.e., headers *NOT* # already supported out-of-the-box by Napoleon) embedded in docstrings # throughout this project. By default, Napolean silently ignores *ALL* content # in non-standard section headers. # # See also: # * This list of all standard section headers: # https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#docstring-sections napoleon_custom_sections = [ 'Caveats', 'Design', 'Motivation', 'Usage', ] #FIXME: Experiment with enabling these non-default settings as well. # napoleon_use_param = False # napoleon_use_ivar = True # ....................{ EXTENSIONS ~ pygments }.................... #FIXME: Uncomment as desired. Let's see how the defaults do first, please. # # Pygments style. # pygments_style = "autumn" # pygments_dark_style = "monokai" # ....................{ BUILD ~ html }.................... #FIXME: Define the "html_favicon" setting as well -- once we actually create a #favicon, of course. *sigh* # Relative filename or URL of a small image (i.e., no wider than 200px) to be # rendered in the upper left-hand corner of the sidebar for this theme. html_logo = 'https://raw.githubusercontent.com/beartype/beartype-assets/main/badge/bear-ified.svg' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # ....................{ BUILD ~ html : mathjax }.................... # URL to the top-level "MathJax.js" script providing MathJax. If unspecified, # the user *MUST* locally install MathJax. Note that MathJax is locally # installable under: # * Debian systems with: # $ sudo apt install libjs-mathjax # # See also: # * https://docs.mathjax.org/en/v2.7-latest/start.html # List of all third-party Content Delivery Networks (CDNs) officially hosting # MathJax assets. mathjax_path="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' :mod:`pytest` **global test configuration** (i.e., early-time configuration guaranteed to be run by :mod:`pytest` *after* passed command-line arguments are parsed). :mod:`pytest` implicitly imports *all* functionality defined by this module into *all* submodules of this subpackage. See Also ---------- https://github.com/pytest-dev/pytest-asyncio/blob/master/pytest_asyncio/plugin.py :mod:`pytest` plugin strongly inspiring this implementation. Despite its popularity,, pytest-asyncio is mostly unmaintained, poorly commented and documented, overly obfuscatory, has an extreme number of unresolved issues and unmerged pull requests, and just generally exhibits code smells. ''' # ....................{ TODO }.................... #FIXME: Consider refactoring the pytest_pyfunc_call() hook defined below into: #* A pull request against pytest itself. Pytest absolutely requires support for # asynchronous test functions. This is 2021, people. #* A new competing "pytest-async" plugin. This is substantially easier but less # ideal, as pytest *REALLY* both wants and needs this functionality. # ....................{ IMPORTS }.................... from asyncio import ( get_event_loop_policy, new_event_loop, set_event_loop, ) from functools import wraps from inspect import iscoroutinefunction from pytest import hookimpl from warnings import ( catch_warnings, simplefilter, ) # ....................{ HOOKS ~ configure }.................... @hookimpl(hookwrapper=True, tryfirst=True) def pytest_pyfunc_call(pyfuncitem: 'Function') -> None: ''' Hook wrapper called immediately *before* calling the passed test function. Specifically, this hook wrapper: * If this test function is synchronous (i.e., declared with ``def``), preserves this test function as is. * If this test function is asynchronous (i.e., declared with ``async def``), wraps this test function in a synchronous wrapper function synchronously running this test function under an event loop uniquely isolated to this test function. For safety, each asynchronous test function is run under a new event loop. This wrapper wraps all non-wrapper ``pytest_pyfunc_call()`` hooks and is hopefully called *before* all wrapper ``pytest_pyfunc_call()`` hooks. See also `the official pytest hook wrapper documentation <hook wrapper_>`__. Parameters ---------- pyfuncitem : Function :mod:`pytest` object encapsulating the test function to be run. .. _hook wrapper: https://docs.pytest.org/en/6.2.x/writing_plugins.html#hookwrapper-executing-around-other-hooks ''' # Test function to be called by this hook. test_func = pyfuncitem.obj # If this test function is an asynchronous coroutine function (i.e., # callable declared with "async def" containing *NO* "yield" # expressions)... # # Note that we intentionally prefer calling this well-tested tester of the # well-tested "inspect" module rather than our comparable # beartype._util.func.utilfunctest.is_func_coro() tester, which # is hopefully but *NOT* necessarily known to be working here. if iscoroutinefunction(test_func): @wraps(test_func) def test_func_synchronous(*args, **kwargs): ''' Closure synchronously calling the current asynchronous test coroutine function under a new event loop uniquely isolated to this coroutine. ''' # With a warning context manager... with catch_warnings(): # Ignore *ALL* deprecating warnings emitted by the # get_event_loop() function called below. For unknown reasons, # CPython 3.11 devs thought that emitting a "There is no current # event loop" warning (erroneously classified as a # "deprecation") was a wonderful idea. "asyncio" is arduous # enough to portably support as it is. Work with me here, guys! simplefilter('ignore', DeprecationWarning) # Current event loop for the current threading context if any # *OR* create a new event loop otherwise. Note that the # higher-level asyncio.get_event_loop() getter is intentionally # *NOT* called here, as Python 3.10 broke backward compatibility # by refactoring that getter to be an alias for the wildly # different asyncio.get_running_loop() getter, which *MUST* be # called only from within either an asynchronous callable or # running event loop. In either case, asyncio.get_running_loop() # and thus asyncio.get_event_loop() is useless in this context. # Instead, we call the lower-level # get_event_loop_policy().get_event_loop() getter -- which # asyncio.get_event_loop() used to wrap. *facepalm* # # This getter should ideally return "None" rather than creating # a new event loop without our permission if no loop has been # set. This getter instead does the latter, implying that this # closure will typically instantiate two event loops per # asynchronous coroutine test function: # * The first useless event loop implicitly created by this # get_event_loop() call. # * The second useful event loop explicitly created by the # subsequent new_event_loop() call. # # Since there exists *NO* other means of querying the current # event loop, we reluctantly bite the bullet and pay the piper. event_loop_old = get_event_loop_policy().get_event_loop() # Close this loop, regardless of whether the prior # get_event_loop() call just implicitly created this loop, # because the "asyncio" API offers *NO* means of differentiating # these two common edge cases. *double facepalm* event_loop_old.close() # New event loop isolated to this coroutine. # # Note that this event loop has yet to be set as the current event # loop for the current threading context. Explicit is better than # implicit. event_loop = new_event_loop() # Set this as the current event loop for this threading context. set_event_loop(event_loop) # Coroutine object produced by this asynchronous coroutine test # function. Technically, coroutine functions are *NOT* actually # coroutines; they're just syntactic sugar implemented as standard # synchronous functions dynamically creating and returning # asynchronous coroutine objects on each call. test_func_coroutine = test_func(*args, **kwargs) # Synchronously run a new asynchronous task implicitly scheduled to # run this coroutine, ignoring the value returned by this coroutine # (if any) while reraising any exception raised by this coroutine # up the call stack to pytest. event_loop.run_until_complete(test_func_coroutine) # Close this event loop. event_loop.close() # Replace this asynchronous coroutine test function with this # synchronous closure wrapping this test function. pyfuncitem.obj = test_func_synchronous # Perform this test by calling this test function. yield
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' :mod:`pytest` **context manager utilities.** ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from contextlib import ( AbstractContextManager, contextmanager, nullcontext, ) # ....................{ CONTEXTS }.................... noop_context_manager = nullcontext ''' **Noop context manager** (i.e., context manager trivially yielding the passed parameter if any *or* ``None`` otherwise). Parameters ---------- enter_result : object, optional Value to be yielded from this context manager. Defaults to ``None``. Returns ---------- AbstractContextManager Noop context manager. '''
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **:mod:`pytest` context manager utilities.** ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTERS }.................... def is_ci() -> bool: ''' ``True`` only if the active Python process is running under a remote continuous integration (CI) workflow. ''' # One-liners for a brighter, bolder, better future... today. return is_ci_github_actions() def is_ci_github_actions() -> bool: ''' ``True`` only if the active Python process is running under a GitHub Actions-based continuous integration (CI) workflow. ''' # Defer test-specific imports. from os import environ # Return true only if the current shell environment declares a GitHub # Actions-specific environment variable. return 'GITHUB_ACTIONS' in environ
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Hear beartype tests roar** as it handles errors and warnings. This submodule defines hierarchies of :mod:`beartype_test`-specific exceptions and warnings emitted by unit and functional tests and fixtures. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To avoid polluting the public module namespace, external attributes # should be locally imported at module scope *ONLY* under alternate private # names (e.g., "from argparse import ArgumentParser as _ArgumentParser" rather # than merely "from argparse import ArgumentParser"). #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from abc import ABCMeta as _ABCMeta from beartype.roar import BeartypeException from beartype._data.datatyping import TypeException from contextlib import contextmanager from pytest import raises # ....................{ CONTEXTS }.................... @contextmanager def raises_uncached(exception_cls: TypeException) -> 'ExceptionInfo': ''' Context manager validating that the block exercised by this manager raises a **cached exception** (i.e., whose message previously containing one or more instances of the magic :data:`beartype._util.error.utilerror.EXCEPTION_PLACEHOLDER` substring since replaced by the :func:`beartype._util.error.utilerror.reraise_exception_placeholder` function) of the passed type. Parameters ---------- exception_cls : str Type of cached exception expected to be raised by this block. Returns ---------- :class:`pytest.nodes.ExceptionInfo` :mod:`pytest`-specific object collecting metadata on the cached exception of this type raised by this block. See Also ---------- https://docs.pytest.org/en/stable/reference.html#pytest._code.ExceptionInfo Official :class:`pytest.nodes.ExceptionInfo` documentation. ''' # Defer test-specific imports. from beartype._util.error.utilerror import ( EXCEPTION_PLACEHOLDER) # Within a "pytest"-specific context manager validating this contextual # block to raise an exception of this type, perform the body of that block. with raises(exception_cls) as exception_info: yield exception_info # Exception message raised by the body of that block. exception_message = str(exception_info.value) # Assert this exception message does *NOT* contain this magic substring. assert EXCEPTION_PLACEHOLDER not in exception_message #FIXME: Inadvisable in the general case, but preserved for posterity. # Assert this exception message does *NOT* contain two concurrent spaces, # implying an upstream failure in substring concatenation. # assert ' ' not in exception_message # ....................{ SUPERCLASS }.................... class BeartypeTestException(BeartypeException, metaclass=_ABCMeta): ''' Abstract base class of all **beartype test exceptions.** Instances of subclasses of this exception are raised at test time from :mod:`beartype_test`-specific unit and functional tests and fixtures. ''' pass class BeartypeTestPathException(BeartypeTestException): ''' **Beartype test path exceptions.** This exception is raised at test time from callables and classes defined by the :mod:`beartype_test._util.path` subpackage. ''' pass class BeartypeTestMarkException(BeartypeTestException): ''' **Beartype test mark exceptions.** This exception is raised at test time from decorators defined by the :mod:`beartype_test._util.mark` subpackage. ''' pass
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **pathable utilities** (i.e., callables querying commands residing in the current ``${PATH}`` and hence executable by specifying merely their basename rather than either relative or absolute path). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from shutil import which # ....................{ TESTERS }.................... #FIXME: Unit test us up, please. def is_pathable(command_basename: str) -> bool: ''' ``True`` only if a **pathable** (i.e., external command with the passed basename corresponding to an executable file in the current ``${PATH}``) exists. Caveats ---------- For safety, avoid appending the passed basename by a platform-specific filetype -- especially, a Windows-specific filetype. On that platform, this function iteratively appends this basename by each filetype associated with executable files listed by the ``%PATHEXT%`` environment variable (e.g., ``.bat``, ``.cmd``, ``.com``, ``.exe``) until the resulting basename is that of an executable file in the current ``%PATH%``. Parameters ---------- command_basename : str Basename of the command to be searched for. Returns ---------- bool ``True`` only if this pathable exists. Raises ---------- BeartypeTestPathException If the passed string is *not* a basename (i.e., contains one or more directory separators). ''' assert isinstance(command_basename, str), ( f'{repr(command_basename)} not string.') # Defer test-specific imports. from beartype_test._util.path.pytpathname import die_unless_basename # If this string is *NOT* a pure basename, raise an exception. die_unless_basename(command_basename) # Return whether this command exists or not. return which(command_basename) is not None
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **external command exit status** (i.e., integer signifying whether a process terminated successfully or unsuccessfully) utilities. This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... # ....................{ CONSTANTS }.................... SUCCESS = 0 ''' Exit status signifying a process to have terminated successfully. ''' FAILURE_DEFAULT = 1 ''' Exit status typically signifying a process to have terminated prematurely with a fatal error. Although any exit status in the range ``[1, 255]`` signifies failure, this particular exit status is the most common and thus preferred default. ''' # ....................{ TESTERS }.................... def is_success(exit_status: int) -> bool: ''' ``True`` only if the passed exit status signifies success. ''' assert isinstance(exit_status, int), f'{exit_status} not integer.' return exit_status == SUCCESS def is_failure(exit_status: int) -> bool: ''' ``True`` only if the passed exit status signifies failure. ''' assert isinstance(exit_status, int), f'{exit_status} not integer.' return exit_status != SUCCESS
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **command runners** (i.e., callables running external commands as subprocesses of the active Python process). This private submodule is *not* intended for importation by downstream callers. Command Words Arguments ---------- Most runners accept a mandatory ``command_words`` parameter, a list of one or more shell words comprising this command whose: * Mandatory first item is either: * This command's absolute or relative path. * This command's basename, in which case the first command with that basename in the current ``${PATH}`` environment variable will be run. If no such command is found, an exception is raised. * Optional subsequent items are this command's arguments (in order). Note that these arguments are passed as is to a low-level system call rather than intprereted by a high-level shell (e.g., ``/bin/sh`` on POSIX-compatible platforms) and hence should *not* be shell-quoted. Indeed, shell quoting these arguments is likely to result in erroneous command behaviour. The principal exception to this heuristic are **GNU-style long value options** (i.e., ``--``-prefixed options accepting a ``=``-delimited value), whose values should either be: * Passed as a separate argument *without* being shell-quoted. * Concatenated to the current ``--``-prefixed argument delimited by ``=`` and shell-quoted. ``Popen()`` Keyword Arguments ---------- Most runners accept the same optional keyword arguments accepted by the :meth:`subprocess.Popen.__init__` constructor, including: * ``cwd``, the absolute path of the current working directory (CWD) from which this command is to be run. Defaults to the current CWD. **Unfortunately, note that this keyword argument appears to be erroneously ignored on numerous platforms (e.g., Windows XP).** For safety, a context manager temporarily changing the current directory should typically be leveraged instead. * ``timeout``, the maximum number of milliseconds this command is to be run for. Commands with execution time exceeding this timeout will be mercifully killed. Defaults to ``None``, in which case this command is run indefinitely. ''' # ....................{ IMPORTS }.................... from beartype.typing import ( Iterable, Mapping, Optional, Tuple, ) from collections.abc import ( Iterable as IterableABC, Mapping as MappingABC, ) from os import environ from subprocess import ( CalledProcessError, TimeoutExpired, call as subprocess_call, check_output as subprocess_check_output, run as subprocess_run, ) # ....................{ GLOBALS }.................... BUFFER_SIZE_DEFAULT = -1 ''' Default subprocess buffer size for the current platform (synonymous with the current :data:`io.DEFAULT_BUFFER_SIZE`) suitable for passing as the ``bufsize`` parameter accepted by :meth:`subprocess.Popen.__init__` method. ''' BUFFER_SIZE_NONE = 0 ''' Unbuffered subprocess buffer size suitable for passing as the ``bufsize`` parameter accepted by :meth:`subprocess.Popen.__init__` method. Both reading from and writing to an unbuffered subprocess is guaranteed to perform exactly one system call (``read()`` and ``write()``, respectively) and can return short (i.e., produce less bytes than the requested number of bytes). ''' BUFFER_SIZE_LINE = 1 ''' Line-buffered subprocess buffer size suitable for passing as the ``bufsize`` parameter accepted by :meth:`subprocess.Popen.__init__` method. Reading from a line-buffered subprocess is guaranteed to block until the subprocess emits a newline, at which point all output emitted between that newline inclusive and the prior newline exclusive is consumed. ''' # ....................{ PRIVATE ~ hints }.................... _HINT_COMMAND_WORDS = Iterable[str] ''' PEP-compliant type hint matching the ``command_words`` parameter passed to most callables declared by this submodule. ''' _HINT_POPEN_KWARGS = Mapping[str, object] ''' PEP-compliant type hint matching the return value of the private :func:`_init_popen_kwargs` function. ''' _HINT_POPEN_KWARGS_OPTIONAL = Optional[_HINT_POPEN_KWARGS] ''' PEP-compliant type hint matching the ``popen_kwargs`` parameter passed to most callables declared by this submodule. ''' # ....................{ RUNNERS ~ command }.................... #FIXME: Unit test us up, please. def run_command_forward_stderr_return_stdout( # Mandatory parameters. command_words: _HINT_COMMAND_WORDS, # Optional parameters. popen_kwargs: _HINT_POPEN_KWARGS_OPTIONAL = None, ) -> str: ''' Run the passed command as a subprocess of the active Python process, raising an exception on subprocess failure while both forwarding all standard error of this subprocess to the standard error file handle of the active Python process *and* capturing and returning all standard output of this subprocess. This exception contains the exit status of this subprocess. Parameters ---------- command_words : _HINT_COMMAND_WORDS Iterable of one or more shell words comprising this command. popen_kwargs : _HINT_POPEN_KWARGS_OPTIONAL Dictionary of all keyword arguments to be passed to the :meth:`subprocess.Popen.__init__` method. Defaults to ``None``, in which case the empty dictionary is assumed. Returns ---------- str All standard output captured from this subprocess, stripped of all trailing newlines (as under most POSIX shells) *and* decoded with the current locale's preferred encoding (e.g., UTF-8). Raises ---------- CalledProcessError If the subprocess running this command report non-zero exit status. ''' # Sanitize these arguments. popen_kwargs = _init_popen_kwargs(command_words, popen_kwargs) # Capture this command's stdout, raising an exception on command failure # (including failure due to an expired timeout). command_stdout = subprocess_check_output(command_words, **popen_kwargs) # Return this stdout, stripped of all trailing newlines. return command_stdout.rstrip('\n') #FIXME: Unit test us up, please. def run_command_forward_output( # Mandatory parameters. command_words: _HINT_COMMAND_WORDS, # Optional parameters. popen_kwargs: _HINT_POPEN_KWARGS_OPTIONAL = None, ) -> None: ''' Run the passed command as a subprocess of the active Python process, raising an exception on subprocess failure while forwarding all standard output and error output by this subprocess to the standard output and error file handles of the active Python process. This exception contains the exit status of this subprocess. Parameters ---------- command_words : _HINT_COMMAND_WORDS Iterable of one or more shell words comprising this command. popen_kwargs : _HINT_POPEN_KWARGS_OPTIONAL Dictionary of all keyword arguments to be passed to the :meth:`subprocess.Popen.__init__` method. Defaults to ``None``, in which case the empty dictionary is assumed. Raises ---------- CalledProcessError If the subprocess running this command report non-zero exit status. ''' # Defer test-specific imports. from beartype_test._util.cmd.pytcmdexit import is_failure # 0-based exit status reported by running this command. exit_status = run_command_forward_output_return_status( command_words=command_words, popen_kwargs=popen_kwargs) # If this command failed, raising an exception on command failure. For # reusability, we reimplement the subprocess.check_call() function here # rather than explicitly call that function. The latter approach would # require duplicating logic between this and the # run_command_forward_output_return_status() runner called above. if is_failure(exit_status): raise CalledProcessError(exit_status, command_words) #FIXME: Unit test us up, please. def run_command_forward_output_return_status( # Mandatory parameters. command_words: _HINT_COMMAND_WORDS, # Optional parameters. popen_kwargs: _HINT_POPEN_KWARGS_OPTIONAL = None ) -> int: ''' Run the passed command as a subprocess of the active Python process, returning only the exit status of this subprocess while forwarding all standard output and error output by this subprocess to the standard output and error file handles of the active Python process. Caveats ---------- **This function raises no exceptions on subprocess failure.** To do so, consider calling the :func:`run_command_forward_output` function instead. Parameters ---------- command_words : _HINT_COMMAND_WORDS Iterable of one or more shell words comprising this command. popen_kwargs : _HINT_POPEN_KWARGS_OPTIONAL Dictionary of all keyword arguments to be passed to the :meth:`subprocess.Popen.__init__` method. Defaults to ``None``, in which case the empty dictionary is assumed. Returns ---------- int Exit status returned by this subprocess. ''' # Defer test-specific imports. from beartype_test._util.cmd.pytcmdexit import FAILURE_DEFAULT # Sanitize these arguments. popen_kwargs = _init_popen_kwargs(command_words, popen_kwargs) # Run this command *WITHOUT* raising an exception on command failure. try: exit_status = subprocess_call(command_words, **popen_kwargs) # If this command failed to halt before triggering a timeout, the "timeout" # keyword argument was passed *AND* this command has effectively failed. # Since the prior call has already guaranteeably terminated this command, # this exception is safely convertible into default failure exit status. except TimeoutExpired: exit_status = FAILURE_DEFAULT # Return this exit status. return exit_status def run_command_return_stdout_stderr( # Mandatory parameters. command_words: _HINT_COMMAND_WORDS, # Optional parameters. popen_kwargs: _HINT_POPEN_KWARGS_OPTIONAL = None, ) -> Tuple[str, str]: ''' Run the passed command as a subprocess of the active Python process, raising an exception on subprocess failure while capturing and returning both all standard output and error of this subprocess. This exception contains the exit status of this subprocess. Parameters ---------- command_words : _HINT_COMMAND_WORDS Iterable of one or more shell words comprising this command. popen_kwargs : _HINT_POPEN_KWARGS_OPTIONAL Dictionary of all keyword arguments to be passed to the :meth:`subprocess.Popen.__init__` method. Defaults to ``None``, in which case the empty dictionary is assumed. Returns ---------- Tuple[str, str] All standard output and error (in that order) captured from this subprocess, stripped of all trailing newlines (as under most POSIX shells) *and* decoded with the current locale's preferred encoding (e.g., UTF-8). Raises ---------- CalledProcessError If the subprocess running this command reports non-zero exit status. ''' # If these keyword arguments are empty, default to the empty dictionary # *BEFORE* setting dictionary keys below. if popen_kwargs is None: popen_kwargs = {} # Enable capturing of both standard output and error. popen_kwargs['capture_output'] = True # Enable raising of a "CalledProcessError" exception when this command # reports non-zero exit status. popen_kwargs['check'] = True # Sanitize these arguments. popen_kwargs = _init_popen_kwargs(command_words, popen_kwargs) # "subprocess.CompletedProcess" object encapsulating the result of running # this command. command_result = subprocess_run(command_words, **popen_kwargs) # Standard output and error emitted by this command, stripped of all # trailing newlines. command_stdout = command_result.stdout.rstrip('\n') command_stderr = command_result.stderr.rstrip('\n') # Return this standard output and error. return command_stdout, command_stderr # ....................{ PRIVATE ~ constants }.................... _INIT_POPEN_KWARGS_POPEN_KWARGS_NAMES_CLOSE_FDS_CONFLICTING = frozenset(( 'stdin', 'stdout', 'stderr', 'close_fds')) ''' Frozen set of the names of all keyword parameters which if passed would prevent the :func:`_init_popen_kwargs` function from safely defaulting the ``close_fds`` parameter to false under **vanilla Microsoft Windows** (i.e., *not* running the Cygwin POSIX compatibility layer). See Also ---------- :func:`_init_popen_kwargs` Further details. ''' # ....................{ PRIVATE }.................... def _init_popen_kwargs( # Mandatory parameters. command_words: _HINT_COMMAND_WORDS, # Optional parameters. popen_kwargs: _HINT_POPEN_KWARGS_OPTIONAL = None ) -> _HINT_POPEN_KWARGS: ''' Sanitized dictionary of all keyword arguments to pass to the :class:`subprocess.Popen` callable when running the command specified by the passed shell words with the passed user-defined keyword arguments. Caveats ---------- If the current platform is vanilla Windows *and* none of the ``stdin``, ``stdout``, ``stderr``, or ``close_fds`` parameters are passed, this function defaults the ``close_fds`` parameter if unpassed to ``False``. Doing so causes this command to inherit all file handles (including stdin, stdout, and stderr) from the active Python process. Note that the :class:`subprocess.Popen` docstring insists that: On Windows, if ``close_fds`` is ``True`` then no handles will be inherited by the child process. The child process will then open new file handles for stdin, stdout, and stderr. If the current terminal is a Windows Console, the underlying terminal devices and hence file handles will remain the same, in which case this is *not* an issue. If the current terminal is Cygwin-based (e.g., MinTTY), however, the underlying terminal devices and hence file handles will differ, in which case this behaviour prevents interaction between the current shell and the vanilla Windows command to be run below. In particular, all output from this command will be squelched. If at least one of stdin, stdout, or stderr are redirected to a blocking pipe, setting ``close_fds`` to ``False`` can induce deadlocks under certain edge-case scenarios. Since all such file handles default to ``None`` and hence are *not* redirected in this case, ``close_fds`` may be safely set to ``False``. On all other platforms, if ``close_fds`` is ``True``, no file handles *except* stdin, stdout, and stderr will be inherited by the child process. This function fundamentally differs in subtle (and only slightly documented ways) between vanilla Windows and all other platforms. These discrepancies appear to be harmful but probably unavoidable, given the philosophical gulf between vanilla Windows and all other platforms. Parameters ---------- command_words : _HINT_COMMAND_WORDS Iterable of one or more shell words comprising this command. popen_kwargs : _HINT_POPEN_KWARGS_OPTIONAL Dictionary of all keyword arguments to be passed to the :meth:`subprocess.Popen.__init__` method. Defaults to ``None``, in which case the empty dictionary is assumed. Returns ---------- _HINT_POPEN_KWARGS This dictionary of keyword arguments sanitized. ''' # Defer test-specific imports. from beartype._util.kind.utilkinddict import is_mapping_keys_any from beartype._util.os.utilostest import is_os_windows_vanilla # If these keyword arguments are empty, default to the empty dictionary # *BEFORE* validating these arguments as a dictionary below. if popen_kwargs is None: popen_kwargs = {} # Validate these parameters *AFTER* defaulting them above if needed. assert isinstance(command_words, IterableABC), ( f'{repr(command_words)} not iterable.') assert bool(command_words), '"command_words" empty.' assert isinstance(popen_kwargs, MappingABC), ( f'{repr(popen_kwargs)} not mapping.') #FIXME: Uncomment if we ever feel like implementing this additional #validation. For the moment, we simply let lower-level functionality in the #stdlib do the dirty work for us. :p # If the first shell word is this list is unrunnable, raise an exception. # die_unless_command(command_words[0]) # Log the command to be run before doing so. # log_debug('Running command: %s', ' '.join(command_words)) # If this is vanilla Windows *AND* the caller passed no keyword arguments # that would prevent us from safely defaulting the "close_fds" parameter to # false, sanitize that parameter to false. if is_os_windows_vanilla() and not is_mapping_keys_any( mapping=popen_kwargs, keys=_INIT_POPEN_KWARGS_POPEN_KWARGS_NAMES_CLOSE_FDS_CONFLICTING, ): popen_kwargs['close_fds'] = False # Isolate the current set of environment variables to this command, # preventing concurrent changes in these variables in the active process # from affecting this command's subprocess. popen_kwargs['env'] = environ.copy() # Decode command output with the current locale's preferred encoding. popen_kwargs['universal_newlines'] = True # Return these keyword arguments. return popen_kwargs
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Test-specific **test suite paths** (i.e., :class:`pathlib.Path` instances encapsulating test-specific paths unique to this test suite). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from beartype.meta import PACKAGE_NAME from beartype._util.cache.utilcachecall import callable_cached from beartype_test._util.path.pytpathlib import ( DirRelative, FileRelative, ) from pathlib import Path # ....................{ GETTERS ~ dir }.................... @callable_cached def get_test_package_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **top-level test package** (i.e., directory providing this project's top-level test package containing at least an ``__init__.py`` file) if found *or* raise an exception otherwise. ''' # Avoid circular import dependencies. from beartype_test._util.path.pytpathmain import get_main_dir # Objectionable action! return DirRelative(get_main_dir(), f'{PACKAGE_NAME}_test') # ....................{ GETTERS ~ dir : func }.................... @callable_cached def get_test_func_subpackage_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **mid-level functional test subpackage** (i.e., directory providing all functional tests of this project's test suite) if found *or* raise an exception otherwise. ''' # Ostensible stencils! return DirRelative(get_test_package_dir(), 'a90_func') @callable_cached def get_test_func_data_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **mid-level functional test data directory** (i.e., directory providing sample data used throughout this project's functional tests) if found *or* raise an exception otherwise. ''' # Questionable destination! return DirRelative(get_test_func_subpackage_dir(), 'data') # ....................{ GETTERS ~ dir : func : lib }.................... @callable_cached def get_test_func_data_lib_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **mid-level third-party dependency functional test data directory** (i.e., directory providing sample data used throughout this project's functional tests exercising third-party dependencies) if found *or* raise an exception otherwise. ''' # Ejective bijection! return DirRelative(get_test_func_data_dir(), 'lib') @callable_cached def get_test_func_data_lib_nuitka_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **low-level nuitka functional test data directory** (i.e., directory providing sample code used throughout this project's :mod:`nuitka`-specific functional tests) if found *or* raise an exception otherwise. ''' # Nascent ascendency! return DirRelative(get_test_func_data_lib_dir(), 'nuitka') @callable_cached def get_test_func_data_lib_sphinx_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **low-level Sphinx functional test data directory** (i.e., directory providing sample data used throughout this project's :mod:`sphinx`-specific functional tests) if found *or* raise an exception otherwise. ''' # Flamboyant buoyancy! return DirRelative(get_test_func_data_lib_dir(), 'sphinx') # ....................{ GETTERS ~ file : func : lib }.................... @callable_cached def get_test_func_data_lib_nuitka_file() -> Path: ''' :mod:`Path` encapsulating the absolute filename of the **low-level nuitka functional test data file** (i.e., file providing sample code used throughout this project's :mod:`nuitka`-specific functional tests) if found *or* raise an exception otherwise. ''' # Ergastically eristic! return FileRelative( get_test_func_data_lib_nuitka_dir(), 'beartype_nuitka.py')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Testable path factories** (i.e., callables creating and returning :class:`pathlib.Path` instances encapsulating testing-specific paths). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from beartype_test._util.pytroar import BeartypeTestPathException from pathlib import Path # ....................{ RELATIVIZERS }.................... # These functions are explicitly camelcased to enable their future refactoring # into actual classes. def DirRelative(parent_dir: Path, relative_dirname: str) -> Path: ''' Concrete platform-agnostic :mod:`Path` object encapsulating the absolute dirname of a directory relative to the passed :mod:`Path` object encapsulating an arbitrary directory if found *or* raise an exception otherwise. Parameters ---------- parent_dir : Path :mod:`Path` encapsulating an arbitrary **parent directory** (i.e., directory containing the subdirectory to be returned). relative_dirname : str Relative dirname of this subdirectory relative to this parent directory. Returns ---------- Path :mod:`Path` directory relative to the passed :mod:`Path` directory. Raises ---------- BeartypeTestPathException If this path exists but is either: * *Not* a directory. * A directory *not* satisfying the expected filesystem structure. FileNotFoundError If this path does *not* exist. RuntimeError If this path exists but whose resolution to a physical path requires resolving one or more cyclic symbolic links inducing an infinite loop. ''' assert isinstance(parent_dir, Path), ( f'{repr(parent_dir)} not "pathlib.Path" object.') assert isinstance(relative_dirname, str), ( f'{repr(relative_dirname)} not string.') # Path encapsulating the relative dirname of this subdirectory relative to # this parent directory, which has yet to be validated. subdir_unresolved = parent_dir / relative_dirname # Canonicalize this relative dirname into an absolute dirname if this path # exists *OR* raise a "FileNotFoundError" or "RuntimeError" exception # otherwise. subdir = subdir_unresolved.resolve() # If this path is *NOT* a directory, raise an exception. if not subdir.is_dir(): raise BeartypeTestPathException(f'Directory "{subdir}" not found.') # Else, this path is a directory. # Return this directory. return subdir def FileRelative(parent_dir: Path, relative_filename: str) -> Path: ''' Concrete platform-agnostic :mod:`Path` object encapsulating the absolute filename of a file relative to the passed :mod:`Path` object encapsulating an arbitrary directory if found *or* raise an exception otherwise. Parameters ---------- parent_dir : Path :mod:`Path` encapsulating an arbitrary **parent directory** (i.e., directory containing the file to be returned). relative_filename : str Relative filename of this file relative to this parent directory. Returns ---------- Path :mod:`Path` file relative to the passed :mod:`Path` directory. Raises ---------- BeartypeTestPathException If this path exists but is either: * *Not* a directory. * A directory *not* satisfying the expected filesystem structure. FileNotFoundError If this path does *not* exist. RuntimeError If this path exists but whose resolution to a physical path requires resolving one or more cyclic symbolic links inducing an infinite loop. ''' assert isinstance(parent_dir, Path), ( f'{repr(parent_dir)} not "pathlib.Path" object.') assert isinstance(relative_filename, str), ( f'{repr(relative_filename)} not string.') # Path encapsulating the relative filename of this file relative to this # parent directory, which has yet to be validated. file_unresolved = parent_dir / relative_filename # Canonicalize this relative filename into an absolute filename if this # path exists *OR* raise a "FileNotFoundError" or "RuntimeError" exception # otherwise. file = file_unresolved.resolve() # If this path is *NOT* a file, raise an exception. if not file.is_file(): raise BeartypeTestPathException(f'File "{file}" not found.') # Else, this path is a file. # Return this file. return file
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **pathname utilities** (i.e., callables inspecting all categories of pathnames, including basenames, dirnames, filenames, and filetypes). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ IMPORTS }.................... from os.path import sep as DIRNAME_DELIMITER # ....................{ EXCEPTIONS ~ basename }.................... #FIXME: Unit test us up, please. def die_unless_basename(pathname: str) -> None: ''' Raise an exception unless the passed pathname is a **pure basename** (i.e., contains one or more directory separators). Parameters ---------- pathname : str Pathname to be validated. Raises ---------- beartype_test._util.pytroar.BeartypeTestPathException If this pathname is *not* a pure basename. See Also ---------- :func:`is_basename` Further details. ''' # Defer test-specific imports. from beartype_test._util.pytroar import BeartypeTestPathException # If this pathname is *NOT* a pure basename, raise an exception. if not is_basename(pathname): raise BeartypeTestPathException( f'Pathname "{pathname}" not pure basename ' f'(i.e., contains one or more "{DIRNAME_DELIMITER}" ' f'directory separator characters).' ) # ....................{ TESTERS ~ basename }.................... #FIXME: Unit test us up, please. def is_basename(pathname: str) -> bool: ''' ``True`` only if the passed pathname is a **pure basename** (i.e., contains no directory separators and hence no directory components). Parameters ---------- pathname : str Pathname to be tested. Returns ---------- bool ``True`` only if this pathname is a pure basename. ''' assert isinstance(pathname, str), f'{repr(pathname)} not string.' # One-liners justify college education. *OR DO THEY*!?!? return DIRNAME_DELIMITER not in pathname
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Test-specific **main codebase paths** (i.e., :class:`pathlib.Path` instances encapsulating test-agnostic paths applicable to the codebase being tested). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from beartype.meta import ( PACKAGE_NAME, PACKAGE_TEST_NAME, ) from beartype._util.cache.utilcachecall import callable_cached from beartype_test._util.path.pytpathlib import ( DirRelative, FileRelative, ) from pathlib import Path # ....................{ GETTERS ~ dir }.................... @callable_cached def get_main_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **top-level project directory** (i.e., directory containing both a ``.git/`` subdirectory and a subdirectory providing this project's package) if found *or* raise an exception otherwise. ''' # print(f'current module paths: {__package__} [{__file__}]') # Path encapsulating the current module. MODULE_FILE = Path(__file__) # Path encapsulating the current module's package. MODULE_PACKAGE_DIR = MODULE_FILE.parent # Path encapsulating the relative dirname of this project's directory # relative to the dirname of the package defining the current module. MAIN_DIR = DirRelative(MODULE_PACKAGE_DIR, '../../..') # If this project's directory either does not contain a "beartype_test" # subdirectory *OR* does but this path is not a directory, raise an # exception. This basic sanity check improves the likelihood that this # project directory is what we assume it is. # # Note that we intentionally avoid testing paths *NOT* bundled with release # tarballs (e.g., a root ".git/" directory), as doing so would prevent # external users and tooling from running tests from release tarballs. DirRelative(MAIN_DIR, PACKAGE_TEST_NAME) # Return this path. return MAIN_DIR @callable_cached def get_main_package_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **top-level project package** (i.e., directory providing this package's top-level package containing at least an ``__init__.py`` file) if found *or* raise an exception otherwise. ''' # Terrifying terseness! return DirRelative(get_main_dir(), PACKAGE_NAME) # ....................{ GETTERS ~ dir : sphinx }.................... @callable_cached def get_main_sphinx_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **top-level Sphinx documentation tree** (i.e., directory containing both the input and output subdirectories leveraged by Sphinx to build documentation for this project) if found *or* raise an exception otherwise. ''' # Immense propensity! return DirRelative(get_main_dir(), 'doc') @callable_cached def get_main_sphinx_source_dir() -> Path: ''' :mod:`Path` encapsulating the absolute dirname of the **source Sphinx documentation tree** (i.e., directory containing the input subdirectory leveraged by Sphinx to build documentation for this project) if found *or* raise an exception otherwise. ''' # Immense propensity! return DirRelative(get_main_sphinx_dir(), 'src') # ....................{ GETTERS ~ file }.................... @callable_cached def get_main_mypy_config_file() -> Path: ''' :mod:`Path` encapsulating the absolute filename of this project's **mypy configuration file** (i.e., top-level ``.mypy.ini`` file) if found *or* raise an exception otherwise. ''' # Obverse obviation! return FileRelative(get_main_dir(), 'mypy.ini') @callable_cached def get_main_readme_file() -> Path: ''' :mod:`Path` encapsulating the absolute filename of the **project readme file** (i.e., this project's front-facing ``README.rst`` file) if found *or* raise an exception otherwise. Note that the :meth:`Path.read_text` method of this object trivially yields the decoded plaintext contents of this file as a string. ''' # Perverse pomposity! return FileRelative(get_main_dir(), 'README.rst')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' :mod:`pytest` **test-marking decorators.** This submodule provides decorators *not* conditionally marking their decorated tests as either failed, parametrized, or skipped. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! import pytest from beartype_test._util.pytroar import BeartypeTestMarkException # ....................{ MARKS }.................... noop = pytest.mark.noop ''' Preserve the decorated test or test parameter as is with *no* modification. Caveats ---------- This decorator has the unintended side effect of also marking all tests and test parameters decorated by this decorated with the ``noop`` tag. This harmless albeit unfortunate side effect is the result of the :mod:`pytest.mark` API, which strictly requires that *all* decorators passed to the ``marks`` parameter of the :mod:`pytest.param` function be strictly generated by the :mod:`pytest.mark` API, which then imposes this seemingly arbitrary constraint. In other words, there's absolutely nothing to see here, folks. ''' # ....................{ IGNORERS }.................... def ignore_warnings(warning_cls: type) -> 'Callable': ''' Decorate the passed test to ignore all warnings subclassing the passed :class:`Warning` class. Caveats ---------- **This high-level decorator should always be called in lieu of the low-level** :func:`pytest.mark.filterwarnings` **decorator,** whose syntax is fragile, poorly documented, and likely to silently fail. Parameters ---------- warning_cls : type :class:`Warning` class to be ignored when running the decorated test. Returns ---------- Callable This test decorated to ignore all warnings of this class. Raises ---------- BeartypeTestMarkException If this object is either: * *Not* a class. * A class that is either *not* the builtin :class:`Warning` class or a subclass of that class. ''' # Defer test-specific imports. from beartype._util.utilobject import get_object_type_name # If this object is *NOT* a class, raise an exception. if not isinstance(warning_cls, type): raise BeartypeTestMarkException(f'{repr(warning_cls)} not type.') # Else, this object is a class. # # If this class is *NOT* a "Warning" subclass, raise an exception. if not issubclass(warning_cls, Warning): raise BeartypeTestMarkException( f'{repr(warning_cls)} not {repr(Warning)} subclass.') # Else, this class is a "Warning" subclass. # Fully-qualified name of this class. warning_classname = get_object_type_name(warning_cls) # Return the low-level pytest mark decorator ignoring all warnings of this # "Warning" subclass with a filter adhering to Python's peculiar warning # filter syntax. See also: # https://docs.python.org/3/library/warnings.html#describing-warning-filters return pytest.mark.filterwarnings(f'ignore::{warning_classname}')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' :mod:`pytest` **test-skipping decorators.** This submodule provides decorators conditionally marking their decorated tests as skipped depending on whether the conditions signified by the passed parameters are satisfied (e.g., the importability of the passed module name). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! import pytest, sys from collections.abc import ( Mapping, Sequence, ) from types import FunctionType from typing import ( Optional, Type, ) # Sadly, the following imports require private modules and packages. from _pytest.runner import Skipped # ....................{ GLOBALS ~ constants }.................... _PYTHON_VERSION_TUPLE = sys.version_info[:3] ''' Machine-readable version of the active Python interpreter as a tuple of integers. See Also ---------- :mod:`beartype.meta` Similar logic performed at :mod:`beartype` importation time. ''' _PYTHON_VERSION_STR = '.'.join( str(version_part) for version_part in sys.version_info[:3]) ''' Human-readable version of the active Python interpreter as a dot-delimited string. See Also ---------- :mod:`beartype.meta` Similar logic performed at :mod:`beartype` importation time. ''' # ....................{ SKIP }.................... skip_if = pytest.mark.skipif ''' Conditionally skip the decorated test or fixture with the passed human-readable justification if the passed boolean is ``False``. Parameters ---------- boolean : bool Boolean to be tested. reason : str Human-readable message justifying the skipping of this test or fixture. ''' def skip(reason: str): ''' Unconditionally skip the decorated test with the passed human-readable justification. This decorator is intended to be called both directly as a function *and* indirectly as a decorator, which differs from both: * :func:`pytest.skip`, intended to be called only directly as a function. Attempting to call that function indirectly as a decorator produces extraneous ignorable messages on standard output resembling ``"SKIP [1] beartype_test/unit/test_import.py:66: could not import 'xdist'"``, for unknown (and probably uninteresting) reasons. * :func:`pytest.mark.skip`, intended to be called only indirectly as a decorator. Attempting to call that decorator directly as a function reduces to a noop, for unknown (and probably uninteresting) reasons. Parameters ---------- reason : str Human-readable message justifying the skipping of this test. Returns ---------- pytest.skipif Decorator skipping the decorated test with this justification. ''' assert isinstance(reason, str), f'{repr(reason)} not string.' return skip_if(True, reason=reason) # ....................{ SKIP ~ command }.................... def skip_unless_pathable(command_basename: str): ''' Skip the decorated test or fixture unless the passed **pathable** (i.e., executable command with the passed basename residing in the current ``${PATH}``) exists on the local filesystem. Parameters ---------- command_basename : str Basename of the command to be searched for. Returns ---------- pytest.skipif Decorator describing these requirements if unmet *or* the identity decorator reducing to a noop otherwise. ''' # Defer heavyweight imports. from beartype_test._util.cmd.pytcmdpath import is_pathable # Skip this test if *NO* command with this basename resides in the ${PATH}. return skip_if( not is_pathable(command_basename), reason=f'Command "{command_basename}" not found.' ) # ....................{ SKIP ~ host }.................... def skip_if_ci(): ''' Skip the decorated test or fixture if the active Python interpreter is running under a remote continuous integration (CI) workflow. Returns ---------- pytest.skipif Decorator skipping this text or fixture if this interpreter is CI-hosted *or* the identity decorator reducing to a noop otherwise. ''' # Defer heavyweight imports. from beartype_test._util.pytci import is_ci # Skip this test if the active Python interpreter is CI-hosted. return skip_if(is_ci(), reason='Incompatible with CI workflows.') # ....................{ SKIP ~ os }.................... def skip_unless_os_linux(): ''' Skip the decorated test or fixture unless the active Python interpreter is running under a Linux distribution. Equivalently, skip the decorated test or fixture if this interpreter is running under either Microsoft Windows *or* Apple macOS. Returns ---------- pytest.skipif Decorator skipping this text or fixture unless this interpreter is running under a Linux distribution *or* the identity decorator reducing to a noop otherwise. ''' # Defer heavyweight imports. from beartype._util.os.utilostest import is_os_linux # Skip this test unless the current platform is Linux return skip_if(not is_os_linux(), reason='OS not Linux.') # ....................{ SKIP ~ pep }.................... #FIXME: Currently unused, but preserved in the likelihood of us requiring #similar PEP-specific conditionality at some point. # def skip_unless_pep544(): # ''' # Skip the decorated test or fixture unless the active Python interpreter # supports :pep:`544` via the :class:`beartype.typing.Protocol` superclass. # # Specifically, this decorator skips this text or function unless this # interpreter targets: # # * Python >= 3.8, which unconditionally supports :pep:`544`. # * Python 3.7 *and* the third-party :mod:`typing_extensions` module is # importable, in which case the :class:`beartype.typing.Protocol` # superclass is a Python 3.7-compatible backport. # # Returns # ---------- # pytest.skipif # Decorator skipping this text or fixture if this interpreter is PyPy # *or* the identity decorator reducing to a noop otherwise. # ''' # # # Avoid circular import dependencies. # from beartype._util.py.utilpyversion import ( # IS_PYTHON_3_7, # IS_PYTHON_AT_LEAST_3_8, # ) # from beartype_test._util.mod.pytmodtest import is_package_typing_extensions # # # True only if the active Python interpreter supports PEP 544. See the # # decorator docstring for further details. # IS_PEP_544 = ( # IS_PYTHON_AT_LEAST_3_8 or ( # IS_PYTHON_3_7 and is_package_typing_extensions() # ) # ) # # print(f'IS_PEP_544: {IS_PEP_544}') # # print(f'IS_PYTHON_3_7: {IS_PYTHON_3_7}') # # print(f'te: {is_package_typing_extensions()}') # # # Skip this test unless the active Python interpreter supports PEP 544. # return skip_if( # not IS_PEP_544, # reason=f'Python {_PYTHON_VERSION_STR} lacks PEP 544 support.', # ) # ....................{ SKIP ~ py }.................... def skip_if_pypy(): ''' Skip the decorated test or fixture if the active Python interpreter is the PyPy, a third-party implementation emphasizing Just In Time (JIT) bytecode optimization. Returns ---------- pytest.skipif Decorator skipping this text or fixture if this interpreter is PyPy *or* the identity decorator reducing to a noop otherwise. ''' # Defer test-specific imports. from beartype._util.py.utilpyinterpreter import is_py_pypy # Skip this test if the active Python interpreter is PyPy. return skip_if(is_py_pypy(), reason='Incompatible with PyPy.') def skip_if_python_version_greater_than_or_equal_to(version: str): ''' Skip the decorated test or fixture if the version of the active Python interpreter is strictly greater than or equal to the passed maximum version. Parameters ---------- version : str Maximum version of the Python interpreter required by this test or fixture as a dot-delimited string (e.g., ``3.5.0``). Returns ---------- pytest.skipif Decorator describing these requirements if unmet *or* the identity decorator reducing to a noop otherwise. See Also ---------- :mod:`beartype.meta` Similar logic performed at :mod:`beartype` importation time. ''' assert isinstance(version, str), f'{repr(version)} not string.' # Defer test-specific imports. from beartype.meta import _convert_version_str_to_tuple # Machine-readable required version of Python as a tuple of integers. version_tuple = _convert_version_str_to_tuple(version) # Skip this test if the current Python version exceeds this requirement. return skip_if( _PYTHON_VERSION_TUPLE >= version_tuple, reason=f'Python {_PYTHON_VERSION_STR} >= {version}.' ) def skip_if_python_version_less_than(version: str): ''' Skip the decorated test or fixture if the version of the active Python interpreter is strictly less than the passed minimum version. Parameters ---------- version : str Minimum version of the Python interpreter required by this test or fixture as a dot-delimited string (e.g., ``3.5.0``). Returns ---------- pytest.skipif Decorator describing these requirements if unmet *or* the identity decorator reducing to a noop otherwise. See Also ---------- :mod:`beartype.meta` Similar logic performed at :mod:`beartype` importation time. ''' assert isinstance(version, str), f'{repr(version)} not string.' # Defer test-specific imports. from beartype.meta import _convert_version_str_to_tuple # Machine-readable required version of Python as a tuple of integers. version_tuple = _convert_version_str_to_tuple(version) # Skip this test if the current Python version is less than this # requirement. return skip_if( _PYTHON_VERSION_TUPLE < version_tuple, reason=f'Python {_PYTHON_VERSION_STR} < {version}.' ) # ....................{ SKIP ~ py : module }.................... def skip_unless_package( package_name: str, minimum_version: Optional[str] = None): ''' Skip the decorated test or fixture if the package with the passed name is **unsatisfied** (i.e., either dynamically unimportable *or* importable but of a version less than the passed minimum version if non-``None``). Parameters ---------- package_name : str Fully-qualified name of the package to be skipped. minimum_version : Optional[str] Optional minimum version of this package as a dot-delimited string (e.g., ``0.4.0``) to be tested for if any *or* ``None`` otherwise, in which case any version is acceptable. Defaults to ``None``. Returns ---------- pytest.skipif Decorator describing these requirements if unmet *or* the identity decorator reducing to a noop otherwise. ''' assert isinstance(package_name, str), ( f'{repr(package_name)} not string.') # Skip the decorated test or fixture unless the requisite dunder submodule # declared by this package satisfies these requirements. return skip_unless_module( module_name=f'{package_name}.__init__', minimum_version=minimum_version, ) def skip_unless_module( module_name: str, minimum_version: Optional[str] = None): ''' Skip the decorated test or fixture if the module with the passed name is **unsatisfied** (i.e., either dynamically unimportable *or* importable but of a version less than the passed minimum version if non-``None``). Caveats ---------- **This decorator should never be passed the fully-qualified name of a package.** Consider calling the :func:`skip_unless_package` decorator instead to skip unsatisfied packages. Calling this decorator with package names guarantees those packages to be skipped, as packages are *not* directly importable as modules. Parameters ---------- module_name : str Fully-qualified name of the module to be skipped. minimum_version : Optional[str] Optional minimum version of this module as a dot-delimited string (e.g., ``0.4.0``) to be tested for if any *or* ``None`` otherwise, in which case any version is acceptable. Defaults to ``None``. Returns ---------- pytest.skipif Decorator describing these requirements if unmet *or* the identity decorator reducing to a noop otherwise. ''' assert isinstance(module_name, str), ( f'{repr(module_name)} not string.') assert isinstance(minimum_version, (str, type(None))), ( f'{repr(minimum_version)} neither string nor "None".') return _skip_if_callable_raises_exception( exception_type=Skipped, func=pytest.importorskip, args=(module_name, minimum_version), ) # ....................{ SKIP ~ private }.................... def _skip_if_callable_raises_exception( # Mandatory parameters. exception_type: Type[BaseException], func: FunctionType, # Optional parameters. args: Optional[Sequence] = None, kwargs: Optional[Mapping] = None, ): ''' Skip the decorated test or fixture if calling the passed callable with the passed positional and keyword arguments raises an exception of the passed type. Specifically, if calling this callable raises: * The passed type of exception, this test is marked as skipped. * Any other type of exception, this test is marked as a failure. * No exception, this test continues as expected. Parameters ---------- exception_type : Type[BaseException] Type of exception expected to be raised by this callable. func : FunctionType Callable to be called. args : Optional[Sequence] Sequence of all positional arguments to unconditionally pass to the passed callable if any *or* ``None`` otherwise. Defaults to ``None``. kwargs : Optional[Mapping] Mapping of all keyword arguments to unconditionally pass to the passed callable if any *or* ``None`` otherwise. Defaults to ``None``. Returns ---------- pytest.skipif Decorator skipping this test if this callable raises this exception *or* the identity decorator reducing to a noop otherwise. ''' # Avoid circular import dependencies. from beartype_test._util.mark.pytmark import noop # Default all unpassed arguments to sane values. if args is None: args = () if kwargs is None: kwargs = {} # Validate *AFTER* defaulting these arguments. assert isinstance(exception_type, type), ( f'{repr((exception_type))} not type.') assert callable(func), f'{repr(func)} uncallable.' assert isinstance(args, Sequence), f'{repr(args)} not sequence.' assert isinstance(kwargs, Mapping), f'{repr(kwargs)} not mapping.' # Attempt to call this callable with these arguments. try: func(*args, **kwargs) # If this callable raises an expected exception, skip this test. except exception_type as exception: return skip(str(exception)) # Else if this callable raises an unexpected exception, fail this test by # permitting this exception to unwind the current call stack. # Else, this callable raised no exception. Silently reduce to a noop. return noop
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Testable path factories** (i.e., callables creating and returning :class:`pathlib.Path` instances encapsulating testing-specific paths). ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ RELATIVIZERS }.................... def shell_quote(text: str) -> str: ''' Shell-quote the passed string in a platform-specific manner. If the current platform is: * *Not* vanilla Windows (e.g., Linux, macOS), the returned string is guaranteed to be suitable for passing as an arbitrary positional argument to external commands. * Windows, the returned string is suitable for passing *only* to external commands parsing arguments in the same manner as the Microsoft C runtime. While *all* applications on POSIX-compliant systems are required to parse arguments in the same manner (i.e., according to Bourne shell lexing), no such standard applies to Windows applications. Shell quoting is therefore fragile under Windows -- like pretty much everything. Parameters ---------- text : str String to be shell-quoted. Returns ---------- str This string shell-quoted. ''' assert isinstance(text, str), f'{repr(text)} not string.' # Defer heavyweight imports. from beartype._util.os.utilostest import is_os_windows_vanilla # If the current platform is vanilla Windows (i.e., neither Cygwin *NOR* the # Windows Subsystem for Linux (WSL)), do *NOT* perform POSIX-compatible # quoting. Vanilla Windows is POSIX-incompatible and hence does *NOT* parse # command-line arguments according to POSIX standards. In particular, # Windows does *NOT* treat single-quoted arguments as single arguments but # rather as multiple shell words delimited by the raw literal `'`. This is # circumventable by calling an officially undocumented Windows-specific # function. (Awesome.) if is_os_windows_vanilla(): import subprocess return subprocess.list2cmdline([text]) # Else, perform POSIX-compatible quoting. else: import shlex return shlex.quote(text)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Test-specific **Python module detection** utilities. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from beartype._util.cache.utilcachecall import callable_cached # ....................{ TESTERS ~ beartype }.................... @callable_cached def is_package_beartype_vale_usable() -> bool: ''' ``True`` only if **beartype validators** (i.e., subscriptions of public classes declared by the :class:`beartype.vale` subpackage) are creatable under the active Python interpreter. Specifically, this tester returns true only if either: * This interpreter targets Python >= 3.9 and thus provides the :attr:`typing.Annotated` type hint required by beartype validators. * This interpreter targets Python >= 3.8 *and* a reasonably recent version of the third-party :mod:`typing_extensions` package is importable under this interpreter and thus provides the alternative :attr:`typing_extensions.Annotated` type hint required by beartype validators. ''' # Defer test-specific imports. from beartype._util.mod.lib.utiltyping import is_typing_attr # Return true only if the "Annotated" type hint is importable from either # the official "typing" or third-party "typing_extensions" modules. return is_typing_attr('Annotated') # ....................{ TESTERS ~ lib }.................... @callable_cached def is_package_sphinx() -> bool: ''' ``True`` only if a reasonably recent version of Sphinx is importable under the active Python interpreter. ''' # Defer test-specific imports. from beartype.meta import _LIB_DOCTIME_MANDATORY_VERSION_MINIMUM_SPHINX from beartype._util.mod.utilmodtest import is_module_version_at_least # Return true only if this version of this package is importable. return is_module_version_at_least( 'sphinx', _LIB_DOCTIME_MANDATORY_VERSION_MINIMUM_SPHINX) @callable_cached def is_package_typing_extensions() -> bool: ''' ``True`` only if a reasonably recent version of the third-party :mod:`typing_extensions` package is importable under the active Python interpreter. ''' # Defer test-specific imports. from beartype.meta import ( _LIB_RUNTIME_OPTIONAL_VERSION_MINIMUM_TYPING_EXTENSIONS) from beartype._util.mod.utilmodtest import is_module_version_at_least # from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8 # Return true only if this version of this package is importable. return is_module_version_at_least( 'typing_extensions', _LIB_RUNTIME_OPTIONAL_VERSION_MINIMUM_TYPING_EXTENSIONS, ) # ....................{ TESTERS ~ lib : numpy }.................... @callable_cached def is_package_numpy() -> bool: ''' ``True`` only if a reasonably recent version of NumPy is importable under the active Python interpreter. ''' # Defer test-specific imports. from beartype.meta import _LIB_RUNTIME_OPTIONAL_VERSION_MINIMUM_NUMPY from beartype._util.mod.utilmodtest import is_module_version_at_least # Return true only if this version of this package is importable. return is_module_version_at_least( 'numpy', _LIB_RUNTIME_OPTIONAL_VERSION_MINIMUM_NUMPY) @callable_cached def is_package_numpy_typing_ndarray_deep() -> bool: ''' ``True`` only if :attr:`numpy.typing.NDArray` type hints are deeply supported by the :func:`beartype.beartype` decorator under the active Python interpreter. Specifically, this tester returns true only if: * A reasonably recent version of NumPy is importable under the active Python interpreter. * Beartype validators are usable under the active Python interpreter, as :func:`beartype.beartype` internally reduces these hints to equivalent beartype validators. See :func:`is_package_beartype_vale_usable`. ''' # Return true only if... return ( # A recent version of NumPy is importable *AND*... is_package_numpy() and # Beartype validators are usable under the active Python interpreter. is_package_beartype_vale_usable() )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Testing-specific **typing attribute utilities** (i.e., functions introspecting attributes with arbitrary names dynamically imported from typing modules). ''' # ....................{ IMPORTS }.................... from beartype.typing import ( Any, Iterable, Tuple, Union, ) from beartype._util.mod.utilmodimport import import_module_attr_or_none from beartype._data.mod.datamodtyping import TYPING_MODULE_NAMES from collections.abc import Iterable as IterableABC from warnings import warn # ....................{ TESTERS }.................... def is_typing_attrs(typing_attr_basenames: Union[str, Iterable[str]]) -> bool: ''' ``True`` only if at least one quasi-standard typing module declares an attribute with the passed basename. Attributes ---------- typing_attr_basenames : Union[str, Iterable[str]] Unqualified name of the attribute to be tested as existing in at least one typing module. Returns ---------- bool ``True`` only if at least one quasi-standard typing module declares an attribute with this basename. ''' # Return true only if at least one typing module defines an attribute with # this name. Glory be to the obtuse generator comprehension expression! return bool(tuple(iter_typing_attrs( typing_attr_basenames=typing_attr_basenames, is_warn=False, ))) # ....................{ ITERATORS }.................... #FIXME: Generalize to also accept an iterable of typing attribute basenames. def iter_typing_attrs( # Mandatory parameters. typing_attr_basenames: Union[str, Iterable[str]], # Optional parameters. is_warn: bool = False, typing_module_names: Iterable[str] = TYPING_MODULE_NAMES, ) -> Iterable[Union[object, Tuple[object]]]: ''' Generator iteratively yielding all attributes with the passed basename declared by the quasi-standard typing modules with the passed fully-qualified names, silently ignoring those modules failing to declare such an attribute. Attributes ---------- typing_attr_basenames : Union[str, Iterable[str]] Either: * Unqualified name of the attribute to be dynamically imported from each typing module, in which case either: * If the currently iterated typing module defines this attribute, this generator yields this attribute imported from that module. * Else, this generator silently ignores that module. * Iterable of one or more such names, in which case either: * If the currently iterated typing module defines *all* attributes, this generator yields a tuple whose items are these attributes imported from that module (in the same order). * Else, this generator silently ignores that module. is_warn : bool ``True`` only if emitting non-fatal warnings for typing modules failing to define all passed attributes. If ``typing_module_names`` is passed, this parameter should typically also be passed as ``True`` for safety. Defaults to ``False``. typing_module_names: Iterable[str] Iterable of the fully-qualified names of all typing modules to dynamically import this attribute from. Defaults to :data:`TYPING_MODULE_NAMES`. Yields ---------- Union[object, Tuple[object]] Either: * If passed only an attribute basename, the attribute with that basename declared by each typing module. * If passed an iterable of one or more attribute basenames, a tuple whose items are the attributes with those basenames (in the same order) declared by each typing module. ''' assert isinstance(is_warn, bool), f'{is_warn} not boolean.' assert isinstance(typing_attr_basenames, (str, IterableABC)), ( f'{typing_attr_basenames} not string.') assert typing_attr_basenames, '"typing_attr_basenames" empty.' assert isinstance(typing_module_names, IterableABC), ( f'{repr(typing_module_names)} not iterable.') assert typing_module_names, '"typing_module_names" empty.' assert all( isinstance(typing_module_name, str) for typing_module_name in typing_module_names ), f'One or more {typing_module_names} items not strings.' # If passed an attribute basename, pack this into a tuple containing only # this basename for ease of use. if isinstance(typing_attr_basenames, str): typing_attr_basenames = (typing_attr_basenames,) # Else, an iterable of attribute basenames was passed. In this case... else: assert all( isinstance(typing_attr_basename, str) for typing_attr_basename in typing_attr_basenames ), f'One or more {typing_attr_basenames} items not strings.' # List of all imported attributes to be yielded from each iteration of the # generator implicitly returned by this generator function. typing_attrs = [] # For the fully-qualified name of each quasi-standard typing module... for typing_module_name in typing_module_names: # Clear this list *BEFORE* appending to this list below. typing_attrs.clear() # For the basename of each attribute to be imported from that module... for typing_attr_basename in typing_attr_basenames: # Fully-qualified name of this attribute declared by that module. module_attr_name = f'{typing_module_name}.{typing_attr_basename}' # Attribute with this name dynamically imported from that module if # that module defines this attribute *OR* "None" otherwise. typing_attr = import_module_attr_or_none( module_attr_name=module_attr_name, exception_prefix=f'"{typing_module_name}" attribute ', ) # If that module fails to declare even a single attribute... if typing_attr is None: # If emitting non-fatal warnings, do so. if is_warn: warn( f'Ignoring undefined typing attribute ' f'"{module_attr_name}"...' ) # Continue to the next module. break # Else, that module declares this attribute. # Append this attribute to this list. typing_attrs.append(typing_attr) # If that module declares *ALL* attributes... else: # If exactly one attribute name was passed, yield this attribute # as is (*WITHOUT* packing this attribute into a tuple). if len(typing_attrs) == 1: yield typing_attrs[0] # Else, two or more attribute names were passed. In this case, # yield these attributes as a tuple. else: yield tuple(typing_attrs) # Else, that module failed to declare one or more attributes. In this # case, silently continue to the next module. # ....................{ IMPORTERS }.................... def import_typing_attr_or_none_safe(typing_attr_basename: str) -> Any: ''' Dynamically import and return the **typing attribute** (i.e., object declared at module scope by either the :mod:`typing` or :mod:`typing_extensions` modules) with the passed unqualified name if importable from one or more of these modules *or* ``None`` otherwise otherwise (i.e., if this attribute is *not* importable from these modules). Caveats ---------- **This higher-level wrapper should typically be called in lieu of the lower-level** :func:`beartype._util.mod.lib.utiltyping.import_typing_attr_or_none` **function.** Unlike the latter, this wrapper imports from the third-party :mod:`typing_extensions` module *only* if the version of that module is sufficiently new and thus satisfies test-time requirements. Parameters ---------- typing_attr_basename : str Unqualified name of the attribute to be imported from a typing module. Returns ---------- object Attribute with this name dynamically imported from a typing module. Raises ---------- beartype.roar._roarexc._BeartypeUtilModuleException If this name is syntactically invalid. Warns ---------- BeartypeModuleUnimportableWarning If any of these modules raise module-scoped exceptions at importation time. That said, the :mod:`typing` and :mod:`typing_extensions` modules are scrupulously tested and thus unlikely to raise such exceptions. ''' # Defer test-specific imports. from beartype._util.mod.lib.utiltyping import import_typing_attr_or_none # from beartype._util.mod.utilmodimport import import_module_attr_or_none from beartype_test._util.mod.pytmodtest import is_package_typing_extensions # print(f'is_package_typing_extensions: {is_package_typing_extensions()}') # Return either... return ( # If a reasonably recent version of the third-party "typing_extensions" # package is importable under the active Python interpreter, defer to # this higher-level importer possibly returning an attribute from that # package; import_typing_attr_or_none(typing_attr_basename) if is_package_typing_extensions() else # Else, either "typing_extensions" is unimportable or only an obsolete # version of "typing_extensions" is importable; in either case, avoid # possibly returning a possibly broken attribute from that package by # importing only from the official "typing" module. import_module_attr_or_none(f'typing.{typing_attr_basename}') )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype object utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.utilobject` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_object_hashable() -> None: ''' Test the :func:`beartype._util.utilobject.is_object_hashable` tester. ''' # Defer test-specific imports. from beartype._util.utilobject import is_object_hashable from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_HASHABLE, NOT_HINTS_UNHASHABLE,) # Assert this tester accepts unhashable objects. for object_hashable in NOT_HINTS_HASHABLE: assert is_object_hashable(object_hashable) is True # Assert this tester rejects unhashable objects. for object_unhashable in NOT_HINTS_UNHASHABLE: assert is_object_hashable(object_unhashable) is False # ....................{ TESTS ~ getter }.................... def test_get_object_basename_scoped() -> None: ''' Test the :func:`beartype._util.utilobject.get_object_basename_scoped` getter. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilObjectNameException from beartype._util.utilobject import get_object_basename_scoped from beartype_test.a00_unit.data.data_type import ( CALLABLES, closure_factory, ) from pytest import raises # Assert this getter returns the fully-qualified names of non-nested # callables unmodified. for callable_obj in CALLABLES: assert get_object_basename_scoped(callable_obj) == ( callable_obj.__qualname__) # Assert this getter returns the fully-qualified names of closures stripped # of meaningless "<locals>." substrings. assert get_object_basename_scoped(closure_factory()) == ( 'closure_factory.closure') # Assert this getter raises "AttributeError" exceptions when passed objects # declaring neither "__qualname__" nor "__name__" dunder attributes. with raises(_BeartypeUtilObjectNameException): get_object_basename_scoped( 'From the ice-gulfs that gird his secret throne,')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **PEP-compliant type hint tester** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.utilpeptest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises # ....................{ TESTS }.................... # Fine-grained tests are intentionally performed *BEFORE* coarse-grained tests, # dramatically improving readability of test failures. # ....................{ TESTS ~ kind : typevar }.................... def test_is_hint_pep_typevars() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_typevars` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import is_hint_pep_typevars from beartype_test.a00_unit.data.hint.data_hint import HINTS_NONPEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert that various "TypeVar"-centric types are correctly detected. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep_typevars(hint_pep_meta.hint) is ( hint_pep_meta.is_typevars) # Assert that various "TypeVar"-agnostic types are correctly detected. for nonhint_pep in HINTS_NONPEP: assert is_hint_pep_typevars(nonhint_pep) is False # ....................{ TESTS ~ typing }.................... def test_is_hint_pep_typing() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_typing` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import ( is_hint_pep_typing) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this tester accepts PEP-compliant type hints defined by the # "typing" module. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep_typing(hint_pep_meta.hint) is ( hint_pep_meta.is_typing) # Assert this tester rejects non-PEP-compliant type hints. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep_typing(not_hint_pep) is False def test_is_hint_pep_type_typing() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_type_typing` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import ( is_hint_pep_type_typing) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this tester accepts PEP-compliant type hints defined by the # "typing" module. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep_type_typing(hint_pep_meta.hint) is ( hint_pep_meta.is_type_typing) # Assert this tester rejects non-PEP-compliant type hints. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep_type_typing(not_hint_pep) is False # ....................{ TESTS }.................... def test_is_hint_pep() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import is_hint_pep from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.nonpep.data_nonpep import ( HINTS_NONPEP_META) from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META # Assert this tester accepts PEP-compliant type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep(hint_pep_meta.hint) is True # Assert this tester rejects PEP-noncompliant type hints implemented by the # "typing" module as normal types indistinguishable from non-"typing" types # and thus effectively non-PEP-compliant for all practical intents. for hint_nonpep_meta in HINTS_NONPEP_META: assert is_hint_pep(hint_nonpep_meta.hint) is False # Assert this tester rejects non-PEP-compliant type hints. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep(not_hint_pep) is False def test_is_hint_pep_args() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_args` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import is_hint_pep_args from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this tester accepts PEP-compliant subscripted type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep_args(hint_pep_meta.hint) is ( hint_pep_meta.is_args) # Assert this tester rejects non-PEP-compliant type hints. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep_args(not_hint_pep) is False #FIXME: Implement us up, please. # def test_is_hint_pep_uncached() -> None: # ''' # Test the # :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_uncached` # tester. # ''' # # # Defer test-specific imports. # from beartype._util.hint.pep.utilpeptest import is_hint_pep_uncached # from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 # from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP # from beartype_test.a00_unit.data.hint.pep.data_pep import ( # HINTS_PEP_META) # # # Assert this tester accepts concrete PEP-compliant type hints. # for hint_pep_meta in HINTS_PEP_META: # # True only if we expect this hint to be non-self-cached, including. # is_hint_pep_uncached_expected = ( # # If th # hint_pep_meta.is_pep585_builtin or # ( # IS_PYTHON_AT_LEAST_3_9 and # hint_pep_meta # ) # ) # # assert is_hint_pep_uncached(hint_pep_meta.hint) is ( # is_hint_pep_uncached_expected) # # # Assert this tester accepts non-PEP-compliant type hints. What? Look, # # folks. This tester should probably raise an exception when passed those # # sort of hints, but this tester *CANNOT* by definition be memoized, which # # means it needs to be fast despite being unmemoized, which means we treat # # *ALL* objects other than a small well-known subset of non-self-cached # # PEP-compliant type hints as self-cached PEP-compliant type hints. *shrug* # for not_hint_pep in NOT_HINTS_PEP: # assert is_hint_pep_uncached(not_hint_pep) is True # ....................{ TESTS ~ supported }.................... def test_is_hint_pep_supported() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.is_hint_pep_supported` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.utilpeptest import is_hint_pep_supported from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_UNHASHABLE, NOT_HINTS_PEP) from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this tester: # * Accepts supported PEP-compliant type hints. # * Rejects unsupported PEP-compliant type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep_supported(hint_pep_meta.hint) is ( hint_pep_meta.is_supported) # Assert this tester rejects objects that are *NOT* PEP-noncompliant. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep_supported(not_hint_pep) is False # Assert this tester rejects unhashable objects. for non_hint_unhashable in NOT_HINTS_UNHASHABLE: assert is_hint_pep_supported(non_hint_unhashable) is False def test_die_if_hint_pep_unsupported() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpeptest.die_if_hint_pep_unsupported` validator. ''' # Defer test-specific imports. from beartype.roar import ( BeartypeDecorHintPepException, BeartypeDecorHintPepUnsupportedException, ) from beartype._util.hint.pep.utilpeptest import ( die_if_hint_pep_unsupported) from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_UNHASHABLE, NOT_HINTS_PEP) from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this validator... for hint_pep_meta in HINTS_PEP_META: # Accepts supported PEP-compliant type hints. if hint_pep_meta.is_supported: die_if_hint_pep_unsupported(hint_pep_meta.hint) # Rejects unsupported PEP-compliant type hints. else: with raises(BeartypeDecorHintPepUnsupportedException): die_if_hint_pep_unsupported(hint_pep_meta.hint) # Assert this validator rejects objects that are *NOT* PEP-noncompliant. for not_hint_pep in NOT_HINTS_PEP: with raises(BeartypeDecorHintPepException): die_if_hint_pep_unsupported(not_hint_pep) # Assert this validator rejects unhashable objects. for non_hint_unhashable in NOT_HINTS_UNHASHABLE: with raises(BeartypeDecorHintPepException): die_if_hint_pep_unsupported(non_hint_unhashable)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **PEP-compliant type hint getter** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.utilpepget` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # from beartype_test._util.mark.pytskip import skip_if_python_version_less_than # ....................{ TESTS ~ attr }.................... def test_get_hint_pep_args() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpepget.get_hint_pep_args` getter. ''' # ....................{ IMPORTS }.................... # Defer test-specific imports. from beartype._util.hint.pep.utilpepget import ( _HINT_ARGS_EMPTY_TUPLE, get_hint_pep_args, ) from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META from typing import Tuple # ....................{ PASS }.................... # For each PEP-compliant hint, assert this getter returns... for hint_pep_meta in HINTS_PEP_META: # Tuple of all arguments subscripting this hint. hint_args = get_hint_pep_args(hint_pep_meta.hint) assert isinstance(hint_args, tuple) # For subscripted hints, one or more arguments. if hint_pep_meta.is_args: assert hint_args # For non-argumentative hints, *NO* arguments. else: assert hint_args == () # ....................{ PASS ~ pep }.................... #FIXME: Explicitly validate that this getter handles both PEP 484- and 585- #compliant empty tuples by returning "_HINT_ARGS_EMPTY_TUPLE" as expected, #please. This is sufficiently critical that we *NEED* to ensure this. # Assert that this getter when passed a PEP 484-compliant empty tuple type # hint returns a tuple containing an empty tuple for disambiguity. assert get_hint_pep_args(Tuple[()]) == _HINT_ARGS_EMPTY_TUPLE # If Python >= 3.9, the active Python interpreter supports PEP 585. In this # case, assert that this getter when passed a PEP 585-compliant empty tuple # type hint returns a tuple containing an empty tuple for disambiguity. if IS_PYTHON_AT_LEAST_3_9: assert get_hint_pep_args(tuple[()]) == _HINT_ARGS_EMPTY_TUPLE # ....................{ FAIL }.................... # Assert this getter returns *NO* type variables for non-"typing" hints. for not_hint_pep in NOT_HINTS_PEP: assert get_hint_pep_args(not_hint_pep) == () def test_get_hint_pep_typevars() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpepget.get_hint_pep_typevars` getter. ''' # Defer test-specific imports. from beartype._data.hint.pep.sign.datapepsigns import HintSignTypeVar from beartype._util.hint.pep.utilpepget import ( get_hint_pep_typevars, get_hint_pep_sign_or_none, ) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META # For each PEP-compliant hint, assert this getter returns... for hint_pep_meta in HINTS_PEP_META: # Tuple of all type variables subscripting this hint. hint_typevars = get_hint_pep_typevars(hint_pep_meta.hint) assert isinstance(hint_typevars, tuple) # For typevared hints, one or more type variables. if hint_pep_meta.is_typevars: assert hint_typevars for hint_typevar in hint_typevars: assert get_hint_pep_sign_or_none(hint_typevar) is ( HintSignTypeVar) # For non-typevared hints, *NO* type variables. else: assert hint_typevars == () # Assert this getter returns *NO* type variables for non-"typing" hints. for not_hint_pep in NOT_HINTS_PEP: assert get_hint_pep_typevars(not_hint_pep) == () # ....................{ TESTS ~ sign }.................... def test_get_hint_pep_sign() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpepget.get_hint_pep_sign` getter. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPepSignException from beartype._util.hint.pep.utilpepget import get_hint_pep_sign from beartype_test.a00_unit.data.hint.data_hint import ( HINTS_NONPEP, NonpepCustomFakeTyping) from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) from pytest import raises # Assert this getter returns the expected unsubscripted "typing" attribute # for all PEP-compliant type hints associated with such an attribute. for hint_pep_meta in HINTS_PEP_META: assert get_hint_pep_sign(hint_pep_meta.hint) is hint_pep_meta.pep_sign # Assert this getter raises the expected exception for an instance of a # class erroneously masquerading as a "typing" class. with raises(BeartypeDecorHintPepSignException): # Localize this return value to simplify debugging. hint_nonpep_sign = get_hint_pep_sign(NonpepCustomFakeTyping()) # Assert this getter raises the expected exception for non-"typing" hints. for hint_nonpep in HINTS_NONPEP: with raises(BeartypeDecorHintPepSignException): # Localize this return value to simplify debugging. hint_nonpep_sign = get_hint_pep_sign(hint_nonpep) # ....................{ TESTS ~ origin : type }.................... def test_get_hint_pep_type_isinstanceable() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpepget.get_hint_pep_origin_type_isinstanceable` getter. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPepException from beartype._util.hint.pep.utilpepget import ( get_hint_pep_origin_type_isinstanceable) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) from pytest import raises # Assert this getter... for hint_pep_meta in HINTS_PEP_META: # Returns the expected type origin for all PEP-compliant type hints # originating from an origin type. if hint_pep_meta.isinstanceable_type is not None: assert get_hint_pep_origin_type_isinstanceable(hint_pep_meta.hint) is ( hint_pep_meta.isinstanceable_type) # Raises the expected exception for all other hints. else: with raises(BeartypeDecorHintPepException): get_hint_pep_origin_type_isinstanceable(hint_pep_meta.hint) # Assert this getter raises the expected exception for non-PEP-compliant # type hints. for not_hint_pep in NOT_HINTS_PEP: with raises(BeartypeDecorHintPepException): get_hint_pep_origin_type_isinstanceable(not_hint_pep) def test_get_hint_pep_type_isinstanceable_or_none() -> None: ''' Test the :func:`beartype._util.hint.pep.utilpepget.get_hint_pep_origin_type_isinstanceable_or_none` getter. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPepException from beartype._util.hint.pep.utilpepget import ( get_hint_pep_origin_type_isinstanceable_or_none) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) from pytest import raises # Assert this getter returns the expected type origin for all PEP-compliant # type hints. for hint_pep_meta in HINTS_PEP_META: assert get_hint_pep_origin_type_isinstanceable_or_none(hint_pep_meta.hint) is ( hint_pep_meta.isinstanceable_type) # Assert this getter raises the expected exception for non-PEP-compliant # type hints. for not_hint_pep in NOT_HINTS_PEP: with raises(BeartypeDecorHintPepException): get_hint_pep_origin_type_isinstanceable_or_none(not_hint_pep)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`557` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.utilpep557` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ getter }.................... def test_get_hint_pep557_initvar_arg() -> None: ''' Test usage of the private :mod:`beartype._util.hint.pep.proposal.utilpep557.get_hint_pep557_initvar_arg` getter. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep557Exception from beartype._util.hint.pep.proposal.utilpep557 import ( get_hint_pep557_initvar_arg) from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8 from pytest import raises # If the active Python interpreter targets at least Python >= 3.8 and thus # supports PEP 557... if IS_PYTHON_AT_LEAST_3_8: # Defer version-specific imports. from dataclasses import InitVar # Assert this getter returns the argument subscripting an InitVar. assert get_hint_pep557_initvar_arg(InitVar[str]) is str # Assert this tester raises the expected exception when passed a # non-InitVar. with raises(BeartypeDecorHintPep557Exception): get_hint_pep557_initvar_arg( 'Large codes of fraud and woe; not understood')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`604` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.utilpep604` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_hint_pep604() -> None: ''' Test usage of the private :mod:`beartype._util.hint.pep.proposal.utilpep604.is_hint_pep604` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.proposal.utilpep604 import is_hint_pep604 from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_10 # If the active Python interpreter targets Python >= 3.10 and thus supports # PEP 604... if IS_PYTHON_AT_LEAST_3_10: # Assert this tester accepts a PEP 604-compliant union. assert is_hint_pep604(int | str | None) is True # Else, this interpreter targets Python < 3.10 and thus fails to support PEP # 604. # Assert this tester rejects an arbitrary PEP 604-noncompliant object. is_hint_pep604('Meet in the vale, and one majestic River,')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`586` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.utilpep586` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from enum import Enum from pytest import raises # ....................{ CONSTANTS }.................... class _Color(Enum): ''' Arbitrary enumeration accessed as given in a prominent :pep:`586` example. ''' RED = 0 _LITERAL_ARGS = ( 26, 0x1A, -4, "hello world", b"hello world", u"hello world", True, _Color.RED, None, ) ''' Tuple of arbitrary objects permissible for use as arguments subscripting :pep:`586`-compliant :attr:`typing.Literal` type hints. For conformance, the items of this tuple are copied verbatim from a prominent :pep:`586` example under the "Legal parameters for Literal at type check time" subsection. ''' # ....................{ TESTS }.................... def test_is_hint_pep586() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.utilpep586.die_unless_hint_pep586` validator. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep586Exception from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 from beartype._util.hint.pep.proposal.utilpep586 import ( die_unless_hint_pep586) from typing import Optional # If the active Python interpreter targets at least Python >= 3.9 and thus # supports PEP 586... if IS_PYTHON_AT_LEAST_3_9: # Defer imports specific to this Python version. from typing import Literal # For each object that is a valid literal argument, assert this # validator raises no exception when passed that singleton subscripted # by that argument. for literal_arg in _LITERAL_ARGS: die_unless_hint_pep586(Literal[literal_arg]) # Assert this validator raises no exception when passed that singleton # subscripted by two or more such arguments. die_unless_hint_pep586(Literal[ 26, "hello world", b"hello world", True, _Color.RED, None]) # Assert this validator raises the expected exception when passed that # singleton subscripted by the empty tuple. with raises(BeartypeDecorHintPep586Exception): die_unless_hint_pep586(Literal[()]) # Assert this validator raises the expected exception when passed that # singleton subscripted by an invalid literal argument. with raises(BeartypeDecorHintPep586Exception): die_unless_hint_pep586(Literal[object()]) # Assert this validator raises the expected exception when passed that # singleton subscripted by one or more valid literal arguments and an # invalid literal argument. with raises(BeartypeDecorHintPep586Exception): die_unless_hint_pep586(Literal[ 26, "hello world", b"hello world", True, object(), _Color.RED]) # Assert this validator raises the expected exception when passed an # object that is *NOT* a literal. with raises(BeartypeDecorHintPep586Exception): die_unless_hint_pep586(Optional[str])
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`544` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.utilpep544` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_hint_pep544_protocol() -> None: ''' Test usage of the private :mod:`beartype._util.hint.pep.proposal.utilpep544.is_hint_pep544_protocol` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.proposal.utilpep544 import ( is_hint_pep544_protocol) from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8 from beartype_test.a00_unit.data.data_type import Class # Assert this tester rejects builtin types erroneously presenting themselves # as PEP 544-compliant protocols under Python >= 3.8. assert is_hint_pep544_protocol(int) is False assert is_hint_pep544_protocol(str) is False assert is_hint_pep544_protocol(type(None)) is False # Assert this tester rejects a user-defined type. assert is_hint_pep544_protocol(Class) is False # class Yam(object): pass # from typing import Protocol # assert not issubclass(Yam, Protocol) # assert is_hint_pep544_protocol(Yam) is False # If the active Python interpreter targets at least Python >= 3.8 and thus # supports PEP 544... if IS_PYTHON_AT_LEAST_3_8: # Defer version-specific imports. from abc import abstractmethod # Intentionally import @beartype-accelerated protocols. from beartype.typing import ( Protocol, runtime_checkable, ) # Intentionally import @beartype-unaccelerated protocols. from typing import SupportsInt # User-defined protocol parametrized by *NO* type variables declaring # arbitrary concrete and abstract methods. @runtime_checkable class ProtocolCustomUntypevared(Protocol): def alpha(self) -> str: return 'Of a Spicily sated' @abstractmethod def omega(self) -> str: pass # Assert this accepts a standardized protocol. assert is_hint_pep544_protocol(SupportsInt) is True # Assert this accepts a user-defined protocol. assert is_hint_pep544_protocol(ProtocolCustomUntypevared) is True
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`593` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.utilpep593` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_hint_pep593_beartype() -> None: ''' Test usage of the private :mod:`beartype._util.hint.pep.proposal.utilpep593.is_hint_pep593_beartype` tester. ''' # Defer test-specific imports. from beartype.roar import ( BeartypeDecorHintPepException, BeartypeValeLambdaWarning, ) from beartype.vale import Is from beartype._util.hint.pep.proposal.utilpep593 import ( is_hint_pep593_beartype) from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 from pytest import raises, warns # If the active Python interpreter targets at least Python >= 3.9 and thus # supports PEP 593... if IS_PYTHON_AT_LEAST_3_9: # Defer version-specific imports. from typing import Annotated # Assert this tester accepts beartype-specific metahints. # # Unfortunately, this test actually induces an error in CPython, which # our codebase emits as a non-fatal warning. Specifically, CPython # reports the "func.__code__.co_firstlineno" attribute of the nested # lambda function defined below to be one less than the expected value. # Since this issue is unlikely to be resolved soon *AND* since we have # no means of monkey-patching CPython itself, we acknowledge the # existence of this warning by simply ignoring it. *sigh* with warns(BeartypeValeLambdaWarning): assert is_hint_pep593_beartype(Annotated[ str, Is[lambda text: bool(text)]]) is True # Assert this tester rejects beartype-agnostic metahints. assert is_hint_pep593_beartype(Annotated[ str, 'And may there be no sadness of farewell']) is False # Assert this tester raises the expected exception when passed a # non-metahint in either case. with raises(BeartypeDecorHintPepException): is_hint_pep593_beartype('When I embark;')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype** :pep:`484`-compliant **type variable utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.pep484.utilpep484typevar` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ kind : typevar }.................... def test_get_hint_pep484_typevar_bound_or_none() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484.utilpep484typevar.get_hint_pep484_typevar_bound_or_none` tester. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep484Exception from beartype._util.hint.pep.proposal.pep484.utilpep484typevar import ( get_hint_pep484_typevar_bound_or_none) from beartype_test.a00_unit.data.hint.pep.proposal.data_pep484 import ( T, T_BOUNDED, T_CONSTRAINED, ) from pytest import raises # Assert this getter returns "None" for unbounded type variables. assert get_hint_pep484_typevar_bound_or_none(T) is None # Assert this getter reduces bounded type variables to their upper bound. assert get_hint_pep484_typevar_bound_or_none(T_BOUNDED) is int # Union of all constraints parametrizing a constrained type variable, # reduced from that type variable. typevar_constraints_union = get_hint_pep484_typevar_bound_or_none( T_CONSTRAINED) # Assert this union contains all constraints parametrizing this variable. assert str in typevar_constraints_union.__args__ assert bytes in typevar_constraints_union.__args__ # Assert this getter raises the expected exception when passed a non-type # variable. with raises(BeartypeDecorHintPep484Exception): get_hint_pep484_typevar_bound_or_none(str)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`484` and :pep:`585` **generic type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ testers }.................... def test_is_hint_pep484585_generic() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic.is_hint_pep484585_generic` tester. ''' # Defer test-specific imports. from beartype._data.hint.pep.sign.datapepsigns import HintSignGeneric from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import ( is_hint_pep484585_generic) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this tester: # * Accepts generic PEP 484-compliant generics. # * Rejects concrete PEP-compliant type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint_pep484585_generic(hint_pep_meta.hint) is ( hint_pep_meta.pep_sign is HintSignGeneric) # Assert this tester rejects non-PEP-compliant type hints. for not_hint_pep in NOT_HINTS_PEP: assert is_hint_pep484585_generic(not_hint_pep) is False # ....................{ TESTS ~ getters }.................... def test_get_hint_pep484585_generic_type_or_none() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic.get_hint_pep484585_generic_type_or_none` getter. ''' # Defer test-specific imports. from beartype._data.hint.pep.sign.datapepsigns import HintSignGeneric from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import ( get_hint_pep484585_generic_type_or_none) from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) # Assert this getter returns the expected type origin for all # PEP-compliant type hint generics. While we could support non-generics as # well, there's little benefit and significant costs to doing so. Instead, # we assert this getter only returns the expected type origin for a small # subset of type hints. for hint_pep_meta in HINTS_PEP_META: if hint_pep_meta.pep_sign is HintSignGeneric: assert get_hint_pep484585_generic_type_or_none( hint_pep_meta.hint) is hint_pep_meta.generic_type #FIXME: Uncomment if we ever want to exercise extreme edge cases. *shrug* # from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP # # # Assert this getter returns the expected type origin for all # # PEP-compliant type hints. # for hint_pep_meta in HINTS_PEP_META: # assert get_hint_pep484585_generic_type_or_none( # hint_pep_meta.hint) is hint_pep_meta.generic_type # # # Assert this getter raises the expected exception for non-PEP-compliant # # type hints. # for not_hint_pep in NOT_HINTS_PEP: # assert get_hint_pep484585_generic_type_or_none(not_hint_pep) is None def test_get_hint_pep484585_generic_bases_unerased() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585generic.get_hint_pep484585_generic_bases_unerased` getter. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPepException from beartype._data.hint.pep.sign.datapepsigns import HintSignGeneric from beartype._util.hint.pep.proposal.pep484585.utilpep484585generic import ( get_hint_pep484585_generic_bases_unerased) from beartype._util.hint.pep.utilpeptest import is_hint_pep_type_typing from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META from pytest import raises # Assert this getter... for hint_pep_meta in HINTS_PEP_META: # Returns one or more unerased pseudo-superclasses for PEP-compliant # generics. if hint_pep_meta.pep_sign is HintSignGeneric: hint_pep_bases = get_hint_pep484585_generic_bases_unerased( hint_pep_meta.hint) assert isinstance(hint_pep_bases, tuple) assert hint_pep_bases # Raises an exception for concrete PEP-compliant type hints *NOT* # defined by the "typing" module. elif not is_hint_pep_type_typing(hint_pep_meta.hint): with raises(BeartypeDecorHintPepException): get_hint_pep484585_generic_bases_unerased(hint_pep_meta.hint) # Else, this hint is defined by the "typing" module. In this case, this # hint may or may not be implemented as a generic conditionally # depending on the current Python version -- especially under the # Python < 3.7.0 implementations of the "typing" module, where # effectively *EVERYTHING* was internally implemented as a generic. # While we could technically correct for this conditionality, doing so # would render the resulting code less maintainable for no useful gain. # Ergo, we quietly ignore this edge case and get on with actual coding. # Assert this getter raises the expected exception for non-PEP-compliant # type hints. for not_hint_pep in NOT_HINTS_PEP: with raises(BeartypeDecorHintPepException): assert get_hint_pep484585_generic_bases_unerased(not_hint_pep)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`484` and :pep:`585` **callable type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.pep484585.utilpep484585callable` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_get_hint_pep484585_callable_params_and_return() -> None: ''' Test both the ``get_hint_pep484585_callable_params`` and ``get_hint_pep484585_callable_return`` getters declared by the :mod:`beartype._util.hint.pep.proposal.pep484585.utilpep484585callable` submodule. Since these getters are inextricably interrelated, this unit test exercises both within the same test to satisfy Don't Repeat Yourself (DRY). ''' # ..................{ IMPORTS }.................. # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep484585Exception from beartype.typing import Any from beartype._data.hint.pep.sign.datapepsigns import HintSignCallable from beartype._util.hint.pep.proposal.pep484585.utilpep484585callable import ( get_hint_pep484585_callable_params, get_hint_pep484585_callable_return, ) from beartype._util.py.utilpyversion import ( IS_PYTHON_AT_LEAST_3_10, IS_PYTHON_AT_LEAST_3_9, ) from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS_PEP from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META from pytest import raises # ..................{ GENERIC }.................. # General-purpose logic generically exercising these getters against all # globally defined type hints. # Assert these getters... for hint_pep_meta in HINTS_PEP_META: # Return zero or more arguments for PEP-compliant callable type hints. if hint_pep_meta.pep_sign is HintSignCallable: hint_callable_params = get_hint_pep484585_callable_params( hint_pep_meta.hint) hint_callable_return = get_hint_pep484585_callable_return( hint_pep_meta.hint) assert isinstance(hint_callable_params, tuple) assert hint_callable_return is not None # Raise an exception for concrete PEP-compliant type hints *NOT* # defined by the "typing" module. else: with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_callable_params(hint_pep_meta.hint) with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_callable_return(hint_pep_meta.hint) # Assert these getters raise the expected exception for non-PEP-compliant # type hints. for not_hint_pep in NOT_HINTS_PEP: with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_callable_params(not_hint_pep) with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_callable_return(not_hint_pep) # ..................{ PEP ~ 484 }.................. # Intentionally import the callable type hint factory from "typing" rather # than "beartype.typing" to guarantee PEP 484-compliance. from typing import Callable # List of 3-tuples "(callable_hint, callable_hint_params, # callable_hint_return)", where: # * "callable_hint" is a PEP-compliant callable type hint to be tested. # * "callable_hint_params" is the parameters type hint subscripting that # callable type hint. # * "callable_hint_return" is the return type hint subscripting that # callable type hint. CALLABLE_HINT_PARAMS_RETURN_CASES = [ # PEP 484-compliant callable type hints. (Callable[[], Any], (), Any), (Callable[[int], bool], (int,), bool), (Callable[[int, bool], float], (int, bool), float), (Callable[..., bytes], Ellipsis, bytes), ] # ..................{ PEP ~ 585 }.................. # If the active Python interpreter targets Python >= 3.9 and thus supports # PEP 585... if IS_PYTHON_AT_LEAST_3_9: # Intentionally import the callable type hint factory from # "collections.abc" rather than "beartype.typing" to guarantee PEP # 585-compliance. from collections.abc import Callable # Extend this list with PEP 585-compliant callable type hints. CALLABLE_HINT_PARAMS_RETURN_CASES.extend(( (Callable[[], Any], (), Any), (Callable[[int], bool], (int,), bool), (Callable[[int, bool], float], (int, bool), float), (Callable[..., bytes], Ellipsis, bytes), # Note this edge case is intentionally *NOT* tested above as a # PEP 484-compliant callable type hint, as the "typing.Callable" # factory refuses to accept the empty tuple here: e.g., # >>> from typing import Callable # >>> Callable[[()], str] # TypeError: Callable[[arg, ...], result]: each arg must be a # type. Got (). (Callable[[()], str], (), str), )) # ..................{ PEP ~ 612 }.................. # If the active Python interpreter targets Python >= 3.10 and thus supports # PEP 612... if IS_PYTHON_AT_LEAST_3_10: # Defer version-specific imports. from beartype.typing import ( Concatenate, ParamSpec, ) # Arbitrary PEP 612-compliant child type hints. P = ParamSpec('P') str_plus_P = Concatenate[str, P] # Extend this list with PEP 585-compliant callable type hints. CALLABLE_HINT_PARAMS_RETURN_CASES.extend(( (Callable[P, Any], P, Any), (Callable[str_plus_P, int], str_plus_P, int), )) # ..................{ PEP }.................. # For each callable type hint defined above... for hint, hint_params, hint_return in CALLABLE_HINT_PARAMS_RETURN_CASES: # Parameters type hint returned by this getter for this hint. hint_params_actual = get_hint_pep484585_callable_params(hint) # If the parameters type hint subscripting this callable type hint is a # tuple, assert this tuple to be equal but *NOT* identical to this # actual tuple. if isinstance(hint_params, tuple): assert hint_params_actual == hint_params # Else, the parameters type hint subscripting this callable type hint is # a non-tuple. In this case, assert this non-tuple to be identical to # this actual non-tuple. else: assert hint_params_actual is hint_params # Assert this getter returns the expected return. assert get_hint_pep484585_callable_return(hint) is hint_return
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`484` and :pep:`585` **subclass type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.pep484585.utilpep484585type` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ kind : subclass }.................... def test_get_hint_pep484585_subclass_superclass() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585type.get_hint_pep484585_subclass_superclass` tester. ''' # Defer test-specific imports. from beartype.roar import ( BeartypeDecorHintPep3119Exception, BeartypeDecorHintPep484585Exception, BeartypeDecorHintPep585Exception, ) from beartype._util.hint.pep.proposal.pep484.utilpep484ref import ( HINT_PEP484_FORWARDREF_TYPE) from beartype._util.hint.pep.proposal.pep484585.utilpep484585type import ( get_hint_pep484585_subclass_superclass) from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 from beartype_test.a00_unit.data.data_type import NonIssubclassableClass from pytest import raises from typing import Type, Union # Assert this getter returns the expected object when passed a PEP # 484-compliant subclass type hint subscripted by a class. assert get_hint_pep484585_subclass_superclass(Type[str], '') is str # Assert this getter returns the expected object when passed a PEP # 484-compliant subclass type hint subscripted by a union of classes. hint_superclass = get_hint_pep484585_subclass_superclass( Type[Union[dict, set]], '') assert hint_superclass == (dict, set) or hint_superclass == (set, dict) # Assert this getter returns the expected object when passed a PEP # 484-compliant subclass type hint subscripted by a forward reference to a # class. assert get_hint_pep484585_subclass_superclass(Type['bytes'], '') == ( HINT_PEP484_FORWARDREF_TYPE('bytes')) # Assert this getter raises the expected exception when passed a PEP # 484-compliant subclass type hint subscripted by a non-issubclassable # class. with raises(BeartypeDecorHintPep3119Exception): get_hint_pep484585_subclass_superclass( Type[NonIssubclassableClass], '') # Assert this getter raises the expected exception when passed an arbitrary # object that is neither a PEP 484- nor 585-compliant subclass type hint. with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_subclass_superclass('Caustically', '') # If the active Python interpreter targets Python >= 3.9 and thus supports # PEP 585... if IS_PYTHON_AT_LEAST_3_9: # Assert this getter returns the expected object when passed a PEP # 585-compliant subclass type hint subscripted by a class. assert get_hint_pep484585_subclass_superclass(type[bool], '') is bool # Assert this getter returns the expected object when passed a PEP # 585-compliant subclass type hint subscripted by a union of classes. hint_superclass = get_hint_pep484585_subclass_superclass( type[Union[dict, set]], '') assert hint_superclass == (dict, set) or hint_superclass == (set, dict) # Assert this getter returns the expected object when passed a PEP # 585-compliant subclass type hint subscripted by a forward reference # to a class. assert get_hint_pep484585_subclass_superclass(type['complex'], '') == ( 'complex') # Assert this getter raises the expected exception when passed a PEP # 585-compliant subclass type hint subscripted by a non-issubclassable # class. with raises(BeartypeDecorHintPep3119Exception): get_hint_pep484585_subclass_superclass( type[NonIssubclassableClass], '') # Assert this getter raises the expected exception when passed a PEP # 585-compliant subclass type hint subscripted by *NO* classes. # # Note there intentionally exists *NO* corresponding PEP 484 test, as # the "typing.Type" factory already validates this to be the case. with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_subclass_superclass(type[()], '') # Assert this getter raises the expected exception when passed a PEP # 585-compliant subclass type hint subscripted by two or more classes. # # Note there intentionally exists *NO* corresponding PEP 484 test, as # the "typing.Type" factory already validates this to be the case. with raises(BeartypeDecorHintPep585Exception): get_hint_pep484585_subclass_superclass(type[int, float], '') # Assert this getter raises the expected exception when passed a PEP # 585-compliant subclass type hint subscripted by an object that is # neither a class nor a forward reference to a class. # # Note there intentionally exists *NO* corresponding PEP 484 test, as # the "typing.Type" factory already validates this to be the case. with raises(BeartypeDecorHintPep484585Exception): get_hint_pep484585_subclass_superclass(type[ b'Counterrevolutionary'], '')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`484` and :pep:`585` **type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.pep.proposal.pep484585.utilpep484585` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_is_hint_pep484585_tuple_empty() -> None: ''' Test the :func:`beartype._util.hint.pep.proposal.pep484585.utilpep484585.is_hint_pep484585_tuple_empty` tester. ''' # Defer test-specific imports. from beartype._util.hint.pep.proposal.pep484585.utilpep484585 import ( is_hint_pep484585_tuple_empty) from typing import Tuple from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_9 # Assert this tester returns true for PEP 484-compliant empty tuple type # hints. assert is_hint_pep484585_tuple_empty(Tuple[()]) is True # Assert this tester returns false for PEP 484-compliant non-empty tuple # type hints. assert is_hint_pep484585_tuple_empty(Tuple[int, ...]) is False # If the active Python interpreter supports PEP 585... if IS_PYTHON_AT_LEAST_3_9: # Assert this tester returns true for PEP 585-compliant empty tuple type # hints. assert is_hint_pep484585_tuple_empty(tuple[()]) is True # Assert this tester returns false for PEP 585-compliant non-empty tuple # type hints. assert is_hint_pep484585_tuple_empty(tuple[int, ...]) is False
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype PEP-agnostic type hint factory** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.hint.utilhintfactory` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_typehinttypefactory() -> None: ''' Test the :func:`beartype._util.hint.utilhintfactory.TypeHintTypeFactory` class. ''' # Defer test-specific imports. from beartype._util.hint.utilhintfactory import TypeHintTypeFactory # Arbitrary instance of this factory. bool_factory = TypeHintTypeFactory(bool) # Assert that this class memoizes this factory on the passed type. assert bool_factory is TypeHintTypeFactory(bool) # Assert that this factory unconditionally returns this type when # subscripted by any arbitrary object. assert bool_factory['The still and solemn power of many sights,'] is bool
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype PEP-agnostic type hint tester utility** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.hint.utilhinttest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_die_unless_hint() -> None: ''' Test the :func:`beartype._util.hint.utilhinttest.die_unless_hint` validator. ''' # Defer test-specific imports. from beartype.roar import ( BeartypeDecorHintNonpepException, BeartypeDecorHintPepUnsupportedException, ) from beartype._util.hint.utilhinttest import die_unless_hint from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS, HINTS_NONPEP) from beartype_test.a00_unit.data.hint.pep.data_pep import ( HINTS_PEP_META) from pytest import raises # Assert this function accepts PEP-noncompliant type hints. for nonhint_pep in HINTS_NONPEP: die_unless_hint(nonhint_pep) # Assert this function... for hint_pep_meta in HINTS_PEP_META: # Accepts supported PEP-compliant type hints. if hint_pep_meta.is_supported: die_unless_hint(hint_pep_meta.hint) # Rejects unsupported PEP-compliant type hints. else: with raises(BeartypeDecorHintPepUnsupportedException): die_unless_hint(hint_pep_meta.hint) # Assert this function rejects objects *NOT* supported as either # PEP-noncompliant or -compliant type hints. for non_hint in NOT_HINTS: with raises(BeartypeDecorHintNonpepException): die_unless_hint(non_hint) def test_is_hint() -> None: ''' Test the :func:`beartype._util.hint.utilhinttest.is_hint` tester. ''' # Defer test-specific imports. from beartype._util.hint.utilhinttest import is_hint from beartype_test.a00_unit.data.hint.data_hint import NOT_HINTS, HINTS_NONPEP from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META # Assert this function accepts PEP-noncompliant type hints. for nonhint_pep in HINTS_NONPEP: assert is_hint(nonhint_pep) is True # Assert this function: # * Accepts supported PEP-compliant type hints. # * Rejects unsupported PEP-compliant type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint(hint_pep_meta.hint) is hint_pep_meta.is_supported # Assert this function rejects objects *NOT* supported as either # PEP-noncompliant or -compliant type hints. for non_hint in NOT_HINTS: assert is_hint(non_hint) is False # Prevent pytest from capturing and displaying all expected non-fatal # beartype-specific warnings emitted by the is_hint_ignorable() tester. # @ignore_warnings(BeartypeDecorHintPepIgnorableDeepWarning) def test_is_hint_ignorable() -> None: ''' Test the :func:`beartype._util.hint.utilhinttest.is_hint_ignorable` tester. ''' # Defer test-specific imports. from beartype._util.hint.utilhinttest import is_hint_ignorable from beartype_test.a00_unit.data.hint.data_hint import ( HINTS_IGNORABLE, HINTS_NONPEP_UNIGNORABLE, ) from beartype_test.a00_unit.data.hint.pep.data_pep import HINTS_PEP_META # Assert this function accepts ignorable type hints. for hint_ignorable in HINTS_IGNORABLE: assert is_hint_ignorable(hint_ignorable) is True # Assert this function rejects unignorable PEP-noncompliant type hints. for hint_unignorable in HINTS_NONPEP_UNIGNORABLE: assert is_hint_ignorable(hint_unignorable) is False # Assert this function: # * Accepts unignorable PEP-compliant type hints. # * Rejects ignorable PEP-compliant type hints. for hint_pep_meta in HINTS_PEP_META: assert is_hint_ignorable(hint_pep_meta.hint) is ( hint_pep_meta.is_ignorable)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype PEP-noncompliant type hint utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.hint.nonpep.utilnonpeptest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises # ....................{ TESTS ~ validator }.................... def test_die_unless_hint_nonpep() -> None: ''' Test the :func:`beartype._util.hint.nonpep.utilnonpeptest.die_unless_hint_nonpep` validator. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintNonpepException from beartype._util.hint.nonpep.utilnonpeptest import ( die_unless_hint_nonpep) from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_UNHASHABLE, HINTS_NONPEP, NOT_HINTS_NONPEP,) # Assert this function accepts PEP-noncompliant type hints. for hint_nonpep in HINTS_NONPEP: die_unless_hint_nonpep(hint_nonpep) # Assert this function rejects objects excepted to be rejected. for not_hint_nonpep in NOT_HINTS_NONPEP: with raises(BeartypeDecorHintNonpepException): die_unless_hint_nonpep(not_hint_nonpep) # Assert this function rejects unhashable objects. for not_hint_unhashable in NOT_HINTS_UNHASHABLE: with raises(BeartypeDecorHintNonpepException): die_unless_hint_nonpep(not_hint_unhashable) # ....................{ TESTS ~ tester }.................... def test_is_hint_nonpep() -> None: ''' Test the :func:`beartype._util.hint.nonpep.utilnonpeptest.is_hint_nonpep` tester. ''' # Defer test-specific imports. from beartype._util.hint.nonpep.utilnonpeptest import is_hint_nonpep from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_UNHASHABLE, HINTS_NONPEP, NOT_HINTS_NONPEP,) # Assert this function accepts PEP-noncompliant type hints. for hint_nonpep in HINTS_NONPEP: assert is_hint_nonpep(hint=hint_nonpep, is_str_valid=True) is True # Assert this function rejects objects excepted to be rejected. for not_hint_nonpep in NOT_HINTS_NONPEP: assert is_hint_nonpep(hint=not_hint_nonpep, is_str_valid=True) is False # Assert this function rejects unhashable objects. for non_hint_unhashable in NOT_HINTS_UNHASHABLE: assert is_hint_nonpep( hint=non_hint_unhashable, is_str_valid=True) is False def test_is_hint_nonpep_tuple() -> None: ''' Test the :func:`beartype._util.hint.nonpep.utilnonpeptest._is_hint_nonpep_tuple` tester. ''' # Defer test-specific imports. from beartype._util.hint.nonpep.utilnonpeptest import ( _is_hint_nonpep_tuple) from beartype_test.a00_unit.data.hint.data_hint import ( NOT_HINTS_UNHASHABLE, HINTS_NONPEP, NOT_HINTS_NONPEP,) # Assert this function accepts PEP-noncompliant tuples. for hint_nonpep in HINTS_NONPEP: assert _is_hint_nonpep_tuple(hint_nonpep, True) is isinstance( hint_nonpep, tuple) # Assert this function rejects objects excepted to be rejected. for not_hint_nonpep in NOT_HINTS_NONPEP: assert _is_hint_nonpep_tuple(not_hint_nonpep, True) is False # Assert this function rejects unhashable objects. for non_hint_unhashable in NOT_HINTS_UNHASHABLE: assert _is_hint_nonpep_tuple(non_hint_unhashable, True) is False
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python word size** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.py.utilpyword` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_word_size() -> None: ''' Test the :func:`beartype._util.py.utilpyword.WORD_SIZE` constant. ''' # Defer test-specific imports. from beartype._util.py.utilpyword import WORD_SIZE # Assert the active Python interpreter to be either 32- or 64-bit. assert WORD_SIZE in {32, 64}
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python interpreter** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.py.utilpyinterpreter` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_py_pypy() -> None: ''' Test the :func:`beartype._util.py.utilpyinterpreter.is_py_pypy` tester. ''' # Defer test-specific imports. from beartype._util.py.utilpyinterpreter import is_py_pypy # Assert this tester returns a boolean. IS_PY_PYPY = is_py_pypy() assert isinstance(IS_PY_PYPY, bool)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **weak reference** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.py.utilpyweakref` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_make_obj_weakref_and_repr() -> None: ''' Test the :func:`beartype._util.py.utilpyweakref.make_obj_weakref_and_repr` factory. ''' # ....................{ IMPORTS }.................... # Defer test-specific imports. from beartype._util.py.utilpyweakref import ( _WEAKREF_NONE, make_obj_weakref_and_repr, ) from beartype._util.text.utiltextrepr import represent_object from weakref import ref as weakref_ref # ....................{ ASSERT }.................... # Assert this factory when passed "None" returns the expected singleton. obj_weakref, obj_repr = make_obj_weakref_and_repr(None) assert obj_repr == represent_object(None, max_len=999999) assert obj_weakref is _WEAKREF_NONE # Assert this factory when passed a mutable C-based container returns # "None". obj_weakref, obj_repr = make_obj_weakref_and_repr(_WINDS_CONTEND) assert obj_repr == represent_object(_WINDS_CONTEND, max_len=999999) assert obj_weakref is None # Assert this factory when passed an immutable C-based container returns # "None". obj_weakref, obj_repr = make_obj_weakref_and_repr(_ITS_HOME) assert obj_repr == represent_object(_ITS_HOME, max_len=999999) assert obj_weakref is None # Assert this factory when passed any objects *OTHER* than "None" and # C-based containers returns a weak reference to those objects. # # Note that integers and strings are both immutable C-based containers. # Neither suffices here, sadly. obj_weakref, obj_repr = make_obj_weakref_and_repr(_IN_THESE_SOLITUDES) assert obj_repr == represent_object(_IN_THESE_SOLITUDES, max_len=999999) assert isinstance(obj_weakref, weakref_ref) assert obj_weakref() is _IN_THESE_SOLITUDES def test_get_weakref_obj_or_repr() -> None: ''' Test the :func:`beartype._util.py.utilpyweakref.get_weakref_obj_or_repr` getter. ''' # ....................{ IMPORTS }.................... # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilPythonWeakrefException from beartype._util.py.utilpyweakref import ( get_weakref_obj_or_repr, make_obj_weakref_and_repr, ) from pytest import raises # ....................{ LOCALS }.................... # Iterable of objects that *CAN* be weakly referenced (e.g., due to *NOT* # being C-based containers). _WEAKREFABLES = (None, _IN_THESE_SOLITUDES) # Iterable of objects that *CANNOT* be weakly referenced (e.g., due to being # C-based containers). _NON_WEAKREFABLES = (_WINDS_CONTEND, _ITS_HOME) # ....................{ PASS }.................... # For each object that *CAN* be weakly referenced... for weakrefable in _WEAKREFABLES: # Weak reference to and representation of this object. weakrefable_weakref, weakrefable_repr = make_obj_weakref_and_repr( weakrefable) # Strong reference to the same object accessed via this weak reference. weakrefable_new = get_weakref_obj_or_repr( weakrefable_weakref, weakrefable_repr) # Assert that these objects are, in fact, the same object. assert weakrefable_new is weakrefable # For each object that *CANNOT* be weakly referenced... for non_weakrefable in _NON_WEAKREFABLES: # Fake weak reference to and representation of this object. non_weakrefable_weakref, non_weakrefable_repr = ( make_obj_weakref_and_repr(non_weakrefable)) # Fake strong reference to this same object accessed via this fake weak # reference. non_weakrefable_new = get_weakref_obj_or_repr( non_weakrefable_weakref, non_weakrefable_repr) # Assert that this fake strong reference is actually just the # representation of this object. assert non_weakrefable_new is non_weakrefable_repr # ....................{ FAIL }.................... # Assert that calling this getter with a valid representation but invalid # weak reference raises the expected exception. with raises(_BeartypeUtilPythonWeakrefException): get_weakref_obj_or_repr( 'Rapid and strong, but silently!', '"Its home"') # ....................{ PRIVATE ~ classes }.................... class _TheVoicelessLightning(object): ''' Arbitrary pure-Python object. ''' # ....................{ PRIVATE ~ classes }.................... class _TheVoicelessLightning(object): ''' Arbitrary pure-Python object. ''' # ....................{ PRIVATE ~ globals }.................... _WINDS_CONTEND = ['Silently there', 'and heap the snow with breath'] ''' Mutable C-based container. ''' _ITS_HOME = ('Rapid and strong', 'but silently') ''' Immutable C-based container. ''' _IN_THESE_SOLITUDES = _TheVoicelessLightning() ''' Arbitrary pure-Python object. '''
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **class-specific utility function** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.cls.utilclstest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_is_type_or_types() -> None: ''' Test the :func:`beartype._util.cls.utilclstest.is_type_or_types` tester. ''' # Defer test-specific imports. from beartype._util.cls.utilclstest import is_type_or_types # Assert this tester accepts an arbitrary type. assert is_type_or_types(str) is True # Assert this tester accepts an arbitrary non-empty tuple of types. assert is_type_or_types((bool, int)) is True # Assert this tester rejects an arbitrary object that is neither a type # nor a non-empty tuple of types. assert is_type_or_types( 'To drink their odours, and their mighty swinging') is False # Assert this tester rejects the empty tuple. assert is_type_or_types(()) is False # Assert this tester rejects an arbitrary non-empty tuple containing one or # more non-types. assert is_type_or_types( (dict, 'To hear—an old and solemn harmony;', float)) is False def test_is_type_builtin() -> None: ''' Test the :func:`beartype._util.cls.utilclstest.is_type_builtin` tester. ''' # Defer test-specific imports. from beartype._util.cls.utilclstest import is_type_builtin from beartype_test.a00_unit.data.data_type import ( TYPES_BUILTIN, TYPES_NONBUILTIN) # Assert this tester accepts all builtin types. for type_builtin in TYPES_BUILTIN: assert is_type_builtin(type_builtin) is True # Assert this tester rejects non-builtin types. for type_nonbuiltin in TYPES_NONBUILTIN: assert is_type_builtin(type_nonbuiltin) is False def test_is_type_subclass() -> None: ''' Test the :func:`beartype._util.cls.utilclstest.is_type_subclass` tester. ''' # Defer test-specific imports. from beartype._util.cls.utilclstest import is_type_subclass from beartype_test.a00_unit.data.data_type import Class, Subclass # Assert this tester accepts objects that are subclasses of superclasses. assert is_type_subclass(Subclass, Class) is True assert is_type_subclass(Class, object) is True assert is_type_subclass(Class, (Class, str)) is True # Assert this tester rejects objects that are superclasses of subclasses. assert is_type_subclass(object, Class) is False assert is_type_subclass(Class, Subclass) is False assert is_type_subclass(Class, (Subclass, str)) is False # Assert this tester rejects objects that are unrelated classes. assert is_type_subclass(str, bool) is False # Assert this tester rejects objects that are non-classes *WITHOUT* raising # an exception. assert is_type_subclass( "Thou many-colour'd, many-voiced vale,", str) is False
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`3119`-compliant **class-specific utility function** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.cls.pep.utilpep3119` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_die_unless_type_isinstanceable() -> None: ''' Test the :func:`beartype._util.cls.pep.utilpep3119.die_unless_type_isinstanceable` validator. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep3119Exception from beartype._util.cls.pep.utilpep3119 import ( die_unless_type_isinstanceable) from beartype_test.a00_unit.data.data_type import ( Class, NonIsinstanceableClass, ) from pytest import raises # Assert this validator accepts an isinstanceable type. die_unless_type_isinstanceable(Class) # Assert this validator raises the expected exception when passed a # non-isinstanceable type. with raises(BeartypeDecorHintPep3119Exception): die_unless_type_isinstanceable(NonIsinstanceableClass) # Assert this validator raises the expected exception when passed a # non-type. with raises(BeartypeDecorHintPep3119Exception): die_unless_type_isinstanceable('Moab.') def test_die_unless_type_issubclassable() -> None: ''' Test the :func:`beartype._util.cls.pep.utilpep3119.die_unless_type_issubclassable` validator. ''' # Defer test-specific imports. from beartype.roar import BeartypeDecorHintPep3119Exception from beartype._util.cls.pep.utilpep3119 import ( die_unless_type_issubclassable) from beartype_test.a00_unit.data.data_type import ( Class, NonIssubclassableClass, ) from pytest import raises # Assert this validator accepts an issubclassable type. die_unless_type_issubclassable(Class) # Assert this validator raises the expected exception when passed a # non-issubclassable type. with raises(BeartypeDecorHintPep3119Exception): die_unless_type_issubclassable(NonIssubclassableClass) # Assert this validator raises the expected exception when passed a # non-type. with raises(BeartypeDecorHintPep3119Exception): die_unless_type_issubclassable('Moab.')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`557`-compliant **class-specific utility function** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.cls.pep.utilpep557` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_is_type_pep557() -> None: ''' Test the :func:`beartype._util.cls.pep.utilpep557.is_type_pep557` tester. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilTypeException from beartype._util.cls.pep.utilpep557 import is_type_pep557 from beartype._util.py.utilpyversion import IS_PYTHON_AT_LEAST_3_8 from pytest import raises # Assert this tester raises the expected exception when passed a non-type. with raises(_BeartypeUtilTypeException): is_type_pep557('The wilderness has a mysterious tongue') # Assert this tester returns false when passed a non-dataclass type. assert is_type_pep557(str) is False # If the active Python interpreter targets Python >= 3.8 and thus supports # PEP 557-compliant dataclasses... if IS_PYTHON_AT_LEAST_3_8: # Defer version-specific imports. from dataclasses import dataclass # Arbitrary dataclass. @dataclass class WhichTeachesAwfulDoubtOrFaithSoMild(object): pass # Assert this tester returns true when passed a dataclass type. assert is_type_pep557(WhichTeachesAwfulDoubtOrFaithSoMild) is True
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **mapping utility** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.kind.utilkinddict` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises # ....................{ CONSTANTS }.................... THE_SONG_OF_HIAWATHA = { 'By the shore': 'of Gitche Gumee', 'By the shining': 'Big-Sea-Water', 'At the': 'doorway of his wigwam', 'In the': 'pleasant Summer morning', 'Hiawatha': 'stood and waited.', } ''' Arbitrary dictionary to be merged. ''' THE_SONG_OF_HIAWATHA_SINGING_IN_THE_SUNSHINE = { 'By the shore': 'of Gitche Gumee', 'By the shining': ['Big-Sea-Water',], 'At the': 'doorway of his wigwam', 'In the': ['pleasant', 'Summer morning',], 'Hiawatha': 'stood and waited.', 'All the air': ['was', 'full of freshness,',], 'All the earth': 'was bright and joyous,', 'And': ['before him,', 'through the sunshine,',], 'Westward': 'toward the neighboring forest', 'Passed in': ['golden swarms', 'the Ahmo,',], 'Passed the': 'bees, the honey-makers,', 'Burning,': ['singing', 'in the sunshine.',], } ''' Arbitrary dictionary to be merged, intentionally containing two key-value collisions with the :data:`THE_SONG_OF_HIAWATHA` dictionary *and* unhashable values. ''' FROM_THE_BROW_OF_HIAWATHA = { 'From the': 'brow of Hiawatha', 'Gone was': 'every trace of sorrow,', 'As the fog': 'from off the water,', 'As the mist': 'from off the meadow.', } ''' Arbitrary dictionary to be merged, intentionally containing neither key nor key-value collisions with any other global dictionary. ''' IN_THE_LODGE_OF_HIAWATHA = { 'I am': 'going, O Nokomis,', 'On a': 'long and distant journey,', 'To the portals': 'of the Sunset,', 'To the regions': 'of the home-wind,', 'Of the Northwest-Wind,': 'Keewaydin.', } ''' Arbitrary dictionary to be merged, intentionally containing: * No key-value collisions with the :data:`THE_SONG_OF_HIAWATHA` dictionary. * Two key collisions but *no* key-value collisions with the :data:`FAREWELL_O_HIAWATHA` dictionary. ''' FAREWELL_O_HIAWATHA = { 'Thus departed': 'Hiawatha,', 'Hiawatha': 'the Beloved,', 'In the': 'glory of the sunset,', 'In the purple': 'mists of evening,', 'To the regions': 'of the home-wind,', 'Of the Northwest-Wind,': 'Keewaydin.', } ''' Arbitrary dictionary to be merged, intentionally containing two key-value collisions with the :data:`THE_SONG_OF_HIAWATHA` dictionary. ''' THE_SONG_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA = { 'By the shore': 'of Gitche Gumee', 'By the shining': 'Big-Sea-Water', 'At the': 'doorway of his wigwam', 'In the': 'pleasant Summer morning', 'Hiawatha': 'stood and waited.', 'I am': 'going, O Nokomis,', 'On a': 'long and distant journey,', 'To the portals': 'of the Sunset,', 'To the regions': 'of the home-wind,', 'Of the Northwest-Wind,': 'Keewaydin.', } ''' Dictionary produced by merging the :data:`THE_SONG_OF_HIAWATHA` and :data:`IN_THE_LODGE_OF_HIAWATHA` dictionaries. ''' IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA = { 'I am': 'going, O Nokomis,', 'On a': 'long and distant journey,', 'To the portals': 'of the Sunset,', 'To the regions': 'of the home-wind,', 'Of the Northwest-Wind,': 'Keewaydin.', 'Thus departed': 'Hiawatha,', 'Hiawatha': 'the Beloved,', 'In the': 'glory of the sunset,', 'In the purple': 'mists of evening,', } ''' Dictionary produced by merging the :data:`IN_THE_LODGE_OF_HIAWATHA` and :data:`FAREWELL_O_HIAWATHA` dictionaries. ''' FROM_THE_BROW_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA = { 'From the': 'brow of Hiawatha', 'Gone was': 'every trace of sorrow,', 'As the fog': 'from off the water,', 'As the mist': 'from off the meadow.', 'I am': 'going, O Nokomis,', 'On a': 'long and distant journey,', 'To the portals': 'of the Sunset,', 'To the regions': 'of the home-wind,', 'Of the Northwest-Wind,': 'Keewaydin.', 'Thus departed': 'Hiawatha,', 'Hiawatha': 'the Beloved,', 'In the': 'glory of the sunset,', 'In the purple': 'mists of evening,', } ''' Dictionary produced by merging the :data:`FROM_THE_BROW_OF_HIAWATHA`, :data:`IN_THE_LODGE_OF_HIAWATHA`, and :data:`FAREWELL_O_HIAWATHA` dictionaries. ''' # ....................{ TESTS ~ validators }.................... def test_die_if_mappings_two_items_collide() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.die_if_mappings_two_items_collide` validator. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilMappingException from beartype._util.kind.utilkinddict import ( die_if_mappings_two_items_collide) # Assert this validator raises the expected exception when passed two # non-empty mappings containing one or more key-value collisions whose # values are all hashable. with raises(_BeartypeUtilMappingException): die_if_mappings_two_items_collide( THE_SONG_OF_HIAWATHA, FAREWELL_O_HIAWATHA) with raises(_BeartypeUtilMappingException): die_if_mappings_two_items_collide( FAREWELL_O_HIAWATHA, THE_SONG_OF_HIAWATHA) # Assert this validator raises the expected exception when passed two # non-empty mappings containing one or more key-value collisions such that # some values of the second mapping are unhashable. with raises(_BeartypeUtilMappingException): die_if_mappings_two_items_collide( THE_SONG_OF_HIAWATHA, THE_SONG_OF_HIAWATHA_SINGING_IN_THE_SUNSHINE) # ....................{ TESTS ~ testers }.................... def test_is_mapping_keys_all() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.is_mapping_keys_all` tester. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilMappingException from beartype._util.kind.utilkinddict import is_mapping_keys_all # Assert this tester returns true when passed a mapping containing all keys # in the passed set. assert is_mapping_keys_all( mapping=THE_SONG_OF_HIAWATHA_SINGING_IN_THE_SUNSHINE, keys=THE_SONG_OF_HIAWATHA.keys(), ) is True # Assert this tester returns false when passed a mapping *NOT* containing # all keys in the passed set. assert is_mapping_keys_all( mapping=THE_SONG_OF_HIAWATHA_SINGING_IN_THE_SUNSHINE, keys=THE_SONG_OF_HIAWATHA.keys() | {'As the mist',}, ) is False def test_is_mapping_keys_any() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.is_mapping_keys_any` tester. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilMappingException from beartype._util.kind.utilkinddict import is_mapping_keys_any # Assert this tester returns true when passed a mapping containing any key # in the passed set. assert is_mapping_keys_any( mapping=FAREWELL_O_HIAWATHA, keys={'Thus departed', 'By the shore', 'To the portals'}, ) is True # Assert this tester returns false when passed a mapping containing *NO* key # in the passed set. assert is_mapping_keys_any( mapping=FAREWELL_O_HIAWATHA, keys={'By the shore', 'To the portals'}, ) is False # ....................{ TESTS ~ updaters }.................... def test_update_mapping() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.update_mapping` function. ''' # Defer test-specific imports. from beartype._util.kind.utilkinddict import update_mapping # Shallow copies of arbitrary mappings to be modified below. farewell_o_hiawatha = FAREWELL_O_HIAWATHA.copy() the_song_of_hiawatha = THE_SONG_OF_HIAWATHA.copy() # Assert this updater preserves this mapping when updated from an empty # mapping. update_mapping(farewell_o_hiawatha, {}) assert farewell_o_hiawatha == FAREWELL_O_HIAWATHA # Assert this updater updates this mapping as expected when updating from a # non-empty mapping containing no key or key-value collisions. update_mapping(the_song_of_hiawatha, IN_THE_LODGE_OF_HIAWATHA) assert the_song_of_hiawatha == ( THE_SONG_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA) # Assert this updater updates this mapping as expected when updating from a # non-empty mapping containing multiple key but no key-value collisions. update_mapping(farewell_o_hiawatha, IN_THE_LODGE_OF_HIAWATHA) assert farewell_o_hiawatha == IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA # ....................{ TESTS ~ mergers }.................... def test_merge_mappings_two() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.merge_mappings` function passed exactly two mappings. ''' # Defer test-specific imports. from beartype._util.kind.utilkinddict import merge_mappings # Assert this function merges two empty mappings into a new empty mapping. assert merge_mappings({}, {}) == {} # Assert this function merges a non-empty mapping and an empty mapping into # the same non-empty mapping. assert merge_mappings(THE_SONG_OF_HIAWATHA, {}) == THE_SONG_OF_HIAWATHA assert merge_mappings({}, THE_SONG_OF_HIAWATHA) == THE_SONG_OF_HIAWATHA # Assert this function merges two non-empty mappings containing no key or # key-value collisions into the expected mapping. assert merge_mappings(THE_SONG_OF_HIAWATHA, IN_THE_LODGE_OF_HIAWATHA) == ( THE_SONG_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA) assert merge_mappings(IN_THE_LODGE_OF_HIAWATHA, THE_SONG_OF_HIAWATHA) == ( THE_SONG_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA) # Assert this function merges two non-empty mappings containing multiple # key but no key-value collisions into the expected mapping. assert merge_mappings(IN_THE_LODGE_OF_HIAWATHA, FAREWELL_O_HIAWATHA) == ( IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA) assert merge_mappings(FAREWELL_O_HIAWATHA, IN_THE_LODGE_OF_HIAWATHA) == ( IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA) def test_merge_mappings_three() -> None: ''' Test the :func:`beartype._util.kind.utilkinddict.merge_mappings` function passed exactly three mappings. ''' # Defer test-specific imports. from beartype._util.kind.utilkinddict import merge_mappings # Assert this function merges three empty mappings into a new empty # mapping. assert merge_mappings({}, {}, {}) == {} # Assert this function merges a non-empty mapping and two empty mappings # into the same non-empty mapping. assert merge_mappings(THE_SONG_OF_HIAWATHA, {}, {}) == THE_SONG_OF_HIAWATHA assert merge_mappings({}, THE_SONG_OF_HIAWATHA, {}) == THE_SONG_OF_HIAWATHA assert merge_mappings({}, {}, THE_SONG_OF_HIAWATHA) == THE_SONG_OF_HIAWATHA # Assert this function merges two non-empty mappings containing multiple # key collisions but no key-value collisions and another non-empty mapping # containing neither key nor key-value collisions into the expected # mapping. assert merge_mappings( FROM_THE_BROW_OF_HIAWATHA, IN_THE_LODGE_OF_HIAWATHA, FAREWELL_O_HIAWATHA, ) == ( FROM_THE_BROW_OF_HIAWATHA_IN_THE_LODGE_OF_HIAWATHA_FAREWELL_O_HIAWATHA)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype callable caching utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.cache.utilcachecall` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_callable_cached() -> None: ''' Test the :func:`beartype._util.cache.utilcachecall.callable_cached` decorator. ''' # ..................{ IMPORTS }.................. # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilCallableCachedException from beartype._util.cache.utilcachecall import callable_cached from pytest import raises # ..................{ CALLABLES }.................. @callable_cached def still_i_rise(bitter, twisted, lies): ''' Arbitrary callable memoized by this decorator. ''' # If an arbitrary condition, raise an exception whose value depends on # these parameters to exercise this decorator's conditional caching of # exceptions. if len(lies) == 6: raise ValueError(lies) # Else, return a value depending on these parameters to exercise this # decorator's conditional caching of return values. return bitter + twisted + lies # ..................{ LOCALS }.................. # Hashable objects to be passed as parameters below. bitter = ('You', 'may', 'write', 'me', 'down', 'in', 'history',) twisted = ('With', 'your', 'bitter,', 'twisted,', 'lies.',) lies = ('You', 'may', 'trod,', 'me,', 'in', 'the', 'very', 'dirt',) dust = ('But', 'still,', 'like', 'dust,', "I'll", 'rise',) # ..................{ ASSERTS ~ pass }.................. # Assert that memoizing two calls passed the same positional arguments # caches and returns the same value. assert ( still_i_rise(bitter, twisted, lies) is still_i_rise(bitter, twisted, lies)) # Assert that memoizing a call expected to raise an exception does so. with raises(ValueError) as exception_first_info: still_i_rise(bitter, twisted, dust) # Assert that repeating that call reraises the same exception. with raises(ValueError) as exception_next_info: still_i_rise(bitter, twisted, dust) assert exception_first_info is exception_next_info # Assert that passing one or more unhashable parameters to this callable # succeeds with the expected return value. assert still_i_rise( ['Just', 'like', 'moons',], ['and', 'like', 'suns',], ['With the certainty of tides',], ) == [ 'Just', 'like', 'moons', 'and', 'like', 'suns', 'With the certainty of tides', ] # ..................{ ASSERTS ~ fail }.................. # Assert that attempting to memoize a callable accepting one or more # variadic positional parameters fails with the expected exception. with raises(_BeartypeUtilCallableCachedException): @callable_cached def see_me_broken(*args): return args def test_method_cached_arg_by_id() -> None: ''' Test the :func:`beartype._util.cache.utilcachecall.method_cached_arg_by_id` decorator. ''' # ..................{ IMPORTS }.................. # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilCallableCachedException from beartype._util.cache.utilcachecall import method_cached_arg_by_id from pytest import raises # ..................{ CLASSES }.................. class LikeDust(object): ''' Arbitrary class containing an arbitrary callable memoized by this decorator. ''' @method_cached_arg_by_id def just_like_moons(self, and_like_suns): ''' Arbitrary callable memoized by this decorator. ''' # If an arbitrary condition, raise an exception whose value depends # on these parameters to exercise this decorator's conditional # caching of exceptions. if len(and_like_suns) == 6: raise ValueError(and_like_suns) # Else, return a value depending on these parameters to exercise # this decorator's conditional caching of return values. return [id(self), and_like_suns] # ..................{ LOCALS }.................. # Instance of this class. like_air = LikeDust() # Hashable objects to be passed as parameters below. moons = ('Just', 'like', 'moons', 'and', 'like', 'suns,') tides = ('With', 'the', 'certainty,', 'of,', 'tides,',) # Shallow copies of hashable objects defined above. # # Note that copying a list in a manner guaranteeing even a shallow copy is # surprisingly non-trivial. See this relevant StackOverflow answer: # https://stackoverflow.com/a/15214661/2809027 tides_copy = tuple(list(tides)) # Unhashable objects to be passed as parameters below. hopes = ['Just', 'like', 'hopes,', 'springing,', 'high',] # ..................{ ASSERTS ~ pass }.................. # Assert that memoizing two calls passed the same positional arguments # caches and returns the same value. assert ( like_air.just_like_moons(tides) is like_air.just_like_moons(tides)) # Assert that memoizing two calls passed a copy of the above arguments # caches and returns a different value. assert ( like_air.just_like_moons(tides_copy) is not like_air.just_like_moons(tides)) # Assert that memoizing a call expected to raise an exception does so. with raises(ValueError) as exception_first_info: like_air.just_like_moons(moons) # Assert that repeating that call reraises the same exception. with raises(ValueError) as exception_next_info: like_air.just_like_moons(moons) assert exception_first_info is exception_next_info # Assert that passing one or more unhashable parameters to this callable # succeeds with the expected return value. assert like_air.just_like_moons(hopes) == [id(like_air), hopes] # ..................{ ASSERTS ~ fail }.................. # Assert that attempting to memoize a callable accepting *NO* parameters # fails with the expected exception. with raises(_BeartypeUtilCallableCachedException): @method_cached_arg_by_id def into_a_daybreak_thats_wondrously_clear(): return 0 # Assert that attempting to memoize a callable accepting one or more # variadic positional parameters fails with the expected exception. with raises(_BeartypeUtilCallableCachedException): @method_cached_arg_by_id def leaving_behind_nights_of_terror_and_fear(*args): return args def test_property_cached() -> None: ''' Test the :func:`beartype._util.cache.utilcachecall.property_cached` decorator. ''' # ..................{ IMPORTS }.................. # Defer test-specific imports. from beartype._util.cache.utilcachecall import property_cached # ..................{ CLASSES }.................. class Keeper(object): ''' Arbitrary class defining the property to be cached. ''' def __init__(self, keys: int) -> None: self.keys = keys @property @property_cached def keys_cached(self) -> int: # Property value to be both cached and returned. keys_cached = self.keys * 2 # To detect erroneous attempts to call this property method multiple # times for the same object, modify the object variable from which # this property value derived in a predictable way on each call of # this property method. self.keys /= 2 # Return this property value. return keys_cached # ..................{ LOCALS }.................. # Value of the "Keeper.keys" attribute *BEFORE* invoking keys_cached(). KEY_COUNT_PRECACHED = 7 # Value of the "Keeper.keys" attribute *AFTER* invoking keys_cached(). KEY_COUNT_POSTCACHED = KEY_COUNT_PRECACHED / 2 # Value of the "Keeper.keys_cached" property. KEY_COUNT_CACHED = KEY_COUNT_PRECACHED * 2 # Instance of this class initialized with this value. i_want_out = Keeper(keys=KEY_COUNT_PRECACHED) # ..................{ ASSERTS }.................. # Assert this attribute to be as initialized. assert i_want_out.keys == KEY_COUNT_PRECACHED # Assert this property to be as cached. assert i_want_out.keys_cached == KEY_COUNT_CACHED # Assert this attribute to have been modified by this property call. assert i_want_out.keys == KEY_COUNT_POSTCACHED # Assert this property to still be as cached. assert i_want_out.keys_cached == KEY_COUNT_CACHED # Assert this attribute to *NOT* have been modified again, validating that # the prior property access returned the previously cached value rather than # recalling this property method. assert i_want_out.keys == KEY_COUNT_POSTCACHED
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. """ Project-wide **Least Recently Used (LRU) cache** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.cache.map.utilmaplru` submodule. """ # ....................{ IMPORTS }.................... # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises from beartype.roar._roarexc import _BeartypeUtilCacheLruException # ....................{ TESTS }.................... def test_lrucachestrong_one_pass() -> None: """ Test successful usage of the :func:`beartype._util.cache.map.utilmaplru.CacheLruStrong` class against an LRU cache caching at most one key-value pair. """ # Defer test-specific imports. from beartype._util.cache.map.utilmaplru import CacheLruStrong # Arbitrary key-value pair. LRU_CACHE_KEY_A = 'KEY_A' LRU_CACHE_VALUE_A = 'VALUE_A' # Another arbitrary key-value pair. LRU_CACHE_KEY_B = 'KEY_B' LRU_CACHE_VALUE_B = 'VALUE_B' lru_cache = CacheLruStrong(size=1) assert len(lru_cache) == 0 # Cache and confirm the first and only key-value pair of this cache is this # pair. lru_cache[LRU_CACHE_KEY_A] = LRU_CACHE_VALUE_A assert len(lru_cache) == 1 assert lru_cache[LRU_CACHE_KEY_A] == LRU_CACHE_VALUE_A # Test the implicit enforcement of cache size lru_cache[LRU_CACHE_KEY_B] = LRU_CACHE_VALUE_B assert len(lru_cache) == 1 assert lru_cache[LRU_CACHE_KEY_B] == LRU_CACHE_VALUE_B del lru_cache[LRU_CACHE_KEY_B] assert len(lru_cache) == 0 def test_lrucachestrong_two_pass() -> None: """ Test successful usage of the :func:`beartype._util.cache.map.utilmaplru.CacheLruStrong` class against an LRU cache caching at most two key-value pairs. """ # Defer test-specific imports. from beartype._util.cache.map.utilmaplru import CacheLruStrong # Arbitrary key-value pair. LRU_CACHE_KEY_A = 'KEY_A' LRU_CACHE_VALUE_A = 'VALUE_A' LRU_CACHE_ITEM_A = (LRU_CACHE_KEY_A, LRU_CACHE_VALUE_A) # Another arbitrary key-value pair. LRU_CACHE_KEY_B = 'KEY_B' LRU_CACHE_VALUE_B = 'VALUE_B' LRU_CACHE_ITEM_B = (LRU_CACHE_KEY_B, LRU_CACHE_VALUE_B) # Another arbitrary key-value pair. LRU_CACHE_KEY_C = 'KEY_C' LRU_CACHE_VALUE_C = 'VALUE_C' LRU_CACHE_ITEM_C = (LRU_CACHE_KEY_C, LRU_CACHE_VALUE_C) lru_cache = CacheLruStrong(size=2) # Cache two arbitrary key-value pairs and confirm they've been cached in # insertion order. lru_cache[LRU_CACHE_KEY_A] = LRU_CACHE_VALUE_A lru_cache[LRU_CACHE_KEY_B] = LRU_CACHE_VALUE_B lru_cache_items = iter(lru_cache.items()) assert len(lru_cache) == 2 assert next(lru_cache_items) == LRU_CACHE_ITEM_A assert next(lru_cache_items) == LRU_CACHE_ITEM_B # Confirm __getitem__ resets the key in the cache. assert lru_cache[LRU_CACHE_KEY_A] == LRU_CACHE_VALUE_A lru_cache_items = iter(lru_cache.items()) assert len(lru_cache) == 2 assert next(lru_cache_items) == LRU_CACHE_ITEM_B assert next(lru_cache_items) == LRU_CACHE_ITEM_A # Confirm __contains__ resets the key in the cache. assert LRU_CACHE_KEY_B in lru_cache lru_cache_items = iter(lru_cache.items()) assert next(lru_cache_items) == LRU_CACHE_ITEM_A assert next(lru_cache_items) == LRU_CACHE_ITEM_B # Confirm the implicit enforcement of cache size lru_cache[LRU_CACHE_KEY_C] = LRU_CACHE_VALUE_C assert len(lru_cache) == 2 assert LRU_CACHE_KEY_A not in lru_cache # Confirm the remaining key-value pairs have been cached in insertion # order. lru_cache_items = iter(lru_cache.items()) assert next(lru_cache_items) == LRU_CACHE_ITEM_B assert next(lru_cache_items) == LRU_CACHE_ITEM_C # Confirm __setitem__ resets a cached key. lru_cache[LRU_CACHE_KEY_B] = LRU_CACHE_VALUE_B lru_cache_items = iter(lru_cache.items()) assert next(lru_cache_items) == LRU_CACHE_ITEM_C assert next(lru_cache_items) == LRU_CACHE_ITEM_B def test_lrucachestrong_fail() -> None: """ Test unsuccessful usage of the :func:`beartype._util.cache.map.utilmaplru.CacheLruStrong` class. """ # Defer test-specific imports. from beartype._util.cache.map.utilmaplru import CacheLruStrong # Confirm behaviour for a non-integer size. with raises(_BeartypeUtilCacheLruException): CacheLruStrong(size="Wait a minute, I'm not an int!") # Confirm behaviour for a non-positive size. with raises(_BeartypeUtilCacheLruException): CacheLruStrong(size=0)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. """ Project-wide **unbounded cache** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.cache.map.utilmapbig` submodule. """ # ....................{ IMPORTS }.................... # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_cacheunboundedstrong() -> None: """ Test successful usage of the :class:`beartype._util.cache.map.utilmapbig.CacheUnboundedStrong` class. """ # Defer test-specific imports. from beartype._util.cache.map.utilmapbig import CacheUnboundedStrong # Initially empty unbounded cache. cache_unbounded = CacheUnboundedStrong() # Arbitrary key-value pairs. KEY_A = 'My own, my human mind, which passively' VALUE_A = 'Now renders and receives fast influencings,' KEY_B = 'Holding an unremitting interchange' VALUE_B = 'With the clear universe of things around;' def value_factory(key) -> object: ''' Arbitrary function accepting an arbitrary key and dynamically returning the value to be associated with this key. ''' # Trivially return the hash of this key. return hash(key) # Assert that statically getting an uncached key returns the passed value # (i.e., caches that key with that value). assert cache_unbounded.cache_or_get_cached_value( key=KEY_A, value=VALUE_A) is VALUE_A # Assert that statically getting a cached key returns the previously # (rather than currently) passed value. assert cache_unbounded.cache_or_get_cached_value( key=KEY_A, value=VALUE_B) is VALUE_A # Assert that dynamically getting a cached key returns the previously # passed value rather than a value returned by the passed value factory. assert cache_unbounded.cache_or_get_cached_func_return_passed_arg( key=KEY_A, value_factory=value_factory, arg=KEY_A) is VALUE_A # Assert that dynamically getting an uncached key returns the value # returned by the passed value factory (i.e., caches that key with that # value). assert cache_unbounded.cache_or_get_cached_func_return_passed_arg( key=KEY_B, value_factory=value_factory, arg=KEY_B) == hash(KEY_B)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype key pool unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.cache.pool.utilcachepool` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_key_pool_pass() -> None: ''' Test successful usage of the :class:`beartype._util.cache.pool.utilcachepool.KeyPool` type. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepool import KeyPool from beartype.roar._roarexc import _BeartypeUtilCachedKeyPoolException from io import StringIO from pytest import raises # Key pool to be tested, seeding empty pools keyed on the "newline" # parameter passed to the StringIO.__init__() method with a new "StringIO" # instance initialized to that parameter. # # Note that the "initial_value" parameter is currently unavailable under # "pypy3" and *MUST* thus be omitted here: # $ pypy3 # >>> from io import StringIO # >>> StringIO(initial_value='', newline=newline) # TypeError: __init__() got an unexpected keyword argument 'initial_value' key_pool = KeyPool(item_maker=lambda newline: StringIO(newline=newline)) # Acquire a new "StringIO" buffer writing Windows-style newlines. windows_stringio = key_pool.acquire(key='\r\n', is_debug=True) # Stanzas delimited by Windows-style newlines to be tested below. THE_DEAD_SHALL_BE_RAISED_INCORRUPTIBLE = '\r\n'.join(( 'My stomach, which has digested', 'four hundred treaties giving the Indians', 'eternal right to their land, I give to the Indians,', 'I throw in my lungs which have spent four hundred years', 'sucking in good faith on peace pipes.', )) BOOK_OF_NIGHTMARES = '\r\n'.join(( 'To the last man surviving on earth', 'I give my eyelids worn out by fear, to wear', 'in his long nights of radiation and silence,', 'so that his eyes can’t close, for regret', 'is like tears seeping through closed eyelids.', )) # Write a series of POSIX-style lines to this buffer. windows_stringio.write('My stomach, which has digested\n') windows_stringio.write('four hundred treaties giving the Indians\n') windows_stringio.write('eternal right to their land, I give to the Indians,\n') windows_stringio.write('I throw in my lungs which have spent four hundred years\n') windows_stringio.write('sucking in good faith on peace pipes.') # Verify the buffer implicitly converted all POSIX- to Windows-style # newlines in the resulting string. assert ( windows_stringio.getvalue() == THE_DEAD_SHALL_BE_RAISED_INCORRUPTIBLE) # Release this buffer back to its parent pool. key_pool.release(key='\r\n', item=windows_stringio, is_debug=True) # Reacquire the same buffer. windows_stringio_too = key_pool.acquire(key='\r\n', is_debug=True) # Confirm the release-require cycle returns the same object assert windows_stringio is windows_stringio_too # Acquire another new "StringIO" buffer writing Windows-style newlines. windows_stringio_new = key_pool.acquire(key='\r\n', is_debug=True) # Assert this to *NOT* be the same buffer. assert windows_stringio is not windows_stringio_new # Write a series of POSIX-style lines to this new buffer. windows_stringio_new.write('To the last man surviving on earth\n') windows_stringio_new.write('I give my eyelids worn out by fear, to wear\n') windows_stringio_new.write('in his long nights of radiation and silence,\n') windows_stringio_new.write('so that his eyes can’t close, for regret\n') windows_stringio_new.write('is like tears seeping through closed eyelids.') # Confirm the new buffer also implicitly converted all POSIX- to # Windows-style newlines in the resulting string. assert windows_stringio_new.getvalue() == BOOK_OF_NIGHTMARES # Release these buffers back to their parent pools (in acquisition order). key_pool.release(key='\r\n', item=windows_stringio, is_debug=True) key_pool.release(key='\r\n', item=windows_stringio_new, is_debug=True) # Confirm the above object is released AND that releasing an already # released object with debugging logic enabled elicits a roar. with raises(_BeartypeUtilCachedKeyPoolException): key_pool.release(key='\r\n', item=windows_stringio_new, is_debug=True) def test_key_pool_fail() -> None: ''' Test unsuccessful usage of the :class:`beartype._util.cache.pool.utilcachepool.KeyPool` type. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepool import KeyPool from beartype.roar._roarexc import _BeartypeUtilCachedKeyPoolException from pytest import raises # Key pool to be tested, seeding empty pools with the identity function. key_pool = KeyPool(item_maker=lambda key: key) # Verify using an unhashable key to acquire a new object throws a TypeError with raises(TypeError): key_pool.acquire( ['Lieutenant!', 'This corpse will not stop burning!'], is_debug=True, ) # Verify releasing a non-existent object elicits a roar with raises(_BeartypeUtilCachedKeyPoolException): key_pool.release(key='I should roar', item=object(), is_debug=True)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype utility fixed list pool unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.cache.pool.utilcachepoolobjecttyped` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from io import StringIO from pytest import raises # ....................{ TESTS ~ pool }.................... def test_objecttyped_pool_pass() -> None: ''' Test successful usage of the :mod:`beartype._util.cache.pool.utilcachepoolobjecttyped` submodule. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoolobjecttyped import ( acquire_object_typed, release_object_typed) # Culturally relevant Clash lyrics to be tested below. PUBLIC_SERVICE_ANNOUNCEMENT = '\n'.join(( 'You have the right not to be killed.', 'Murder is a crime,', 'Unless it was done', 'By a policeman', 'Or an aristocrat.', )) KNOW_YOUR_RIGHTS = '\n'.join(( 'You have the right to food money --', 'Providing, of course, you', "Don't mind a little", 'Investigation, humiliation,', 'And (if you cross your fingers)', 'Rehabilitation.', )) # Acquire an arbitrary string buffer. public_service_announcement = acquire_object_typed(cls=StringIO) # Clear this buffer and reset its position to the start. public_service_announcement.truncate(0) public_service_announcement.seek(0) # Write a series of culturally relevant Clash lyrics to this buffer. public_service_announcement.write('You have the right not to be killed.\n') public_service_announcement.write('Murder is a crime,\n') public_service_announcement.write('Unless it was done\n') public_service_announcement.write('By a policeman\n') public_service_announcement.write('Or an aristocrat.') # Acquire another arbitrary string buffer. know_your_rights = acquire_object_typed(cls=StringIO) # Clear this buffer and reset its position to the start. know_your_rights.truncate(0) know_your_rights.seek(0) # Write another series of culturally relevant Clash lyrics to this buffer. know_your_rights.write('You have the right to food money --\n') know_your_rights.write('Providing, of course, you\n') know_your_rights.write("Don't mind a little\n") know_your_rights.write('Investigation, humiliation,\n') know_your_rights.write('And (if you cross your fingers)\n') know_your_rights.write('Rehabilitation.') # Assert the contents of these buffers to still be as expected. assert ( public_service_announcement.getvalue() == PUBLIC_SERVICE_ANNOUNCEMENT) assert know_your_rights.getvalue() == KNOW_YOUR_RIGHTS # Release the first buffer back to its parent pool. release_object_typed(public_service_announcement) # Reacquire the same buffer again. public_service_announcement_too = acquire_object_typed(cls=StringIO) # Assert this to be the same buffer. assert public_service_announcement is public_service_announcement_too # Assert the second buffer to *NOT* be the same buffer. assert public_service_announcement is not know_your_rights # Release these buffers back to their parent pools (in acquisition order). release_object_typed(public_service_announcement) release_object_typed(know_your_rights) def test_objecttyped_pool_fail() -> None: ''' Test unsuccessful usage of the :mod:`beartype._util.cache.pool.utilcachepoolobjecttyped` submodule. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoolobjecttyped import ( acquire_object_typed) from beartype.roar._roarexc import _BeartypeUtilCachedObjectTypedException # Assert that typed objects may only be acquired with types. with raises(_BeartypeUtilCachedObjectTypedException): acquire_object_typed(( 'You have the right to free speech', 'As long as', "You're not dumb enough to actually try it.", )) with raises(_BeartypeUtilCachedObjectTypedException): acquire_object_typed(1977)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype utility fixed list pool unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.cache.pool.utilcachepoollistfixed` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises # ....................{ TESTS ~ pool }.................... def test_listfixed_pool_pass() -> None: ''' Test successful usage of the :mod:`beartype._util.cache.pool.utilcachepoollistfixed` submodule. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoollistfixed import ( acquire_fixed_list, release_fixed_list) # Acquire a fixed list of some length. moloch_solitude_filth = acquire_fixed_list(size=3) # Initialize this list. moloch_solitude_filth[:] = ( 'Moloch! Solitude! Filth! Ugliness! Ashcans and unobtainable dollars!', 'Children screaming under the stairways! Boys sobbing in armies! Old', 'men weeping in the parks!', ) # Acquire another fixed list of the same length. moloch_whose = acquire_fixed_list(size=3) # Initialize this list. moloch_whose[:] = ( 'Moloch whose mind is pure machinery! Moloch whose blood is running', 'money! Moloch whose fingers are ten armies! Moloch whose breast is a', 'cannibal dynamo! Moloch whose ear is a smoking tomb!', ) # Assert the contents of these lists to still be as expected. assert moloch_solitude_filth[0] == ( 'Moloch! Solitude! Filth! Ugliness! Ashcans and unobtainable dollars!') assert moloch_whose[-1] == ( 'cannibal dynamo! Moloch whose ear is a smoking tomb!') # Release these lists. release_fixed_list(moloch_solitude_filth) release_fixed_list(moloch_whose) def test_listfixed_pool_fail() -> None: ''' Test unsuccessful usage of the :mod:`beartype._util.cache.pool.utilcachepoollistfixed` submodule. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoollistfixed import ( acquire_fixed_list) from beartype.roar._roarexc import _BeartypeUtilCachedFixedListException # Assert that fixed lists may only be acquired with positive integers. with raises(_BeartypeUtilCachedFixedListException): acquire_fixed_list(( 'Moloch the incomprehensible prison! Moloch the crossbone soulless', 'jailhouse and Congress of sorrows! Moloch whose buildings are', 'judgment! Moloch the vast stone of war! Moloch the stunned', 'governments!', )) with raises(_BeartypeUtilCachedFixedListException): acquire_fixed_list(-67) # ....................{ TESTS ~ type }.................... def test_listfixed_type_pass() -> None: ''' Test successful usage of the :mod:`beartype._util.cache.pool.utilcachepoollistfixed.FixedList` type. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoollistfixed import FixedList # Fixed list to be tested. fixed_list = FixedList(size=11) # Assert this list to be of the expected size. assert len(fixed_list) == 11 # Assert that list slicing to an iterable of the same length succeeds. fixed_list[:] = ( 'Love the quick profit, the annual raise,', 'vacation with pay. Want more', 'of everything ready-made. Be afraid', 'to know your neighbors and to die.', 'And you will have a window in your head.', 'Not even your future will be a mystery', 'any more. Your mind will be punched in a card', 'and shut away in a little drawer.', 'When they want you to buy something', 'they will call you. When they want you', 'to die for profit they will let you know.', ) assert fixed_list[ 0] == 'Love the quick profit, the annual raise,' assert fixed_list[10] == 'to die for profit they will let you know.' # Assert that list copying succeeds. fixed_list_copy = fixed_list.copy() assert isinstance(fixed_list_copy, FixedList) assert fixed_list_copy == fixed_list def test_listfixed_type_fail() -> None: ''' Test unsuccessful usage of the :mod:`beartype._util.cache.pool.utilcachepoollistfixed.FixedList` type. ''' # Defer test-specific imports. from beartype._util.cache.pool.utilcachepoollistfixed import FixedList from beartype.roar._roarexc import _BeartypeUtilCachedFixedListException # Fixed list to be tested. fixed_list = FixedList(size=8) fixed_list[:] = ( 'Ask the questions that have no answers.', 'Invest in the millennium. Plant sequoias.', 'Say that your main crop is the forest', 'that you did not plant,', 'that you will not live to harvest.', 'Say that the leaves are harvested', 'when they have rotted into the mold.', 'Call that profit. Prophesy such returns.', ) # Assert that fixed lists refuse to support item deletion. with raises(_BeartypeUtilCachedFixedListException): del fixed_list[0] # Assert that fixed lists refuse to support in-place addition. with raises(_BeartypeUtilCachedFixedListException): fixed_list += ( 'Put your faith in the two inches of humus', 'that will build under the trees', 'every thousand years.', 'Listen to carrion – put your ear', 'close, and hear the faint chattering', 'of the songs that are to come.', 'Expect the end of the world. Laugh.', 'Laughter is immeasurable. Be joyful', 'though you have considered all the facts.', ) # Assert that fixed lists refuse to support in-place multiplication. with raises(_BeartypeUtilCachedFixedListException): fixed_list *= 0xDEADBEEF #FIXME: Disabled. For efficiency, fixed lists currently permissively #support slicing to an iterable of differing length. It is what it is. # # Assert that fixed lists refuse to support slicing to an iterable of # # differing length. # with raises(_BeartypeUtilCachedFixedListException): # fixed_list[0:2] = ( # 'Go with your love to the fields.', # 'Lie down in the shade. Rest your head', # 'in her lap. Swear allegiance', # 'to what is nighest your thoughts.', # 'As soon as the generals and the politicos', # 'can predict the motions of your mind,', # 'lose it. Leave it as a sign', # 'to mark the false trail, the way', # 'you didn’t go. Be like the fox', # 'who makes more tracks than necessary,', # 'some in the wrong direction.', # 'Practice resurrection.', # ) # Assert that fixed lists refuse to support appending. with raises(_BeartypeUtilCachedFixedListException): fixed_list.append('Love the world. Work for nothing.') # Assert that fixed lists refuse to support extending. with raises(_BeartypeUtilCachedFixedListException): fixed_list.extend(( 'Take all that you have and be poor.', 'Love someone who does not deserve it.', )) # Assert that fixed lists refuse to support clearing. with raises(_BeartypeUtilCachedFixedListException): fixed_list.clear() # Assert that fixed lists refuse to support popping. with raises(_BeartypeUtilCachedFixedListException): fixed_list.pop() # Assert that fixed lists refuse to support removal. with raises(_BeartypeUtilCachedFixedListException): fixed_list.remove('Invest in the millennium. Plant sequoias.')
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **platform tester** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.os.utilostest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_os_macos() -> None: ''' Test the :func:`beartype._util.os.utilostest.is_os_macos` tester. ''' # Defer test-specific imports. from beartype._util.os.utilostest import is_os_macos # Assert this tester returns a boolean. IS_OS_MACOS = is_os_macos() assert isinstance(IS_OS_MACOS, bool) def test_is_os_windows_vanilla() -> None: ''' Test the :func:`beartype._util.os.utilostest.is_os_windows_vanilla` tester. ''' # Defer test-specific imports. from beartype._util.os.utilostest import is_os_windows_vanilla # Assert this tester returns a boolean. IS_OS_WINDOWS_VANILLA = is_os_windows_vanilla() assert isinstance(IS_OS_WINDOWS_VANILLA, bool)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **terminal tester** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.os.utilostty` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ tester }.................... def test_is_stdout_terminal() -> None: ''' Test the :func:`beartype._util.os.utilostty.is_stdout_terminal` tester. ''' # Defer test-specific imports. from beartype._util.os.utilostty import is_stdout_terminal # Assert this tester returns a boolean. IS_STDOUT_TERMINAL = is_stdout_terminal() assert isinstance(IS_STDOUT_TERMINAL, bool)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. """ **Beartype object label utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.text.utiltextmunge.py` submodule. """ # ....................{ IMPORTS }.................... # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ labellers }.................... def test_label_type() -> None: ''' Test the :func:`beartype._util.text.utiltextlabel.label_type` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextlabel import label_type from beartype_test.a00_unit.data.data_type import Class # Assert this labeller returns the expected label for a builtin type. assert label_type(str) == 'str' # Assert this labeller returns the expected label for the non-builtin type # of the "None" singleton, exercising a common edge case. assert label_type(type(None)) == '<class "builtins.NoneType">' # Assert this labeller returns the expected label for a user-defined type. assert label_type(Class) == ( '<class "beartype_test.a00_unit.data.data_type.Class">') # ....................{ TESTS ~ prefixers }.................... def test_prefix_callable() -> None: ''' Test the :func:`beartype._util.text.utiltextlabel.prefix_callable` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextlabel import prefix_callable from beartype_test.a00_unit.data.data_type import ( async_coroutine_factory, async_generator_factory, sync_generator_factory, ) from beartype_test.a00_unit.data.util.mod.data_utilmodule_line import ( like_snakes_that_watch_their_prey, ozymandias, which_yet_survive, ) # Assert this labeller labels an on-disk lambda function as expected. two_vast_and_trunkless_legs_of_stone = prefix_callable(ozymandias) assert isinstance(two_vast_and_trunkless_legs_of_stone, str) assert 'lambda' in two_vast_and_trunkless_legs_of_stone # Assert this labeller labels an in-memory lambda function as expected. the_hand_that_mocked_them = prefix_callable(which_yet_survive) assert isinstance(the_hand_that_mocked_them, str) assert 'lambda' in the_hand_that_mocked_them # Assert this labeller labels an on-disk non-lambda callable as expected. tell_that_its_sculptor_well_those_passions_read = prefix_callable( like_snakes_that_watch_their_prey) assert isinstance(tell_that_its_sculptor_well_those_passions_read, str) assert like_snakes_that_watch_their_prey.__name__ in ( tell_that_its_sculptor_well_those_passions_read) # Assert this labeller labels an on-disk coroutine as expected. async_coroutine_label = prefix_callable(async_coroutine_factory) assert isinstance(async_coroutine_label, str) assert async_coroutine_factory.__name__ in async_coroutine_label assert 'coroutine' in async_coroutine_label # Assert this labeller labels an on-disk asynchronous generator as expected. async_generator_label = prefix_callable(async_generator_factory) assert isinstance(async_generator_label, str) assert async_generator_factory.__name__ in async_generator_label assert 'asynchronous generator' in async_generator_label # Assert this labeller labels an on-disk synchronous generator as expected. sync_generator_label = prefix_callable(sync_generator_factory) assert isinstance(sync_generator_label, str) assert sync_generator_factory.__name__ in sync_generator_label assert 'generator' in sync_generator_label
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python identifier** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.text.utiltextident` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_is_identifier() -> None: ''' Test the :func:`beartype._util.text.utiltextident.is_identifier` tester. ''' # Defer test-specific imports. from beartype._util.text.utiltextident import is_identifier # Assert this tester accepts an unqualified Python identifier prefixed by # an underscore and suffixed by a digit. assert is_identifier('_the_lucy_poems_5') is True # Assert this tester accepts a fully-qualified Python identifier containing # underscores and digits. assert is_identifier('She_dwelt.among_the.untrodden.ways_2') is ( True) # Assert this tester rejects the empty string. assert is_identifier('') is False # Assert this tester rejects a non-empty string prefixed by a digit. assert is_identifier('42147') is False # Assert this tester rejects an unqualified Python identifier suffixed by a # non-empty string prefixed by a digit. assert is_identifier('Sentient.6') is False
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **string munging** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.text.utiltextmunge` submodule. ''' # ....................{ IMPORTS }.................... # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_represent_object(): ''' Test the :func:`beartype._util.text.utiltextrepr.represent_object` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextrepr import represent_object # Arbitrary class defining an unpunctuated representation (i.e., # representation *NOT* already suffixed by punctuation). class ToASkylark(object): def __repr__(self): return 'Like a cloud of fire;' # Arbitrary class defining an empty representation. class ThouDostFloatAndRun(object): def __repr__(self): return '' # Assert this representer preserves the representations of terse objects # already suffixed by punctuation as is. assert represent_object(b'Higher still and higher') == repr( b'Higher still and higher') assert represent_object('From the earth thou springest') == repr( 'From the earth thou springest') assert represent_object(ToASkylark) == repr(ToASkylark) # Assert this representer punctuates the representations of terse objects # *NOT* already suffixed by punctuation. assert represent_object(ToASkylark()) == '"Like a cloud of fire;"' # Assert this representer double-quotes empty representations. assert represent_object(ThouDostFloatAndRun()) == '""' # Arbitrary object whose representation is both length *AND* contains one # or more newlines. THE_EVERLASTING_UNIVERSE_OF_THINGS = ( 'And singing still dost soar,\nand soaring ever singest.') # Representation of this object. the_blue_deep_thou_wingest = represent_object( obj=THE_EVERLASTING_UNIVERSE_OF_THINGS, max_len=42) # Assert this representer truncates this representations to that length. assert len(the_blue_deep_thou_wingest) == 42 # Assert this representer removes *ALL* newlines from this representation. assert '\n' not in the_blue_deep_thou_wingest # Representation of this object, reproduced to exercise caching # optimizations performed within this function. the_pale_purple_even = represent_object( obj=THE_EVERLASTING_UNIVERSE_OF_THINGS, max_len=42) # Assert the two representations to be the same. assert the_blue_deep_thou_wingest == the_pale_purple_even # Assert this representer truncates the representations of any objects # exceeding an unreasonably small maximum length to that length. like_a_star_of_heaven = represent_object( obj='In the golden lightning\nOf the sunken sun,', max_len=2) assert len(like_a_star_of_heaven) == 2
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **string munging** utility unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.text.utiltextmunge` submodule. ''' # ....................{ IMPORTS }.................... # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ case }.................... def test_uppercase_char_first(): ''' Test the :func:`beartype._util.text.utiltextmunge.uppercase_char_first` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextmunge import uppercase_char_first from pytest import raises with raises(AssertionError): uppercase_char_first(7) assert uppercase_char_first(text='beArTyPe') == "BeArTyPe" assert uppercase_char_first(text="<bear>") == "<bear>" assert uppercase_char_first(text="") == "" # ....................{ TESTS ~ number }.................... def test_number_lines(): ''' Test the :func:`beartype._util.text.utiltextmunge.number_lines` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextmunge import number_lines from pytest import raises from re import search with raises(AssertionError): number_lines(7) # No lines to split. assert number_lines(text="") == "" NEWLINE_COUNT = 20 base_string = 'bears, beats, battlestar galactica' total_string = f'{base_string}\n' * NEWLINE_COUNT numbered_lines_string = number_lines(total_string) numbered_lines_string = numbered_lines_string.splitlines() # Confirm the function preserves newlines as is. assert len(numbered_lines_string) == NEWLINE_COUNT # Confirm the base string is prefixed with something. for line_number in range(NEWLINE_COUNT): assert search( pattern=fr'(?<!^){base_string}$', string=numbered_lines_string[line_number], ) is not None # ....................{ TESTS ~ replace }.................... def test_replace_str_substrs(): ''' Test the :func:`beartype._util.text.utiltextmunge.replace_str_substrs` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextmunge import replace_str_substrs from beartype.roar._roarexc import _BeartypeUtilTextException from pytest import raises with raises(AssertionError): replace_str_substrs(text=7, old='Oh No!', new='A non-str value') with raises(AssertionError): replace_str_substrs(text='Oh No!', old=7.0, new='is a non-str value') with raises(AssertionError): replace_str_substrs(text='Oh No!', old='A non-str value of ', new=7) with raises(_BeartypeUtilTextException): replace_str_substrs(text="OG Beartype", old="I DON'T EXIST!", new="Therefore I do not think.") assert replace_str_substrs(text="I do not think, therefore I am.", old="do not think", new="think") == "I think, therefore I am." # ....................{ TESTS ~ [pre|suf]fix }.................... def test_suffix_unless_suffixed(): ''' Test the :func:`beartype._util.text.utiltextmunge.suffix_unless_suffixed` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextmunge import suffix_unless_suffixed from pytest import raises with raises(AssertionError): suffix_unless_suffixed(text=7, suffix="That's not a string!") with raises(AssertionError): suffix_unless_suffixed(text="HEY! You're not a string!", suffix=7) not_suffixed_text = "somefile" suffix = ".py" suffixed_text = suffix_unless_suffixed(text=not_suffixed_text, suffix=suffix) # Confirm text is suffixed assert suffixed_text == "somefile.py" # Attempt to reapply the suffix suffix_unless_suffixed(text=suffixed_text, suffix=suffix) # Confirm the text is unchanged assert suffixed_text == "somefile.py"
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **string-joining utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.text.utiltextjoin` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_join_delimited() -> None: ''' Test the :func:`beartype._util.text.utiltextjoin.join_delimited` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextjoin import join_delimited # Assert that joining a sequence of no strings returns the empty string. assert join_delimited( strs=(), delimiter_if_two='In Xanadu did Kubla Khan', delimiter_if_three_or_more_nonlast='A stately pleasure-dome decree:', delimiter_if_three_or_more_last='Where Alph, the sacred river, ran', ) == '' # Assert that joining a sequence of one string returns that string. assert join_delimited( strs=('Through caverns measureless to man',), delimiter_if_two='Down to a sunless sea.', delimiter_if_three_or_more_nonlast=( 'So twice five miles of fertile ground'), delimiter_if_three_or_more_last=( 'With walls and towers were girdled round;'), ) == 'Through caverns measureless to man' # Assert that joining a sequence of two strings returns these strings # conditionally delimited by the appropriate delimiter. assert join_delimited( strs=( 'And there were gardens bright with sinuous rills,', 'Where blossomed many an incense-bearing tree;', ), delimiter_if_two='And here were forests ancient as the hills,', delimiter_if_three_or_more_nonlast=( 'Enfolding sunny spots of greenery.'), delimiter_if_three_or_more_last=( 'But oh! that deep romantic chasm which slanted'), ) == ( 'And there were gardens bright with sinuous rills,' 'And here were forests ancient as the hills,' 'Where blossomed many an incense-bearing tree;' ) # Assert that joining a sequence of three strings returns these strings # conditionally delimited by the appropriate delimiters. assert join_delimited( strs=( 'Down the green hill athwart a cedarn cover!', 'A savage place! as holy and enchanted', 'As e’er beneath a waning moon was haunted', ), delimiter_if_two='By woman wailing for her demon-lover!', delimiter_if_three_or_more_nonlast=( 'And from this chasm, with ceaseless turmoil seething,'), delimiter_if_three_or_more_last=( 'As if this earth in fast thick pants were breathing,'), ) == ( 'Down the green hill athwart a cedarn cover!' 'And from this chasm, with ceaseless turmoil seething,' 'A savage place! as holy and enchanted' 'As if this earth in fast thick pants were breathing,' 'As e’er beneath a waning moon was haunted' ) def test_join_delimited_disjunction() -> None: ''' Test the :func:`beartype._util.text.utiltextjoin.join_delimited_disjunction` function. ''' # Defer test-specific imports. from beartype._util.text.utiltextjoin import join_delimited_disjunction # Assert that joining a sequence of no strings returns the empty string. assert join_delimited_disjunction(( 'A mighty fountain momently was forced:', 'Amid whose swift half-intermitted burst', 'Huge fragments vaulted like rebounding hail,', )) == ( 'A mighty fountain momently was forced:, ' 'Amid whose swift half-intermitted burst, or ' 'Huge fragments vaulted like rebounding hail,' )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' **Beartype exception caching utility unit tests.** This submodule unit tests the public API of the private :mod:`beartype._util.error.utilerror` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! from pytest import raises from random import getrandbits # ....................{ CLASSES }.................... class CachedException(ValueError): ''' Test-specific exception raised by unit tests exercising the :func:`beartype._util.error.utilerror.reraise_exception_placeholder` function. ''' pass # ....................{ TESTS ~ exception }.................... def test_reraise_exception_cached() -> None: ''' Test the :func:`beartype._util.error.utilerror.reraise_exception_placeholder` function. ''' # Defer test-specific imports. from beartype._util.cache.utilcachecall import callable_cached from beartype._util.error.utilerror import reraise_exception_placeholder # Source substring to be hard-coded into the messages of all exceptions # raised by the low-level memoized callable defined below. TEST_SOURCE_STR = '{its_got_bro}' # Low-level memoized callable raising non-human-readable exceptions # conditionally depending on the value of passed parameters. @callable_cached def portend_low_level_winter(is_winter_coming: bool) -> str: if is_winter_coming: raise CachedException( f'{TEST_SOURCE_STR} intimates that winter is coming.') else: return 'PRAISE THE SUN' # High-level non-memoized callable calling the low-level memoized callable # and reraising non-human-readable exceptions raised by the latter with # equivalent human-readable exceptions. def portend_high_level_winter() -> None: try: # Call the low-level memoized callable without raising exceptions. print(portend_low_level_winter(False)) # Call the low-level memoized callable with raising exceptions. print(portend_low_level_winter(True)) except CachedException as exception: # print('exception.args: {!r} ({!r})'.format(exception.args, type(exception.args))) reraise_exception_placeholder( exception=exception, source_str=TEST_SOURCE_STR, target_str=( 'Random "Song of Fire and Ice" spoiler' if getrandbits(1) else 'Random "Dark Souls" plaintext meme' ), ) # Assert this high-level non-memoized callable raises the same type of # exception raised by this low-level memoized callable and preserve this # exception for subsequent assertion. with raises(CachedException) as exception_info: portend_high_level_winter() # Assert this exception's message does *NOT* contain the non-human-readable # source substring hard-coded into the messages of all exceptions raised by # this low-level memoized callable. assert TEST_SOURCE_STR not in str(exception_info.value) # Assert that exceptions messages may contain *NO* source substrings. try: raise CachedException( "What's bravery without a dash of recklessness?") except Exception as exception: with raises(CachedException): reraise_exception_placeholder( exception=exception, source_str=TEST_SOURCE_STR, target_str='and man sees not light,', ) # Assert that exception messages may be empty. try: raise CachedException() except Exception as exception: with raises(CachedException): reraise_exception_placeholder( exception=exception, source_str=TEST_SOURCE_STR, target_str='but only endless nights.', ) # Assert that exception messages need *NOT* be strings. try: raise CachedException(0xDEADBEEF) except Exception as exception: with raises(CachedException): reraise_exception_placeholder( exception=exception, source_str=TEST_SOURCE_STR, target_str='Rise if you would, for that is our curse.', )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python module deprecation** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.mod.utilmoddeprecate` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_deprecate_module_attr() -> None: ''' Test the :func:`beartype._util.mod.utilmoddeprecate.deprecate_module_attr` function. ''' # ..................{ IMPORTS }.................. # Defer test-specific imports. from beartype._util.mod.utilmoddeprecate import deprecate_module_attr from pytest import raises, warns # ..................{ LOCALS }.................. # Dictionary mapping from the deprecated to non-deprecated name of # arbitrary objects masquerading as deprecated and non-deprecated # attributes (respectively) of an arbitrary submodule. ATTR_DEPRECATED_NAME_TO_NONDEPRECATED_NAME = { # Deprecated names originating from public non-deprecated names in the # "ATTR_NONDEPRECATED_NAME_TO_VALUE" dictionary defined below. 'Robes_some_unsculptured_image': 'Thine_earthly_rainbows', # Deprecated names originating from private non-deprecated names in # that dictionary, exercising an edge case. 'The_strange_sleep': '_Of_the_aethereal_waterfall', # Deprecated names originating from non-deprecated names *NOT* in that # dictionary, exercising an edge case. 'Wraps_all_in': 'its_own_deep_eternity', } # Dictionary mapping from the name to value of arbitrary objects # masquerading as non-deprecated attributes of an arbitrary submodule. ATTR_NONDEPRECATED_NAME_TO_VALUE = { 'Thine_earthly_rainbows': "stretch'd across the sweep", '_Of_the_aethereal_waterfall': 'whose veil', # Globally scoped attribute required by deprecate_module_attr(). '__name__': 'Lines.Written_in_the.Vale_of.Chamouni', } # ..................{ WARNS }.................. # Assert this function both emits the expected warning and returns the # expected value of a deprecated attribute originating from a public # non-deprecated attribute of an arbitrary submodule. with warns(DeprecationWarning): assert deprecate_module_attr( attr_deprecated_name='Robes_some_unsculptured_image', attr_deprecated_name_to_nondeprecated_name=( ATTR_DEPRECATED_NAME_TO_NONDEPRECATED_NAME), attr_nondeprecated_name_to_value=ATTR_NONDEPRECATED_NAME_TO_VALUE, ) == "stretch'd across the sweep" # Assert this function both emits the expected warning and returns the # expected value of a deprecated attribute originating from a private # non-deprecated attribute of an arbitrary submodule. with warns(DeprecationWarning): assert deprecate_module_attr( attr_deprecated_name='The_strange_sleep', attr_deprecated_name_to_nondeprecated_name=( ATTR_DEPRECATED_NAME_TO_NONDEPRECATED_NAME), attr_nondeprecated_name_to_value=ATTR_NONDEPRECATED_NAME_TO_VALUE, ) == 'whose veil' # ..................{ RAISES }.................. # Assert this function raises the expected exception when passed any name # other than that of a deprecated attribute. with raises(AttributeError): assert deprecate_module_attr( attr_deprecated_name='Which when the voices of the desert fail', attr_deprecated_name_to_nondeprecated_name=( ATTR_DEPRECATED_NAME_TO_NONDEPRECATED_NAME), attr_nondeprecated_name_to_value=ATTR_NONDEPRECATED_NAME_TO_VALUE, ) # Assert this function raises the expected exception when passed the name # of a deprecated attribute whose corresponding non-deprecated attribute is # *NOT* defined by this submodule. with raises(ImportError): assert deprecate_module_attr( attr_deprecated_name='Wraps_all_in', attr_deprecated_name_to_nondeprecated_name=( ATTR_DEPRECATED_NAME_TO_NONDEPRECATED_NAME), attr_nondeprecated_name_to_value=ATTR_NONDEPRECATED_NAME_TO_VALUE, )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python module tester** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.mod.utilmodtest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ validator }.................... def test_die_unless_module_attr_name() -> None: ''' Test the :func:`beartype._util.mod.utilmodtest.die_unless_module_attr_name` validator. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilModuleException from beartype._util.mod.utilmodtest import die_unless_module_attr_name from pytest import raises # Assert this validator raises *NO* exception when passed a syntactically # valid Python identifier. die_unless_module_attr_name('She_dwelt.among_the.untrodden.ways_2') # Assert this validator raises the expected exception when passed: # * A non-string. # * The empty string. # * A non-empty string containing *NO* "." delimiters. # * A non-empty string syntactically invalid as a Python identifier. with raises(_BeartypeUtilModuleException): die_unless_module_attr_name(b'Sentient.No6') with raises(_BeartypeUtilModuleException): die_unless_module_attr_name('') with raises(_BeartypeUtilModuleException): die_unless_module_attr_name('typing') with raises(_BeartypeUtilModuleException): die_unless_module_attr_name('Sentient.6') # ....................{ TESTS ~ tester }.................... def test_is_module() -> None: ''' Test the :func:`beartype._util.mod.utilmodtest.is_module` tester. ''' # Defer test-specific imports. from beartype.roar import BeartypeModuleUnimportableWarning from beartype._util.mod.utilmodtest import is_module from pytest import warns # Assert this tester accepts the name of a (possibly unimported) existing # importable module. assert is_module( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good') is True # Assert this tester accepts the name of an already imported module. assert is_module( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good') is True # Assert this tester rejects the name of a module guaranteed *NOT* to # exist, because we fully control the "beartype_test" package. assert is_module( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_nonexistent' ) is False # Assert this function emits the expected warning when passed the name of # an existing unimportable module. with warns(BeartypeModuleUnimportableWarning): assert is_module( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_bad') is ( False)
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python module importer** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.mod.utilmodimport` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS }.................... def test_import_module_or_none() -> None: ''' Test the :func:`beartype._util.mod.utilmodget.import_module_or_none` function. ''' # Defer test-specific imports. import beartype from beartype.roar import BeartypeModuleUnimportableWarning from beartype._util.mod.utilmodimport import import_module_or_none from pytest import warns # Assert this function returns the expected module when passed the # fully-qualified name of a previously imported module. assert import_module_or_none('beartype') is beartype # Assert this function returns the expected module when passed the # fully-qualified name of a module effectively guaranteed to *NOT* have # been previously imported by virtue of its irrelevance. xmlrpc_client_dynamic = import_module_or_none('xmlrpc.client') from xmlrpc import client as xmlrpc_client_static assert xmlrpc_client_dynamic is xmlrpc_client_static # Assert this function returns "None" when passed the fully-qualified name # of a module effectively guaranteed to *NEVER* exist by virtue of the # excess inscrutability, stupidity, and verbosity of its name. assert import_module_or_none( 'phnglui_mglwnafh_Cthulhu_Rlyeh_wgahnagl_fhtagn') is None # Assert this function emits the expected warning when passed the # fully-qualified name of an unimportable module. with warns(BeartypeModuleUnimportableWarning): assert import_module_or_none( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_bad') is ( None) # ....................{ TESTS ~ attr }.................... def test_import_module_attr() -> None: ''' Test the :func:`beartype._util.mod.utilmodget.import_module_attr` function. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilModuleException from beartype._util.mod.utilmodimport import import_module_attr from pytest import raises # Attribute dynamically imported from a module. module_attr = import_module_attr( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good.attrgood') # Assert this to be the expected attribute. assert isinstance(module_attr, str) assert module_attr.startswith('I started to see human beings as little') # Assert this function raises the expected exception when passed the # syntactically valid fully-qualified name of a non-existent attribute of # an importable module. with raises(_BeartypeUtilModuleException): import_module_attr( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good.attrbad') def test_import_module_attr_or_none() -> None: ''' Test the :func:`beartype._util.mod.utilmodget.import_module_attr_or_none` function. ''' # Defer test-specific imports. from beartype.roar import BeartypeModuleUnimportableWarning from beartype.roar._roarexc import _BeartypeUtilModuleException from beartype._util.mod.utilmodimport import import_module_attr_or_none from pytest import raises, warns # Attribute declared by an importable module. module_attr_good = import_module_attr_or_none( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good.attrgood') # Attribute *NOT* declared by an importable module. module_attr_bad = import_module_attr_or_none( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_good.attrbad') # Assert this to be the expected attribute. assert isinstance(module_attr_good, str) assert module_attr_good.startswith( 'I started to see human beings as little') # Assert this function returns "None" when passed the syntactically valid # fully-qualified name of a non-existent attribute of an importable module. assert module_attr_bad is None # Assert this function emits the expected warning when passed the # syntactically valid fully-qualified name of a non-existent attribute of # an unimportable module. with warns(BeartypeModuleUnimportableWarning): bad_module_attr = import_module_attr_or_none( 'beartype_test.a00_unit.data.util.mod.data_utilmodule_bad.attrbad') assert bad_module_attr is None # Assert this function raises the expected exception when passed a # non-string. with raises(_BeartypeUtilModuleException): import_module_attr_or_none( b'In far countries little men have closely studied your longing ' b'to be an indiscriminate slave.' ) # Assert this function raises the expected exception when passed a # string containing no "." characters. with raises(_BeartypeUtilModuleException): import_module_attr_or_none( 'These little men were not born in mansions, ' 'they rose from your ranks' ) # Assert this function raises the expected exception when passed a # string containing one or more "." characters but syntactically invalid as # a fully-qualified module attribute name. with raises(_BeartypeUtilModuleException): import_module_attr_or_none( 'They have gone hungry like you, suffered like you. And they have ' 'found a quicker way of changing masters.' )
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2022 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **Python module tester** unit tests. This submodule unit tests the public API of the private :mod:`beartype._util.mod.utilmodtest` submodule. ''' # ....................{ IMPORTS }.................... #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING: To raise human-readable test errors, avoid importing from # package-specific submodules at module scope. #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ....................{ TESTS ~ getter }.................... def test_die_unless_module_attr_name() -> None: ''' Test the :func:`beartype._util.mod.utilmodtest.die_unless_module_attr_name` validator. ''' # Defer test-specific imports. from beartype.roar._roarexc import _BeartypeUtilModuleException from beartype._util.mod.utilmodget import ( get_object_module_line_number_begin) from beartype_test.a00_unit.data.util.mod.data_utilmodule_line import ( SlowRollingOn, like_snakes_that_watch_their_prey, ) from pytest import raises # Assert this getter returns the expected line number for this callable. assert get_object_module_line_number_begin( like_snakes_that_watch_their_prey) == 20 #FIXME: The inspect.findsource() function underlying this call incorrectly #suggests this class to be declared at this line of its submodule, when in #fact this class is declared at the following line of its submodule. Sadly, #there's nothing meaningful we can do about this. Just be aware, please. # Assert this getter returns the expected line number for this class. assert get_object_module_line_number_begin(SlowRollingOn) == 39 # Assert this validator raises the expected exception when passed an object # that is neither a callable nor class. with raises(_BeartypeUtilModuleException): get_object_module_line_number_begin( 'Frost and the Sun in scorn of mortal power')