diff --git a/CHANGELOG.md b/CHANGELOG.md index 0851406..23161f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,13 @@ # Changelog +## Pedantic 3.0.0 +- removed decorator `@count_calls` +- removed decorator `@does_same_as_function` +- removed decorator `@mock` +- removed decorator `@rename_kwargs` +- removed decorator `@timer` +- removed decorator `@timer_class` +- removed decorator `@uminplemented` + ## Pedantic 2.4.0 - migrate from unittest to pytest - exclude tests from package deployment diff --git a/docs/pedantic/decorators/class_decorators.html b/docs/pedantic/decorators/class_decorators.html index 9ce85e5..dfed229 100644 --- a/docs/pedantic/decorators/class_decorators.html +++ b/docs/pedantic/decorators/class_decorators.html @@ -128,20 +128,6 @@

Functions

Shortcut for @for_all_methods(pedantic_require_docstring)

-
-def timer_class(cls: ~C) ‑> ~C -
-
-
- -Expand source code - -
def timer_class(cls: C) -> C:
-    """ Shortcut for @for_all_methods(timer) """
-    return for_all_methods(decorator=timer)(cls=cls)
-
-

Shortcut for @for_all_methods(timer)

-
def trace_class(cls: ~C) ‑> ~C
@@ -176,7 +162,6 @@

Functions

  • for_all_methods
  • pedantic_class
  • pedantic_class_require_docstring
  • -
  • timer_class
  • trace_class
  • diff --git a/docs/pedantic/decorators/fn_deco_count_calls.html b/docs/pedantic/decorators/fn_deco_count_calls.html deleted file mode 100644 index 6ad3b2a..0000000 --- a/docs/pedantic/decorators/fn_deco_count_calls.html +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_count_calls API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_count_calls

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def count_calls(func: Callable[..., ~ReturnType]) ‑> Callable[..., ~ReturnType] -
    -
    -
    - -Expand source code - -
    def count_calls(func: F) -> F:
    -    """
    -        Prints how often the method is called during program execution.
    -
    -        Example:
    -
    -        >>> @count_calls
    -        ... def often_used_method():
    -        ...    return 42
    -        >>> often_used_method()
    -        Count Calls: Call 1 of function 'often_used_method' at ...
    -        >>> often_used_method()
    -        Count Calls: Call 2 of function 'often_used_method' at ...
    -        >>> often_used_method()
    -        Count Calls: Call 3 of function 'often_used_method' at ...
    -    """
    -
    -    @wraps(func)
    -    def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -        wrapper.num_calls += 1
    -        print(f"Count Calls: Call {wrapper.num_calls} of function {func.__name__!r} at {datetime.now()}.")
    -        return func(*args, **kwargs)
    -
    -    wrapper.num_calls = 0
    -    return wrapper
    -
    -

    Prints how often the method is called during program execution.

    -

    Example:

    -
    >>> @count_calls
    -... def often_used_method():
    -...    return 42
    ->>> often_used_method()
    -Count Calls: Call 1 of function 'often_used_method' at ...
    ->>> often_used_method()
    -Count Calls: Call 2 of function 'often_used_method' at ...
    ->>> often_used_method()
    -Count Calls: Call 3 of function 'often_used_method' at ...
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/fn_deco_does_same_as_function.html b/docs/pedantic/decorators/fn_deco_does_same_as_function.html deleted file mode 100644 index 9292832..0000000 --- a/docs/pedantic/decorators/fn_deco_does_same_as_function.html +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_does_same_as_function API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_does_same_as_function

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def does_same_as_function(other_func: Callable[..., ~ReturnType]) ‑> Callable[..., ~ReturnType] -
    -
    -
    - -Expand source code - -
    def does_same_as_function(other_func: F) -> F:
    -    """
    -        Each time the decorated function is executed, the function other_func is also executed and the results
    -        are compared. An AssertionError is raised if the results are not equal.
    -
    -        Example:
    -
    -        >>> def other_calculation(a, b, c):
    -        ...     return c + b + a
    -        >>> @does_same_as_function(other_calculation)
    -        ... def some_calculation(a, b, c):
    -        ...     return a + b + c
    -        >>> some_calculation(1, 2, 3)
    -        6
    -    """
    -
    -    def decorator(decorated_func: F) -> F:
    -        @wraps(decorated_func)
    -        def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -            result = decorated_func(*args, **kwargs)
    -            other = other_func(*args, **kwargs)
    -
    -            if other != result:
    -                raise AssertionError(f'Different outputs: Function "{decorated_func.__name__}" returns {result} and '
    -                                     f'function "{other_func.__name__}" returns {other} for parameters {args} {kwargs}')
    -            return result
    -
    -        @wraps(decorated_func)
    -        async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -            result = await decorated_func(*args, **kwargs)
    -
    -            if inspect.iscoroutinefunction(other_func):
    -                other = await other_func(*args, **kwargs)
    -            else:
    -                other = other_func(*args, **kwargs)
    -
    -            if other != result:
    -                raise AssertionError(f'Different outputs: Function "{decorated_func.__name__}" returns {result} and '
    -                                     f'function "{other_func.__name__}" returns {other} for parameters {args} {kwargs}')
    -            return result
    -
    -        if inspect.iscoroutinefunction(decorated_func):
    -            return async_wrapper
    -        else:
    -            return wrapper
    -
    -    return decorator
    -
    -

    Each time the decorated function is executed, the function other_func is also executed and the results -are compared. An AssertionError is raised if the results are not equal.

    -

    Example:

    -
    >>> def other_calculation(a, b, c):
    -...     return c + b + a
    ->>> @does_same_as_function(other_calculation)
    -... def some_calculation(a, b, c):
    -...     return a + b + c
    ->>> some_calculation(1, 2, 3)
    -6
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/fn_deco_mock.html b/docs/pedantic/decorators/fn_deco_mock.html deleted file mode 100644 index d7f46ca..0000000 --- a/docs/pedantic/decorators/fn_deco_mock.html +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_mock API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_mock

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def mock(return_value: ~ReturnType) ‑> Callable[..., ~ReturnType] -
    -
    -
    - -Expand source code - -
    def mock(return_value: ReturnType) -> F:
    -    """
    -        Skip the execution of the function and simply return the given return value instead.
    -        This can be useful you want to check quickly if the behavior of the function causes a specific problem.
    -        Without this decorator you actually need to change the implementation of the function temporarily.
    -
    -        Example:
    -
    -        >>> @mock(return_value=42)
    -        ... def my_function(a, b, c):
    -        ...     return a + b + c
    -        >>> my_function(1, 2, 3)
    -        42
    -        >>> my_function(1000, 88, 204)
    -        42
    -    """
    -
    -    def decorator(func: F) -> F:
    -        @wraps(func)
    -        def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -            return return_value
    -
    -        @wraps(func)
    -        async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -            return return_value
    -
    -        if inspect.iscoroutinefunction(func):
    -            return async_wrapper
    -        else:
    -            return wrapper
    -    return decorator
    -
    -

    Skip the execution of the function and simply return the given return value instead. -This can be useful you want to check quickly if the behavior of the function causes a specific problem. -Without this decorator you actually need to change the implementation of the function temporarily.

    -

    Example:

    -
    >>> @mock(return_value=42)
    -... def my_function(a, b, c):
    -...     return a + b + c
    ->>> my_function(1, 2, 3)
    -42
    ->>> my_function(1000, 88, 204)
    -42
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/fn_deco_rename_kwargs.html b/docs/pedantic/decorators/fn_deco_rename_kwargs.html deleted file mode 100644 index 8f126b8..0000000 --- a/docs/pedantic/decorators/fn_deco_rename_kwargs.html +++ /dev/null @@ -1,159 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_rename_kwargs API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_rename_kwargs

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def rename_kwargs(*params: Rename) ‑> Callable[[Callable[..., ~ReturnType]], Callable[..., ~ReturnType]] -
    -
    -
    - -Expand source code - -
    def rename_kwargs(*params: Rename) -> Callable[[F], F]:
    -    """
    -        Renames the keyword arguments based on the given "Rename" rules when the decorated function is called.
    -        You can also use this to define aliases for keyword arguments.
    -
    -        Example:
    -
    -        >>> @rename_kwargs(
    -        ...     Rename(from_='firstname', to='a'),
    -        ...     Rename(from_='lastname', to='b'),
    -        ... )
    -        ... def my_function(a, b):
    -        ...     return a + ' ' + b
    -        >>> my_function(a='egon', b='olsen')  # the normal way
    -        'egon olsen'
    -        >>> my_function(firstname='egon', lastname='olsen')  # using new defined keyword arguments
    -        'egon olsen'
    -    """
    -
    -    param_dict = {p.from_: p.to for p in params}
    -
    -    def decorator(func: F) -> F:
    -        @wraps(func)
    -        def wrapper(*args, **kwargs) -> ReturnType:
    -            result_kwargs = {}
    -
    -            for k, v in kwargs.items():
    -                if k in param_dict:
    -                    result_kwargs[param_dict[k]] = kwargs[k]
    -                else:
    -                    result_kwargs[k] = kwargs[k]
    -
    -            return func(*args, **result_kwargs)
    -        return wrapper
    -    return decorator
    -
    -

    Renames the keyword arguments based on the given "Rename" rules when the decorated function is called. -You can also use this to define aliases for keyword arguments.

    -

    Example:

    -
    >>> @rename_kwargs(
    -...     Rename(from_='firstname', to='a'),
    -...     Rename(from_='lastname', to='b'),
    -... )
    -... def my_function(a, b):
    -...     return a + ' ' + b
    ->>> my_function(a='egon', b='olsen')  # the normal way
    -'egon olsen'
    ->>> my_function(firstname='egon', lastname='olsen')  # using new defined keyword arguments
    -'egon olsen'
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Rename -(from_: str, to: str) -
    -
    -
    - -Expand source code - -
    class Rename:
    -    def __init__(self, from_: str, to: str) -> None:
    -        self.from_ = from_
    -        self.to = to
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/fn_deco_timer.html b/docs/pedantic/decorators/fn_deco_timer.html deleted file mode 100644 index 8ab369b..0000000 --- a/docs/pedantic/decorators/fn_deco_timer.html +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_timer API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_timer

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def timer(func: Callable[..., ~ReturnType]) ‑> Callable[..., ~ReturnType] -
    -
    -
    - -Expand source code - -
    def timer(func: F) -> F:
    -    """
    -        Prints how long the execution of the decorated function takes.
    -
    -        Example:
    -
    -        >>> @timer
    -        ... def long_taking_calculation():
    -        ...     return 42
    -        >>> long_taking_calculation()
    -        Timer: Finished function "long_taking_calculation" in 0:00:00...
    -        42
    -    """
    -
    -    @wraps(func)
    -    def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -        start_time: datetime = datetime.now()
    -        value = func(*args, **kwargs)
    -        end_time = datetime.now()
    -        run_time = end_time - start_time
    -        print(f'Timer: Finished function "{func.__name__}" in {run_time}.')
    -        return value
    -
    -    @wraps(func)
    -    async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -        start_time: datetime = datetime.now()
    -        value = await func(*args, **kwargs)
    -        end_time = datetime.now()
    -        run_time = end_time - start_time
    -        print(f'Timer: Finished function "{func.__name__}" in {run_time}.')
    -        return value
    -
    -    if inspect.iscoroutinefunction(func):
    -        return async_wrapper
    -    else:
    -        return wrapper
    -
    -

    Prints how long the execution of the decorated function takes.

    -

    Example:

    -
    >>> @timer
    -... def long_taking_calculation():
    -...     return 42
    ->>> long_taking_calculation()
    -Timer: Finished function "long_taking_calculation" in 0:00:00...
    -42
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/fn_deco_unimplemented.html b/docs/pedantic/decorators/fn_deco_unimplemented.html deleted file mode 100644 index 7e059dd..0000000 --- a/docs/pedantic/decorators/fn_deco_unimplemented.html +++ /dev/null @@ -1,113 +0,0 @@ - - - - - - -pedantic.decorators.fn_deco_unimplemented API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.decorators.fn_deco_unimplemented

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def unimplemented(func: Callable[..., ~ReturnType]) ‑> Callable[..., ~ReturnType] -
    -
    -
    - -Expand source code - -
    def unimplemented(func: F) -> F:
    -    """
    -        For documentation purposes. Throw NotImplementedException if the function is called.
    -
    -        Example:
    -
    -        >>> @unimplemented
    -        ... def my_function(a, b, c):
    -        ...     pass
    -        >>> my_function(5, 4, 3)
    -        Traceback (most recent call last):
    -        ...
    -        pedantic.exceptions.NotImplementedException: Function "my_function" is not implemented yet!
    -    """
    -
    -    @wraps(func)
    -    def wrapper(*args: Any, **kwargs: Any) -> ReturnType:
    -        raise NotImplementedException(f'Function "{func.__qualname__}" is not implemented yet!')
    -    return wrapper
    -
    -

    For documentation purposes. Throw NotImplementedException if the function is called.

    -

    Example:

    -
    >>> @unimplemented
    -... def my_function(a, b, c):
    -...     pass
    ->>> my_function(5, 4, 3)
    -Traceback (most recent call last):
    -...
    -pedantic.exceptions.NotImplementedException: Function "my_function" is not implemented yet!
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/decorators/index.html b/docs/pedantic/decorators/index.html index a7b0f04..e585ae3 100644 --- a/docs/pedantic/decorators/index.html +++ b/docs/pedantic/decorators/index.html @@ -52,26 +52,14 @@

    Sub-modules

    -
    pedantic.decorators.fn_deco_count_calls
    -
    -
    -
    pedantic.decorators.fn_deco_deprecated
    -
    pedantic.decorators.fn_deco_does_same_as_function
    -
    -
    -
    pedantic.decorators.fn_deco_in_subprocess
    -
    pedantic.decorators.fn_deco_mock
    -
    -
    -
    pedantic.decorators.fn_deco_overrides
    @@ -80,10 +68,6 @@

    Sub-modules

    -
    pedantic.decorators.fn_deco_rename_kwargs
    -
    -
    -
    pedantic.decorators.fn_deco_require_kwargs
    @@ -92,10 +76,6 @@

    Sub-modules

    -
    pedantic.decorators.fn_deco_timer
    -
    -
    -
    pedantic.decorators.fn_deco_trace
    @@ -104,10 +84,6 @@

    Sub-modules

    -
    pedantic.decorators.fn_deco_unimplemented
    -
    -
    -
    pedantic.decorators.fn_deco_validate
    @@ -136,20 +112,14 @@

    Sub-modules

  • pedantic.decorators.class_decorators
  • pedantic.decorators.cls_deco_frozen_dataclass
  • pedantic.decorators.fn_deco_context_manager
  • -
  • pedantic.decorators.fn_deco_count_calls
  • pedantic.decorators.fn_deco_deprecated
  • -
  • pedantic.decorators.fn_deco_does_same_as_function
  • pedantic.decorators.fn_deco_in_subprocess
  • -
  • pedantic.decorators.fn_deco_mock
  • pedantic.decorators.fn_deco_overrides
  • pedantic.decorators.fn_deco_pedantic
  • -
  • pedantic.decorators.fn_deco_rename_kwargs
  • pedantic.decorators.fn_deco_require_kwargs
  • pedantic.decorators.fn_deco_retry
  • -
  • pedantic.decorators.fn_deco_timer
  • pedantic.decorators.fn_deco_trace
  • pedantic.decorators.fn_deco_trace_if_returns
  • -
  • pedantic.decorators.fn_deco_unimplemented
  • pedantic.decorators.fn_deco_validate
  • diff --git a/docs/pedantic/helper_methods.html b/docs/pedantic/helper_methods.html deleted file mode 100644 index 0f2da38..0000000 --- a/docs/pedantic/helper_methods.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - -pedantic.helper_methods API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.helper_methods

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/index.html b/docs/pedantic/tests/index.html deleted file mode 100644 index 98d274f..0000000 --- a/docs/pedantic/tests/index.html +++ /dev/null @@ -1,218 +0,0 @@ - - - - - - -pedantic.tests API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests

    -
    -
    -
    -
    -

    Sub-modules

    -
    -
    pedantic.tests.test_assert_value_matches_type
    -
    -
    -
    -
    pedantic.tests.test_async_context_manager
    -
    -
    -
    -
    pedantic.tests.test_context_manager
    -
    -
    -
    -
    pedantic.tests.test_frozen_dataclass
    -
    -
    -
    -
    pedantic.tests.test_generator_wrapper
    -
    -
    -
    -
    pedantic.tests.test_generic_mixin
    -
    -
    -
    -
    pedantic.tests.test_in_subprocess
    -
    -
    -
    -
    pedantic.tests.test_rename_kwargs
    -
    -
    -
    -
    pedantic.tests.test_resolve_forward_ref
    -
    -
    -
    -
    pedantic.tests.test_retry
    -
    -
    -
    -
    pedantic.tests.test_with_decorated_methods
    -
    -
    -
    -
    pedantic.tests.tests_class_decorators
    -
    -
    -
    -
    pedantic.tests.tests_combination_of_decorators
    -
    -
    -
    -
    pedantic.tests.tests_decorated_function
    -
    -
    -
    -
    pedantic.tests.tests_docstring
    -
    -
    -
    -
    pedantic.tests.tests_doctests
    -
    -
    -
    -
    pedantic.tests.tests_environment_variables
    -
    -
    -
    -
    pedantic.tests.tests_generator
    -
    -
    -
    -
    pedantic.tests.tests_generic_classes
    -
    -
    -
    -
    pedantic.tests.tests_main
    -
    -
    -
    -
    pedantic.tests.tests_mock
    -
    -
    -
    -
    pedantic.tests.tests_pedantic
    -
    -
    -
    -
    pedantic.tests.tests_pedantic_async
    -
    -
    -
    -
    pedantic.tests.tests_pedantic_class
    -
    -
    -
    -
    pedantic.tests.tests_pedantic_class_docstring
    -
    -
    -
    -
    pedantic.tests.tests_pedantic_python_311
    -
    -
    -
    -
    pedantic.tests.tests_require_kwargs
    -
    -
    -
    -
    pedantic.tests.tests_small_method_decorators
    -
    -
    -
    -
    pedantic.tests.validate
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_assert_value_matches_type.html b/docs/pedantic/tests/test_assert_value_matches_type.html deleted file mode 100644 index 004f72c..0000000 --- a/docs/pedantic/tests/test_assert_value_matches_type.html +++ /dev/null @@ -1,650 +0,0 @@ - - - - - - -pedantic.tests.test_assert_value_matches_type API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_assert_value_matches_type

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Foo -(value: int) -
    -
    -
    - -Expand source code - -
    @dataclass
    -class Foo:
    -    value: int
    -
    -

    Foo(value: int)

    -

    Instance variables

    -
    -
    var value : int
    -
    -

    The type of the None singleton.

    -
    -
    -
    -
    -class TestAssertValueMatchesType -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestAssertValueMatchesType(unittest.TestCase):
    -    def test_callable(self):
    -        def _cb(foo: Foo) -> str:
    -            return str(foo.value)
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., str],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., int],
    -                err='',
    -                type_vars={},
    -            )
    -
    -    def test_callable_return_type_none(self):
    -        def _cb(foo: Foo) -> None:
    -            return print(foo)
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., None],
    -            err='',
    -            type_vars={},
    -        )
    -
    -    def test_callable_awaitable(self):
    -        async def _cb(foo: Foo) -> str:
    -            return str(foo.value)
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[str]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[Any]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., Awaitable[int]],
    -                err='',
    -                type_vars={},
    -            )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., str],
    -                err='',
    -                type_vars={},
    -            )
    -
    -    def test_callable_coroutine(self):
    -        async def _cb(foo: Foo) -> str:
    -            return str(foo.value)
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Coroutine[None, None, str]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., Coroutine[None, None, int]],
    -                err='',
    -                type_vars={},
    -            )
    -
    -    def test_callable_awaitable_with_none_return_type(self):
    -        async def _cb(foo: Foo) -> None:
    -            print(foo)
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[None]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[Any]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -    def test_callable_with_old_union_type_hint(self):
    -        async def _cb(machine_id: str) -> Union[int, None]:
    -            return 42
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[Union[int, None]]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., Awaitable[int]],
    -                err='',
    -                type_vars={},
    -            )
    -
    -    def test_callable_with_new_union_type_hint(self):
    -        async def _cb(machine_id: str) -> int | None:
    -            return 42
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[int | None]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[Any]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            assert_value_matches_type(
    -                value=_cb,
    -                type_=Callable[..., Awaitable[int]],
    -                err='',
    -                type_vars={},
    -            )
    -
    -    def test_forward_ref_inheritance(self):
    -        T = TypeVar('T')
    -
    -        class State(Generic[T], ABC):
    -            pass
    -
    -        class StateMachine(Generic[T], ABC):
    -            pass
    -
    -        class MachineState(State['MachineStateMachine']):
    -            pass
    -
    -        class OfflineMachineState(MachineState):
    -            pass
    -
    -        class MachineStateMachine(StateMachine[MachineState]):
    -            pass
    -
    -        assert_value_matches_type(
    -            value=OfflineMachineState(),
    -            type_=Optional['MachineState'],
    -            err='',
    -            type_vars={},
    -            context=locals(),
    -        )
    -
    -    def test_tuple_with_ellipsis(self):
    -        """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/75 """
    -
    -        assert_value_matches_type(
    -            value=(1, 2.0, 'hello'),
    -            type_=Tuple[Any, ...],
    -            err='',
    -            type_vars={},
    -            context=locals(),
    -        )
    -
    -    def test_union_of_callable(self):
    -        """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/74 """
    -
    -        assert_value_matches_type(
    -            value=datetime.now(),
    -            type_=Union[datetime, Callable[[], datetime]],
    -            err='',
    -            type_vars={},
    -            context=locals(),
    -        )
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_callable(self) -
    -
    -
    - -Expand source code - -
    def test_callable(self):
    -    def _cb(foo: Foo) -> str:
    -        return str(foo.value)
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., str],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., int],
    -            err='',
    -            type_vars={},
    -        )
    -
    -
    -
    -
    -def test_callable_awaitable(self) -
    -
    -
    - -Expand source code - -
    def test_callable_awaitable(self):
    -    async def _cb(foo: Foo) -> str:
    -        return str(foo.value)
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[str]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[Any]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[int]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., str],
    -            err='',
    -            type_vars={},
    -        )
    -
    -
    -
    -
    -def test_callable_awaitable_with_none_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_callable_awaitable_with_none_return_type(self):
    -    async def _cb(foo: Foo) -> None:
    -        print(foo)
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[None]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[Any]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -
    -
    -
    -def test_callable_coroutine(self) -
    -
    -
    - -Expand source code - -
    def test_callable_coroutine(self):
    -    async def _cb(foo: Foo) -> str:
    -        return str(foo.value)
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Coroutine[None, None, str]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Coroutine[None, None, int]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -
    -
    -
    -def test_callable_return_type_none(self) -
    -
    -
    - -Expand source code - -
    def test_callable_return_type_none(self):
    -    def _cb(foo: Foo) -> None:
    -        return print(foo)
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., None],
    -        err='',
    -        type_vars={},
    -    )
    -
    -
    -
    -
    -def test_callable_with_new_union_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_callable_with_new_union_type_hint(self):
    -    async def _cb(machine_id: str) -> int | None:
    -        return 42
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[int | None]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[Any]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[int]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -
    -
    -
    -def test_callable_with_old_union_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_callable_with_old_union_type_hint(self):
    -    async def _cb(machine_id: str) -> Union[int, None]:
    -        return 42
    -
    -    assert_value_matches_type(
    -        value=_cb,
    -        type_=Callable[..., Awaitable[Union[int, None]]],
    -        err='',
    -        type_vars={},
    -    )
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        assert_value_matches_type(
    -            value=_cb,
    -            type_=Callable[..., Awaitable[int]],
    -            err='',
    -            type_vars={},
    -        )
    -
    -
    -
    -
    -def test_forward_ref_inheritance(self) -
    -
    -
    - -Expand source code - -
    def test_forward_ref_inheritance(self):
    -    T = TypeVar('T')
    -
    -    class State(Generic[T], ABC):
    -        pass
    -
    -    class StateMachine(Generic[T], ABC):
    -        pass
    -
    -    class MachineState(State['MachineStateMachine']):
    -        pass
    -
    -    class OfflineMachineState(MachineState):
    -        pass
    -
    -    class MachineStateMachine(StateMachine[MachineState]):
    -        pass
    -
    -    assert_value_matches_type(
    -        value=OfflineMachineState(),
    -        type_=Optional['MachineState'],
    -        err='',
    -        type_vars={},
    -        context=locals(),
    -    )
    -
    -
    -
    -
    -def test_tuple_with_ellipsis(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_with_ellipsis(self):
    -    """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/75 """
    -
    -    assert_value_matches_type(
    -        value=(1, 2.0, 'hello'),
    -        type_=Tuple[Any, ...],
    -        err='',
    -        type_vars={},
    -        context=locals(),
    -    )
    -
    - -
    -
    -def test_union_of_callable(self) -
    -
    -
    - -Expand source code - -
    def test_union_of_callable(self):
    -    """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/74 """
    -
    -    assert_value_matches_type(
    -        value=datetime.now(),
    -        type_=Union[datetime, Callable[[], datetime]],
    -        err='',
    -        type_vars={},
    -        context=locals(),
    -    )
    -
    - -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_async_context_manager.html b/docs/pedantic/tests/test_async_context_manager.html deleted file mode 100644 index 7393a93..0000000 --- a/docs/pedantic/tests/test_async_context_manager.html +++ /dev/null @@ -1,324 +0,0 @@ - - - - - - -pedantic.tests.test_async_context_manager API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_async_context_manager

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestAsyncContextManager -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestAsyncContextManager(unittest.IsolatedAsyncioTestCase):
    -    async def test_safe_context_manager_no_exception(self):
    -        before = False
    -        after = False
    -
    -        @safe_async_contextmanager
    -        async def foo():
    -            nonlocal before, after
    -            before = True
    -            yield 42
    -            after = True
    -
    -        self.assertFalse(before)
    -        self.assertFalse(after)
    -
    -        async with foo() as f:
    -            self.assertTrue(before)
    -            self.assertFalse(after)
    -            self.assertEqual(42, f)
    -
    -        self.assertTrue(before)
    -        self.assertTrue(after)
    -
    -    async def test_safe_context_manager_with_exception(self):
    -        before = False
    -        after = False
    -
    -        @safe_async_contextmanager
    -        async def foo():
    -            nonlocal before, after
    -            before = True
    -            yield 42
    -            after = True
    -
    -        self.assertFalse(before)
    -        self.assertFalse(after)
    -
    -        with self.assertRaises(expected_exception=ValueError):
    -            async with foo() as f:
    -                self.assertTrue(before)
    -                self.assertFalse(after)
    -                self.assertEqual(42, f)
    -                raise ValueError('oh no')
    -
    -        self.assertTrue(before)
    -        self.assertTrue(after)
    -
    -    async def test_safe_context_manager_with_args_kwargs(self):
    -        @safe_async_contextmanager
    -        async def foo(a, b):
    -            yield a, b
    -
    -        async with foo(42, b=43) as f:
    -            self.assertEqual((42, 43), f)
    -
    -    def test_safe_context_manager_async(self):
    -        with self.assertRaises(expected_exception=AssertionError) as e:
    -            @safe_async_contextmanager
    -            def foo(a, b):
    -                yield a, b
    -
    -        expected = 'foo is not an async generator. So you need to use "safe_contextmanager" instead.'
    -        self.assertEqual(expected, e.exception.args[0])
    -
    -    async def test_safe_context_manager_non_generator(self):
    -        with self.assertRaises(expected_exception=AssertionError) as e:
    -            @safe_async_contextmanager
    -            async def foo(a, b):
    -                return a, b
    -
    -        expected = 'foo is not a generator.'
    -        self.assertEqual(expected, e.exception.args[0])
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.async_case.IsolatedAsyncioTestCase
    • -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_safe_context_manager_async(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_async(self):
    -    with self.assertRaises(expected_exception=AssertionError) as e:
    -        @safe_async_contextmanager
    -        def foo(a, b):
    -            yield a, b
    -
    -    expected = 'foo is not an async generator. So you need to use "safe_contextmanager" instead.'
    -    self.assertEqual(expected, e.exception.args[0])
    -
    -
    -
    -
    -async def test_safe_context_manager_no_exception(self) -
    -
    -
    - -Expand source code - -
    async def test_safe_context_manager_no_exception(self):
    -    before = False
    -    after = False
    -
    -    @safe_async_contextmanager
    -    async def foo():
    -        nonlocal before, after
    -        before = True
    -        yield 42
    -        after = True
    -
    -    self.assertFalse(before)
    -    self.assertFalse(after)
    -
    -    async with foo() as f:
    -        self.assertTrue(before)
    -        self.assertFalse(after)
    -        self.assertEqual(42, f)
    -
    -    self.assertTrue(before)
    -    self.assertTrue(after)
    -
    -
    -
    -
    -async def test_safe_context_manager_non_generator(self) -
    -
    -
    - -Expand source code - -
    async def test_safe_context_manager_non_generator(self):
    -    with self.assertRaises(expected_exception=AssertionError) as e:
    -        @safe_async_contextmanager
    -        async def foo(a, b):
    -            return a, b
    -
    -    expected = 'foo is not a generator.'
    -    self.assertEqual(expected, e.exception.args[0])
    -
    -
    -
    -
    -async def test_safe_context_manager_with_args_kwargs(self) -
    -
    -
    - -Expand source code - -
    async def test_safe_context_manager_with_args_kwargs(self):
    -    @safe_async_contextmanager
    -    async def foo(a, b):
    -        yield a, b
    -
    -    async with foo(42, b=43) as f:
    -        self.assertEqual((42, 43), f)
    -
    -
    -
    -
    -async def test_safe_context_manager_with_exception(self) -
    -
    -
    - -Expand source code - -
    async def test_safe_context_manager_with_exception(self):
    -    before = False
    -    after = False
    -
    -    @safe_async_contextmanager
    -    async def foo():
    -        nonlocal before, after
    -        before = True
    -        yield 42
    -        after = True
    -
    -    self.assertFalse(before)
    -    self.assertFalse(after)
    -
    -    with self.assertRaises(expected_exception=ValueError):
    -        async with foo() as f:
    -            self.assertTrue(before)
    -            self.assertFalse(after)
    -            self.assertEqual(42, f)
    -            raise ValueError('oh no')
    -
    -    self.assertTrue(before)
    -    self.assertTrue(after)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_context_manager.html b/docs/pedantic/tests/test_context_manager.html deleted file mode 100644 index 2db18d1..0000000 --- a/docs/pedantic/tests/test_context_manager.html +++ /dev/null @@ -1,323 +0,0 @@ - - - - - - -pedantic.tests.test_context_manager API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_context_manager

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestContextManager -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestContextManager(TestCase):
    -    def test_safe_context_manager_no_exception(self):
    -        before = False
    -        after = False
    -
    -        @safe_contextmanager
    -        def foo():
    -            nonlocal before, after
    -            before = True
    -            yield 42
    -            after = True
    -
    -        self.assertFalse(before)
    -        self.assertFalse(after)
    -
    -        with foo() as f:
    -            self.assertTrue(before)
    -            self.assertFalse(after)
    -            self.assertEqual(42, f)
    -
    -        self.assertTrue(before)
    -        self.assertTrue(after)
    -
    -    def test_safe_context_manager_with_exception(self):
    -        before = False
    -        after = False
    -
    -        @safe_contextmanager
    -        def foo():
    -            nonlocal before, after
    -            before = True
    -            yield 42
    -            after = True
    -
    -        self.assertFalse(before)
    -        self.assertFalse(after)
    -
    -        with self.assertRaises(expected_exception=ValueError):
    -            with foo() as f:
    -                self.assertTrue(before)
    -                self.assertFalse(after)
    -                self.assertEqual(42, f)
    -                raise ValueError('oh no')
    -
    -        self.assertTrue(before)
    -        self.assertTrue(after)
    -
    -    def test_safe_context_manager_with_args_kwargs(self):
    -        @safe_contextmanager
    -        def foo(a, b):
    -            yield a, b
    -
    -        with foo(42, b=43) as f:
    -            self.assertEqual((42, 43), f)
    -
    -    def test_safe_context_manager_async(self):
    -        with self.assertRaises(expected_exception=AssertionError) as e:
    -            @safe_contextmanager
    -            async def foo(a, b):
    -                yield a, b
    -
    -        expected = 'foo is async. So you need to use "safe_async_contextmanager" instead.'
    -        self.assertEqual(expected, e.exception.args[0])
    -
    -    def test_safe_context_manager_non_generator(self):
    -        with self.assertRaises(expected_exception=AssertionError) as e:
    -            @safe_contextmanager
    -            def foo(a, b):
    -                return a, b
    -
    -        expected = 'foo is not a generator.'
    -        self.assertEqual(expected, e.exception.args[0])
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_safe_context_manager_async(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_async(self):
    -    with self.assertRaises(expected_exception=AssertionError) as e:
    -        @safe_contextmanager
    -        async def foo(a, b):
    -            yield a, b
    -
    -    expected = 'foo is async. So you need to use "safe_async_contextmanager" instead.'
    -    self.assertEqual(expected, e.exception.args[0])
    -
    -
    -
    -
    -def test_safe_context_manager_no_exception(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_no_exception(self):
    -    before = False
    -    after = False
    -
    -    @safe_contextmanager
    -    def foo():
    -        nonlocal before, after
    -        before = True
    -        yield 42
    -        after = True
    -
    -    self.assertFalse(before)
    -    self.assertFalse(after)
    -
    -    with foo() as f:
    -        self.assertTrue(before)
    -        self.assertFalse(after)
    -        self.assertEqual(42, f)
    -
    -    self.assertTrue(before)
    -    self.assertTrue(after)
    -
    -
    -
    -
    -def test_safe_context_manager_non_generator(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_non_generator(self):
    -    with self.assertRaises(expected_exception=AssertionError) as e:
    -        @safe_contextmanager
    -        def foo(a, b):
    -            return a, b
    -
    -    expected = 'foo is not a generator.'
    -    self.assertEqual(expected, e.exception.args[0])
    -
    -
    -
    -
    -def test_safe_context_manager_with_args_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_with_args_kwargs(self):
    -    @safe_contextmanager
    -    def foo(a, b):
    -        yield a, b
    -
    -    with foo(42, b=43) as f:
    -        self.assertEqual((42, 43), f)
    -
    -
    -
    -
    -def test_safe_context_manager_with_exception(self) -
    -
    -
    - -Expand source code - -
    def test_safe_context_manager_with_exception(self):
    -    before = False
    -    after = False
    -
    -    @safe_contextmanager
    -    def foo():
    -        nonlocal before, after
    -        before = True
    -        yield 42
    -        after = True
    -
    -    self.assertFalse(before)
    -    self.assertFalse(after)
    -
    -    with self.assertRaises(expected_exception=ValueError):
    -        with foo() as f:
    -            self.assertTrue(before)
    -            self.assertFalse(after)
    -            self.assertEqual(42, f)
    -            raise ValueError('oh no')
    -
    -    self.assertTrue(before)
    -    self.assertTrue(after)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_frozen_dataclass.html b/docs/pedantic/tests/test_frozen_dataclass.html deleted file mode 100644 index 3dc0e8e..0000000 --- a/docs/pedantic/tests/test_frozen_dataclass.html +++ /dev/null @@ -1,1378 +0,0 @@ - - - - - - -pedantic.tests.test_frozen_dataclass API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_frozen_dataclass

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class A -(*,
    foo: List[int],
    bar: Dict[str, str],
    values: Tuple[BB])
    -
    -
    -
    - -Expand source code - -
    @frozen_type_safe_dataclass
    -class A:
    -    foo: List[int]
    -    bar: Dict[str, str]
    -    values: Tuple[B, B]
    -
    -

    A(*, foo: List[int], bar: Dict[str, str], values: Tuple[pedantic.tests.test_frozen_dataclass.B, pedantic.tests.test_frozen_dataclass.B])

    -

    Instance variables

    -
    -
    var bar : Dict[str, str]
    -
    -

    The type of the None singleton.

    -
    -
    var foo : List[int]
    -
    -

    The type of the None singleton.

    -
    -
    var values : Tuple[BB]
    -
    -

    The type of the None singleton.

    -
    -
    -

    Methods

    -
    -
    -def copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by copying all fields of this instance replaced by the new values.
    -        Keep in mind that this is a shallow copy!
    -    """
    -
    -    return replace(self, **kwargs)
    -
    -

    Creates a new immutable instance that by copying all fields of this instance replaced by the new values. -Keep in mind that this is a shallow copy!

    -
    -
    -def deep_copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def deep_copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by deep copying all fields of
    -        this instance replaced by the new values.
    -    """
    -
    -    current_values = {field.name: deepcopy(getattr(self, field.name)) for field in fields(self)}
    -    return new_class(**{**current_values, **kwargs})
    -
    -

    Creates a new immutable instance that by deep copying all fields of -this instance replaced by the new values.

    -
    -
    -def validate_types(self) ‑> None -
    -
    -
    - -Expand source code - -
    def validate_types(self, *, _context: Dict[str, Type] = None) -> None:
    -    """
    -        Checks that all instance variable have the correct type.
    -        Raises a [PedanticTypeCheckException] if at least one type is incorrect.
    -    """
    -
    -    props = fields(new_class)
    -
    -    if _context is None:
    -        # method was called by user
    -        _context = get_context(depth=2)
    -
    -    _context = {**_context, **self.__init__.__globals__, self.__class__.__name__: self.__class__}
    -
    -    for field in props:
    -        assert_value_matches_type(
    -            value=getattr(self, field.name),
    -            type_=field.type,
    -            err=f'In dataclass "{cls_.__name__}" in field "{field.name}": ',
    -            type_vars={},
    -            context=_context,
    -        )
    -
    -

    Checks that all instance variable have the correct type. -Raises a [PedanticTypeCheckException] if at least one type is incorrect.

    -
    -
    -
    -
    -class B -(*, v: Set[int]) -
    -
    -
    - -Expand source code - -
    @frozen_type_safe_dataclass
    -class B:
    -    v: Set[int]
    -
    -

    B(*, v: Set[int])

    -

    Instance variables

    -
    -
    var v : Set[int]
    -
    -

    The type of the None singleton.

    -
    -
    -

    Methods

    -
    -
    -def copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by copying all fields of this instance replaced by the new values.
    -        Keep in mind that this is a shallow copy!
    -    """
    -
    -    return replace(self, **kwargs)
    -
    -

    Creates a new immutable instance that by copying all fields of this instance replaced by the new values. -Keep in mind that this is a shallow copy!

    -
    -
    -def deep_copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def deep_copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by deep copying all fields of
    -        this instance replaced by the new values.
    -    """
    -
    -    current_values = {field.name: deepcopy(getattr(self, field.name)) for field in fields(self)}
    -    return new_class(**{**current_values, **kwargs})
    -
    -

    Creates a new immutable instance that by deep copying all fields of -this instance replaced by the new values.

    -
    -
    -def validate_types(self) ‑> None -
    -
    -
    - -Expand source code - -
    def validate_types(self, *, _context: Dict[str, Type] = None) -> None:
    -    """
    -        Checks that all instance variable have the correct type.
    -        Raises a [PedanticTypeCheckException] if at least one type is incorrect.
    -    """
    -
    -    props = fields(new_class)
    -
    -    if _context is None:
    -        # method was called by user
    -        _context = get_context(depth=2)
    -
    -    _context = {**_context, **self.__init__.__globals__, self.__class__.__name__: self.__class__}
    -
    -    for field in props:
    -        assert_value_matches_type(
    -            value=getattr(self, field.name),
    -            type_=field.type,
    -            err=f'In dataclass "{cls_.__name__}" in field "{field.name}": ',
    -            type_vars={},
    -            context=_context,
    -        )
    -
    -

    Checks that all instance variable have the correct type. -Raises a [PedanticTypeCheckException] if at least one type is incorrect.

    -
    -
    -
    -
    -class Foo -(*, a: int, b: str, c: bool) -
    -
    -
    - -Expand source code - -
    @frozen_dataclass
    -class Foo:
    -    a: int
    -    b: str
    -    c: bool
    -
    -

    Foo(*, a: int, b: str, c: bool)

    -

    Instance variables

    -
    -
    var a : int
    -
    -

    The type of the None singleton.

    -
    -
    var b : str
    -
    -

    The type of the None singleton.

    -
    -
    var c : bool
    -
    -

    The type of the None singleton.

    -
    -
    -

    Methods

    -
    -
    -def copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by copying all fields of this instance replaced by the new values.
    -        Keep in mind that this is a shallow copy!
    -    """
    -
    -    return replace(self, **kwargs)
    -
    -

    Creates a new immutable instance that by copying all fields of this instance replaced by the new values. -Keep in mind that this is a shallow copy!

    -
    -
    -def deep_copy_with(self, **kwargs: Any) ‑> ~T -
    -
    -
    - -Expand source code - -
    def deep_copy_with(self, **kwargs: Any) -> T:
    -    """
    -        Creates a new immutable instance that by deep copying all fields of
    -        this instance replaced by the new values.
    -    """
    -
    -    current_values = {field.name: deepcopy(getattr(self, field.name)) for field in fields(self)}
    -    return new_class(**{**current_values, **kwargs})
    -
    -

    Creates a new immutable instance that by deep copying all fields of -this instance replaced by the new values.

    -
    -
    -def validate_types(self) ‑> None -
    -
    -
    - -Expand source code - -
    def validate_types(self, *, _context: Dict[str, Type] = None) -> None:
    -    """
    -        Checks that all instance variable have the correct type.
    -        Raises a [PedanticTypeCheckException] if at least one type is incorrect.
    -    """
    -
    -    props = fields(new_class)
    -
    -    if _context is None:
    -        # method was called by user
    -        _context = get_context(depth=2)
    -
    -    _context = {**_context, **self.__init__.__globals__, self.__class__.__name__: self.__class__}
    -
    -    for field in props:
    -        assert_value_matches_type(
    -            value=getattr(self, field.name),
    -            type_=field.type,
    -            err=f'In dataclass "{cls_.__name__}" in field "{field.name}": ',
    -            type_vars={},
    -            context=_context,
    -        )
    -
    -

    Checks that all instance variable have the correct type. -Raises a [PedanticTypeCheckException] if at least one type is incorrect.

    -
    -
    -
    -
    -class TestFrozenDataclass -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestFrozenDataclass(unittest.TestCase):
    -    def test_equals_and_hash(self):
    -        a = Foo(a=6, b='hi', c=True)
    -        b = Foo(a=6, b='hi', c=True)
    -        c = Foo(a=7, b='hi', c=True)
    -
    -        self.assertEqual(a, b)
    -        self.assertEqual(hash(a), hash(b))
    -
    -        self.assertNotEqual(a, c)
    -        self.assertNotEqual(hash(a), hash(c))
    -
    -    def test_copy_with(self):
    -        foo = Foo(a=6, b='hi', c=True)
    -
    -        copy_1 = foo.copy_with()
    -        self.assertEqual(foo, copy_1)
    -
    -        copy_2 = foo.copy_with(a=42)
    -        self.assertNotEqual(foo, copy_2)
    -        self.assertEqual(42, copy_2.a)
    -        self.assertEqual(foo.b, copy_2.b)
    -        self.assertEqual(foo.c, copy_2.c)
    -
    -        copy_3 = foo.copy_with(b='Hello')
    -        self.assertNotEqual(foo, copy_3)
    -        self.assertEqual(foo.a, copy_3.a)
    -        self.assertEqual('Hello', copy_3.b)
    -        self.assertEqual(foo.c, copy_3.c)
    -
    -        copy_4 = foo.copy_with(c=False)
    -        self.assertNotEqual(foo, copy_4)
    -        self.assertEqual(foo.a, copy_4.a)
    -        self.assertEqual(foo.b, copy_4.b)
    -        self.assertEqual(False, copy_4.c)
    -
    -        copy_5 = foo.copy_with(a=676676, b='new', c=False)
    -        self.assertNotEqual(foo, copy_5)
    -        self.assertEqual(676676, copy_5.a)
    -        self.assertEqual('new', copy_5.b)
    -        self.assertEqual(False, copy_5.c)
    -
    -    def test_validate_types(self):
    -        foo = Foo(a=6, b='hi', c=True)
    -        foo.validate_types()
    -
    -        bar = Foo(a=6.6, b='hi', c=True)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -            bar.validate_types()
    -
    -        expected = 'In dataclass "Foo" in field "a": Type hint is incorrect: Argument 6.6 of type <class \'float\'> ' \
    -                   'does not match expected type <class \'int\'>.'
    -        self.assertEqual(str(exc.exception), expected)
    -
    -    def test_frozen_dataclass_above_dataclass(self):
    -        # This is the same behavior like
    -        # >>> @dataclass(frozen=True)
    -        # ... @dataclass
    -        # ... class C:
    -        # ...     foo: int
    -
    -        @frozen_dataclass
    -        @dataclass
    -        class A:
    -            foo: int
    -
    -        with self.assertRaises(expected_exception=TypeError):
    -            A()
    -
    -        with self.assertRaises(expected_exception=FrozenInstanceError):
    -            A(foo=3)
    -
    -    def test_frozen_dataclass_below_dataclass(self):
    -        @dataclass
    -        @frozen_dataclass
    -        class A:
    -            foo: int
    -
    -        with self.assertRaises(expected_exception=TypeError):
    -            A()
    -
    -        a = A(foo=3)
    -
    -        with self.assertRaises(expected_exception=FrozenInstanceError):
    -            a.foo = 4
    -
    -        b = a.copy_with(foo=4)
    -        self.assertEqual(4, b.foo)
    -
    -
    -    def test_frozen_typesafe_dataclass_with_post_init(self):
    -        b = 3
    -
    -        @frozen_dataclass(type_safe=True)
    -        class A:
    -            foo: int
    -
    -            def __post_init__(self) -> None:
    -                nonlocal b
    -                b = 33
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -            A(foo=42.7)
    -
    -        self.assertEqual(
    -            'In dataclass "A" in field "foo": Type hint is incorrect: Argument 42.7 of type'
    -            ' <class \'float\'> does not match expected type <class \'int\'>.',
    -            str(exc.exception)
    -        )
    -
    -        # we check that the __post_init__ method is executed
    -        self.assertEqual(33, b)
    -
    -    def test_frozen_typesafe_dataclass_without_post_init(self):
    -        @frozen_dataclass(type_safe=True)
    -        class A:
    -            foo: int
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -            A(foo=42.7)
    -
    -        self.assertEqual(
    -            'In dataclass "A" in field "foo": Type hint is incorrect: Argument 42.7 of type'
    -            ' <class \'float\'> does not match expected type <class \'int\'>.',
    -            str(exc.exception)
    -        )
    -
    -    def test_frozen_dataclass_with_empty_braces(self):
    -        @frozen_dataclass()
    -        class A:
    -            foo: int
    -
    -        a = A(foo=42)
    -        self.assertEqual(42, a.foo)
    -
    -    def test_frozen_dataclass_no_braces(self):
    -        @frozen_dataclass
    -        class A:
    -            foo: int
    -
    -        a = A(foo=42)
    -        self.assertEqual(42, a.foo)
    -
    -    def test_frozen_dataclass_order(self):
    -        @frozen_dataclass(order=True)
    -        class A:
    -            foo: int
    -            bar: int
    -
    -        a = A(foo=42, bar=43)
    -        b = A(foo=42, bar=42)
    -        c = A(foo=41, bar=44)
    -        d = A(foo=44, bar=0)
    -        self.assertLess(b, a)
    -        self.assertLess(c, b)
    -        self.assertLess(a, d)
    -
    -    def test_frozen_type_safe_dataclass_copy_with_check(self):
    -        @frozen_type_safe_dataclass
    -        class A:
    -            foo: int
    -            bar: bool
    -
    -        a = A(foo=42, bar=False)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            a.copy_with(foo=1.1)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            a.copy_with(bar=11)
    -
    -        a.copy_with(foo=11, bar=True)
    -
    -    def test_copy_with_is_shallow(self):
    -        a = A(foo=[1, 2], bar={'hello': 'world'}, values=(B(v={4, 5}), B(v={6})))
    -        shallow = a.copy_with()
    -
    -        # manipulation
    -        shallow.bar['hello'] = 'pedantic'
    -        shallow.foo.append(3)
    -
    -        self.assertEqual([1, 2, 3], a.foo)
    -        self.assertEqual([1, 2, 3], shallow.foo)
    -        self.assertEqual('pedantic', a.bar['hello'])
    -        self.assertEqual('pedantic', shallow.bar['hello'])
    -
    -    def test_copy_with_and_deep_copy_with(self):
    -        a = A(foo=[1, 2], bar={'hello': 'world'}, values=(B(v={4, 5}), B(v={6})))
    -        deep = a.deep_copy_with()
    -
    -        # manipulation
    -        deep.bar['hello'] = 'pedantic'
    -        deep.foo.append(3)
    -
    -        self.assertEqual([1, 2], a.foo)
    -        self.assertEqual([1, 2, 3], deep.foo)
    -        self.assertEqual('world', a.bar['hello'])
    -        self.assertEqual('pedantic', deep.bar['hello'])
    -
    -    def test_frozen_dataclass_inheritance_override_post_init(self):
    -        i = 1
    -
    -        @frozen_type_safe_dataclass
    -        class A:
    -            bar: int
    -
    -            def __post_init__(self):
    -                nonlocal i
    -                i += 1
    -                print('hello a')
    -
    -        @frozen_type_safe_dataclass
    -        class B(A):
    -            foo: int
    -
    -            def __post_init__(self):
    -                nonlocal i
    -                i *= 10
    -                print('hello b')
    -
    -        A(bar=3)
    -        self.assertEqual(2, i)
    -
    -        b = B(bar=3, foo=42)
    -        self.assertEqual(20, i)  # post init of A was not called
    -        self.assertEqual(3, b.bar)
    -        self.assertEqual(42, b.foo)
    -
    -        a = b.copy_with()
    -        self.assertEqual(b, a)
    -        self.assertEqual(200, i)
    -
    -    def test_frozen_dataclass_inheritance_not_override_post_init(self):
    -        i = 1
    -
    -        @frozen_type_safe_dataclass
    -        class A:
    -            bar: int
    -
    -            def __post_init__(self):
    -                nonlocal i
    -                i += 1
    -                print('hello a')
    -
    -        @frozen_type_safe_dataclass
    -        class B(A):
    -            foo: int
    -
    -        A(bar=3)
    -        self.assertEqual(2, i)
    -
    -        b = B(bar=3, foo=42)
    -        self.assertEqual(3, i)  # post init of A was called
    -        self.assertEqual(3, b.bar)
    -        self.assertEqual(42, b.foo)
    -
    -        a = b.copy_with()
    -        self.assertEqual(b, a)
    -        self.assertEqual(4, i)
    -
    -    def test_type_safe_frozen_dataclass_with_awaitable(self):
    -        @frozen_type_safe_dataclass
    -        class A:
    -            f: Callable[..., Awaitable[int]]
    -
    -        async def _cb() -> int:
    -            return 42
    -
    -        async def _cb_2() -> str:
    -            return '42'
    -
    -        A(f=_cb)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            A(f=_cb_2)
    -
    -    def test_type_safe_frozen_dataclass_with_forward_ref(self):
    -        T = TypeVar('T')
    -
    -        class State(Generic[T], ABC):
    -            pass
    -
    -        class StateMachine(Generic[T], ABC):
    -            pass
    -
    -        @frozen_type_safe_dataclass
    -        class StateChangeResult:
    -            new_state: Optional['MachineState']
    -
    -        class MachineState(State['MachineStateMachine']):
    -            pass
    -
    -        class OfflineMachineState(MachineState):
    -            pass
    -
    -        class OnlineMachineState:
    -            pass
    -
    -        class MachineStateMachine(StateMachine[MachineState]):
    -            pass
    -
    -        s = StateChangeResult(new_state=OfflineMachineState())
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            StateChangeResult(new_state=OnlineMachineState())
    -
    -        s.validate_types()
    -
    -    def test_forward_ref_to_itself(self):
    -        """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/72 """
    -
    -        @frozen_type_safe_dataclass
    -        class Comment:
    -            replies: List['Comment']
    -
    -        comment = Comment(replies=[Comment(replies=[])])
    -        comment.copy_with(replies=[Comment(replies=[])])
    -        comment.validate_types()
    -
    -    def test_forward_ref_to_itself_while_class_not_in_scope(self):
    -        """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/72 """
    -
    -        def _scope():
    -            @frozen_type_safe_dataclass
    -            class Comment:
    -                replies: List['Comment']
    -
    -            def _make(replies=None):
    -                return Comment(replies=replies or [])
    -
    -            return _make
    -
    -        make = _scope()
    -
    -        comment = make(replies=[make(replies=[])])
    -        comment.copy_with(replies=[make(replies=[])])
    -        comment.validate_types()
    -
    -    def test_slots_work_with_equals(self):
    -        @frozen_dataclass(slots=True)
    -        class Foo:
    -            a: int
    -
    -        o = Foo(a=0)
    -        assert o == o.copy_with()
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_copy_with(self) -
    -
    -
    - -Expand source code - -
    def test_copy_with(self):
    -    foo = Foo(a=6, b='hi', c=True)
    -
    -    copy_1 = foo.copy_with()
    -    self.assertEqual(foo, copy_1)
    -
    -    copy_2 = foo.copy_with(a=42)
    -    self.assertNotEqual(foo, copy_2)
    -    self.assertEqual(42, copy_2.a)
    -    self.assertEqual(foo.b, copy_2.b)
    -    self.assertEqual(foo.c, copy_2.c)
    -
    -    copy_3 = foo.copy_with(b='Hello')
    -    self.assertNotEqual(foo, copy_3)
    -    self.assertEqual(foo.a, copy_3.a)
    -    self.assertEqual('Hello', copy_3.b)
    -    self.assertEqual(foo.c, copy_3.c)
    -
    -    copy_4 = foo.copy_with(c=False)
    -    self.assertNotEqual(foo, copy_4)
    -    self.assertEqual(foo.a, copy_4.a)
    -    self.assertEqual(foo.b, copy_4.b)
    -    self.assertEqual(False, copy_4.c)
    -
    -    copy_5 = foo.copy_with(a=676676, b='new', c=False)
    -    self.assertNotEqual(foo, copy_5)
    -    self.assertEqual(676676, copy_5.a)
    -    self.assertEqual('new', copy_5.b)
    -    self.assertEqual(False, copy_5.c)
    -
    -
    -
    -
    -def test_copy_with_and_deep_copy_with(self) -
    -
    -
    - -Expand source code - -
    def test_copy_with_and_deep_copy_with(self):
    -    a = A(foo=[1, 2], bar={'hello': 'world'}, values=(B(v={4, 5}), B(v={6})))
    -    deep = a.deep_copy_with()
    -
    -    # manipulation
    -    deep.bar['hello'] = 'pedantic'
    -    deep.foo.append(3)
    -
    -    self.assertEqual([1, 2], a.foo)
    -    self.assertEqual([1, 2, 3], deep.foo)
    -    self.assertEqual('world', a.bar['hello'])
    -    self.assertEqual('pedantic', deep.bar['hello'])
    -
    -
    -
    -
    -def test_copy_with_is_shallow(self) -
    -
    -
    - -Expand source code - -
    def test_copy_with_is_shallow(self):
    -    a = A(foo=[1, 2], bar={'hello': 'world'}, values=(B(v={4, 5}), B(v={6})))
    -    shallow = a.copy_with()
    -
    -    # manipulation
    -    shallow.bar['hello'] = 'pedantic'
    -    shallow.foo.append(3)
    -
    -    self.assertEqual([1, 2, 3], a.foo)
    -    self.assertEqual([1, 2, 3], shallow.foo)
    -    self.assertEqual('pedantic', a.bar['hello'])
    -    self.assertEqual('pedantic', shallow.bar['hello'])
    -
    -
    -
    -
    -def test_equals_and_hash(self) -
    -
    -
    - -Expand source code - -
    def test_equals_and_hash(self):
    -    a = Foo(a=6, b='hi', c=True)
    -    b = Foo(a=6, b='hi', c=True)
    -    c = Foo(a=7, b='hi', c=True)
    -
    -    self.assertEqual(a, b)
    -    self.assertEqual(hash(a), hash(b))
    -
    -    self.assertNotEqual(a, c)
    -    self.assertNotEqual(hash(a), hash(c))
    -
    -
    -
    -
    -def test_forward_ref_to_itself(self) -
    -
    -
    - -Expand source code - -
    def test_forward_ref_to_itself(self):
    -    """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/72 """
    -
    -    @frozen_type_safe_dataclass
    -    class Comment:
    -        replies: List['Comment']
    -
    -    comment = Comment(replies=[Comment(replies=[])])
    -    comment.copy_with(replies=[Comment(replies=[])])
    -    comment.validate_types()
    -
    - -
    -
    -def test_forward_ref_to_itself_while_class_not_in_scope(self) -
    -
    -
    - -Expand source code - -
    def test_forward_ref_to_itself_while_class_not_in_scope(self):
    -    """ Regression test for https://github.com/LostInDarkMath/pedantic-python-decorators/issues/72 """
    -
    -    def _scope():
    -        @frozen_type_safe_dataclass
    -        class Comment:
    -            replies: List['Comment']
    -
    -        def _make(replies=None):
    -            return Comment(replies=replies or [])
    -
    -        return _make
    -
    -    make = _scope()
    -
    -    comment = make(replies=[make(replies=[])])
    -    comment.copy_with(replies=[make(replies=[])])
    -    comment.validate_types()
    -
    - -
    -
    -def test_frozen_dataclass_above_dataclass(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_above_dataclass(self):
    -    # This is the same behavior like
    -    # >>> @dataclass(frozen=True)
    -    # ... @dataclass
    -    # ... class C:
    -    # ...     foo: int
    -
    -    @frozen_dataclass
    -    @dataclass
    -    class A:
    -        foo: int
    -
    -    with self.assertRaises(expected_exception=TypeError):
    -        A()
    -
    -    with self.assertRaises(expected_exception=FrozenInstanceError):
    -        A(foo=3)
    -
    -
    -
    -
    -def test_frozen_dataclass_below_dataclass(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_below_dataclass(self):
    -    @dataclass
    -    @frozen_dataclass
    -    class A:
    -        foo: int
    -
    -    with self.assertRaises(expected_exception=TypeError):
    -        A()
    -
    -    a = A(foo=3)
    -
    -    with self.assertRaises(expected_exception=FrozenInstanceError):
    -        a.foo = 4
    -
    -    b = a.copy_with(foo=4)
    -    self.assertEqual(4, b.foo)
    -
    -
    -
    -
    -def test_frozen_dataclass_inheritance_not_override_post_init(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_inheritance_not_override_post_init(self):
    -    i = 1
    -
    -    @frozen_type_safe_dataclass
    -    class A:
    -        bar: int
    -
    -        def __post_init__(self):
    -            nonlocal i
    -            i += 1
    -            print('hello a')
    -
    -    @frozen_type_safe_dataclass
    -    class B(A):
    -        foo: int
    -
    -    A(bar=3)
    -    self.assertEqual(2, i)
    -
    -    b = B(bar=3, foo=42)
    -    self.assertEqual(3, i)  # post init of A was called
    -    self.assertEqual(3, b.bar)
    -    self.assertEqual(42, b.foo)
    -
    -    a = b.copy_with()
    -    self.assertEqual(b, a)
    -    self.assertEqual(4, i)
    -
    -
    -
    -
    -def test_frozen_dataclass_inheritance_override_post_init(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_inheritance_override_post_init(self):
    -    i = 1
    -
    -    @frozen_type_safe_dataclass
    -    class A:
    -        bar: int
    -
    -        def __post_init__(self):
    -            nonlocal i
    -            i += 1
    -            print('hello a')
    -
    -    @frozen_type_safe_dataclass
    -    class B(A):
    -        foo: int
    -
    -        def __post_init__(self):
    -            nonlocal i
    -            i *= 10
    -            print('hello b')
    -
    -    A(bar=3)
    -    self.assertEqual(2, i)
    -
    -    b = B(bar=3, foo=42)
    -    self.assertEqual(20, i)  # post init of A was not called
    -    self.assertEqual(3, b.bar)
    -    self.assertEqual(42, b.foo)
    -
    -    a = b.copy_with()
    -    self.assertEqual(b, a)
    -    self.assertEqual(200, i)
    -
    -
    -
    -
    -def test_frozen_dataclass_no_braces(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_no_braces(self):
    -    @frozen_dataclass
    -    class A:
    -        foo: int
    -
    -    a = A(foo=42)
    -    self.assertEqual(42, a.foo)
    -
    -
    -
    -
    -def test_frozen_dataclass_order(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_order(self):
    -    @frozen_dataclass(order=True)
    -    class A:
    -        foo: int
    -        bar: int
    -
    -    a = A(foo=42, bar=43)
    -    b = A(foo=42, bar=42)
    -    c = A(foo=41, bar=44)
    -    d = A(foo=44, bar=0)
    -    self.assertLess(b, a)
    -    self.assertLess(c, b)
    -    self.assertLess(a, d)
    -
    -
    -
    -
    -def test_frozen_dataclass_with_empty_braces(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_dataclass_with_empty_braces(self):
    -    @frozen_dataclass()
    -    class A:
    -        foo: int
    -
    -    a = A(foo=42)
    -    self.assertEqual(42, a.foo)
    -
    -
    -
    -
    -def test_frozen_type_safe_dataclass_copy_with_check(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_type_safe_dataclass_copy_with_check(self):
    -    @frozen_type_safe_dataclass
    -    class A:
    -        foo: int
    -        bar: bool
    -
    -    a = A(foo=42, bar=False)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        a.copy_with(foo=1.1)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        a.copy_with(bar=11)
    -
    -    a.copy_with(foo=11, bar=True)
    -
    -
    -
    -
    -def test_frozen_typesafe_dataclass_with_post_init(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_typesafe_dataclass_with_post_init(self):
    -    b = 3
    -
    -    @frozen_dataclass(type_safe=True)
    -    class A:
    -        foo: int
    -
    -        def __post_init__(self) -> None:
    -            nonlocal b
    -            b = 33
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -        A(foo=42.7)
    -
    -    self.assertEqual(
    -        'In dataclass "A" in field "foo": Type hint is incorrect: Argument 42.7 of type'
    -        ' <class \'float\'> does not match expected type <class \'int\'>.',
    -        str(exc.exception)
    -    )
    -
    -    # we check that the __post_init__ method is executed
    -    self.assertEqual(33, b)
    -
    -
    -
    -
    -def test_frozen_typesafe_dataclass_without_post_init(self) -
    -
    -
    - -Expand source code - -
    def test_frozen_typesafe_dataclass_without_post_init(self):
    -    @frozen_dataclass(type_safe=True)
    -    class A:
    -        foo: int
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -        A(foo=42.7)
    -
    -    self.assertEqual(
    -        'In dataclass "A" in field "foo": Type hint is incorrect: Argument 42.7 of type'
    -        ' <class \'float\'> does not match expected type <class \'int\'>.',
    -        str(exc.exception)
    -    )
    -
    -
    -
    -
    -def test_slots_work_with_equals(self) -
    -
    -
    - -Expand source code - -
    def test_slots_work_with_equals(self):
    -    @frozen_dataclass(slots=True)
    -    class Foo:
    -        a: int
    -
    -    o = Foo(a=0)
    -    assert o == o.copy_with()
    -
    -
    -
    -
    -def test_type_safe_frozen_dataclass_with_awaitable(self) -
    -
    -
    - -Expand source code - -
    def test_type_safe_frozen_dataclass_with_awaitable(self):
    -    @frozen_type_safe_dataclass
    -    class A:
    -        f: Callable[..., Awaitable[int]]
    -
    -    async def _cb() -> int:
    -        return 42
    -
    -    async def _cb_2() -> str:
    -        return '42'
    -
    -    A(f=_cb)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        A(f=_cb_2)
    -
    -
    -
    -
    -def test_type_safe_frozen_dataclass_with_forward_ref(self) -
    -
    -
    - -Expand source code - -
    def test_type_safe_frozen_dataclass_with_forward_ref(self):
    -    T = TypeVar('T')
    -
    -    class State(Generic[T], ABC):
    -        pass
    -
    -    class StateMachine(Generic[T], ABC):
    -        pass
    -
    -    @frozen_type_safe_dataclass
    -    class StateChangeResult:
    -        new_state: Optional['MachineState']
    -
    -    class MachineState(State['MachineStateMachine']):
    -        pass
    -
    -    class OfflineMachineState(MachineState):
    -        pass
    -
    -    class OnlineMachineState:
    -        pass
    -
    -    class MachineStateMachine(StateMachine[MachineState]):
    -        pass
    -
    -    s = StateChangeResult(new_state=OfflineMachineState())
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        StateChangeResult(new_state=OnlineMachineState())
    -
    -    s.validate_types()
    -
    -
    -
    -
    -def test_validate_types(self) -
    -
    -
    - -Expand source code - -
    def test_validate_types(self):
    -    foo = Foo(a=6, b='hi', c=True)
    -    foo.validate_types()
    -
    -    bar = Foo(a=6.6, b='hi', c=True)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -        bar.validate_types()
    -
    -    expected = 'In dataclass "Foo" in field "a": Type hint is incorrect: Argument 6.6 of type <class \'float\'> ' \
    -               'does not match expected type <class \'int\'>.'
    -    self.assertEqual(str(exc.exception), expected)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_generator_wrapper.html b/docs/pedantic/tests/test_generator_wrapper.html deleted file mode 100644 index 634d796..0000000 --- a/docs/pedantic/tests/test_generator_wrapper.html +++ /dev/null @@ -1,189 +0,0 @@ - - - - - - -pedantic.tests.test_generator_wrapper API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_generator_wrapper

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestGeneratorWrapper -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestGeneratorWrapper(TestCase):
    -    def test_generator_wrapper(self) -> None:
    -        def gen_func() -> Iterator[int]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        generator = gen_func()
    -
    -        g = GeneratorWrapper(
    -            wrapped=generator,
    -            expected_type=Iterator[int],
    -            err_msg='msg',
    -            type_vars={},
    -        )
    -
    -        print(sum([x for x in g]))
    -
    -        with self.assertRaises(expected_exception=Exception):
    -            g.throw(Exception('error'))
    -
    -        with self.assertRaises(expected_exception=AttributeError):
    -            g.invalid
    -
    -        g.close()
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_generator_wrapper(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_generator_wrapper(self) -> None:
    -    def gen_func() -> Iterator[int]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    generator = gen_func()
    -
    -    g = GeneratorWrapper(
    -        wrapped=generator,
    -        expected_type=Iterator[int],
    -        err_msg='msg',
    -        type_vars={},
    -    )
    -
    -    print(sum([x for x in g]))
    -
    -    with self.assertRaises(expected_exception=Exception):
    -        g.throw(Exception('error'))
    -
    -    with self.assertRaises(expected_exception=AttributeError):
    -        g.invalid
    -
    -    g.close()
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_generic_mixin.html b/docs/pedantic/tests/test_generic_mixin.html deleted file mode 100644 index f23d421..0000000 --- a/docs/pedantic/tests/test_generic_mixin.html +++ /dev/null @@ -1,540 +0,0 @@ - - - - - - -pedantic.tests.test_generic_mixin API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_generic_mixin

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestGenericMixin -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestGenericMixin(unittest.TestCase):
    -    def test_single_type_var(self):
    -        class Foo(Generic[T], GenericMixin):
    -            value: T
    -
    -        foo = Foo[str]()
    -        assert foo.type_var == str
    -        assert foo.type_vars == {T: str}
    -
    -        invalid = Foo()
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -            invalid.type_var
    -
    -        assert f'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -    def test_multiple_type_vars(self):
    -        class Foo(Generic[T, U], GenericMixin):
    -            value: T
    -            values: List[U]
    -
    -        foo = Foo[str, int]()
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -           foo.type_var
    -
    -        self.assertEqual(err.exception.args[0], 'You have multiple type parameters. '
    -                                                'Please use "type_vars" instead of "type_var".')
    -
    -        assert foo.type_vars == {T: str, U: int}
    -
    -        invalid = Foo()
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -            invalid.type_var
    -
    -        assert f'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -    def test_non_generic_class(self):
    -        class Foo(GenericMixin):
    -            value: int
    -
    -        invalid = Foo()
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -            invalid.type_var
    -
    -        self.assertEqual(err.exception.args[0], f'Foo is not a generic class. To make it generic, declare it like: '
    -                                                f'class Foo(Generic[T], GenericMixin):...')
    -
    -    def test_call_type_var_in_constructor(self):
    -        class Foo(Generic[T], GenericMixin):
    -            def __init__(self) -> None:
    -                self.x = self.type_var()
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -            Foo[str]()
    -
    -        assert 'make sure that you do not call this in the __init__() method' in err.exception.args[0]
    -
    -    def test_subclass_set_type_variable(self):
    -        class Gen(Generic[T], GenericMixin):
    -            def __init__(self, value: T) -> None:
    -                self.value = value
    -
    -            def get_type(self) -> dict[TypeVar, Type]:
    -                return self.type_vars
    -
    -        class MyClass(Gen[int]):
    -            pass
    -
    -        bar = Gen[int](value=4)
    -        assert bar.get_type() == {T: int}
    -
    -        foo = MyClass(value=4)
    -        assert foo.get_type() == {T: int}
    -
    -    def test_subclass_with_multiple_parents(self):
    -        class Gen(Generic[T], GenericMixin):
    -            def __init__(self, value: T) -> None:
    -                self.value = value
    -
    -            def get_type(self) -> dict[TypeVar, Type]:
    -                return self.type_vars
    -
    -        class MyMixin:
    -            value = 42
    -
    -        class MyClass(MyMixin, Gen[int]):
    -            pass
    -
    -        bar = Gen[int](value=4)
    -        assert bar.get_type() == {T: int}
    -
    -        foo = MyClass(value=4)
    -        assert foo.get_type() == {T: int}
    -
    -    def test_resolved_type_var_inheritance(self):
    -        class Foo(Generic[T]): ...
    -
    -        class Bar(Foo[int], Generic[U], GenericMixin): ...
    -
    -        bar = Bar[str]()
    -        assert bar.type_vars == {T: int, U: str}
    -
    -    def test_resolved_type_var_inheritance_2(self):
    -        class Foo(Generic[T], GenericMixin): ...
    -
    -        class Bar(Foo[int], Generic[U]): ...
    -
    -        bar = Bar[str]()
    -        assert bar.type_vars == {T: int, U: str}
    -
    -    def test_very_complex_inheritance(self):
    -        class Foo(Generic[E], GenericMixin): ...
    -        class Bar(Foo[int], Generic[S]): ...
    -        class Baz(Foo[int]): ...
    -        class Deep(Baz): ...
    -        class Deeper(Baz, Generic[T]): ...
    -
    -        foo = Foo[str]()
    -        actual = foo.type_vars
    -        assert actual == {E: str}
    -
    -        bar = Bar[str]()
    -        actual = bar.type_vars
    -        assert actual == {E: int, S: str}
    -
    -        baz = Baz()
    -        actual = baz.type_vars
    -        assert actual == {E: int}
    -
    -        deep = Deep()
    -        actual = deep.type_vars
    -        assert actual == {E: int}
    -
    -        deeper = Deeper[bool]()
    -        actual = deeper.type_vars
    -        assert actual == {E: int, T: bool}
    -
    -        with self.assertRaises(expected_exception=AssertionError) as err:
    -            Foo().type_vars
    -
    -        assert 'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -    def test_substitution_lookup_hits(self):
    -        class Base(Generic[A], GenericMixin): ...
    -        class Mid(Base[A], Generic[A]): ...
    -        class Final(Mid[int]): ...
    -
    -        obj = Final()
    -        actual = obj.type_vars
    -        assert actual == {A: int}
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_call_type_var_in_constructor(self) -
    -
    -
    - -Expand source code - -
    def test_call_type_var_in_constructor(self):
    -    class Foo(Generic[T], GenericMixin):
    -        def __init__(self) -> None:
    -            self.x = self.type_var()
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -        Foo[str]()
    -
    -    assert 'make sure that you do not call this in the __init__() method' in err.exception.args[0]
    -
    -
    -
    -
    -def test_multiple_type_vars(self) -
    -
    -
    - -Expand source code - -
    def test_multiple_type_vars(self):
    -    class Foo(Generic[T, U], GenericMixin):
    -        value: T
    -        values: List[U]
    -
    -    foo = Foo[str, int]()
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -       foo.type_var
    -
    -    self.assertEqual(err.exception.args[0], 'You have multiple type parameters. '
    -                                            'Please use "type_vars" instead of "type_var".')
    -
    -    assert foo.type_vars == {T: str, U: int}
    -
    -    invalid = Foo()
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -        invalid.type_var
    -
    -    assert f'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -
    -
    -
    -def test_non_generic_class(self) -
    -
    -
    - -Expand source code - -
    def test_non_generic_class(self):
    -    class Foo(GenericMixin):
    -        value: int
    -
    -    invalid = Foo()
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -        invalid.type_var
    -
    -    self.assertEqual(err.exception.args[0], f'Foo is not a generic class. To make it generic, declare it like: '
    -                                            f'class Foo(Generic[T], GenericMixin):...')
    -
    -
    -
    -
    -def test_resolved_type_var_inheritance(self) -
    -
    -
    - -Expand source code - -
    def test_resolved_type_var_inheritance(self):
    -    class Foo(Generic[T]): ...
    -
    -    class Bar(Foo[int], Generic[U], GenericMixin): ...
    -
    -    bar = Bar[str]()
    -    assert bar.type_vars == {T: int, U: str}
    -
    -
    -
    -
    -def test_resolved_type_var_inheritance_2(self) -
    -
    -
    - -Expand source code - -
    def test_resolved_type_var_inheritance_2(self):
    -    class Foo(Generic[T], GenericMixin): ...
    -
    -    class Bar(Foo[int], Generic[U]): ...
    -
    -    bar = Bar[str]()
    -    assert bar.type_vars == {T: int, U: str}
    -
    -
    -
    -
    -def test_single_type_var(self) -
    -
    -
    - -Expand source code - -
    def test_single_type_var(self):
    -    class Foo(Generic[T], GenericMixin):
    -        value: T
    -
    -    foo = Foo[str]()
    -    assert foo.type_var == str
    -    assert foo.type_vars == {T: str}
    -
    -    invalid = Foo()
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -        invalid.type_var
    -
    -    assert f'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -
    -
    -
    -def test_subclass_set_type_variable(self) -
    -
    -
    - -Expand source code - -
    def test_subclass_set_type_variable(self):
    -    class Gen(Generic[T], GenericMixin):
    -        def __init__(self, value: T) -> None:
    -            self.value = value
    -
    -        def get_type(self) -> dict[TypeVar, Type]:
    -            return self.type_vars
    -
    -    class MyClass(Gen[int]):
    -        pass
    -
    -    bar = Gen[int](value=4)
    -    assert bar.get_type() == {T: int}
    -
    -    foo = MyClass(value=4)
    -    assert foo.get_type() == {T: int}
    -
    -
    -
    -
    -def test_subclass_with_multiple_parents(self) -
    -
    -
    - -Expand source code - -
    def test_subclass_with_multiple_parents(self):
    -    class Gen(Generic[T], GenericMixin):
    -        def __init__(self, value: T) -> None:
    -            self.value = value
    -
    -        def get_type(self) -> dict[TypeVar, Type]:
    -            return self.type_vars
    -
    -    class MyMixin:
    -        value = 42
    -
    -    class MyClass(MyMixin, Gen[int]):
    -        pass
    -
    -    bar = Gen[int](value=4)
    -    assert bar.get_type() == {T: int}
    -
    -    foo = MyClass(value=4)
    -    assert foo.get_type() == {T: int}
    -
    -
    -
    -
    -def test_substitution_lookup_hits(self) -
    -
    -
    - -Expand source code - -
    def test_substitution_lookup_hits(self):
    -    class Base(Generic[A], GenericMixin): ...
    -    class Mid(Base[A], Generic[A]): ...
    -    class Final(Mid[int]): ...
    -
    -    obj = Final()
    -    actual = obj.type_vars
    -    assert actual == {A: int}
    -
    -
    -
    -
    -def test_very_complex_inheritance(self) -
    -
    -
    - -Expand source code - -
    def test_very_complex_inheritance(self):
    -    class Foo(Generic[E], GenericMixin): ...
    -    class Bar(Foo[int], Generic[S]): ...
    -    class Baz(Foo[int]): ...
    -    class Deep(Baz): ...
    -    class Deeper(Baz, Generic[T]): ...
    -
    -    foo = Foo[str]()
    -    actual = foo.type_vars
    -    assert actual == {E: str}
    -
    -    bar = Bar[str]()
    -    actual = bar.type_vars
    -    assert actual == {E: int, S: str}
    -
    -    baz = Baz()
    -    actual = baz.type_vars
    -    assert actual == {E: int}
    -
    -    deep = Deep()
    -    actual = deep.type_vars
    -    assert actual == {E: int}
    -
    -    deeper = Deeper[bool]()
    -    actual = deeper.type_vars
    -    assert actual == {E: int, T: bool}
    -
    -    with self.assertRaises(expected_exception=AssertionError) as err:
    -        Foo().type_vars
    -
    -    assert 'You need to instantiate this class with type parameters! Example: Foo[int]()' in err.exception.args[0]
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_in_subprocess.html b/docs/pedantic/tests/test_in_subprocess.html deleted file mode 100644 index c2ae42f..0000000 --- a/docs/pedantic/tests/test_in_subprocess.html +++ /dev/null @@ -1,539 +0,0 @@ - - - - - - -pedantic.tests.test_in_subprocess API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_in_subprocess

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestInSubprocess -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestInSubprocess(unittest.IsolatedAsyncioTestCase):
    -    async def test_in_subprocess_simple(self):
    -        @in_subprocess
    -        def f() -> int:
    -            return 42
    -
    -        assert await f() == 42
    -
    -    async def test_in_subprocess_custom_object(self):
    -        class Foo:
    -            def __init__(self, v) -> None:
    -                self._value = v
    -
    -        @in_subprocess
    -        def f() -> Foo:
    -            return Foo(v=42)
    -
    -        assert (await f())._value == 42
    -
    -    async def test_in_subprocess_simple_async(self):
    -        @in_subprocess
    -        async def f() -> int:
    -            return 42
    -
    -        assert await f() == 42
    -
    -    async def test_in_subprocess_no_args(self):
    -        @in_subprocess
    -        def f() -> int:
    -            time.sleep(0.1)
    -            return 42
    -
    -        async def t() -> None:
    -            for _ in range(6):
    -                await asyncio.sleep(0.01)
    -                nonlocal counter
    -                counter += 1
    -
    -        counter = 0
    -        task = asyncio.create_task(t())
    -        assert await f() == 42
    -        assert counter >= 5
    -        await task
    -
    -    async def test_in_subprocess_no_args_no_return(self):
    -        @in_subprocess
    -        def f() -> None:
    -            time.sleep(0.1)
    -
    -        assert await f() is None
    -
    -    async def test_in_subprocess_exception(self):
    -        @in_subprocess
    -        def f() -> NoReturn:
    -            raise RuntimeError('foo')
    -
    -        with self.assertRaises(expected_exception=RuntimeError):
    -            await f()
    -
    -    async def test_not_in_subprocess_blocks(self):
    -        async def f() -> int:
    -            time.sleep(0.1)
    -            return 42
    -
    -        async def t() -> None:
    -            for _ in range(6):
    -                await asyncio.sleep(0.05)
    -                nonlocal counter
    -                counter += 1
    -
    -        counter = 0
    -        task = asyncio.create_task(t())
    -        assert await f() == 42
    -        assert counter == 0
    -        await task
    -
    -    async def test_in_subprocess_with_arguments(self):
    -        @in_subprocess
    -        def f(a: int, b: int) -> int:
    -            return a + b
    -
    -        assert await f(4, 5) == 9
    -        assert await f(a=4, b=5) == 9
    -
    -    def test_inner_function_sync(self):
    -        """ Needed for line coverage"""
    -
    -        rx, tx = Pipe(duplex=False)
    -        _inner(tx, lambda x: 1 / x, x=42)
    -        assert rx.recv() == 1 / 42
    -
    -        _inner(tx, lambda x: 1 / x, x=0)
    -        ex = rx.recv()
    -        assert isinstance(ex, SubprocessError)
    -
    -    def test_inner_function_async(self):
    -        """ Needed for line coverage"""
    -
    -        async def foo(x):
    -            return 1/x
    -
    -        rx, tx = Pipe(duplex=False)
    -        _inner(tx, foo, x=42)
    -        assert rx.recv() == 1 / 42
    -
    -        _inner(tx, foo, x=0)
    -        ex = rx.recv()
    -        assert isinstance(ex, SubprocessError)
    -
    -    async def test_in_subprocess_instance_method(self):
    -        class Foo:
    -            async def pos_args(self) -> int:
    -                return await self.f(4, 5)
    -
    -            async def kw_args(self) -> int:
    -                return await self.f(a=4, b=5)
    -
    -            @in_subprocess
    -            def f(self, a: int, b: int) -> int:
    -                return a + b
    -
    -        foo = Foo()
    -        assert await foo.pos_args() == 9
    -        assert await foo.kw_args() == 9
    -
    -    async def test_in_subprocess_static_method(self):
    -        class Foo:
    -            async def pos_args(self) -> int:
    -                return await self.f(4, 5)
    -
    -            async def kw_args(self) -> int:
    -                return await self.f(a=4, b=5)
    -
    -            @staticmethod
    -            @in_subprocess
    -            def f(a: int, b: int) -> int:
    -                return a + b
    -
    -        foo = Foo()
    -        assert await foo.pos_args() == 9
    -        assert await foo.kw_args() == 9
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.async_case.IsolatedAsyncioTestCase
    • -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -async def test_in_subprocess_custom_object(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_custom_object(self):
    -    class Foo:
    -        def __init__(self, v) -> None:
    -            self._value = v
    -
    -    @in_subprocess
    -    def f() -> Foo:
    -        return Foo(v=42)
    -
    -    assert (await f())._value == 42
    -
    -
    -
    -
    -async def test_in_subprocess_exception(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_exception(self):
    -    @in_subprocess
    -    def f() -> NoReturn:
    -        raise RuntimeError('foo')
    -
    -    with self.assertRaises(expected_exception=RuntimeError):
    -        await f()
    -
    -
    -
    -
    -async def test_in_subprocess_instance_method(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_instance_method(self):
    -    class Foo:
    -        async def pos_args(self) -> int:
    -            return await self.f(4, 5)
    -
    -        async def kw_args(self) -> int:
    -            return await self.f(a=4, b=5)
    -
    -        @in_subprocess
    -        def f(self, a: int, b: int) -> int:
    -            return a + b
    -
    -    foo = Foo()
    -    assert await foo.pos_args() == 9
    -    assert await foo.kw_args() == 9
    -
    -
    -
    -
    -async def test_in_subprocess_no_args(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_no_args(self):
    -    @in_subprocess
    -    def f() -> int:
    -        time.sleep(0.1)
    -        return 42
    -
    -    async def t() -> None:
    -        for _ in range(6):
    -            await asyncio.sleep(0.01)
    -            nonlocal counter
    -            counter += 1
    -
    -    counter = 0
    -    task = asyncio.create_task(t())
    -    assert await f() == 42
    -    assert counter >= 5
    -    await task
    -
    -
    -
    -
    -async def test_in_subprocess_no_args_no_return(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_no_args_no_return(self):
    -    @in_subprocess
    -    def f() -> None:
    -        time.sleep(0.1)
    -
    -    assert await f() is None
    -
    -
    -
    -
    -async def test_in_subprocess_simple(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_simple(self):
    -    @in_subprocess
    -    def f() -> int:
    -        return 42
    -
    -    assert await f() == 42
    -
    -
    -
    -
    -async def test_in_subprocess_simple_async(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_simple_async(self):
    -    @in_subprocess
    -    async def f() -> int:
    -        return 42
    -
    -    assert await f() == 42
    -
    -
    -
    -
    -async def test_in_subprocess_static_method(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_static_method(self):
    -    class Foo:
    -        async def pos_args(self) -> int:
    -            return await self.f(4, 5)
    -
    -        async def kw_args(self) -> int:
    -            return await self.f(a=4, b=5)
    -
    -        @staticmethod
    -        @in_subprocess
    -        def f(a: int, b: int) -> int:
    -            return a + b
    -
    -    foo = Foo()
    -    assert await foo.pos_args() == 9
    -    assert await foo.kw_args() == 9
    -
    -
    -
    -
    -async def test_in_subprocess_with_arguments(self) -
    -
    -
    - -Expand source code - -
    async def test_in_subprocess_with_arguments(self):
    -    @in_subprocess
    -    def f(a: int, b: int) -> int:
    -        return a + b
    -
    -    assert await f(4, 5) == 9
    -    assert await f(a=4, b=5) == 9
    -
    -
    -
    -
    -def test_inner_function_async(self) -
    -
    -
    - -Expand source code - -
    def test_inner_function_async(self):
    -    """ Needed for line coverage"""
    -
    -    async def foo(x):
    -        return 1/x
    -
    -    rx, tx = Pipe(duplex=False)
    -    _inner(tx, foo, x=42)
    -    assert rx.recv() == 1 / 42
    -
    -    _inner(tx, foo, x=0)
    -    ex = rx.recv()
    -    assert isinstance(ex, SubprocessError)
    -
    -

    Needed for line coverage

    -
    -
    -def test_inner_function_sync(self) -
    -
    -
    - -Expand source code - -
    def test_inner_function_sync(self):
    -    """ Needed for line coverage"""
    -
    -    rx, tx = Pipe(duplex=False)
    -    _inner(tx, lambda x: 1 / x, x=42)
    -    assert rx.recv() == 1 / 42
    -
    -    _inner(tx, lambda x: 1 / x, x=0)
    -    ex = rx.recv()
    -    assert isinstance(ex, SubprocessError)
    -
    -

    Needed for line coverage

    -
    -
    -async def test_not_in_subprocess_blocks(self) -
    -
    -
    - -Expand source code - -
    async def test_not_in_subprocess_blocks(self):
    -    async def f() -> int:
    -        time.sleep(0.1)
    -        return 42
    -
    -    async def t() -> None:
    -        for _ in range(6):
    -            await asyncio.sleep(0.05)
    -            nonlocal counter
    -            counter += 1
    -
    -    counter = 0
    -    task = asyncio.create_task(t())
    -    assert await f() == 42
    -    assert counter == 0
    -    await task
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_rename_kwargs.html b/docs/pedantic/tests/test_rename_kwargs.html deleted file mode 100644 index 6915f80..0000000 --- a/docs/pedantic/tests/test_rename_kwargs.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - -pedantic.tests.test_rename_kwargs API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_rename_kwargs

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestRenameKwargs -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestRenameKwargs(unittest.TestCase):
    -    def test_rename_kwargs(self):
    -        @rename_kwargs(
    -            Rename(from_='x', to='a'),
    -            Rename(from_='y', to='b'),
    -        )
    -        def operation(a: int, b: int) -> int:
    -            return a + b
    -
    -        operation(4, 5)
    -        operation(a=4, b=5)
    -        operation(x=4, y=5)
    -        operation(x=4, b=5)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_rename_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_rename_kwargs(self):
    -    @rename_kwargs(
    -        Rename(from_='x', to='a'),
    -        Rename(from_='y', to='b'),
    -    )
    -    def operation(a: int, b: int) -> int:
    -        return a + b
    -
    -    operation(4, 5)
    -    operation(a=4, b=5)
    -    operation(x=4, y=5)
    -    operation(x=4, b=5)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_resolve_forward_ref.html b/docs/pedantic/tests/test_resolve_forward_ref.html deleted file mode 100644 index a6e3473..0000000 --- a/docs/pedantic/tests/test_resolve_forward_ref.html +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - -pedantic.tests.test_resolve_forward_ref API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_resolve_forward_ref

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestResolveForwardRef -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestResolveForwardRef(TestCase):
    -    def test_resolve_forward_ref_primitive_types(self):
    -        assert resolve_forward_ref(type_='int') == int
    -        assert resolve_forward_ref(type_='float') == float
    -        assert resolve_forward_ref(type_='str') == str
    -        assert resolve_forward_ref(type_='bool') == bool
    -
    -    def test_resolve_forward_ref_typing_types(self):
    -        assert resolve_forward_ref(type_='List[int]') == List[int]
    -        assert resolve_forward_ref(type_='Optional[List[Union[str, float]]]') == Optional[List[Union[str, float]]]
    -
    -    def test_unresolvable_type(self):
    -        with self.assertRaises(NameError):
    -            resolve_forward_ref(type_='Invalid')
    -
    -    def test_resolve_forward_ref_custom_class(self):
    -        class Foo:
    -            pass
    -
    -        context = locals()
    -        assert resolve_forward_ref(type_='Foo', context=context) == Foo
    -        assert resolve_forward_ref(type_='Optional[Foo]', context=context) == Optional[Foo]
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_resolve_forward_ref_custom_class(self) -
    -
    -
    - -Expand source code - -
    def test_resolve_forward_ref_custom_class(self):
    -    class Foo:
    -        pass
    -
    -    context = locals()
    -    assert resolve_forward_ref(type_='Foo', context=context) == Foo
    -    assert resolve_forward_ref(type_='Optional[Foo]', context=context) == Optional[Foo]
    -
    -
    -
    -
    -def test_resolve_forward_ref_primitive_types(self) -
    -
    -
    - -Expand source code - -
    def test_resolve_forward_ref_primitive_types(self):
    -    assert resolve_forward_ref(type_='int') == int
    -    assert resolve_forward_ref(type_='float') == float
    -    assert resolve_forward_ref(type_='str') == str
    -    assert resolve_forward_ref(type_='bool') == bool
    -
    -
    -
    -
    -def test_resolve_forward_ref_typing_types(self) -
    -
    -
    - -Expand source code - -
    def test_resolve_forward_ref_typing_types(self):
    -    assert resolve_forward_ref(type_='List[int]') == List[int]
    -    assert resolve_forward_ref(type_='Optional[List[Union[str, float]]]') == Optional[List[Union[str, float]]]
    -
    -
    -
    -
    -def test_unresolvable_type(self) -
    -
    -
    - -Expand source code - -
    def test_unresolvable_type(self):
    -    with self.assertRaises(NameError):
    -        resolve_forward_ref(type_='Invalid')
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_retry.html b/docs/pedantic/tests/test_retry.html deleted file mode 100644 index db668a9..0000000 --- a/docs/pedantic/tests/test_retry.html +++ /dev/null @@ -1,615 +0,0 @@ - - - - - - -pedantic.tests.test_retry API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_retry

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestRetry -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestRetry(unittest.TestCase):
    -    def test_retry_positive_no_args(self):
    -        count = 0
    -
    -        @retry(attempts=5)
    -        def foo():
    -            nonlocal count
    -            count += 1
    -
    -        foo()
    -        assert count == 1
    -
    -    def test_retry_positive_args_and_kwargs(self):
    -        count = 0
    -
    -        @retry(attempts=5)
    -        def foo(x, y):
    -            nonlocal count
    -            count += x + y
    -
    -        foo(12, y=42)
    -        assert count == 54
    -
    -    def test_retry_positive_no_args_fails_every_time(self):
    -        count = 0
    -
    -        @retry(attempts=5)
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise ValueError('foo')
    -
    -        with self.assertRaises(ValueError):
    -            foo()
    -
    -        assert count == 5
    -
    -    def test_retry_positive_no_args_fails_different_exception_type(self):
    -        count = 0
    -
    -        @retry(attempts=5, exceptions=AssertionError)
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise ValueError('foo')
    -
    -        with self.assertRaises(ValueError):
    -            foo()
    -
    -        assert count == 1
    -
    -    def test_retry_fails_same_exception_type(self):
    -        count = 0
    -
    -        @retry(attempts=5, exceptions=AssertionError)
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise AssertionError('foo')
    -
    -        with self.assertRaises(AssertionError):
    -            foo()
    -
    -        assert count == 5
    -
    -    def test_retry_positive_no_args_fails_on_first_times(self):
    -        count = 0
    -
    -        @retry(attempts=5)
    -        def foo() -> int:
    -            nonlocal count
    -            count += 1
    -
    -            if count < 3:
    -                raise ValueError('foo')
    -
    -            return count
    -
    -        assert foo() == 3
    -        assert count == 3
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_retry_fails_same_exception_type(self) -
    -
    -
    - -Expand source code - -
    def test_retry_fails_same_exception_type(self):
    -    count = 0
    -
    -    @retry(attempts=5, exceptions=AssertionError)
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise AssertionError('foo')
    -
    -    with self.assertRaises(AssertionError):
    -        foo()
    -
    -    assert count == 5
    -
    -
    -
    -
    -def test_retry_positive_args_and_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_args_and_kwargs(self):
    -    count = 0
    -
    -    @retry(attempts=5)
    -    def foo(x, y):
    -        nonlocal count
    -        count += x + y
    -
    -    foo(12, y=42)
    -    assert count == 54
    -
    -
    -
    -
    -def test_retry_positive_no_args(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args(self):
    -    count = 0
    -
    -    @retry(attempts=5)
    -    def foo():
    -        nonlocal count
    -        count += 1
    -
    -    foo()
    -    assert count == 1
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_different_exception_type(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_different_exception_type(self):
    -    count = 0
    -
    -    @retry(attempts=5, exceptions=AssertionError)
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise ValueError('foo')
    -
    -    with self.assertRaises(ValueError):
    -        foo()
    -
    -    assert count == 1
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_every_time(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_every_time(self):
    -    count = 0
    -
    -    @retry(attempts=5)
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise ValueError('foo')
    -
    -    with self.assertRaises(ValueError):
    -        foo()
    -
    -    assert count == 5
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_on_first_times(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_on_first_times(self):
    -    count = 0
    -
    -    @retry(attempts=5)
    -    def foo() -> int:
    -        nonlocal count
    -        count += 1
    -
    -        if count < 3:
    -            raise ValueError('foo')
    -
    -        return count
    -
    -    assert foo() == 3
    -    assert count == 3
    -
    -
    -
    -
    -
    -
    -class TestRetryFunc -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestRetryFunc(unittest.TestCase):
    -    def test_retry_positive_no_args(self):
    -        count = 0
    -
    -        def foo():
    -            nonlocal count
    -            count += 1
    -
    -        retry_func(func=foo, attempts=5)
    -        assert count == 1
    -
    -    def test_retry_positive_args_and_kwargs(self):
    -        count = 0
    -
    -        def foo(x, y):
    -            nonlocal count
    -            count += x + y
    -
    -        retry_func(foo, 12, attempts=5, y=42)
    -        assert count == 54
    -
    -    def test_retry_positive_no_args_fails_every_time(self):
    -        count = 0
    -
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise ValueError('foo')
    -
    -        with self.assertRaises(ValueError):
    -            retry_func(func=foo, attempts=5)
    -
    -        assert count == 5
    -
    -    def test_retry_positive_no_args_fails_different_exception_type(self):
    -        count = 0
    -
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise ValueError('foo')
    -
    -        with self.assertRaises(ValueError):
    -            retry_func(func=foo, attempts=5, exceptions=AssertionError)
    -
    -        assert count == 1
    -
    -    def test_retry_fails_same_exception_type(self):
    -        count = 0
    -
    -        def foo():
    -            nonlocal count
    -            count += 1
    -            raise AssertionError('foo')
    -
    -        with self.assertRaises(AssertionError):
    -            retry_func(func=foo, attempts=5, exceptions=AssertionError)
    -
    -        assert count == 5
    -
    -    def test_retry_positive_no_args_fails_on_first_times(self):
    -        count = 0
    -
    -        def foo() -> int:
    -            nonlocal count
    -            count += 1
    -
    -            if count < 3:
    -                raise ValueError('foo')
    -
    -            return count
    -
    -        assert retry_func(func=foo, attempts=5) == 3
    -        assert count == 3
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_retry_fails_same_exception_type(self) -
    -
    -
    - -Expand source code - -
    def test_retry_fails_same_exception_type(self):
    -    count = 0
    -
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise AssertionError('foo')
    -
    -    with self.assertRaises(AssertionError):
    -        retry_func(func=foo, attempts=5, exceptions=AssertionError)
    -
    -    assert count == 5
    -
    -
    -
    -
    -def test_retry_positive_args_and_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_args_and_kwargs(self):
    -    count = 0
    -
    -    def foo(x, y):
    -        nonlocal count
    -        count += x + y
    -
    -    retry_func(foo, 12, attempts=5, y=42)
    -    assert count == 54
    -
    -
    -
    -
    -def test_retry_positive_no_args(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args(self):
    -    count = 0
    -
    -    def foo():
    -        nonlocal count
    -        count += 1
    -
    -    retry_func(func=foo, attempts=5)
    -    assert count == 1
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_different_exception_type(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_different_exception_type(self):
    -    count = 0
    -
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise ValueError('foo')
    -
    -    with self.assertRaises(ValueError):
    -        retry_func(func=foo, attempts=5, exceptions=AssertionError)
    -
    -    assert count == 1
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_every_time(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_every_time(self):
    -    count = 0
    -
    -    def foo():
    -        nonlocal count
    -        count += 1
    -        raise ValueError('foo')
    -
    -    with self.assertRaises(ValueError):
    -        retry_func(func=foo, attempts=5)
    -
    -    assert count == 5
    -
    -
    -
    -
    -def test_retry_positive_no_args_fails_on_first_times(self) -
    -
    -
    - -Expand source code - -
    def test_retry_positive_no_args_fails_on_first_times(self):
    -    count = 0
    -
    -    def foo() -> int:
    -        nonlocal count
    -        count += 1
    -
    -        if count < 3:
    -            raise ValueError('foo')
    -
    -        return count
    -
    -    assert retry_func(func=foo, attempts=5) == 3
    -    assert count == 3
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/test_with_decorated_methods.html b/docs/pedantic/tests/test_with_decorated_methods.html deleted file mode 100644 index a92c7a5..0000000 --- a/docs/pedantic/tests/test_with_decorated_methods.html +++ /dev/null @@ -1,452 +0,0 @@ - - - - - - -pedantic.tests.test_with_decorated_methods API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.test_with_decorated_methods

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Decorators -(*args, **kwds) -
    -
    -
    - -Expand source code - -
    class Decorators(DecoratorType):
    -    FOO = '_foo'
    -    BAR = '_bar'
    -
    -

    The interface that defines all possible decorators types.

    -

    The values of this enum are used as property names and the properties are added to the decorated functions. -So I would recommend naming them with a leading underscore to keep them private and also write it lowercase.

    -

    Example

    -
    >>> class Decorators(DecoratorType):
    -...     FOO = '_foo'
    -
    -

    Ancestors

    -
      -
    • DecoratorType
    • -
    • enum.StrEnum
    • -
    • builtins.str
    • -
    • enum.ReprEnum
    • -
    • enum.Enum
    • -
    -

    Class variables

    -
    -
    var BAR
    -
    -

    The type of the None singleton.

    -
    -
    var FOO
    -
    -

    The type of the None singleton.

    -
    -
    -
    -
    -class TestWithDecoratedMethods -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestWithDecoratedMethods(unittest.TestCase):
    -    def test_no_decorated_methods(self):
    -        class MyClass(WithDecoratedMethods[Decorators]):
    -            pass
    -
    -        instance = MyClass()
    -        assert instance.get_decorated_functions() == {Decorators.FOO: {}, Decorators.BAR: {}}
    -
    -    def test_class_with_bad_property(self):
    -        class MyClass(WithDecoratedMethods[Decorators]):
    -            @property
    -            def bad(self) -> NoReturn:
    -                raise RuntimeError('bad man')
    -
    -        instance = MyClass()
    -        assert instance.get_decorated_functions() == {Decorators.FOO: {}, Decorators.BAR: {}}
    -
    -    def test_with_decorated_methods_sync(self):
    -        class MyClass(WithDecoratedMethods[Decorators]):
    -            @foo(42)
    -            def m1(self) -> None:
    -                print('bar')
    -
    -            @foo(value=43)
    -            def m2(self) -> None:
    -                print('bar')
    -
    -            @bar(value=44)
    -            def m3(self) -> None:
    -                print('bar')
    -
    -        instance = MyClass()
    -        expected = {
    -            Decorators.FOO: {
    -                instance.m1: 42,
    -                instance.m2: 43,
    -            },
    -            Decorators.BAR: {
    -                instance.m3: 44,
    -            }
    -        }
    -        assert instance.get_decorated_functions() == expected
    -
    -    def test_with_decorated_methods_async(self):
    -        class MyClass(WithDecoratedMethods[Decorators]):
    -            @foo(42)
    -            async def m1(self) -> None:
    -                print('bar')
    -
    -            @foo(value=43)
    -            async def m2(self) -> None:
    -                print('bar')
    -
    -            @bar(value=44)
    -            async def m3(self) -> None:
    -                print('bar')
    -
    -        instance = MyClass()
    -        expected = {
    -            Decorators.FOO: {
    -                instance.m1: 42,
    -                instance.m2: 43,
    -            },
    -            Decorators.BAR: {
    -                instance.m3: 44,
    -            }
    -        }
    -        assert instance.get_decorated_functions() == expected
    -
    -
    -    def test_with_custom_transformation(self):
    -        def my_transformation(f, decorator_type, value):
    -            assert decorator_type == Decorators.BAR
    -            assert value == 42
    -
    -            @wraps(f)
    -            def wrapper(*args, **kwargs):
    -                f(*args, **kwargs)
    -                return 4422  # we add a return value
    -
    -            return wrapper
    -
    -        my_decorator = create_decorator(decorator_type=Decorators.BAR, transformation=my_transformation)
    -
    -        class MyClass(WithDecoratedMethods[Decorators]):
    -            @my_decorator(42)
    -            def m1(self) -> int:
    -                return 1
    -
    -        instance = MyClass()
    -        expected = {
    -            Decorators.BAR: {
    -                instance.m1: 42,
    -            },
    -            Decorators.FOO: {},
    -        }
    -        assert instance.get_decorated_functions() == expected
    -
    -        assert instance.m1() == 4422  # check that transformation was applied
    -
    -    def test_with_decorated_methods_can_have_generic_child_class(self):
    -        class MyClass(Generic[T], WithDecoratedMethods[Decorators]):
    -            @foo(42)
    -            def m1(self) -> None: ...
    -
    -        instance = MyClass[int]()
    -        actual = instance.get_decorated_functions()
    -        assert actual == {Decorators.FOO: {instance.m1: 42}, Decorators.BAR: {}}
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_class_with_bad_property(self) -
    -
    -
    - -Expand source code - -
    def test_class_with_bad_property(self):
    -    class MyClass(WithDecoratedMethods[Decorators]):
    -        @property
    -        def bad(self) -> NoReturn:
    -            raise RuntimeError('bad man')
    -
    -    instance = MyClass()
    -    assert instance.get_decorated_functions() == {Decorators.FOO: {}, Decorators.BAR: {}}
    -
    -
    -
    -
    -def test_no_decorated_methods(self) -
    -
    -
    - -Expand source code - -
    def test_no_decorated_methods(self):
    -    class MyClass(WithDecoratedMethods[Decorators]):
    -        pass
    -
    -    instance = MyClass()
    -    assert instance.get_decorated_functions() == {Decorators.FOO: {}, Decorators.BAR: {}}
    -
    -
    -
    -
    -def test_with_custom_transformation(self) -
    -
    -
    - -Expand source code - -
    def test_with_custom_transformation(self):
    -    def my_transformation(f, decorator_type, value):
    -        assert decorator_type == Decorators.BAR
    -        assert value == 42
    -
    -        @wraps(f)
    -        def wrapper(*args, **kwargs):
    -            f(*args, **kwargs)
    -            return 4422  # we add a return value
    -
    -        return wrapper
    -
    -    my_decorator = create_decorator(decorator_type=Decorators.BAR, transformation=my_transformation)
    -
    -    class MyClass(WithDecoratedMethods[Decorators]):
    -        @my_decorator(42)
    -        def m1(self) -> int:
    -            return 1
    -
    -    instance = MyClass()
    -    expected = {
    -        Decorators.BAR: {
    -            instance.m1: 42,
    -        },
    -        Decorators.FOO: {},
    -    }
    -    assert instance.get_decorated_functions() == expected
    -
    -    assert instance.m1() == 4422  # check that transformation was applied
    -
    -
    -
    -
    -def test_with_decorated_methods_async(self) -
    -
    -
    - -Expand source code - -
    def test_with_decorated_methods_async(self):
    -    class MyClass(WithDecoratedMethods[Decorators]):
    -        @foo(42)
    -        async def m1(self) -> None:
    -            print('bar')
    -
    -        @foo(value=43)
    -        async def m2(self) -> None:
    -            print('bar')
    -
    -        @bar(value=44)
    -        async def m3(self) -> None:
    -            print('bar')
    -
    -    instance = MyClass()
    -    expected = {
    -        Decorators.FOO: {
    -            instance.m1: 42,
    -            instance.m2: 43,
    -        },
    -        Decorators.BAR: {
    -            instance.m3: 44,
    -        }
    -    }
    -    assert instance.get_decorated_functions() == expected
    -
    -
    -
    -
    -def test_with_decorated_methods_can_have_generic_child_class(self) -
    -
    -
    - -Expand source code - -
    def test_with_decorated_methods_can_have_generic_child_class(self):
    -    class MyClass(Generic[T], WithDecoratedMethods[Decorators]):
    -        @foo(42)
    -        def m1(self) -> None: ...
    -
    -    instance = MyClass[int]()
    -    actual = instance.get_decorated_functions()
    -    assert actual == {Decorators.FOO: {instance.m1: 42}, Decorators.BAR: {}}
    -
    -
    -
    -
    -def test_with_decorated_methods_sync(self) -
    -
    -
    - -Expand source code - -
    def test_with_decorated_methods_sync(self):
    -    class MyClass(WithDecoratedMethods[Decorators]):
    -        @foo(42)
    -        def m1(self) -> None:
    -            print('bar')
    -
    -        @foo(value=43)
    -        def m2(self) -> None:
    -            print('bar')
    -
    -        @bar(value=44)
    -        def m3(self) -> None:
    -            print('bar')
    -
    -    instance = MyClass()
    -    expected = {
    -        Decorators.FOO: {
    -            instance.m1: 42,
    -            instance.m2: 43,
    -        },
    -        Decorators.BAR: {
    -            instance.m3: 44,
    -        }
    -    }
    -    assert instance.get_decorated_functions() == expected
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_class_decorators.html b/docs/pedantic/tests/tests_class_decorators.html deleted file mode 100644 index ed678fd..0000000 --- a/docs/pedantic/tests/tests_class_decorators.html +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - -pedantic.tests.tests_class_decorators API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_class_decorators

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestClassDecorators -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestClassDecorators(unittest.TestCase):
    -
    -    def test_trace_class(self):
    -        @trace_class
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                self.s = s
    -
    -            def double(self, b: int) -> str:
    -                return self.s + str(b)
    -
    -            @staticmethod
    -            def generator() -> 'MyClass':
    -                return MyClass(s='generated')
    -
    -        m = MyClass.generator()
    -        m.double(b=42)
    -
    -    def test_timer_class(self):
    -        @timer_class
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                self.s = s
    -
    -            def double(self, b: int) -> str:
    -                return self.s + str(b)
    -
    -            @staticmethod
    -            def generator() -> 'MyClass':
    -                return MyClass(s='generated')
    -
    -        m = MyClass.generator()
    -        m.double(b=42)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_timer_class(self) -
    -
    -
    - -Expand source code - -
    def test_timer_class(self):
    -    @timer_class
    -    class MyClass:
    -        def __init__(self, s: str) -> None:
    -            self.s = s
    -
    -        def double(self, b: int) -> str:
    -            return self.s + str(b)
    -
    -        @staticmethod
    -        def generator() -> 'MyClass':
    -            return MyClass(s='generated')
    -
    -    m = MyClass.generator()
    -    m.double(b=42)
    -
    -
    -
    -
    -def test_trace_class(self) -
    -
    -
    - -Expand source code - -
    def test_trace_class(self):
    -    @trace_class
    -    class MyClass:
    -        def __init__(self, s: str) -> None:
    -            self.s = s
    -
    -        def double(self, b: int) -> str:
    -            return self.s + str(b)
    -
    -        @staticmethod
    -        def generator() -> 'MyClass':
    -            return MyClass(s='generated')
    -
    -    m = MyClass.generator()
    -    m.double(b=42)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_combination_of_decorators.html b/docs/pedantic/tests/tests_combination_of_decorators.html deleted file mode 100644 index cd9fd39..0000000 --- a/docs/pedantic/tests/tests_combination_of_decorators.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - -pedantic.tests.tests_combination_of_decorators API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_combination_of_decorators

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestCombinationOfDecorators -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestCombinationOfDecorators(unittest.TestCase):
    -    def test_pedantic_overrides(self):
    -        class MyClass(ABC):
    -            @pedantic
    -            @abstractmethod
    -            def op(self, a: int) -> None:
    -                pass
    -
    -        class Child(MyClass):
    -            a = 0
    -
    -            @pedantic
    -            @overrides(MyClass)
    -            def op(self, a: int) -> None:
    -                self.a = a
    -
    -        c = Child()
    -        c.op(a=42)
    -
    -    def test_pedantic_below_validate(self):
    -        @validate(
    -            Parameter(name='x', validators=[Min(0)]),
    -            return_as=ReturnAs.KWARGS_WITH_NONE,
    -        )
    -        @pedantic
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -        some_calculation(x=42)
    -        some_calculation(42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(x=-1)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(x=-42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_calculation(x=1.0)
    -
    -    def test_pedantic_above_validate(self):
    -        @pedantic
    -        @validate(
    -            Parameter(name='x', validators=[Min(0)]),
    -        )
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -        some_calculation(x=42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(x=-1)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(x=-42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_calculation(x=1.0)
    -        with self.assertRaises(expected_exception=PedanticException):
    -            some_calculation(42)
    -
    -    def test_pedantic_above_validate_on_instance_method(self):
    -        class MyClass:
    -            @pedantic
    -            @validate(
    -                Parameter(name='x', validators=[Min(0)]),
    -            )
    -            def some_calculation(self, x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-1)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_calculation(x=1.0)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.some_calculation(42)
    -
    -    def test_pedantic_below_validate_on_instance_method(self):
    -        class MyClass:
    -            @validate(
    -                Parameter(name='x', validators=[Min(0)]),
    -            )
    -            @pedantic
    -            def some_calculation(self, x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        m.some_calculation(42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-1)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_calculation(x=1.0)
    -
    -    def test_pedantic_class_with_validate_instance_method(self):
    -        @pedantic_class
    -        class MyClass:
    -            @validate(
    -                Parameter(name='x', validators=[Min(0)]),
    -            )
    -            def some_calculation(self, x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-1)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(x=-42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_calculation(x=1.0)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.some_calculation(42)
    -
    -    def test_pedantic_class_static_method_1(self):
    -        @pedantic_class
    -        class MyClass:
    -            @staticmethod
    -            def some_calculation(x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        MyClass.some_calculation(x=45)
    -
    -    def test_pedantic_class_static_method_2(self):
    -        """Never do this, but it works"""
    -        @for_all_methods(staticmethod)
    -        @pedantic_class
    -        class MyClass:
    -            def some_calculation(x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_calculation(x=42.0)
    -        MyClass.some_calculation(x=45)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.some_calculation(x=45.0)
    -
    -    def test_pedantic_static_method_1(self):
    -        class MyClass:
    -            @staticmethod
    -            @pedantic
    -            def some_calculation(x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(x=42)
    -        MyClass.some_calculation(x=45)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_pedantic_above_validate(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_above_validate(self):
    -    @pedantic
    -    @validate(
    -        Parameter(name='x', validators=[Min(0)]),
    -    )
    -    def some_calculation(x: int) -> int:
    -        return x
    -
    -    some_calculation(x=42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(x=-1)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(x=-42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_calculation(x=1.0)
    -    with self.assertRaises(expected_exception=PedanticException):
    -        some_calculation(42)
    -
    -
    -
    -
    -def test_pedantic_above_validate_on_instance_method(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_above_validate_on_instance_method(self):
    -    class MyClass:
    -        @pedantic
    -        @validate(
    -            Parameter(name='x', validators=[Min(0)]),
    -        )
    -        def some_calculation(self, x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-1)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_calculation(x=1.0)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.some_calculation(42)
    -
    -
    -
    -
    -def test_pedantic_below_validate(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_below_validate(self):
    -    @validate(
    -        Parameter(name='x', validators=[Min(0)]),
    -        return_as=ReturnAs.KWARGS_WITH_NONE,
    -    )
    -    @pedantic
    -    def some_calculation(x: int) -> int:
    -        return x
    -
    -    some_calculation(x=42)
    -    some_calculation(42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(x=-1)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(x=-42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_calculation(x=1.0)
    -
    -
    -
    -
    -def test_pedantic_below_validate_on_instance_method(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_below_validate_on_instance_method(self):
    -    class MyClass:
    -        @validate(
    -            Parameter(name='x', validators=[Min(0)]),
    -        )
    -        @pedantic
    -        def some_calculation(self, x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    m.some_calculation(42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-1)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_calculation(x=1.0)
    -
    -
    -
    -
    -def test_pedantic_class_static_method_1(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_class_static_method_1(self):
    -    @pedantic_class
    -    class MyClass:
    -        @staticmethod
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    MyClass.some_calculation(x=45)
    -
    -
    -
    -
    -def test_pedantic_class_static_method_2(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_class_static_method_2(self):
    -    """Never do this, but it works"""
    -    @for_all_methods(staticmethod)
    -    @pedantic_class
    -    class MyClass:
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_calculation(x=42.0)
    -    MyClass.some_calculation(x=45)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.some_calculation(x=45.0)
    -
    -

    Never do this, but it works

    -
    -
    -def test_pedantic_class_with_validate_instance_method(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_class_with_validate_instance_method(self):
    -    @pedantic_class
    -    class MyClass:
    -        @validate(
    -            Parameter(name='x', validators=[Min(0)]),
    -        )
    -        def some_calculation(self, x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-1)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(x=-42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_calculation(x=1.0)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.some_calculation(42)
    -
    -
    -
    -
    -def test_pedantic_overrides(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_overrides(self):
    -    class MyClass(ABC):
    -        @pedantic
    -        @abstractmethod
    -        def op(self, a: int) -> None:
    -            pass
    -
    -    class Child(MyClass):
    -        a = 0
    -
    -        @pedantic
    -        @overrides(MyClass)
    -        def op(self, a: int) -> None:
    -            self.a = a
    -
    -    c = Child()
    -    c.op(a=42)
    -
    -
    -
    -
    -def test_pedantic_static_method_1(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_static_method_1(self):
    -    class MyClass:
    -        @staticmethod
    -        @pedantic
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(x=42)
    -    MyClass.some_calculation(x=45)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_decorated_function.html b/docs/pedantic/tests/tests_decorated_function.html deleted file mode 100644 index a1c6829..0000000 --- a/docs/pedantic/tests/tests_decorated_function.html +++ /dev/null @@ -1,460 +0,0 @@ - - - - - - -pedantic.tests.tests_decorated_function API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_decorated_function

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestDecoratedFunction -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestDecoratedFunction(unittest.TestCase):
    -    def test_static_method(self):
    -        def f_1(): pass
    -
    -        deco_f = DecoratedFunction(f_1)
    -        self.assertFalse(deco_f.is_static_method)
    -
    -        class MyClass:
    -            def f_1(self): pass
    -
    -            @staticmethod
    -            def f_2(): pass
    -
    -            @classmethod
    -            def f_3(cls): pass
    -
    -        deco_f_1 = DecoratedFunction(MyClass.f_1)
    -        deco_f_2 = DecoratedFunction(MyClass.f_2)
    -        deco_f_3 = DecoratedFunction(MyClass.f_3)
    -
    -        self.assertFalse(deco_f_1.is_static_method)
    -        self.assertTrue(deco_f_2.is_static_method)
    -        self.assertFalse(deco_f_3.is_static_method)
    -
    -    def test_function_wants_args(self):
    -        def f_1(*args, **kwargs): pass
    -
    -        def f_2(a, b, *args, **kwargs): pass
    -
    -        def f_3(a, b, *args): pass
    -
    -        def f_4(*args): pass
    -
    -        def f_5(): pass
    -
    -        self.assertTrue(DecoratedFunction(f_1).wants_args)
    -        self.assertTrue(DecoratedFunction(f_2).wants_args)
    -        self.assertTrue(DecoratedFunction(f_3).wants_args)
    -        self.assertTrue(DecoratedFunction(f_4).wants_args)
    -        self.assertFalse(DecoratedFunction(f_5).wants_args)
    -
    -        class MyClass:
    -            def f(self): pass
    -
    -            @staticmethod
    -            def g(): pass
    -
    -        self.assertFalse(DecoratedFunction(MyClass.f).wants_args)
    -        self.assertFalse(DecoratedFunction(MyClass.g).wants_args)
    -
    -    def test_is_property_setter(self):
    -        def f_1(): pass
    -
    -        self.assertFalse(DecoratedFunction(f_1).is_property_setter)
    -
    -        class MyClass:
    -            _h = 42
    -
    -            def f_1(self): pass
    -
    -            @staticmethod
    -            def f_2(): pass
    -
    -        self.assertFalse(DecoratedFunction(MyClass.f_1).is_property_setter)
    -        self.assertFalse(DecoratedFunction(MyClass.f_2).is_property_setter)
    -
    -    def test_wants_kwargs(self):
    -        def f_1(*args, **kwargs): pass
    -
    -        def f_2(a, b, *args, **kwargs): pass
    -
    -        def f_3(a, b, *args): pass
    -
    -        def f_4(*args): pass
    -
    -        def f_5(): pass
    -
    -        def f_6(a, b, c): pass
    -
    -        self.assertFalse(DecoratedFunction(f_1).should_have_kwargs)
    -        self.assertFalse(DecoratedFunction(f_2).should_have_kwargs)
    -        self.assertFalse(DecoratedFunction(f_3).should_have_kwargs)
    -        self.assertFalse(DecoratedFunction(f_4).should_have_kwargs)
    -        self.assertTrue(DecoratedFunction(f_5).should_have_kwargs)
    -        self.assertTrue(DecoratedFunction(f_6).should_have_kwargs)
    -
    -        class A:
    -            def f(self): pass
    -
    -            @staticmethod
    -            def g(): pass
    -
    -            def __compare__(self, other): pass
    -
    -        self.assertTrue(DecoratedFunction(A.f).should_have_kwargs)
    -        self.assertTrue(DecoratedFunction(A.g).should_have_kwargs)
    -        self.assertFalse(DecoratedFunction(A.__compare__).should_have_kwargs)
    -
    -    def test_instance_method(self):
    -        def h(): pass
    -
    -        self.assertFalse(DecoratedFunction(h).is_instance_method)
    -
    -        class A:
    -            def f(self): pass
    -
    -            @staticmethod
    -            def g(): pass
    -
    -        self.assertTrue(DecoratedFunction(A.f).is_instance_method)
    -        self.assertFalse(DecoratedFunction(A.g).is_instance_method)
    -
    -    def test_num_decorators(self):
    -        def decorator(f):
    -            return f
    -
    -        def f_1(): pass
    -
    -        @decorator
    -        def f_2(): pass
    -
    -        @decorator
    -        @decorator
    -        def f_3(): pass
    -
    -        @decorator
    -        @decorator
    -        @decorator
    -        def f_4():
    -            pass
    -
    -        self.assertEqual(DecoratedFunction(f_1).num_of_decorators, 0)
    -        self.assertEqual(DecoratedFunction(f_2).num_of_decorators, 1)
    -        self.assertEqual(DecoratedFunction(f_3).num_of_decorators, 2)
    -        self.assertEqual(DecoratedFunction(f_4).num_of_decorators, 3)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_function_wants_args(self) -
    -
    -
    - -Expand source code - -
    def test_function_wants_args(self):
    -    def f_1(*args, **kwargs): pass
    -
    -    def f_2(a, b, *args, **kwargs): pass
    -
    -    def f_3(a, b, *args): pass
    -
    -    def f_4(*args): pass
    -
    -    def f_5(): pass
    -
    -    self.assertTrue(DecoratedFunction(f_1).wants_args)
    -    self.assertTrue(DecoratedFunction(f_2).wants_args)
    -    self.assertTrue(DecoratedFunction(f_3).wants_args)
    -    self.assertTrue(DecoratedFunction(f_4).wants_args)
    -    self.assertFalse(DecoratedFunction(f_5).wants_args)
    -
    -    class MyClass:
    -        def f(self): pass
    -
    -        @staticmethod
    -        def g(): pass
    -
    -    self.assertFalse(DecoratedFunction(MyClass.f).wants_args)
    -    self.assertFalse(DecoratedFunction(MyClass.g).wants_args)
    -
    -
    -
    -
    -def test_instance_method(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method(self):
    -    def h(): pass
    -
    -    self.assertFalse(DecoratedFunction(h).is_instance_method)
    -
    -    class A:
    -        def f(self): pass
    -
    -        @staticmethod
    -        def g(): pass
    -
    -    self.assertTrue(DecoratedFunction(A.f).is_instance_method)
    -    self.assertFalse(DecoratedFunction(A.g).is_instance_method)
    -
    -
    -
    -
    -def test_is_property_setter(self) -
    -
    -
    - -Expand source code - -
    def test_is_property_setter(self):
    -    def f_1(): pass
    -
    -    self.assertFalse(DecoratedFunction(f_1).is_property_setter)
    -
    -    class MyClass:
    -        _h = 42
    -
    -        def f_1(self): pass
    -
    -        @staticmethod
    -        def f_2(): pass
    -
    -    self.assertFalse(DecoratedFunction(MyClass.f_1).is_property_setter)
    -    self.assertFalse(DecoratedFunction(MyClass.f_2).is_property_setter)
    -
    -
    -
    -
    -def test_num_decorators(self) -
    -
    -
    - -Expand source code - -
    def test_num_decorators(self):
    -    def decorator(f):
    -        return f
    -
    -    def f_1(): pass
    -
    -    @decorator
    -    def f_2(): pass
    -
    -    @decorator
    -    @decorator
    -    def f_3(): pass
    -
    -    @decorator
    -    @decorator
    -    @decorator
    -    def f_4():
    -        pass
    -
    -    self.assertEqual(DecoratedFunction(f_1).num_of_decorators, 0)
    -    self.assertEqual(DecoratedFunction(f_2).num_of_decorators, 1)
    -    self.assertEqual(DecoratedFunction(f_3).num_of_decorators, 2)
    -    self.assertEqual(DecoratedFunction(f_4).num_of_decorators, 3)
    -
    -
    -
    -
    -def test_static_method(self) -
    -
    -
    - -Expand source code - -
    def test_static_method(self):
    -    def f_1(): pass
    -
    -    deco_f = DecoratedFunction(f_1)
    -    self.assertFalse(deco_f.is_static_method)
    -
    -    class MyClass:
    -        def f_1(self): pass
    -
    -        @staticmethod
    -        def f_2(): pass
    -
    -        @classmethod
    -        def f_3(cls): pass
    -
    -    deco_f_1 = DecoratedFunction(MyClass.f_1)
    -    deco_f_2 = DecoratedFunction(MyClass.f_2)
    -    deco_f_3 = DecoratedFunction(MyClass.f_3)
    -
    -    self.assertFalse(deco_f_1.is_static_method)
    -    self.assertTrue(deco_f_2.is_static_method)
    -    self.assertFalse(deco_f_3.is_static_method)
    -
    -
    -
    -
    -def test_wants_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_wants_kwargs(self):
    -    def f_1(*args, **kwargs): pass
    -
    -    def f_2(a, b, *args, **kwargs): pass
    -
    -    def f_3(a, b, *args): pass
    -
    -    def f_4(*args): pass
    -
    -    def f_5(): pass
    -
    -    def f_6(a, b, c): pass
    -
    -    self.assertFalse(DecoratedFunction(f_1).should_have_kwargs)
    -    self.assertFalse(DecoratedFunction(f_2).should_have_kwargs)
    -    self.assertFalse(DecoratedFunction(f_3).should_have_kwargs)
    -    self.assertFalse(DecoratedFunction(f_4).should_have_kwargs)
    -    self.assertTrue(DecoratedFunction(f_5).should_have_kwargs)
    -    self.assertTrue(DecoratedFunction(f_6).should_have_kwargs)
    -
    -    class A:
    -        def f(self): pass
    -
    -        @staticmethod
    -        def g(): pass
    -
    -        def __compare__(self, other): pass
    -
    -    self.assertTrue(DecoratedFunction(A.f).should_have_kwargs)
    -    self.assertTrue(DecoratedFunction(A.g).should_have_kwargs)
    -    self.assertFalse(DecoratedFunction(A.__compare__).should_have_kwargs)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_docstring.html b/docs/pedantic/tests/tests_docstring.html deleted file mode 100644 index feb88df..0000000 --- a/docs/pedantic/tests/tests_docstring.html +++ /dev/null @@ -1,1410 +0,0 @@ - - - - - - -pedantic.tests.tests_docstring API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_docstring

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestRequireDocstringGoogleFormat -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestRequireDocstringGoogleFormat(TestCase):
    -
    -    def test_no_docstring(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(n: int, m: int, i: int) -> int:
    -                return n + m + i
    -
    -    def test_one_line_doc_string_missing_arguments_and_return(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(n: int, m: int, i: int) -> int:
    -                """Returns the sum of the three args."""
    -                return n + m + i
    -
    -    def test_one_line_doc_string_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(n: int, m: int, i: int) -> int:
    -            """Returns the sum of the three args.
    -
    -            Args:
    -                n (int): something
    -                m (int): something
    -                i (int): something
    -
    -            Returns:
    -                int: bar
    -            """
    -            return n + m + i
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_list_vs_typing_list(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -
    -                Returns:
    -                    list: a list of strings representing the header columns
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_google_docstring_2(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -
    -            return [file_loc, str(print_cols)]
    -
    -        calc(file_loc='Hi', print_cols=False)
    -
    -    def test_google_docstring_3(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -
    -            return [file_loc, str(print_cols)]
    -
    -        calc(file_loc='Hi', print_cols=False)
    -
    -    def test_more_parameter_documented_than_the_function_takes(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -                    amount (int): THIS ARGUMENT IS NOT TAKEN BY THE FUNCTION
    -
    -                Returns:
    -                    List[str]: a list of strings representing the header columns
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_google_docstring_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool, amount: int) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -                amount (int): now it is
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -
    -            return [file_loc, str(print_cols), str(amount)]
    -
    -        calc(file_loc='Hi', print_cols=False, amount=42)
    -
    -    def test_no_args_keyword_before_documented_arguments(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> list:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -                Returns:
    -                    list: a list of strings representing the header columns
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_google_no_return_keyword(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> list:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -
    -                list: a list of strings representing the header columns
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_keep_it_simple(self):
    -        @pedantic_require_docstring
    -        def calc() -> None:
    -            """Gets and prints the spreadsheet's header columns"""
    -            pass
    -
    -        calc()
    -
    -    def test_docstring_misses_argument(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(name: str) -> None:
    -                """Gets and prints the spreadsheet's header columns"""
    -                print('hi ' + name)
    -
    -    def test_keep_it_simple_2_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(name: str) -> None:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                name (str): the name
    -            """
    -            print('hi ' + name)
    -
    -        calc(name='maria')
    -
    -    def test_undocumented_arg(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool, number: int) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -
    -                Returns:
    -                    List[str]: a list of strings representing the header columns
    -                """
    -                return [file_loc, str(print_cols), str(number)]
    -
    -    def test_undocumented_arg_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool, number: int) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -                number (int): magic number
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -
    -            return [file_loc, str(print_cols), str(number)]
    -
    -        calc(file_loc='Hi', print_cols=False, number=42)
    -
    -    def test_restructured_text_style_doctsring_cannot_be_parsed_yet(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                :param file_loc: The file location of the spreadsheet
    -                :type file_loc: str
    -                :param print_cols: A flag used to print the columns to the console
    -                :type print_cols: bool
    -                :returns: a list of strings representing the header column
    -                :rtype: List[str]
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_return_nothing_but_document_return_value(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool):
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -
    -                Returns:
    -                    list: a list of strings representing the header columns
    -                """
    -                print([file_loc, str(print_cols)])
    -
    -    def test_return_nothing_but_document_return_value_2(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> None:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -
    -                Returns:
    -                    list: a list of strings representing the header columns
    -                """
    -                print([file_loc, str(print_cols)])
    -
    -    def test_return_value_1_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> None:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -            """
    -
    -            a = [file_loc, str(print_cols)]
    -        calc(file_loc='Hi', print_cols=False)
    -
    -    def test_return_value_is_not_documented(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            # the error message here is actually wrong due to the behavior of the docstring-parser package
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console (default is False)
    -
    -                Returns:
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_return_value_2_corrected(self):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                List[str]: results
    -            """
    -
    -            return [file_loc, str(print_cols)]
    -
    -        calc(file_loc='Hi', print_cols=False)
    -
    -    def test_return_value_is_not_documented_3(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc(file_loc: str, print_cols: bool) -> List[str]:
    -                """Gets and prints the spreadsheet's header columns
    -
    -                Args:
    -                    file_loc (str): The file location of the spreadsheet
    -                    print_cols (bool): A flag used to print the columns to the console
    -                        (default is False)
    -                """
    -                return [file_loc, str(print_cols)]
    -
    -    def test_wrong_format_1(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            class MyText:
    -                text = 'hi'
    -
    -                @pedantic_require_docstring
    -                def __contains__(self, substring: str) -> bool:
    -                    """
    -                    Checks if contains substring.
    -                    Overriding __contains__ build in functions allows to use the 'in' operator blah readability
    -
    -                    Example:
    -                    my_text = MyText('abc')
    -                    if 'ab' in my_text -> true
    -                    :param: substring: substring
    -                    :return: True if substring is stored, False otherwise.
    -                    """
    -                    return substring in self.text
    -
    -    def test_undocumented_arg_3(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic
    -            def calc(a: int, b: float, c: str) -> str:
    -                """Returns some cool string
    -
    -                Args:
    -                    a (int): something
    -                    b (float): something
    -
    -                Returns:
    -                    str: something
    -                """
    -                return str(a) + str(b) + c
    -
    -            calc(a=42, b=3.14, c='hi')
    -
    -    def test_pedantic_1_corrected(self):
    -        @pedantic
    -        def calc(a: int, b: float, c: str) -> str:
    -            """Returns some cool string
    -
    -            Args:
    -                a (int): something
    -                b (float): something
    -                c (str): something
    -
    -            Returns:
    -                str: something
    -            """
    -            return str(a) + str(b) + c
    -
    -        calc(a=42, b=3.14, c='hi')
    -
    -    def test_documented_none_as_return_type(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def calc() -> None:
    -                """some cool stuff
    -
    -                Returns:
    -                    None: the evil void
    -                """
    -                pass
    -
    -    def test_exception_in_docstring_parser(self):
    -        @pedantic_class
    -        class Foo:
    -            def func(self, b: str) -> str:
    -                """
    -                Function with docstring syntax error below.
    -                Args:
    -                    b (str):
    -                    simple string
    -                Returns:
    -                    str: simple string
    -                """
    -                return b
    -
    -    def test_user_class(self):
    -        class BPMNEnum:
    -            attr = 'BPMNEnum'
    -
    -        class BPMNElement:
    -            attr = 'BPMNElement'
    -
    -        @pedantic_class_require_docstring
    -        class MyClass:
    -            def make_element(self, element_type: BPMNEnum,
    -                             src_tgt_elements: Optional[List[BPMNElement]] = None) -> List[BPMNElement]:
    -                """
    -                Searches all element_types in XML-DOM and returns corresponding
    -                BPMN-Objects.
    -                Args:
    -                    element_type(BPMNEnum): abc
    -                    src_tgt_elements (Optional[List[BPMNElement]]): abc
    -
    -                Returns:
    -                    List[BPMNElement]: abc
    -                """
    -                element_type.attr = '42'
    -                return src_tgt_elements
    -
    -        m = MyClass()
    -        m.make_element(element_type=BPMNEnum(), src_tgt_elements=[BPMNElement()])
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.make_element(element_type=BPMNElement(), src_tgt_elements=[BPMNEnum()])
    -
    -    def test_user_class_with_typing(self):
    -        class BPMNEnum:
    -            attr = 'BPMNEnum'
    -
    -        class BPMNElement:
    -            attr = 'BPMNElement'
    -
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_class_require_docstring
    -            class MyClass:
    -
    -                def make_element(self, element_type: BPMNEnum,
    -                                 src_tgt_elements: Optional[List[BPMNElement]] = None) -> List[BPMNElement]:
    -                    """
    -                    Searches all element_types in XML-DOM and returns corresponding
    -                    BPMN-Objects.
    -                    Args:
    -                        element_type(BPMNEnum): abc
    -                        src_tgt_elements (typing.Optional[List[BPMNElement]]): abc
    -
    -                    Returns:
    -                        List[BPMNElement]: abc
    -                    """
    -                    element_type.attr = '42'
    -                    return src_tgt_elements
    -
    -    def test_factory(self):
    -        @pedantic_require_docstring
    -        def get_instance() -> TestCase:
    -            """
    -            Returns:
    -                TestCase: A new TestCase
    -            """
    -            return TestCase()
    -
    -        get_instance()
    -
    -    def test_pedantic_args(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic(require_docstring=True)
    -            def no_docstrings() -> None:
    -                print('.')
    -
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_require_docstring
    -            def no_docstrings() -> None:
    -                print('.')
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_docstring_misses_argument(self) -
    -
    -
    - -Expand source code - -
    def test_docstring_misses_argument(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(name: str) -> None:
    -            """Gets and prints the spreadsheet's header columns"""
    -            print('hi ' + name)
    -
    -
    -
    -
    -def test_documented_none_as_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_documented_none_as_return_type(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc() -> None:
    -            """some cool stuff
    -
    -            Returns:
    -                None: the evil void
    -            """
    -            pass
    -
    -
    -
    -
    -def test_exception_in_docstring_parser(self) -
    -
    -
    - -Expand source code - -
    def test_exception_in_docstring_parser(self):
    -    @pedantic_class
    -    class Foo:
    -        def func(self, b: str) -> str:
    -            """
    -            Function with docstring syntax error below.
    -            Args:
    -                b (str):
    -                simple string
    -            Returns:
    -                str: simple string
    -            """
    -            return b
    -
    -
    -
    -
    -def test_factory(self) -
    -
    -
    - -Expand source code - -
    def test_factory(self):
    -    @pedantic_require_docstring
    -    def get_instance() -> TestCase:
    -        """
    -        Returns:
    -            TestCase: A new TestCase
    -        """
    -        return TestCase()
    -
    -    get_instance()
    -
    -
    -
    -
    -def test_google_docstring_2(self) -
    -
    -
    - -Expand source code - -
    def test_google_docstring_2(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool) -> List[str]:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -
    -        Returns:
    -            List[str]: a list of strings representing the header columns
    -        """
    -
    -        return [file_loc, str(print_cols)]
    -
    -    calc(file_loc='Hi', print_cols=False)
    -
    -
    -
    -
    -def test_google_docstring_3(self) -
    -
    -
    - -Expand source code - -
    def test_google_docstring_3(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool) -> List[str]:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -
    -        Returns:
    -            List[str]: a list of strings representing the header columns
    -        """
    -
    -        return [file_loc, str(print_cols)]
    -
    -    calc(file_loc='Hi', print_cols=False)
    -
    -
    -
    -
    -def test_google_docstring_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_google_docstring_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool, amount: int) -> List[str]:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -            amount (int): now it is
    -
    -        Returns:
    -            List[str]: a list of strings representing the header columns
    -        """
    -
    -        return [file_loc, str(print_cols), str(amount)]
    -
    -    calc(file_loc='Hi', print_cols=False, amount=42)
    -
    -
    -
    -
    -def test_google_no_return_keyword(self) -
    -
    -
    - -Expand source code - -
    def test_google_no_return_keyword(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> list:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            list: a list of strings representing the header columns
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_keep_it_simple(self) -
    -
    -
    - -Expand source code - -
    def test_keep_it_simple(self):
    -    @pedantic_require_docstring
    -    def calc() -> None:
    -        """Gets and prints the spreadsheet's header columns"""
    -        pass
    -
    -    calc()
    -
    -
    -
    -
    -def test_keep_it_simple_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_keep_it_simple_2_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(name: str) -> None:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            name (str): the name
    -        """
    -        print('hi ' + name)
    -
    -    calc(name='maria')
    -
    -
    -
    -
    -def test_list_vs_typing_list(self) -
    -
    -
    - -Expand source code - -
    def test_list_vs_typing_list(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                list: a list of strings representing the header columns
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_more_parameter_documented_than_the_function_takes(self) -
    -
    -
    - -Expand source code - -
    def test_more_parameter_documented_than_the_function_takes(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -                amount (int): THIS ARGUMENT IS NOT TAKEN BY THE FUNCTION
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_no_args_keyword_before_documented_arguments(self) -
    -
    -
    - -Expand source code - -
    def test_no_args_keyword_before_documented_arguments(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> list:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -
    -            Returns:
    -                list: a list of strings representing the header columns
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_no_docstring(self) -
    -
    -
    - -Expand source code - -
    def test_no_docstring(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -
    -
    -
    -def test_one_line_doc_string_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_one_line_doc_string_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(n: int, m: int, i: int) -> int:
    -        """Returns the sum of the three args.
    -
    -        Args:
    -            n (int): something
    -            m (int): something
    -            i (int): something
    -
    -        Returns:
    -            int: bar
    -        """
    -        return n + m + i
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_one_line_doc_string_missing_arguments_and_return(self) -
    -
    -
    - -Expand source code - -
    def test_one_line_doc_string_missing_arguments_and_return(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(n: int, m: int, i: int) -> int:
    -            """Returns the sum of the three args."""
    -            return n + m + i
    -
    -
    -
    -
    -def test_pedantic_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_1_corrected(self):
    -    @pedantic
    -    def calc(a: int, b: float, c: str) -> str:
    -        """Returns some cool string
    -
    -        Args:
    -            a (int): something
    -            b (float): something
    -            c (str): something
    -
    -        Returns:
    -            str: something
    -        """
    -        return str(a) + str(b) + c
    -
    -    calc(a=42, b=3.14, c='hi')
    -
    -
    -
    -
    -def test_pedantic_args(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_args(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic(require_docstring=True)
    -        def no_docstrings() -> None:
    -            print('.')
    -
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def no_docstrings() -> None:
    -            print('.')
    -
    -
    -
    -
    -def test_restructured_text_style_doctsring_cannot_be_parsed_yet(self) -
    -
    -
    - -Expand source code - -
    def test_restructured_text_style_doctsring_cannot_be_parsed_yet(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            :param file_loc: The file location of the spreadsheet
    -            :type file_loc: str
    -            :param print_cols: A flag used to print the columns to the console
    -            :type print_cols: bool
    -            :returns: a list of strings representing the header column
    -            :rtype: List[str]
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_return_nothing_but_document_return_value(self) -
    -
    -
    - -Expand source code - -
    def test_return_nothing_but_document_return_value(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool):
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                list: a list of strings representing the header columns
    -            """
    -            print([file_loc, str(print_cols)])
    -
    -
    -
    -
    -def test_return_nothing_but_document_return_value_2(self) -
    -
    -
    - -Expand source code - -
    def test_return_nothing_but_document_return_value_2(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> None:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                list: a list of strings representing the header columns
    -            """
    -            print([file_loc, str(print_cols)])
    -
    -
    -
    -
    -def test_return_value_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_return_value_1_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool) -> None:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -        """
    -
    -        a = [file_loc, str(print_cols)]
    -    calc(file_loc='Hi', print_cols=False)
    -
    -
    -
    -
    -def test_return_value_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_return_value_2_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool) -> List[str]:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -
    -        Returns:
    -            List[str]: results
    -        """
    -
    -        return [file_loc, str(print_cols)]
    -
    -    calc(file_loc='Hi', print_cols=False)
    -
    -
    -
    -
    -def test_return_value_is_not_documented(self) -
    -
    -
    - -Expand source code - -
    def test_return_value_is_not_documented(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        # the error message here is actually wrong due to the behavior of the docstring-parser package
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console (default is False)
    -
    -            Returns:
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_return_value_is_not_documented_3(self) -
    -
    -
    - -Expand source code - -
    def test_return_value_is_not_documented_3(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -            """
    -            return [file_loc, str(print_cols)]
    -
    -
    -
    -
    -def test_undocumented_arg(self) -
    -
    -
    - -Expand source code - -
    def test_undocumented_arg(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_require_docstring
    -        def calc(file_loc: str, print_cols: bool, number: int) -> List[str]:
    -            """Gets and prints the spreadsheet's header columns
    -
    -            Args:
    -                file_loc (str): The file location of the spreadsheet
    -                print_cols (bool): A flag used to print the columns to the console
    -                    (default is False)
    -
    -            Returns:
    -                List[str]: a list of strings representing the header columns
    -            """
    -            return [file_loc, str(print_cols), str(number)]
    -
    -
    -
    -
    -def test_undocumented_arg_3(self) -
    -
    -
    - -Expand source code - -
    def test_undocumented_arg_3(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic
    -        def calc(a: int, b: float, c: str) -> str:
    -            """Returns some cool string
    -
    -            Args:
    -                a (int): something
    -                b (float): something
    -
    -            Returns:
    -                str: something
    -            """
    -            return str(a) + str(b) + c
    -
    -        calc(a=42, b=3.14, c='hi')
    -
    -
    -
    -
    -def test_undocumented_arg_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_undocumented_arg_corrected(self):
    -    @pedantic_require_docstring
    -    def calc(file_loc: str, print_cols: bool, number: int) -> List[str]:
    -        """Gets and prints the spreadsheet's header columns
    -
    -        Args:
    -            file_loc (str): The file location of the spreadsheet
    -            print_cols (bool): A flag used to print the columns to the console
    -                (default is False)
    -            number (int): magic number
    -
    -        Returns:
    -            List[str]: a list of strings representing the header columns
    -        """
    -
    -        return [file_loc, str(print_cols), str(number)]
    -
    -    calc(file_loc='Hi', print_cols=False, number=42)
    -
    -
    -
    -
    -def test_user_class(self) -
    -
    -
    - -Expand source code - -
    def test_user_class(self):
    -    class BPMNEnum:
    -        attr = 'BPMNEnum'
    -
    -    class BPMNElement:
    -        attr = 'BPMNElement'
    -
    -    @pedantic_class_require_docstring
    -    class MyClass:
    -        def make_element(self, element_type: BPMNEnum,
    -                         src_tgt_elements: Optional[List[BPMNElement]] = None) -> List[BPMNElement]:
    -            """
    -            Searches all element_types in XML-DOM and returns corresponding
    -            BPMN-Objects.
    -            Args:
    -                element_type(BPMNEnum): abc
    -                src_tgt_elements (Optional[List[BPMNElement]]): abc
    -
    -            Returns:
    -                List[BPMNElement]: abc
    -            """
    -            element_type.attr = '42'
    -            return src_tgt_elements
    -
    -    m = MyClass()
    -    m.make_element(element_type=BPMNEnum(), src_tgt_elements=[BPMNElement()])
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.make_element(element_type=BPMNElement(), src_tgt_elements=[BPMNEnum()])
    -
    -
    -
    -
    -def test_user_class_with_typing(self) -
    -
    -
    - -Expand source code - -
    def test_user_class_with_typing(self):
    -    class BPMNEnum:
    -        attr = 'BPMNEnum'
    -
    -    class BPMNElement:
    -        attr = 'BPMNElement'
    -
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_class_require_docstring
    -        class MyClass:
    -
    -            def make_element(self, element_type: BPMNEnum,
    -                             src_tgt_elements: Optional[List[BPMNElement]] = None) -> List[BPMNElement]:
    -                """
    -                Searches all element_types in XML-DOM and returns corresponding
    -                BPMN-Objects.
    -                Args:
    -                    element_type(BPMNEnum): abc
    -                    src_tgt_elements (typing.Optional[List[BPMNElement]]): abc
    -
    -                Returns:
    -                    List[BPMNElement]: abc
    -                """
    -                element_type.attr = '42'
    -                return src_tgt_elements
    -
    -
    -
    -
    -def test_wrong_format_1(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_format_1(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        class MyText:
    -            text = 'hi'
    -
    -            @pedantic_require_docstring
    -            def __contains__(self, substring: str) -> bool:
    -                """
    -                Checks if contains substring.
    -                Overriding __contains__ build in functions allows to use the 'in' operator blah readability
    -
    -                Example:
    -                my_text = MyText('abc')
    -                if 'ab' in my_text -> true
    -                :param: substring: substring
    -                :return: True if substring is stored, False otherwise.
    -                """
    -                return substring in self.text
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_doctests.html b/docs/pedantic/tests/tests_doctests.html deleted file mode 100644 index 709e903..0000000 --- a/docs/pedantic/tests/tests_doctests.html +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - -pedantic.tests.tests_doctests API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_doctests

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def get_doctest_test_suite() ‑> unittest.suite.TestSuite -
    -
    -
    - -Expand source code - -
    def get_doctest_test_suite() -> unittest.TestSuite:
    -    parent_module = __import__('pedantic')
    -    modules = [
    -        parent_module.decorators.fn_deco_count_calls,
    -        parent_module.decorators.fn_deco_deprecated,
    -        parent_module.decorators.fn_deco_does_same_as_function,
    -        parent_module.decorators.fn_deco_in_subprocess,
    -        parent_module.decorators.fn_deco_overrides,
    -        parent_module.decorators.fn_deco_pedantic,
    -        parent_module.decorators.fn_deco_rename_kwargs,
    -        parent_module.decorators.fn_deco_timer,
    -        parent_module.decorators.fn_deco_trace,
    -        parent_module.decorators.fn_deco_trace_if_returns,
    -        parent_module.decorators.fn_deco_unimplemented,
    -        parent_module.mixins.generic_mixin,
    -        parent_module.type_checking_logic.check_types,
    -        parent_module.type_checking_logic.check_generic_classes,
    -        parent_module.type_checking_logic.check_docstring,
    -        parent_module.decorators.cls_deco_frozen_dataclass,
    -    ]
    -    test_suites = [doctest.DocTestSuite(module=module, optionflags=doctest.ELLIPSIS) for module in modules]
    -    return unittest.TestSuite(test_suites)
    -
    -
    -
    -
    -def run_doctests() ‑> None -
    -
    -
    - -Expand source code - -
    def run_doctests() -> None:
    -    unittest.TextTestRunner().run(get_doctest_test_suite())
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_environment_variables.html b/docs/pedantic/tests/tests_environment_variables.html deleted file mode 100644 index 110791b..0000000 --- a/docs/pedantic/tests/tests_environment_variables.html +++ /dev/null @@ -1,247 +0,0 @@ - - - - - - -pedantic.tests.tests_environment_variables API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_environment_variables

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestEnvironmentVariables -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestEnvironmentVariables(unittest.TestCase):
    -    def setUp(self) -> None:
    -        self.state = is_enabled()
    -        enable_pedantic()
    -
    -    def tearDown(self) -> None:
    -        enable_pedantic()
    -
    -    def test_pedantic_enabled(self):
    -        enable_pedantic()
    -
    -        @pedantic
    -        def some_method():
    -            return 42
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_method()
    -
    -    def test_pedantic_disabled(self):
    -        disable_pedantic()
    -
    -        @pedantic
    -        def some_method():
    -            return 42
    -
    -        some_method()
    -
    -    def test_enable_disable(self):
    -        enable_pedantic()
    -        self.assertTrue(is_enabled())
    -        disable_pedantic()
    -        self.assertFalse(is_enabled())
    -        enable_pedantic()
    -        self.assertTrue(is_enabled())
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def setUp(self) ‑> None -
    -
    -
    - -Expand source code - -
    def setUp(self) -> None:
    -    self.state = is_enabled()
    -    enable_pedantic()
    -
    -

    Hook method for setting up the test fixture before exercising it.

    -
    -
    -def tearDown(self) ‑> None -
    -
    -
    - -Expand source code - -
    def tearDown(self) -> None:
    -    enable_pedantic()
    -
    -

    Hook method for deconstructing the test fixture after testing it.

    -
    -
    -def test_enable_disable(self) -
    -
    -
    - -Expand source code - -
    def test_enable_disable(self):
    -    enable_pedantic()
    -    self.assertTrue(is_enabled())
    -    disable_pedantic()
    -    self.assertFalse(is_enabled())
    -    enable_pedantic()
    -    self.assertTrue(is_enabled())
    -
    -
    -
    -
    -def test_pedantic_disabled(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_disabled(self):
    -    disable_pedantic()
    -
    -    @pedantic
    -    def some_method():
    -        return 42
    -
    -    some_method()
    -
    -
    -
    -
    -def test_pedantic_enabled(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_enabled(self):
    -    enable_pedantic()
    -
    -    @pedantic
    -    def some_method():
    -        return 42
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_method()
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_generator.html b/docs/pedantic/tests/tests_generator.html deleted file mode 100644 index 211f078..0000000 --- a/docs/pedantic/tests/tests_generator.html +++ /dev/null @@ -1,410 +0,0 @@ - - - - - - -pedantic.tests.tests_generator API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_generator

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestGenerator -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestGenerator(unittest.TestCase):
    -    def test_iterator(self):
    -        @pedantic
    -        def gen_func() -> Iterator[int]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        gen = gen_func()
    -        next(gen)
    -
    -    def test_iterator_wrong_type_hint(self):
    -        @pedantic
    -        def genfunc() -> Iterator[float]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        gen = genfunc()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            next(gen)
    -
    -    def test_iterator_no_type_args(self):
    -        @pedantic
    -        def genfunc() -> Iterator:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            genfunc()
    -
    -    def test_iterator_completely_wrong_type_hint(self):
    -        @pedantic
    -        def gen_func() -> List[int]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            gen_func()
    -
    -    def test_iterable(self):
    -        @pedantic
    -        def gen_func() -> Iterable[int]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        gen = gen_func()
    -        next(gen)
    -
    -    def test_iterable_no_type_args(self):
    -        @pedantic
    -        def gen_func() -> Iterable:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            gen_func()
    -
    -    def test_generator(self):
    -        @pedantic
    -        def gen_func() -> Generator[int, None, str]:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -            return 'Done'
    -
    -        gen = gen_func()
    -        next(gen)
    -
    -    def test_invalid_no_type_args_generator(self):
    -        @pedantic
    -        def gen_func() -> Generator:
    -            num = 0
    -
    -            while num < 100:
    -                yield num
    -                num += 1
    -            return 'Done'
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            gen_func()
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_generator(self) -
    -
    -
    - -Expand source code - -
    def test_generator(self):
    -    @pedantic
    -    def gen_func() -> Generator[int, None, str]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -        return 'Done'
    -
    -    gen = gen_func()
    -    next(gen)
    -
    -
    -
    -
    -def test_invalid_no_type_args_generator(self) -
    -
    -
    - -Expand source code - -
    def test_invalid_no_type_args_generator(self):
    -    @pedantic
    -    def gen_func() -> Generator:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -        return 'Done'
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        gen_func()
    -
    -
    -
    -
    -def test_iterable(self) -
    -
    -
    - -Expand source code - -
    def test_iterable(self):
    -    @pedantic
    -    def gen_func() -> Iterable[int]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    gen = gen_func()
    -    next(gen)
    -
    -
    -
    -
    -def test_iterable_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_iterable_no_type_args(self):
    -    @pedantic
    -    def gen_func() -> Iterable:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        gen_func()
    -
    -
    -
    -
    -def test_iterator(self) -
    -
    -
    - -Expand source code - -
    def test_iterator(self):
    -    @pedantic
    -    def gen_func() -> Iterator[int]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    gen = gen_func()
    -    next(gen)
    -
    -
    -
    -
    -def test_iterator_completely_wrong_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_iterator_completely_wrong_type_hint(self):
    -    @pedantic
    -    def gen_func() -> List[int]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        gen_func()
    -
    -
    -
    -
    -def test_iterator_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_iterator_no_type_args(self):
    -    @pedantic
    -    def genfunc() -> Iterator:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        genfunc()
    -
    -
    -
    -
    -def test_iterator_wrong_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_iterator_wrong_type_hint(self):
    -    @pedantic
    -    def genfunc() -> Iterator[float]:
    -        num = 0
    -
    -        while num < 100:
    -            yield num
    -            num += 1
    -
    -    gen = genfunc()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        next(gen)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_generic_classes.html b/docs/pedantic/tests/tests_generic_classes.html deleted file mode 100644 index 4f4789a..0000000 --- a/docs/pedantic/tests/tests_generic_classes.html +++ /dev/null @@ -1,841 +0,0 @@ - - - - - - -pedantic.tests.tests_generic_classes API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_generic_classes

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestGenericClasses -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestGenericClasses(unittest.TestCase):
    -    def test_pedantic_generic_class(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class LoggedVar(Generic[T]):
    -            def __init__(self, value: T, name: str, logger: Any) -> None:
    -                self.name = name
    -                self.logger = logger
    -                self.value = value
    -
    -            def set(self, new: T) -> None:
    -                self.log(message='Set ' + repr(self.value))
    -                self.value = new
    -
    -            def get(self) -> T:
    -                self.log(message='Get ' + repr(self.value))
    -                return self.value
    -
    -            def log(self, message: str) -> None:
    -                self.logger = self.name + message
    -
    -        o = LoggedVar[int](value=42, name='hi', logger='test')
    -        o.set(new=57)
    -        self.assertTrue(isinstance(o.get(), int))
    -
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            o.set(new=3.14)
    -
    -    def test_stack(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class Stack(Generic[T]):
    -            def __init__(self) -> None:
    -                self.items: List[T] = []
    -
    -            def push(self, item: T) -> None:
    -                self.items.append(item)
    -
    -            def pop(self) -> T:
    -                return self.items.pop()
    -
    -            def empty(self) -> bool:
    -                return not self.items
    -
    -            def top(self) -> Optional[T]:
    -                if len(self.items) > 0:
    -                    return self.items[len(self.items) - 1]
    -                else:
    -                    return None
    -
    -        my_stack = Stack[str]()
    -        get_type_vars = getattr(my_stack, TYPE_VAR_METHOD_NAME)
    -        self.assertEqual(get_type_vars(), {T: str, TYPE_VAR_SELF: Stack})
    -        with self.assertRaises(expected_exception=IndexError):
    -            my_stack.pop()
    -        self.assertIsNone(my_stack.top())
    -        self.assertIsNone(my_stack.top())
    -        # self.assertFalse(T in get_type_vars())
    -        my_stack.push(item='hi')
    -        self.assertTrue(T in get_type_vars())
    -        my_stack.push(item='world')
    -        self.assertTrue(T in get_type_vars())
    -        self.assertTrue(len(get_type_vars()), 1)
    -        self.assertEqual(my_stack.pop(), 'world')
    -        self.assertEqual(my_stack.pop(), 'hi')
    -        self.assertIsNone(my_stack.top())
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            my_stack.push(item=42)
    -
    -        my_other_stack = Stack[int]()
    -        get_type_vars = getattr(my_other_stack, TYPE_VAR_METHOD_NAME)
    -        self.assertEqual(get_type_vars(), {T: int, TYPE_VAR_SELF: Stack})
    -        with self.assertRaises(expected_exception=IndexError):
    -            my_other_stack.pop()
    -        self.assertIsNone(my_other_stack.top())
    -        self.assertIsNone(my_other_stack.top())
    -        my_other_stack.push(item=100)
    -        self.assertTrue(len(get_type_vars()), 1)
    -        my_other_stack.push(item=142)
    -        self.assertTrue(len(get_type_vars()), 1)
    -        self.assertEqual(my_other_stack.pop(), 142)
    -        self.assertEqual(my_other_stack.pop(), 100)
    -        self.assertIsNone(my_other_stack.top())
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            my_other_stack.push(item='42')
    -
    -    def test_generic_class_initialised_without_generics(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class MyClass(Generic[T]):
    -            def __init__(self, a: T) -> None:
    -                self.a = a
    -
    -            def get_a(self) -> T:
    -                return self.a
    -
    -            def set_a(self, val: T) -> None:
    -                self.a = val
    -
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            m = MyClass(a=42)
    -
    -    def test_generic_class_initialised_without_generics_2(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class MyClass(Generic[T]):
    -            def __init__(self, a: T) -> None:
    -                self.a = a
    -
    -            def get_a(self) -> T:
    -                return self.a
    -
    -            def set_a(self, val: T) -> None:
    -                self.a = val
    -
    -        MyClass(a=42)  # it is not recognized if it isn't assigned
    -
    -    def test_generic_class_inheritance(self):
    -        class Parent:
    -            pass
    -
    -        class Child1(Parent):
    -            pass
    -
    -        class Child2(Parent):
    -            pass
    -
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class MyClass(Generic[T]):
    -            def __init__(self, a: T) -> None:
    -                self.a = a
    -
    -            def get_a(self) -> T:
    -                return self.a
    -
    -            def set_a(self, val: T) -> None:
    -                self.a = val
    -
    -        m = MyClass[Parent](a=Child1())
    -        self.assertTrue(isinstance(m.get_a(), Child1))
    -        self.assertFalse(isinstance(m.get_a(), Child2))
    -        m.set_a(val=Child2())
    -        self.assertTrue(isinstance(m.get_a(), Child2))
    -        self.assertFalse(isinstance(m.get_a(), Child1))
    -
    -    def test_merge_dicts(self):
    -        def create():
    -            T = TypeVar('T')
    -
    -            @pedantic_class
    -            class MyClass(Generic[T]):
    -                def __init__(self, a: T) -> None:
    -                    self.a = a
    -
    -                def get_a(self) -> T:
    -                    return self.a
    -
    -                def set_a(self, val: T) -> None:
    -                    self.a = val
    -            return MyClass(a=42)
    -        a = create()
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            a.set_a(val='hi')
    -
    -    def test_recursion_depth_exceeded(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class Stack(Generic[T]):
    -            def __init__(self) -> None:
    -                self.items: List[T] = []
    -
    -            def len(self) -> int:
    -                return len(self.items)
    -
    -            def push(self, item: T) -> None:
    -                self.items.append(item)
    -
    -            def pop(self) -> T:
    -                if len(self.items) > 0:
    -                    return self.items.pop()
    -                else:
    -                    raise ValueError()
    -
    -            def empty(self) -> bool:
    -                return not self.items
    -
    -            def top(self) -> Optional[T]:
    -                if len(self.items) > 0:
    -                    return self.items[len(self.items) - 1]
    -                else:
    -                    return None
    -
    -            def __len__(self) -> int:
    -                return len(self.items)
    -
    -        def create_stack():
    -            stack = Stack[int]()
    -            return stack
    -
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            stack: Stack[int] = Stack()
    -            self.assertTrue(stack.empty())
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            stack = Stack()
    -            self.assertTrue(stack.empty())
    -        stack = create_stack()
    -        self.assertTrue(stack.empty())
    -
    -    def test_generic_union(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class Stack(Generic[T]):
    -            def __init__(self) -> None:
    -                self.items: List[T] = []
    -
    -            def len(self) -> int:
    -                return len(self.items)
    -
    -            def push(self, item: T) -> None:
    -                self.items.append(item)
    -
    -            def pop(self) -> T:
    -                if len(self.items) > 0:
    -                    return self.items.pop()
    -                else:
    -                    raise ValueError()
    -
    -            def empty(self) -> bool:
    -                return not self.items
    -
    -            def top(self) -> Optional[T]:
    -                if len(self.items) > 0:
    -                    return self.items[len(self.items) - 1]
    -                else:
    -                    return None
    -
    -            def __len__(self) -> int:
    -                return len(self.items)
    -
    -        s = Stack[Union[int, float, str]]()
    -        s.push(item=42)
    -        s.push(item='hello')
    -        s.push(item=3.1415)
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            s.push(item=[1, 2])
    -
    -    def test_inheritance(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class Stack(Generic[T]):
    -            def __init__(self) -> None:
    -                self.items: List[T] = []
    -
    -            def len(self) -> int:
    -                return len(self.items)
    -
    -            def push(self, item: T) -> None:
    -                self.items.append(item)
    -
    -            def pop(self) -> T:
    -                if len(self.items) > 0:
    -                    return self.items.pop()
    -                else:
    -                    raise ValueError()
    -
    -            def empty(self) -> bool:
    -                return not self.items
    -
    -            def top(self) -> Optional[T]:
    -                if len(self.items) > 0:
    -                    return self.items[len(self.items) - 1]
    -                else:
    -                    return None
    -
    -            def __len__(self) -> int:
    -                return len(self.items)
    -
    -        @pedantic_class
    -        class Parent:
    -            pass
    -
    -        @pedantic_class
    -        class Child1(Parent):
    -            pass
    -
    -        @pedantic_class
    -        class Child2(Parent):
    -            pass
    -
    -        parent_stack = Stack[Parent]()
    -        parent_stack.push(item=Child1())
    -        parent_stack.push(item=Child2())
    -        parent_stack.push(item=Parent())
    -
    -        child_1_stack = Stack[Child1]()
    -        child_1_stack.push(item=Child1())
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            child_1_stack.push(item=Child2())
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            child_1_stack.push(item=Parent())
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_generic_class_inheritance(self) -
    -
    -
    - -Expand source code - -
    def test_generic_class_inheritance(self):
    -    class Parent:
    -        pass
    -
    -    class Child1(Parent):
    -        pass
    -
    -    class Child2(Parent):
    -        pass
    -
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class MyClass(Generic[T]):
    -        def __init__(self, a: T) -> None:
    -            self.a = a
    -
    -        def get_a(self) -> T:
    -            return self.a
    -
    -        def set_a(self, val: T) -> None:
    -            self.a = val
    -
    -    m = MyClass[Parent](a=Child1())
    -    self.assertTrue(isinstance(m.get_a(), Child1))
    -    self.assertFalse(isinstance(m.get_a(), Child2))
    -    m.set_a(val=Child2())
    -    self.assertTrue(isinstance(m.get_a(), Child2))
    -    self.assertFalse(isinstance(m.get_a(), Child1))
    -
    -
    -
    -
    -def test_generic_class_initialised_without_generics(self) -
    -
    -
    - -Expand source code - -
    def test_generic_class_initialised_without_generics(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class MyClass(Generic[T]):
    -        def __init__(self, a: T) -> None:
    -            self.a = a
    -
    -        def get_a(self) -> T:
    -            return self.a
    -
    -        def set_a(self, val: T) -> None:
    -            self.a = val
    -
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        m = MyClass(a=42)
    -
    -
    -
    -
    -def test_generic_class_initialised_without_generics_2(self) -
    -
    -
    - -Expand source code - -
    def test_generic_class_initialised_without_generics_2(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class MyClass(Generic[T]):
    -        def __init__(self, a: T) -> None:
    -            self.a = a
    -
    -        def get_a(self) -> T:
    -            return self.a
    -
    -        def set_a(self, val: T) -> None:
    -            self.a = val
    -
    -    MyClass(a=42)  # it is not recognized if it isn't assigned
    -
    -
    -
    -
    -def test_generic_union(self) -
    -
    -
    - -Expand source code - -
    def test_generic_union(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class Stack(Generic[T]):
    -        def __init__(self) -> None:
    -            self.items: List[T] = []
    -
    -        def len(self) -> int:
    -            return len(self.items)
    -
    -        def push(self, item: T) -> None:
    -            self.items.append(item)
    -
    -        def pop(self) -> T:
    -            if len(self.items) > 0:
    -                return self.items.pop()
    -            else:
    -                raise ValueError()
    -
    -        def empty(self) -> bool:
    -            return not self.items
    -
    -        def top(self) -> Optional[T]:
    -            if len(self.items) > 0:
    -                return self.items[len(self.items) - 1]
    -            else:
    -                return None
    -
    -        def __len__(self) -> int:
    -            return len(self.items)
    -
    -    s = Stack[Union[int, float, str]]()
    -    s.push(item=42)
    -    s.push(item='hello')
    -    s.push(item=3.1415)
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        s.push(item=[1, 2])
    -
    -
    -
    -
    -def test_inheritance(self) -
    -
    -
    - -Expand source code - -
    def test_inheritance(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class Stack(Generic[T]):
    -        def __init__(self) -> None:
    -            self.items: List[T] = []
    -
    -        def len(self) -> int:
    -            return len(self.items)
    -
    -        def push(self, item: T) -> None:
    -            self.items.append(item)
    -
    -        def pop(self) -> T:
    -            if len(self.items) > 0:
    -                return self.items.pop()
    -            else:
    -                raise ValueError()
    -
    -        def empty(self) -> bool:
    -            return not self.items
    -
    -        def top(self) -> Optional[T]:
    -            if len(self.items) > 0:
    -                return self.items[len(self.items) - 1]
    -            else:
    -                return None
    -
    -        def __len__(self) -> int:
    -            return len(self.items)
    -
    -    @pedantic_class
    -    class Parent:
    -        pass
    -
    -    @pedantic_class
    -    class Child1(Parent):
    -        pass
    -
    -    @pedantic_class
    -    class Child2(Parent):
    -        pass
    -
    -    parent_stack = Stack[Parent]()
    -    parent_stack.push(item=Child1())
    -    parent_stack.push(item=Child2())
    -    parent_stack.push(item=Parent())
    -
    -    child_1_stack = Stack[Child1]()
    -    child_1_stack.push(item=Child1())
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        child_1_stack.push(item=Child2())
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        child_1_stack.push(item=Parent())
    -
    -
    -
    -
    -def test_merge_dicts(self) -
    -
    -
    - -Expand source code - -
    def test_merge_dicts(self):
    -    def create():
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class MyClass(Generic[T]):
    -            def __init__(self, a: T) -> None:
    -                self.a = a
    -
    -            def get_a(self) -> T:
    -                return self.a
    -
    -            def set_a(self, val: T) -> None:
    -                self.a = val
    -        return MyClass(a=42)
    -    a = create()
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        a.set_a(val='hi')
    -
    -
    -
    -
    -def test_pedantic_generic_class(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_generic_class(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class LoggedVar(Generic[T]):
    -        def __init__(self, value: T, name: str, logger: Any) -> None:
    -            self.name = name
    -            self.logger = logger
    -            self.value = value
    -
    -        def set(self, new: T) -> None:
    -            self.log(message='Set ' + repr(self.value))
    -            self.value = new
    -
    -        def get(self) -> T:
    -            self.log(message='Get ' + repr(self.value))
    -            return self.value
    -
    -        def log(self, message: str) -> None:
    -            self.logger = self.name + message
    -
    -    o = LoggedVar[int](value=42, name='hi', logger='test')
    -    o.set(new=57)
    -    self.assertTrue(isinstance(o.get(), int))
    -
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        o.set(new=3.14)
    -
    -
    -
    -
    -def test_recursion_depth_exceeded(self) -
    -
    -
    - -Expand source code - -
    def test_recursion_depth_exceeded(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class Stack(Generic[T]):
    -        def __init__(self) -> None:
    -            self.items: List[T] = []
    -
    -        def len(self) -> int:
    -            return len(self.items)
    -
    -        def push(self, item: T) -> None:
    -            self.items.append(item)
    -
    -        def pop(self) -> T:
    -            if len(self.items) > 0:
    -                return self.items.pop()
    -            else:
    -                raise ValueError()
    -
    -        def empty(self) -> bool:
    -            return not self.items
    -
    -        def top(self) -> Optional[T]:
    -            if len(self.items) > 0:
    -                return self.items[len(self.items) - 1]
    -            else:
    -                return None
    -
    -        def __len__(self) -> int:
    -            return len(self.items)
    -
    -    def create_stack():
    -        stack = Stack[int]()
    -        return stack
    -
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        stack: Stack[int] = Stack()
    -        self.assertTrue(stack.empty())
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        stack = Stack()
    -        self.assertTrue(stack.empty())
    -    stack = create_stack()
    -    self.assertTrue(stack.empty())
    -
    -
    -
    -
    -def test_stack(self) -
    -
    -
    - -Expand source code - -
    def test_stack(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class Stack(Generic[T]):
    -        def __init__(self) -> None:
    -            self.items: List[T] = []
    -
    -        def push(self, item: T) -> None:
    -            self.items.append(item)
    -
    -        def pop(self) -> T:
    -            return self.items.pop()
    -
    -        def empty(self) -> bool:
    -            return not self.items
    -
    -        def top(self) -> Optional[T]:
    -            if len(self.items) > 0:
    -                return self.items[len(self.items) - 1]
    -            else:
    -                return None
    -
    -    my_stack = Stack[str]()
    -    get_type_vars = getattr(my_stack, TYPE_VAR_METHOD_NAME)
    -    self.assertEqual(get_type_vars(), {T: str, TYPE_VAR_SELF: Stack})
    -    with self.assertRaises(expected_exception=IndexError):
    -        my_stack.pop()
    -    self.assertIsNone(my_stack.top())
    -    self.assertIsNone(my_stack.top())
    -    # self.assertFalse(T in get_type_vars())
    -    my_stack.push(item='hi')
    -    self.assertTrue(T in get_type_vars())
    -    my_stack.push(item='world')
    -    self.assertTrue(T in get_type_vars())
    -    self.assertTrue(len(get_type_vars()), 1)
    -    self.assertEqual(my_stack.pop(), 'world')
    -    self.assertEqual(my_stack.pop(), 'hi')
    -    self.assertIsNone(my_stack.top())
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        my_stack.push(item=42)
    -
    -    my_other_stack = Stack[int]()
    -    get_type_vars = getattr(my_other_stack, TYPE_VAR_METHOD_NAME)
    -    self.assertEqual(get_type_vars(), {T: int, TYPE_VAR_SELF: Stack})
    -    with self.assertRaises(expected_exception=IndexError):
    -        my_other_stack.pop()
    -    self.assertIsNone(my_other_stack.top())
    -    self.assertIsNone(my_other_stack.top())
    -    my_other_stack.push(item=100)
    -    self.assertTrue(len(get_type_vars()), 1)
    -    my_other_stack.push(item=142)
    -    self.assertTrue(len(get_type_vars()), 1)
    -    self.assertEqual(my_other_stack.pop(), 142)
    -    self.assertEqual(my_other_stack.pop(), 100)
    -    self.assertIsNone(my_other_stack.top())
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        my_other_stack.push(item='42')
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_main.html b/docs/pedantic/tests/tests_main.html deleted file mode 100644 index 3604caa..0000000 --- a/docs/pedantic/tests/tests_main.html +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - -pedantic.tests.tests_main API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_main

    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def run_all_tests() ‑> None -
    -
    -
    - -Expand source code - -
    def run_all_tests() -> None:
    -    test_classes_to_run = [
    -        TestAssertValueMatchesType,
    -        TestGenericMixin,
    -        TestWithDecoratedMethods,
    -        TestRequireKwargs,
    -        TestClassDecorators,
    -        TestContextManager,
    -        TestFrozenDataclass,
    -        TestPedanticClass,
    -        TestDecoratorRequireKwargsAndTypeCheck,
    -        TestSmallDecoratorMethods,
    -        TestCombinationOfDecorators,
    -        TestRequireDocstringGoogleFormat,
    -        TestPedanticClassDocstring,
    -        TestDecoratedFunction,
    -        TestEnvironmentVariables,
    -        TestGenericClasses,
    -        TestGenerator,
    -        TestMock,
    -        TestGeneratorWrapper,
    -        TestRenameKwargs,
    -        TestRetry,
    -        TestRetryFunc,
    -        TestResolveForwardRef,
    -        # validate
    -        TestValidatorDatetimeIsoformat,
    -        TestFlaskParameters,
    -        TestParameterEnvironmentVariable,
    -        TestConvertValue,
    -        TestValidate,
    -        TestValidatorComposite,
    -        TestValidatorDatetimeUnixTimestamp,
    -        TestValidatorEmail,
    -        TestValidatorForEach,
    -        TestValidatorIsEnum,
    -        TestValidatorIsUUID,
    -        TestValidatorMatchPattern,
    -        TestValidatorMax,
    -        TestValidatorMaxLength,
    -        TestValidatorMin,
    -        TestValidatorMinLength,
    -        TestValidatorNotEmpty,
    -
    -        # async
    -        AsyncValidateTests,
    -        AsyncSmallDecoratorTests,
    -        TestPedanticAsyncio,
    -        TestInSubprocess,
    -        TestAsyncContextManager,
    -
    -        TestPedanticPython311AddedStuff,
    -    ]
    -
    -    loader = unittest.TestLoader()
    -    suites_list = [get_doctest_test_suite()]
    -
    -    for test_class in test_classes_to_run:
    -        suite = loader.loadTestsFromTestCase(test_class)
    -        suites_list.append(suite)
    -
    -    big_suite = unittest.TestSuite(suites_list)
    -    runner = unittest.TextTestRunner()
    -    result = runner.run(big_suite)
    -    assert not result.errors and not result.failures, f'Some tests failed!'
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_mock.html b/docs/pedantic/tests/tests_mock.html deleted file mode 100644 index f91a477..0000000 --- a/docs/pedantic/tests/tests_mock.html +++ /dev/null @@ -1,151 +0,0 @@ - - - - - - -pedantic.tests.tests_mock API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_mock

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestMock -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestMock(TestCase):
    -    def test_mock(self) -> None:
    -        @mock(return_value=42)
    -        def my_function(a, b, c):
    -            return a + b + c
    -
    -        assert my_function(1, 2, 3) == 42
    -        assert my_function(100, 200, 300) == 42
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_mock(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_mock(self) -> None:
    -    @mock(return_value=42)
    -    def my_function(a, b, c):
    -        return a + b + c
    -
    -    assert my_function(1, 2, 3) == 42
    -    assert my_function(100, 200, 300) == 42
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_pedantic.html b/docs/pedantic/tests/tests_pedantic.html deleted file mode 100644 index 2cad989..0000000 --- a/docs/pedantic/tests/tests_pedantic.html +++ /dev/null @@ -1,7613 +0,0 @@ - - - - - - -pedantic.tests.tests_pedantic API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_pedantic

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Child -
    -
    -
    - -Expand source code - -
    class Child(Parent):
    -    def method(self, a: int):
    -        pass
    -
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def method(self, a: int) -
    -
    -
    - -Expand source code - -
    def method(self, a: int):
    -    pass
    -
    -
    -
    -
    -
    -
    -class Parent -
    -
    -
    - -Expand source code - -
    class Parent:
    -    pass
    -
    -
    -

    Subclasses

    - -
    -
    -class TestDecoratorRequireKwargsAndTypeCheck -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestDecoratorRequireKwargsAndTypeCheck(unittest.TestCase):
    -    def tearDown(self) -> None:
    -        if os.path.isfile(TEST_FILE):
    -            os.remove(TEST_FILE)
    -
    -    def test_no_kwargs(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            calc(42, 40, 38)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            calc(42, m=40, i=38)
    -        calc(n=42, m=40, i=38)
    -
    -    def test_nested_type_hints_1(self):
    -        @pedantic
    -        def calc(n: int) -> List[List[float]]:
    -            return [0.0 * n]
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)
    -
    -    def test_nested_type_hints_1_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> List[List[float]]:
    -            return [[0.0 * n]]
    -
    -        calc(n=42)
    -
    -    def test_nested_type_hints_2(self):
    -        """Problem here: int != float"""
    -        @pedantic
    -        def calc(n: int) -> List[Tuple[float, str]]:
    -            return [(n, str(n))]
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)
    -
    -    def test_nested_type_hints_2_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> List[Tuple[int, str]]:
    -            return [(n, str(n))]
    -
    -        @pedantic
    -        def calc_2(n: float) -> List[Tuple[float, str]]:
    -            return [(n, str(n))]
    -
    -        calc(n=42)
    -        calc_2(n=42.0)
    -
    -    def test_nested_type_hints_3(self):
    -        """Problem here: inner function actually returns Tuple[int, str]"""
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[float, str]:
    -                return n * x, str(y)
    -            return f
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)(x=3, y=3.14)
    -
    -    def test_nested_type_hints_3_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[int, str]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[int, str]:
    -                return n * x, str(y)
    -
    -            return f
    -
    -        calc(n=42)(x=3, y=3.14)
    -
    -    def test_nested_type_hints_4(self):
    -        """Problem here: return type is actually float"""
    -        @pedantic
    -        def calc(n: List[List[float]]) -> int:
    -            return n[0][0]
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=[[42.0]])
    -
    -    def test_nested_type_hints_corrected(self):
    -        @pedantic
    -        def calc(n: List[List[float]]) -> int:
    -            return int(n[0][0])
    -
    -        calc(n=[[42.0]])
    -
    -    def test_nested_type_hints_5(self):
    -        """Problem here: Tuple[float, str] != Tuple[float, float]"""
    -
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[float, float]:
    -                return n * float(x), y
    -            return f
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)
    -
    -    def test_nested_type_hints_5_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[float, float]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[float, float]:
    -                return n * float(x), y
    -            return f
    -
    -        calc(n=42)
    -
    -    def test_missing_type_hint_1(self):
    -        """Problem here: type hint for n missed"""
    -        @pedantic
    -        def calc(n) -> float:
    -            return 42.0 * n
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)
    -
    -    def test_missing_type_hint_1_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> float:
    -            return 42.0 * n
    -
    -        calc(n=42)
    -
    -    def test_missing_type_hint_2(self):
    -        """Problem here: Return type annotation missed"""
    -        @pedantic
    -        def calc(n: int):
    -            return 'Hi' + str(n)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42)
    -
    -    def test_missing_type_hint_2_corrected(self):
    -        @pedantic
    -        def calc(n: int) -> str:
    -            return 'Hi' + str(n)
    -
    -        calc(n=42)
    -
    -    def test_missing_type_hint_3(self):
    -        """Problem here: type hint for i missed"""
    -        @pedantic
    -        def calc(n: int, m: int, i) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=38)
    -
    -    def test_missing_type_hint_3_corrected(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_all_ok_2(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> str:
    -            return str(n + m + i)
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_all_ok_3(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> None:
    -            str(n + m + i)
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_all_ok_4(self):
    -        @pedantic
    -        def calc(n: int) -> List[List[int]]:
    -            return [[n]]
    -
    -        calc(n=42)
    -
    -    def test_all_ok_5(self):
    -        @pedantic
    -        def calc(n: int) -> List[Tuple[float, str]]:
    -            return [(float(n), str(n))]
    -
    -        calc(n=42)
    -
    -    def test_all_ok_6(self):
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[float, str]:
    -                return n * float(x), str(y)
    -            return f
    -
    -        calc(n=42)(x=72, y=3.14)
    -
    -    def test_all_ok_7(self):
    -        @pedantic
    -        def calc(n: List[List[float]]) -> Any:
    -            return n[0][0]
    -
    -        calc(n=[[42.0]])
    -
    -    def test_all_ok_8(self):
    -        @pedantic
    -        def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -            @pedantic
    -            def f(x: int, y: float) -> Tuple[float, str]:
    -                return n * float(x), str(y)
    -
    -            return f
    -
    -        calc(n=42)(x=3, y=3.14)
    -
    -    def test_wrong_type_hint_1(self):
    -        """Problem here: str != int"""
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> str:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_1_corrected(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> str:
    -            return str(n + m + i)
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_2(self):
    -        """Problem here: str != int"""
    -        @pedantic
    -        def calc(n: int, m: int, i: str) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_2_corrected(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: str) -> int:
    -            return n + m + int(i)
    -
    -        calc(n=42, m=40, i='38')
    -
    -    def test_wrong_type_hint_3(self):
    -        """Problem here: None != int"""
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> None:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_corrected(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> None:
    -            print(n + m + i)
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_4(self):
    -        """Problem here: None != int"""
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> int:
    -            print(n + m + i)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=38)
    -
    -    def test_wrong_type_hint_4_corrected(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        calc(n=42, m=40, i=38)
    -
    -    def test_none_1(self):
    -        """Problem here: None is not accepted"""
    -        @pedantic
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=None)
    -
    -    def test_none_2(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: Optional[int]) -> int:
    -            return n + m + i if i is not None else n + m
    -
    -        calc(n=42, m=40, i=None)
    -
    -    def test_none_3(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: Union[int, None]) -> int:
    -            return n + m + i if i is not None else n + m
    -
    -        calc(n=42, m=40, i=None)
    -
    -    def test_none_4(self):
    -        """Problem here: function may return None"""
    -        @pedantic
    -        def calc(n: int, m: int, i: Union[int, None]) -> int:
    -            return n + m + i if i is not None else None
    -
    -        calc(n=42, m=40, i=42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(n=42, m=40, i=None)
    -
    -    def test_none_5(self):
    -        @pedantic
    -        def calc(n: int, m: int, i: Union[int, None]) -> Optional[int]:
    -            return n + m + i if i is not None else None
    -
    -        calc(n=42, m=40, i=None)
    -
    -    def test_inheritance_1(self):
    -        class MyClassA:
    -            pass
    -
    -        class MyClassB(MyClassA):
    -            pass
    -
    -        @pedantic
    -        def calc(a: MyClassA) -> str:
    -            return str(a)
    -
    -        calc(a=MyClassA())
    -        calc(a=MyClassB())
    -
    -    def test_inheritance_2(self):
    -        """Problem here: A is not a subtype of B"""
    -        class MyClassA:
    -            pass
    -
    -        class MyClassB(MyClassA):
    -            pass
    -
    -        @pedantic
    -        def calc(a: MyClassB) -> str:
    -            return str(a)
    -
    -        calc(a=MyClassB())
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(a=MyClassA())
    -
    -    def test_instance_method_1(self):
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: int) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        a.calc(i=42)
    -
    -    def test_instance_method_2(self):
    -        """Problem here: 'i' has no type annotation"""
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            a.calc(i=42)
    -
    -    def test_instance_method_2_corrected(self):
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: int) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        a.calc(i=42)
    -
    -    def test_instance_method_int_is_not_float(self):
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: float) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            a.calc(i=42)
    -
    -    def test_instance_method_3_corrected(self):
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: float) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        a.calc(i=42.0)
    -
    -    def test_instance_method_no_kwargs(self):
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: int) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            a.calc(42)
    -
    -    def test_instance_method_5(self):
    -        """Problem here: instance methods is not called with kwargs"""
    -        class MyClassA:
    -            @pedantic
    -            def calc(self, i: int) -> str:
    -                return str(i)
    -
    -        a = MyClassA()
    -        a.calc(i=42)
    -
    -    def test_lambda_1(self):
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            return lambda x: str(x * i)
    -
    -        calc(i=42.0)(10.0)
    -
    -    def test_lambda_3(self):
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            def res(x: float) -> str:
    -                return str(x * i)
    -            return res
    -
    -        calc(i=42.0)(10.0)
    -
    -    def test_lambda_int_is_not_float(self):
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            def res(x: int) -> str:
    -                return str(x * i)
    -            return res
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=42.0)(x=10)
    -
    -    def test_lambda_4_almost_corrected(self):
    -        """Problem here: float != str"""
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            @pedantic
    -            def res(x: int) -> str:
    -                return str(x * i)
    -            return res
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=42.0)(x=10)
    -
    -    def test_lambda_4_almost_corrected_2(self):
    -        @pedantic
    -        def calc(i: float) -> Callable[[int], str]:
    -            @pedantic
    -            def res(x: int) -> str:
    -                return str(x * i)
    -            return res
    -
    -        calc(i=42.0)(x=10)
    -
    -    def test_lambda_5(self):
    -        """Problem here: float != int"""
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            @pedantic
    -            def res(x: float) -> str:
    -                return str(x * i)
    -            return res
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=42.0)(x=10)
    -
    -    def test_lambda_corrected(self):
    -        @pedantic
    -        def calc(i: float) -> Callable[[float], str]:
    -            @pedantic
    -            def res(x: float) -> str:
    -                return str(x * i)
    -
    -            return res
    -
    -        calc(i=42.0)(x=10.0)
    -
    -    def test_tuple_without_type_args(self):
    -        @pedantic
    -        def calc(i: Tuple) -> str:
    -            return str(i)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=(42.0, 43, 'hi'))
    -
    -    def test_tuple_without_args_corrected(self):
    -        @pedantic
    -        def calc(i: Tuple[Any, ...]) -> str:
    -            return str(i)
    -
    -        calc(i=(42.0, 43, 'hi'))
    -
    -    def test_callable_without_type_args(self):
    -        @pedantic
    -        def calc(i: Callable) -> str:
    -            return str(i(' you'))
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=lambda x: (42.0, 43, 'hi', x))
    -
    -    def test_callable_without_args_correct_with_lambdas(self):
    -        @pedantic
    -        def calc(i: Callable[[Any], Tuple[Any, ...]]) -> str:
    -            return str(i(x=' you'))
    -
    -        calc(i=lambda x: (42.0, 43, 'hi', x))
    -
    -    def test_callable_without_args_corrected(self):
    -        @pedantic
    -        def calc(i: Callable[[Any], Tuple[Any, ...]]) -> str:
    -            return str(i(x=' you'))
    -
    -        @pedantic
    -        def arg(x: Any) -> Tuple[Any, ...]:
    -            return 42.0, 43, 'hi', x
    -        calc(i=arg)
    -
    -    def test_list_without_args(self):
    -        @pedantic
    -        def calc(i: List) -> Any:
    -            return [i]
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(i=[42.0, 43, 'hi'])
    -
    -    def test_list_without_args_corrected(self):
    -        @pedantic
    -        def calc(i: List[Any]) -> List[List[Any]]:
    -            return [i]
    -
    -        calc(i=[42.0, 43, 'hi'])
    -
    -    def test_ellipsis_in_callable_1(self):
    -        @pedantic
    -        def calc(i: Callable[..., int]) -> int:
    -            return i()
    -
    -        @pedantic
    -        def call() -> int:
    -            return 42
    -
    -        calc(i=call)
    -
    -    def test_ellipsis_in_callable_2(self):
    -        @pedantic
    -        def calc(i: Callable[..., int]) -> int:
    -            return i(x=3.14, y=5)
    -
    -        @pedantic
    -        def call(x: float, y: int) -> int:
    -            return 42
    -
    -        calc(i=call)
    -
    -    def test_ellipsis_in_callable_3(self):
    -        """Problem here: call to "call" misses one argument"""
    -        @pedantic
    -        def calc(i: Callable[..., int]) -> int:
    -            return i(x=3.14)
    -
    -        @pedantic
    -        def call(x: float, y: int) -> int:
    -            return 42
    -
    -        with self.assertRaises(expected_exception=PedanticException):
    -            calc(i=call)
    -
    -    def test_optional_args_1(self):
    -        @pedantic
    -        def calc(a: int, b: int = 42) -> int:
    -            return a + b
    -
    -        calc(a=2)
    -
    -    def test_optional_args_2(self):
    -        @pedantic
    -        def calc(a: int = 3, b: int = 42, c: float = 5.0) -> float:
    -            return a + b + c
    -
    -        calc()
    -        calc(a=1)
    -        calc(b=1)
    -        calc(c=1.0)
    -        calc(a=1, b=1)
    -        calc(a=1, c=1.0)
    -        calc(b=1, c=1.0)
    -        calc(a=1, b=1, c=1.0)
    -
    -    def test_optional_args_3(self):
    -        """Problem here: optional argument c: 5 is not a float"""
    -        @pedantic
    -        def calc(a: int = 3, b: int = 42, c: float = 5) -> float:
    -            return a + b + c
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc()
    -
    -    def test_optional_args_3_corrected(self):
    -        @pedantic
    -        def calc(a: int = 3, b: int = 42, c: float = 5.0) -> float:
    -            return a + b + c
    -
    -        calc()
    -
    -    def test_optional_args_4(self):
    -        class MyClass:
    -            @pedantic
    -            def foo(self, a: int, b: Optional[int] = 1) -> int:
    -                return a + b
    -
    -        my_class = MyClass()
    -        my_class.foo(a=10)
    -
    -    def test_optional_args_5(self):
    -        @pedantic
    -        def calc(d: Optional[Dict[int, int]] = None) -> Optional[int]:
    -            if d is None:
    -                return None
    -            return sum(d.keys())
    -
    -        calc(d=None)
    -        calc()
    -        calc(d={42: 3})
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(d={42: 3.14})
    -
    -    def test_optional_args_6(self):
    -        """"Problem here: str != int"""
    -        @pedantic
    -        def calc(d: int = 42) -> int:
    -            return int(d)
    -
    -        calc(d=99999)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(d='999999')
    -
    -    def test_enum_1(self):
    -        """Problem here: Type hint for 'a' should be MyEnum instead of MyEnum.GAMMA"""
    -        class MyEnum(Enum):
    -            ALPHA = 'startEvent'
    -            BETA = 'task'
    -            GAMMA = 'sequenceFlow'
    -
    -        class MyClass:
    -            @pedantic
    -            def operation(self, a: MyEnum.GAMMA) -> None:
    -                print(a)
    -
    -        m = MyClass()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.operation(a=MyEnum.GAMMA)
    -
    -    def test_enum_1_corrected(self):
    -        class MyEnum(Enum):
    -            ALPHA = 'startEvent'
    -            BETA = 'task'
    -            GAMMA = 'sequenceFlow'
    -
    -        @pedantic
    -        def operation(a: MyEnum) -> None:
    -            print(a)
    -
    -        operation(a=MyEnum.GAMMA)
    -
    -    def test_sloppy_types_dict(self):
    -        @pedantic
    -        def operation(d: dict) -> int:
    -            return len(d.keys())
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d={1: 1, 2: 2})
    -
    -    def test_sloppy_types_dict_almost_corrected_no_type_args(self):
    -        @pedantic
    -        def operation(d: Dict) -> int:
    -            return len(d.keys())
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d={1: 1, 2: 2})
    -
    -    def test_sloppy_types_dict_corrected(self):
    -        @pedantic
    -        def operation(d: Dict[int, int]) -> int:
    -            return len(d.keys())
    -
    -        operation(d={1: 1, 2: 2})
    -
    -    def test_sloppy_types_list(self):
    -        @pedantic
    -        def operation(d: list) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=[1, 2, 3, 4])
    -
    -    def test_sloppy_types_list_almost_corrected_no_type_args(self):
    -        @pedantic
    -        def operation(d: List) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=[1, 2, 3, 4])
    -
    -    def test_sloppy_types_list_corrected(self):
    -        @pedantic
    -        def operation(d: List[int]) -> int:
    -            return len(d)
    -
    -        operation(d=[1, 2, 3, 4])
    -
    -    def test_sloppy_types_tuple(self):
    -        @pedantic
    -        def operation(d: tuple) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=(1, 2, 3))
    -
    -    def test_sloppy_types_tuple_almost_corrected_no_type_args(self):
    -        @pedantic
    -        def operation(d: Tuple) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=(1, 2, 3))
    -
    -    def test_sloppy_types_tuple_corrected(self):
    -        @pedantic
    -        def operation(d: Tuple[int, int, int]) -> int:
    -            return len(d)
    -
    -        operation(d=(1, 2, 3))
    -
    -    def test_sloppy_types_set(self):
    -        @pedantic
    -        def operation(d: set) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d={1, 2, 3})
    -
    -    def test_sloppy_types_set_almost_corrected_to_type_args(self):
    -        @pedantic
    -        def operation(d: Set) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d={1, 2, 3})
    -
    -    def test_sloppy_types_set_corrected(self):
    -        @pedantic
    -        def operation(d: Set[int]) -> int:
    -            return len(d)
    -
    -        operation(d={1, 2, 3})
    -
    -    def test_sloppy_types_frozenset(self):
    -        @pedantic
    -        def operation(d: frozenset) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=frozenset({1, 2, 3}))
    -
    -    def test_sloppy_types_frozenset_almost_corrected_no_type_args(self):
    -        @pedantic
    -        def operation(d: FrozenSet) -> int:
    -            return len(d)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            operation(d=frozenset({1, 2, 3}))
    -
    -    def test_sloppy_types_frozenset_corrected(self):
    -        @pedantic
    -        def operation(d: FrozenSet[int]) -> int:
    -            return len(d)
    -
    -        operation(d=frozenset({1, 2, 3}))
    -
    -    def test_type_list_but_got_tuple(self):
    -        @pedantic
    -        def calc(ls: List[Any]) -> int:
    -            return len(ls)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            calc(ls=(1, 2, 3))
    -
    -    def test_type_list_corrected(self):
    -        @pedantic
    -        def calc(ls: Tuple[Any, ...]) -> int:
    -            return len(ls)
    -
    -        calc(ls=(1, 2, 3))
    -
    -    def test_any(self):
    -        @pedantic
    -        def calc(ls: List[Any]) -> Dict[int, Any]:
    -            return {i: ls[i] for i in range(0, len(ls))}
    -
    -        calc(ls=[1, 2, 3])
    -        calc(ls=[1.11, 2.0, 3.0])
    -        calc(ls=['1', '2', '3'])
    -        calc(ls=[10.5, '2', (3, 4, 5)])
    -
    -    def test_aliases(self):
    -        Vector = List[float]
    -
    -        @pedantic
    -        def scale(scalar: float, vector: Vector) -> Vector:
    -            return [scalar * num for num in vector]
    -
    -        scale(scalar=2.0, vector=[1.0, -4.2, 5.4])
    -
    -    def test_new_type(self):
    -        UserId = NewType('UserId', int)
    -
    -        @pedantic
    -        def get_user_name(user_id: UserId) -> str:
    -            return str(user_id)
    -
    -        some_id = UserId(524313)
    -        get_user_name(user_id=some_id)
    -
    -        # the following would be desirable but impossible to check at runtime:
    -        # with self.assertRaises(expected_exception=AssertionError):
    -        #     get_user_name(user_id=-1)
    -
    -    def test_list_of_new_type(self):
    -        UserId = NewType('UserId', int)
    -
    -        @pedantic
    -        def get_user_name(user_ids: List[UserId]) -> str:
    -            return str(user_ids)
    -
    -        get_user_name(user_ids=[UserId(524313), UserId(42)])
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            get_user_name(user_ids=[UserId(524313), UserId(42), 430.0])
    -
    -    def test_callable_no_args(self):
    -        @pedantic
    -        def f(g: Callable[[], str]) -> str:
    -            return g()
    -
    -        @pedantic
    -        def greetings() -> str:
    -            return 'hello world'
    -
    -        f(g=greetings)
    -
    -    def test_type_var(self):
    -        T = TypeVar('T')
    -
    -        @pedantic
    -        def first(ls: List[T]) -> T:
    -            return ls[0]
    -
    -        first(ls=[1, 2, 3])
    -
    -    def test_type_var_wrong(self):
    -        T = TypeVar('T')
    -
    -        @pedantic
    -        def first(ls: List[T]) -> T:
    -            return str(ls[0])
    -
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            first(ls=[1, 2, 3])
    -
    -    def test_type_var_wrong_sequence(self):
    -        T = TypeVar('T')
    -
    -        @pedantic
    -        def first(ls: Sequence[T]) -> T:
    -            return str(ls[0])
    -
    -        with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -            first(ls=[1, 2, 3])
    -
    -    def test_double_pedantic(self):
    -        @pedantic
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, str]:
    -            return float(x), str(y)
    -
    -        f(x=5, y=3.14)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f(x=5.0, y=3.14)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            f(5, 3.14)
    -
    -    def test_args_kwargs(self):
    -        @pedantic
    -        def some_method(a: int = 0, b: float = 0.0) -> float:
    -            return a * b
    -
    -        @pedantic
    -        def wrapper_method(*args: Union[int, float], **kwargs: Union[int, float]) -> float:
    -            return some_method(*args, **kwargs)
    -
    -        some_method()
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            some_method(3, 3.0)
    -        some_method(a=3, b=3.0)
    -        wrapper_method()
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            wrapper_method(3, 3.0)
    -        wrapper_method(a=3, b=3.0)
    -
    -    def test_args_kwargs_no_type_hint(self):
    -        @pedantic
    -        def method_no_type_hint(*args, **kwargs) -> None:
    -            print(args)
    -            print(kwargs)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            method_no_type_hint(a=3, b=3.0)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            method_no_type_hint()
    -
    -    def test_args_kwargs_wrong_type_hint(self):
    -        """See: https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values"""
    -        @pedantic
    -        def wrapper_method(*args: str, **kwargs: str) -> None:
    -            print(args)
    -            print(kwargs)
    -
    -        wrapper_method()
    -        wrapper_method('hi', 'you', ':)')
    -        wrapper_method(a='hi', b='you', c=':)')
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            wrapper_method('hi', 'you', ':)', 7)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            wrapper_method(3, 3.0)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            wrapper_method(a=3, b=3.0)
    -
    -    def test_additional_kwargs(self):
    -        @pedantic
    -        def some_method(a: int, b: float = 0.0, **kwargs: int) -> float:
    -            return sum([a, b])
    -
    -        some_method(a=5)
    -        some_method(a=5, b=0.1)
    -        some_method(a=5, b=0.1, c=4)
    -        some_method(a=5, b=0.1, c=4, d=5, e=6)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_method(a=5, b=0.1, c=4, d=5.0, e=6)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_method(a=5.0, b=0.1, c=4, d=5, e=6)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            some_method(a=5, b=0, c=4, d=5, e=6)
    -
    -    def test_args_kwargs_different_types(self):
    -        @pedantic
    -        def foo(*args: str, **kwds: int) -> None:
    -            print(args)
    -            print(kwds)
    -
    -        foo('a', 'b', 'c')
    -        foo(x=1, y=2)
    -        foo('', z=0)
    -
    -    def test_pedantic_on_class(self):
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            @pedantic
    -            class MyClass:
    -                pass
    -            MyClass()
    -
    -    def test_is_subtype_tuple(self):
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            @pedantic
    -            def foo() -> Callable[[Tuple[float, str]], Tuple[int]]:
    -                def bar(a: Tuple[float]) -> Tuple[int]:
    -                    return len(a[1]) + int(a[0]),
    -                return bar
    -            foo()
    -
    -    def test_is_subtype_tuple_corrected(self):
    -        @pedantic
    -        def foo() -> Callable[[Tuple[float, str]], Tuple[int]]:
    -            def bar(a: Tuple[float, str]) -> Tuple[int]:
    -                return len(a[1]) + int(a[0]),
    -            return bar
    -        foo()
    -
    -    def test_forward_ref(self):
    -        class Conversation:
    -            pass
    -
    -        @pedantic
    -        def get_conversations() -> List['Conversation']:
    -            return [Conversation(), Conversation()]
    -
    -        get_conversations()
    -
    -    def test_alternative_list_type_hint(self):
    -        @pedantic
    -        def _is_digit_in_int(digit: [int], num: int) -> bool:
    -            num_str = str(num)
    -            for i in num_str:
    -                if int(i) == digit:
    -                    return True
    -            return False
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            _is_digit_in_int(digit=4, num=42)
    -
    -    def test_callable_with_union_return(self):
    -        class MyClass:
    -            pass
    -
    -        @pedantic
    -        def admin_required(func: Callable[..., Union[str, MyClass]]) -> Callable[..., Union[str, MyClass]]:
    -            @wraps(func)
    -            def decorated_function(*args, **kwargs):
    -                return func(*args, **kwargs)
    -            return decorated_function
    -
    -        @admin_required
    -        @pedantic
    -        def get_server_info() -> str:
    -            return 'info'
    -
    -        get_server_info()
    -
    -    def test_pedantic(self):
    -        @pedantic
    -        def foo(a: int, b: str) -> str:
    -            return 'abc'
    -
    -        self.assertEqual('abc', foo(a=4, b='abc'))
    -
    -    def test_pedantic_always(self):
    -        @pedantic
    -        def foo(a: int, b: str) -> str:
    -            return 'abc'
    -
    -        self.assertEqual('abc', foo(a=4, b='abc'))
    -
    -    def test_pedantic_arguments_fail(self):
    -        @pedantic
    -        def foo(a: int, b: str) -> str:
    -            return 'abc'
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            foo(a=4, b=5)
    -
    -    def test_pedantic_return_type_fail(self):
    -        @pedantic
    -        def foo(a: int, b: str) -> str:
    -            return 6
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            foo(a=4, b='abc')
    -
    -    def test_return_type_none(self):
    -        @pedantic
    -        def foo() -> None:
    -            return 'a'
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            foo()
    -
    -    def test_marco(self):
    -        @pedantic_class
    -        class A:
    -            def __init__(self, val: int) -> None:
    -                self.val = val
    -
    -            def __eq__(self, other: 'A') -> bool:  # other: A and all subclasses
    -                return self.val == other.val
    -
    -        @pedantic_class
    -        class B(A):
    -            def __init__(self, val: int) -> None:
    -                super().__init__(val=val)
    -
    -        @pedantic_class
    -        class C(A):
    -            def __init__(self, val: int) -> None:
    -                super().__init__(val=val)
    -
    -        a = A(val=42)
    -        b = B(val=42)
    -        c = C(val=42)
    -
    -        assert a == b  # works
    -        assert a == c  # works
    -        assert b == c  # error
    -
    -    def test_date_datetime(self):
    -        @pedantic
    -        def foo(a: datetime, b: date) -> None:
    -            pass
    -
    -        foo(a=datetime(1995, 2, 5), b=date(1987, 8, 7))
    -        foo(a=datetime(1995, 2, 5), b=datetime(1987, 8, 7))
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            foo(a=date(1995, 2, 5), b=date(1987, 8, 7))
    -
    -    def test_any_type(self):
    -        @pedantic
    -        def foo(a: Any) -> None:
    -            pass
    -
    -        foo(a='aa')
    -
    -    def test_callable_exact_arg_count(self):
    -        @pedantic
    -        def foo(a: Callable[[int, str], int]) -> None:
    -            pass
    -
    -        def some_callable(x: int, y: str) -> int:
    -            pass
    -
    -        foo(a=some_callable)
    -
    -    def test_callable_bad_type(self):
    -        @pedantic
    -        def foo(a: Callable[..., int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_callable_too_few_arguments(self):
    -        @pedantic
    -        def foo(a: Callable[[int, str], int]) -> None:
    -            pass
    -
    -        def some_callable(x: int) -> int:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=some_callable)
    -
    -    def test_callable_mandatory_kwonlyargs(self):
    -        @pedantic
    -        def foo(a: Callable[[int, str], int]) -> None:
    -            pass
    -
    -        def some_callable(x: int, y: str, *, z: float, bar: str) -> int:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=some_callable)
    -
    -    def test_callable_class(self):
    -        """
    -        Test that passing a class as a callable does not count the "self" argument "a"gainst the
    -        ones declared in the Callable specification.
    -
    -        """
    -        @pedantic
    -        def foo(a: Callable[[int, str], Any]) -> None:
    -            pass
    -
    -        class SomeClass:
    -            def __init__(self, x: int, y: str):
    -                pass
    -
    -        foo(a=SomeClass)
    -
    -    def test_callable_plain(self):
    -        @pedantic
    -        def foo(a: Callable[..., Any]) -> None:
    -            pass
    -
    -        def callback(a):
    -            pass
    -
    -        foo(a=callback)
    -
    -    def test_callable_bound_method(self):
    -        @pedantic
    -        def foo(callback: Callable[[int], Any]) -> None:
    -            pass
    -
    -        foo(callback=Child().method)
    -
    -    def test_callable_defaults(self):
    -        """
    -        Test that a callable having "too many" arguments don't raise an error if the extra
    -        arguments have default values.
    -
    -        """
    -        @pedantic
    -        def foo(callback: Callable[[int, str], Any]) -> None:
    -            pass
    -
    -        def some_callable(x: int, y: str, z: float = 1.2) -> int:
    -            pass
    -
    -        foo(callback=some_callable)
    -
    -    def test_callable_builtin(self):
    -        @pedantic
    -        def foo(callback: types.BuiltinFunctionType) -> None:
    -            pass
    -
    -        foo(callback=[].append)
    -
    -    def test_dict_bad_type(self):
    -        @pedantic
    -        def foo(a: Dict[str, int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_dict_bad_key_type(self):
    -        @pedantic
    -        def foo(a: Dict[str, int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a={1: 2})
    -
    -    def test_dict_bad_value_type(self):
    -        @pedantic
    -        def foo(a: Dict[str, int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a={'x': 'a'})
    -
    -    def test_list_bad_type(self):
    -        @pedantic
    -        def foo(a: List[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_list_bad_element(self):
    -        @pedantic
    -        def foo(a: List[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=[1, 2, 'bb'])
    -
    -    def test_sequence_bad_type(self):
    -        @pedantic
    -        def foo(a: Sequence[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_sequence_bad_element(self):
    -        @pedantic
    -        def foo(a: Sequence[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=[1, 2, 'bb'])
    -
    -    def test_abstractset_custom_type(self):
    -        T = TypeVar('T')
    -
    -        @pedantic_class
    -        class DummySet(AbstractSet[T]):
    -            def __contains__(self, x: object) -> bool:
    -                return x == 1
    -
    -            def __len__(self) -> T:
    -                return 1
    -
    -            def __iter__(self) -> Iterator[T]:
    -                yield 1
    -
    -        @pedantic
    -        def foo(a: AbstractSet[int]) -> None:
    -            pass
    -
    -        foo(a=DummySet[int]())
    -
    -    def test_abstractset_bad_type(self):
    -        @pedantic
    -        def foo(a: AbstractSet[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_set_bad_type(self):
    -        @pedantic
    -        def foo(a: Set[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_abstractset_bad_element(self):
    -        @pedantic
    -        def foo(a: AbstractSet[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a={1, 2, 'bb'})
    -
    -    def test_set_bad_element(self):
    -        @pedantic
    -        def foo(a: Set[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a={1, 2, 'bb'})
    -
    -    def test_tuple_bad_type(self):
    -        @pedantic
    -        def foo(a: Tuple[int]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=5)
    -
    -    def test_tuple_too_many_elements(self):
    -        @pedantic
    -        def foo(a: Tuple[int, str]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=(1, 'aa', 2))
    -
    -    def test_tuple_too_few_elements(self):
    -        @pedantic
    -        def foo(a: Tuple[int, str]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=(1,))
    -
    -    def test_tuple_bad_element(self):
    -        @pedantic
    -        def foo(a: Tuple[int, str]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=(1, 2))
    -
    -    def test_tuple_ellipsis_bad_element(self):
    -        @pedantic
    -        def foo(a: Tuple[int, ...]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=(1, 2, 'blah'))
    -
    -    def test_namedtuple(self):
    -        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -        @pedantic
    -        def foo(bar: Employee) -> None:
    -            print(bar)
    -
    -        foo(bar=Employee('bob', 1))
    -
    -    def test_namedtuple_key_mismatch(self):
    -        Employee1 = NamedTuple('Employee', [('name', str), ('id', int)])
    -        Employee2 = NamedTuple('Employee', [('firstname', str), ('id', int)])
    -
    -        @pedantic
    -        def foo(bar: Employee1) -> None:
    -            print(bar)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(bar=Employee2('bob', 1))
    -
    -    def test_namedtuple_type_mismatch(self):
    -        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -        @pedantic
    -        def foo(bar: Employee) -> None:
    -            print(bar)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(bar=('bob', 1))
    -
    -    def test_namedtuple_huge_type_mismatch(self):
    -        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -        @pedantic
    -        def foo(bar: int) -> None:
    -            print(bar)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(bar=foo(bar=Employee('bob', 1)))
    -
    -    def test_namedtuple_wrong_field_type(self):
    -        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -        @pedantic
    -        def foo(bar: Employee) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(bar=Employee(2, 1))
    -
    -    def test_union(self):
    -        @pedantic
    -        def foo(a: Union[str, int]) -> None:
    -            pass
    -
    -        for value in [6, 'xa']:
    -            foo(a=value)
    -
    -    def test_union_new_syntax(self):
    -        @pedantic
    -        def foo(a: str | int) -> None:
    -            pass
    -
    -        for value in [6, 'xa']:
    -            foo(a=value)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1.7)
    -
    -    def test_union_typing_type(self):
    -        @pedantic
    -        def foo(a: Union[str, Collection]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1)
    -
    -    def test_union_fail(self):
    -        @pedantic
    -        def foo(a: Union[str, int]) -> None:
    -            pass
    -
    -        for value in [5.6, b'xa']:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo(a=value)
    -
    -    def test_type_var_constraints(self):
    -        T = TypeVar('T', int, str)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        for values in [
    -            {'a': 6, 'b': 7},
    -            {'a': 'aa', 'b': "bb"},
    -        ]:
    -            foo(**values)
    -
    -    def test_type_var_constraints_fail_typing_type(self):
    -        T = TypeVar('T', int, Collection)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a='aa', b='bb')
    -
    -    def test_typevar_constraints_fail(self):
    -        T = TypeVar('T', int, str)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=2.5, b='aa')
    -
    -    def test_typevar_bound(self):
    -        T = TypeVar('T', bound=Parent)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        foo(a=Child(), b=Child())
    -
    -    def test_type_var_bound_fail(self):
    -        T = TypeVar('T', bound=Child)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=Parent(), b=Parent())
    -
    -    def test_type_var_invariant_fail(self):
    -        T = TypeVar('T', int, str)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=2, b=3.6)
    -
    -    def test_type_var_covariant(self):
    -        T = TypeVar('T', covariant=True)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        foo(a=Parent(), b=Child())
    -
    -    def test_type_var_covariant_fail(self):
    -        T = TypeVar('T', covariant=True)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeVarMismatchException):
    -            foo(a=Child(), b=Parent())
    -
    -    def test_type_var_contravariant(self):
    -        T = TypeVar('T', contravariant=True)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        foo(a=Child(), b=Parent())
    -
    -    def test_type_var_contravariant_fail(self):
    -        T = TypeVar('T', contravariant=True)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeVarMismatchException):
    -            foo(a=Parent(), b=Child())
    -
    -    def test_class_bad_subclass(self):
    -        @pedantic
    -        def foo(a: Type[Child]) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=Parent)
    -
    -    def test_class_any(self):
    -        @pedantic
    -        def foo(a: Type[Any]) -> None:
    -            pass
    -
    -        foo(a=str)
    -
    -    def test_wrapped_function(self):
    -        def decorator(func):
    -            @wraps(func)
    -            def wrapper(*args, **kwargs):
    -                return func(*args, **kwargs)
    -            return wrapper
    -
    -        @pedantic
    -        @decorator
    -        def foo(a: 'Child') -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=Parent())
    -
    -    def test_mismatching_default_type(self):
    -        @pedantic
    -        def foo(a: str = 1) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo()
    -
    -    def test_implicit_default_none(self):
    -        """
    -        Test that if the default value is ``None``, a ``None`` argument can be passed.
    -
    -        """
    -        @pedantic
    -        def foo(a: Optional[str] = None) -> None:
    -            pass
    -
    -        foo()
    -
    -    def test_generator_simple(self):
    -        """Test that argument type checking works in a generator function too."""
    -        @pedantic
    -        def generate(a: int) -> Generator[int, int, None]:
    -            yield a
    -            yield a + 1
    -
    -        gen = generate(a=1)
    -        next(gen)
    -
    -    def test_wrapped_generator_no_return_type_annotation(self):
    -        """Test that return type checking works in a generator function too."""
    -        @pedantic
    -        def generate(a: int) -> Generator[int, int, None]:
    -            yield a
    -            yield a + 1
    -
    -        gen = generate(a=1)
    -        next(gen)
    -
    -    def test_varargs(self):
    -        @pedantic
    -        def foo(*args: int) -> None:
    -            pass
    -
    -        foo(1, 2)
    -
    -    def test_varargs_fail(self):
    -        @pedantic
    -        def foo(*args: int) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(1, 'a')
    -
    -    def test_kwargs(self):
    -        @pedantic
    -        def foo(**kwargs: int) -> None:
    -            pass
    -
    -        foo(a=1, b=2)
    -
    -    def test_kwargs_fail(self):
    -        @pedantic
    -        def foo(**kwargs: int) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1, b='a')
    -
    -    def test_generic(self):
    -        T_Foo = TypeVar('T_Foo')
    -
    -        class FooGeneric(Generic[T_Foo]):
    -            pass
    -
    -        @pedantic
    -        def foo(a: FooGeneric[str]) -> None:
    -            print(a)
    -
    -        foo(a=FooGeneric[str]())
    -
    -    def test_newtype(self):
    -        myint = NewType("myint", int)
    -
    -        @pedantic
    -        def foo(a: myint) -> int:
    -            return 42
    -
    -        assert foo(a=1) == 42
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a="a")
    -
    -    def test_collection(self):
    -        @pedantic
    -        def foo(a: Collection) -> None:
    -            pass
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=True)
    -
    -    def test_binary_io(self):
    -        @pedantic
    -        def foo(a: BinaryIO) -> None:
    -            print(a)
    -
    -        foo(a=BytesIO())
    -
    -    def test_text_io(self):
    -        @pedantic
    -        def foo(a: TextIO) -> None:
    -            print(a)
    -
    -        foo(a=StringIO())
    -
    -    def test_binary_io_fail(self):
    -        @pedantic
    -        def foo(a: TextIO) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=BytesIO())
    -
    -    def test_text_io_fail(self):
    -        @pedantic
    -        def foo(a: BinaryIO) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=StringIO())
    -
    -    def test_binary_io_real_file(self):
    -        @pedantic
    -        def foo(a: BinaryIO) -> None:
    -            print(a)
    -
    -        with open(file=TEST_FILE, mode='wb') as f:
    -            foo(a=f)
    -
    -    def test_text_io_real_file(self):
    -        @pedantic
    -        def foo(a: TextIO) -> None:
    -            print(a)
    -
    -        with open(file=TEST_FILE, mode='w') as f:
    -            foo(a=f)
    -
    -    def test_pedantic_return_type_var_fail(self):
    -        T = TypeVar('T', int, float)
    -
    -        @pedantic
    -        def foo(a: T, b: T) -> T:
    -            return 'a'
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=4, b=2)
    -
    -    def test_callable(self):
    -        @pedantic
    -        def foo_1(a: Callable[..., int]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Callable) -> None:
    -            print(a)
    -
    -        def some_callable() -> int:
    -            return 4
    -
    -        foo_1(a=some_callable)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a=some_callable)
    -
    -    def test_list(self):
    -        @pedantic
    -        def foo_1(a: List[int]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: List) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_3(a: list) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_4(a: list[int]) -> None:
    -            print(a)
    -
    -        foo_1(a=[1, 2])
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a=[1, 2])
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_3(a=[1, 2])
    -
    -
    -        foo_4(a=[1, 2])
    -
    -    def test_dict(self):
    -        @pedantic
    -        def foo_1(a: Dict[str, int]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Dict) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_3(a: dict) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_4(a: dict[str, int]) -> None:
    -            print(a)
    -
    -        foo_1(a={'x': 2})
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a={'x': 2})
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_3(a={'x': 2})
    -
    -        foo_4(a={'x': 2})
    -
    -    def test_sequence(self):
    -        @pedantic
    -        def foo(a: Sequence[str]) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            foo(a=value)
    -
    -    def test_sequence_no_type_args(self):
    -        @pedantic
    -        def foo(a: Sequence) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo(a=value)
    -
    -    def test_iterable(self):
    -        @pedantic
    -        def foo(a: Iterable[str]) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            foo(a=value)
    -
    -    def test_iterable_no_type_args(self):
    -        @pedantic
    -        def foo(a: Iterable) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo(a=value)
    -
    -    def test_container(self):
    -        @pedantic
    -        def foo(a: Container[str]) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            foo(a=value)
    -
    -    def test_container_no_type_args(self):
    -        @pedantic
    -        def foo(a: Container) -> None:
    -            print(a)
    -
    -        for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo(a=value)
    -
    -    def test_set(self):
    -        @pedantic
    -        def foo_1(a: AbstractSet[int]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Set[int]) -> None:
    -            print(a)
    -
    -        for value in [set(), {6}]:
    -            foo_1(a=value)
    -            foo_2(a=value)
    -
    -    def test_set_no_type_args(self):
    -        @pedantic
    -        def foo_1(a: AbstractSet) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Set) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_3(a: set) -> None:
    -            print(a)
    -
    -        for value in [set(), {6}]:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo_1(a=value)
    -
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo_2(a=value)
    -
    -            with self.assertRaises(PedanticTypeCheckException):
    -                foo_3(a=value)
    -
    -    def test_tuple(self):
    -        @pedantic
    -        def foo_1(a: Tuple[int, int]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Tuple[int, ...]) -> None:
    -            print(a)
    -
    -        foo_1(a=(1, 2))
    -        foo_2(a=(1, 2))
    -
    -    def test_tuple_no_type_args(self):
    -        @pedantic
    -        def foo_1(a: Tuple) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: tuple) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_1(a=(1, 2))
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a=(1, 2))
    -
    -    def test_empty_tuple(self):
    -        @pedantic
    -        def foo(a: Tuple[()]) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=())
    -
    -    def test_class(self):
    -        @pedantic
    -        def foo_1(a: Type[Parent]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: Type[TypeVar('UnboundType')]) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_3(a: Type[TypeVar('BoundType', bound=Parent)]) -> None:
    -            print(a)
    -
    -        foo_1(a=Child)
    -        foo_2(a=Child)
    -        foo_3(a=Child)
    -
    -    def test_class_no_type_vars(self):
    -        @pedantic
    -        def foo_1(a: Type) -> None:
    -            print(a)
    -
    -        @pedantic
    -        def foo_2(a: type) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_1(a=Child)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a=Child)
    -
    -    def test_class_not_a_class(self):
    -        @pedantic
    -        def foo(a: Type[Parent]) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1)
    -
    -    def test_complex(self):
    -        @pedantic
    -        def foo(a: complex) -> None:
    -            print(a)
    -
    -        foo(a=complex(1, 5))
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1.0)
    -
    -    def test_float(self):
    -        @pedantic
    -        def foo(a: float) -> None:
    -            print(a)
    -
    -        foo(a=1.5)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=1)
    -
    -    def test_coroutine_correct_return_type(self):
    -        @pedantic
    -        async def foo() -> str:
    -            return 'foo'
    -
    -        coro = foo()
    -
    -        with self.assertRaises(StopIteration):
    -            coro.send(None)
    -
    -    def test_coroutine_wrong_return_type(self):
    -        @pedantic
    -        async def foo() -> str:
    -            return 1
    -
    -        coro = foo()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            coro.send(None)
    -
    -    def test_bytearray_bytes(self):
    -        @pedantic
    -        def foo(x: bytearray) -> None:
    -            pass
    -
    -        foo(x=bytearray([1]))
    -
    -    def test_class_decorator(self):
    -        @pedantic_class
    -        class Foo:
    -            @staticmethod
    -            def staticmethod() -> int:
    -                return 'foo'
    -
    -            @classmethod
    -            def classmethod(cls) -> int:
    -                return 'foo'
    -
    -            def method(self) -> int:
    -                return 'foo'
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            Foo.staticmethod()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            Foo.classmethod()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            Foo().method()
    -
    -    def test_generator(self):
    -        @pedantic
    -        def genfunc() -> Generator[int, str, List[str]]:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        gen = genfunc()
    -
    -        with self.assertRaises(StopIteration):
    -            value = next(gen)
    -            while True:
    -                value = gen.send(str(value))
    -                assert isinstance(value, int)
    -
    -    def test_generator_no_type_args(self):
    -        @pedantic
    -        def genfunc() -> Generator:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            genfunc()
    -
    -    def test_iterator(self):
    -        @pedantic
    -        def genfunc() -> Iterator[int]:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        gen = genfunc()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            value = next(gen)
    -            while True:
    -                value = gen.send(str(value))
    -                assert isinstance(value, int)
    -
    -    def test_iterator_no_type_args(self):
    -        @pedantic
    -        def genfunc() -> Iterator:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            genfunc()
    -
    -    def test_iterable_advanced(self):
    -        @pedantic
    -        def genfunc() -> Iterable[int]:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        gen = genfunc()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            value = next(gen)
    -            while True:
    -                value = gen.send(str(value))
    -                assert isinstance(value, int)
    -
    -    def test_iterable_advanced_no_type_args(self):
    -        @pedantic
    -        def genfunc() -> Iterable:
    -            val1 = yield 2
    -            val2 = yield 3
    -            val3 = yield 4
    -            return [val1, val2, val3]
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            genfunc()
    -
    -    def test_generator_bad_yield(self):
    -        @pedantic
    -        def genfunc_1() -> Generator[int, str, None]:
    -            yield 'foo'
    -
    -        @pedantic
    -        def genfunc_2() -> Iterable[int]:
    -            yield 'foo'
    -
    -        @pedantic
    -        def genfunc_3() -> Iterator[int]:
    -            yield 'foo'
    -
    -        gen = genfunc_1()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            next(gen)
    -
    -        gen = genfunc_2()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            next(gen)
    -
    -        gen = genfunc_3()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            next(gen)
    -
    -    def test_generator_bad_send(self):
    -        @pedantic
    -        def genfunc() -> Generator[int, str, None]:
    -            yield 1
    -            yield 2
    -
    -        gen = genfunc()
    -        next(gen)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            gen.send(2)
    -
    -    def test_generator_bad_return(self):
    -        @pedantic
    -        def genfunc() -> Generator[int, str, str]:
    -            yield 1
    -            return 6
    -
    -        gen = genfunc()
    -        next(gen)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            gen.send('foo')
    -
    -    def test_return_generator(self):
    -        @pedantic
    -        def genfunc() -> Generator[int, None, None]:
    -            yield 1
    -
    -        @pedantic
    -        def foo() -> Generator[int, None, None]:
    -            return genfunc()
    -
    -        foo()
    -
    -    def test_local_class(self):
    -        @pedantic_class
    -        class LocalClass:
    -            class Inner:
    -                pass
    -
    -            def create_inner(self) -> 'Inner':
    -                return self.Inner()
    -
    -        retval = LocalClass().create_inner()
    -        assert isinstance(retval, LocalClass.Inner)
    -
    -    def test_local_class_async(self):
    -        @pedantic_class
    -        class LocalClass:
    -            class Inner:
    -                pass
    -
    -            async def create_inner(self) -> 'Inner':
    -                return self.Inner()
    -
    -        coro = LocalClass().create_inner()
    -
    -        with self.assertRaises(StopIteration):
    -            coro.send(None)
    -
    -    def test_callable_nonmember(self):
    -        class CallableClass:
    -            def __call__(self):
    -                pass
    -
    -        @pedantic_class
    -        class LocalClass:
    -            some_callable = CallableClass()
    -
    -    def test_inherited_class_method(self):
    -        @pedantic_class
    -        class Parent:
    -            @classmethod
    -            def foo(cls, x: str) -> str:
    -                return cls.__name__
    -
    -        @pedantic_class
    -        class Child(Parent):
    -            pass
    -
    -        self.assertEqual('Parent', Child.foo(x='bar'))
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            Child.foo(x=1)
    -
    -    def test_type_var_forward_ref_bound(self):
    -        TBound = TypeVar('TBound', bound='Parent')
    -
    -        @pedantic
    -        def func(x: TBound) -> None:
    -            pass
    -
    -        func(x=Parent())
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            func(x='foo')
    -
    -    def test_noreturn(self):
    -        @pedantic
    -        def foo() -> NoReturn:
    -            pass
    -
    -        @pedantic
    -        def bar() -> NoReturn:
    -            raise ZeroDivisionError('bar')
    -
    -        with self.assertRaises(expected_exception=ZeroDivisionError):
    -            bar()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo()
    -
    -    def test_literal(self):
    -        @pedantic
    -        def foo(a: Literal[1, True, 'x', b'y', 404]) -> None:
    -            print(a)
    -
    -        foo(a=404)
    -        foo(a=True)
    -        foo(a='x')
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=4)
    -
    -    def test_literal_union(self):
    -        @pedantic
    -        def foo(a: Union[str, Literal[1, 6, 8]]) -> None:
    -            print(a)
    -
    -        foo(a=6)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=4)
    -
    -    def test_literal_illegal_value(self):
    -        @pedantic
    -        def foo(a: Literal[1, 1.1]) -> None:
    -            print(a)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=4)
    -
    -    def test_enum(self):
    -        with self.assertRaises(PedanticTypeCheckException):
    -            @pedantic_class
    -            class MyEnum(Enum):
    -                A = 'a'
    -
    -    def test_enum_aggregate(self):
    -        T = TypeVar('T', bound=IntEnum)
    -
    -        @pedantic_class
    -        class EnumAggregate(Generic[T]):
    -            enum: ClassVar[Type[T]]
    -
    -            def __init__(self, value: Union[int, str, List[T]]) -> None:
    -                assert len(self.enum) < 10
    -
    -                if value == '':
    -                    raise ValueError(f'Parameter "value" cannot be empty!')
    -
    -                if isinstance(value, list):
    -                    self._value = ''.join([str(x.value) for x in value])
    -                else:
    -                    self._value = str(value)
    -
    -                self._value = ''.join(sorted(self._value))  # sort characters in string
    -                self.to_list()  # check if is valid
    -
    -            def __contains__(self, item: T) -> bool:
    -                return item in self.to_list()
    -
    -            def __eq__(self, other: Union['EnumAggregate', str]) -> bool:
    -                if isinstance(other, str):
    -                    return self._value == other
    -
    -                return self._value == other._value
    -
    -            def __str__(self) -> str:
    -                return self._value
    -
    -            def to_list(self) -> List[T]:
    -                return [self.enum(int(character)) for character in self._value]
    -
    -            @property
    -            def value(self) -> str:
    -                return self._value
    -
    -            @classmethod
    -            def all(cls) -> str:
    -                return ''.join([str(x.value) for x in cls.enum])
    -
    -        class Gender(IntEnum):
    -            MALE = 1
    -            FEMALE = 2
    -            DIVERS = 3
    -
    -        @pedantic_class
    -        class Genders(EnumAggregate[Gender]):
    -            enum = Gender
    -
    -        Genders(value=12)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            Genders(value=Child())
    -
    -    def test_primitive_list_dict_tuple(self):
    -        @pedantic
    -        def f(x: list[dict[int, tuple[float, str]]]) -> list[Any]:
    -            return x
    -
    -        f(x=[{3: (3.24, 'hi')}])
    -
    -        for value in [
    -            [{3, (3, 'hi')}],
    -            [{3: (3, 'hi')}],
    -            [{3: (3.24, 3)}],
    -            [{3: (3.24, 'hi')}, {0}],
    -        ]:
    -            with self.assertRaises(PedanticTypeCheckException):
    -                f(x=value)
    -
    -    def test_dataclass_protocol(self):
    -        class IsDataclass(typing.Protocol):
    -            __dataclass_fields__: ClassVar[Dict]
    -
    -        @dataclass
    -        class Foo:
    -            v: int
    -
    -        @pedantic
    -        def foo(x: IsDataclass) -> IsDataclass:
    -            return x
    -
    -        foo(x=Foo(v=42))
    -
    -    def test_dataclass_protocol_in_type(self):
    -        class IsDataclass(typing.Protocol):
    -            __dataclass_fields__: ClassVar[Dict]
    -
    -        @dataclass
    -        class Foo:
    -            v: int
    -
    -        @pedantic
    -        def foo(x: type[IsDataclass]) -> IsDataclass:
    -            return x
    -
    -        assert foo(x=Foo) == Foo
    -
    -    def test_dataclass_protocol_in_type_with_union(self):
    -        class IsDataclass(typing.Protocol):
    -            __dataclass_fields__: ClassVar[Dict]
    -
    -        @dataclass
    -        class Foo:
    -            v: int
    -
    -        @pedantic
    -        def foo(x: type[None | bool | IsDataclass]) -> IsDataclass:
    -            return x
    -
    -        assert foo(x=Foo) == Foo
    -
    -    def test_partial_function(self):
    -        @pedantic
    -        def f(a: int, b: int) -> int:
    -            return a + b
    -
    -        g = pedantic(partial(f, a=1))
    -
    -        assert f(a=2, b=3) == 5
    -        assert g(b=3) == 4
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            f(a='2', b=3)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            g(b='2')
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def tearDown(self) ‑> None -
    -
    -
    - -Expand source code - -
    def tearDown(self) -> None:
    -    if os.path.isfile(TEST_FILE):
    -        os.remove(TEST_FILE)
    -
    -

    Hook method for deconstructing the test fixture after testing it.

    -
    -
    -def test_abstractset_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_abstractset_bad_element(self):
    -    @pedantic
    -    def foo(a: AbstractSet[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a={1, 2, 'bb'})
    -
    -
    -
    -
    -def test_abstractset_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_abstractset_bad_type(self):
    -    @pedantic
    -    def foo(a: AbstractSet[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_abstractset_custom_type(self) -
    -
    -
    - -Expand source code - -
    def test_abstractset_custom_type(self):
    -    T = TypeVar('T')
    -
    -    @pedantic_class
    -    class DummySet(AbstractSet[T]):
    -        def __contains__(self, x: object) -> bool:
    -            return x == 1
    -
    -        def __len__(self) -> T:
    -            return 1
    -
    -        def __iter__(self) -> Iterator[T]:
    -            yield 1
    -
    -    @pedantic
    -    def foo(a: AbstractSet[int]) -> None:
    -        pass
    -
    -    foo(a=DummySet[int]())
    -
    -
    -
    -
    -def test_additional_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_additional_kwargs(self):
    -    @pedantic
    -    def some_method(a: int, b: float = 0.0, **kwargs: int) -> float:
    -        return sum([a, b])
    -
    -    some_method(a=5)
    -    some_method(a=5, b=0.1)
    -    some_method(a=5, b=0.1, c=4)
    -    some_method(a=5, b=0.1, c=4, d=5, e=6)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_method(a=5, b=0.1, c=4, d=5.0, e=6)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_method(a=5.0, b=0.1, c=4, d=5, e=6)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        some_method(a=5, b=0, c=4, d=5, e=6)
    -
    -
    -
    -
    -def test_aliases(self) -
    -
    -
    - -Expand source code - -
    def test_aliases(self):
    -    Vector = List[float]
    -
    -    @pedantic
    -    def scale(scalar: float, vector: Vector) -> Vector:
    -        return [scalar * num for num in vector]
    -
    -    scale(scalar=2.0, vector=[1.0, -4.2, 5.4])
    -
    -
    -
    -
    -def test_all_ok_2(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_2(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> str:
    -        return str(n + m + i)
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_all_ok_3(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_3(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> None:
    -        str(n + m + i)
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_all_ok_4(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_4(self):
    -    @pedantic
    -    def calc(n: int) -> List[List[int]]:
    -        return [[n]]
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_all_ok_5(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_5(self):
    -    @pedantic
    -    def calc(n: int) -> List[Tuple[float, str]]:
    -        return [(float(n), str(n))]
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_all_ok_6(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_6(self):
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, str]:
    -            return n * float(x), str(y)
    -        return f
    -
    -    calc(n=42)(x=72, y=3.14)
    -
    -
    -
    -
    -def test_all_ok_7(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_7(self):
    -    @pedantic
    -    def calc(n: List[List[float]]) -> Any:
    -        return n[0][0]
    -
    -    calc(n=[[42.0]])
    -
    -
    -
    -
    -def test_all_ok_8(self) -
    -
    -
    - -Expand source code - -
    def test_all_ok_8(self):
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, str]:
    -            return n * float(x), str(y)
    -
    -        return f
    -
    -    calc(n=42)(x=3, y=3.14)
    -
    -
    -
    -
    -def test_alternative_list_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_alternative_list_type_hint(self):
    -    @pedantic
    -    def _is_digit_in_int(digit: [int], num: int) -> bool:
    -        num_str = str(num)
    -        for i in num_str:
    -            if int(i) == digit:
    -                return True
    -        return False
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        _is_digit_in_int(digit=4, num=42)
    -
    -
    -
    -
    -def test_any(self) -
    -
    -
    - -Expand source code - -
    def test_any(self):
    -    @pedantic
    -    def calc(ls: List[Any]) -> Dict[int, Any]:
    -        return {i: ls[i] for i in range(0, len(ls))}
    -
    -    calc(ls=[1, 2, 3])
    -    calc(ls=[1.11, 2.0, 3.0])
    -    calc(ls=['1', '2', '3'])
    -    calc(ls=[10.5, '2', (3, 4, 5)])
    -
    -
    -
    -
    -def test_any_type(self) -
    -
    -
    - -Expand source code - -
    def test_any_type(self):
    -    @pedantic
    -    def foo(a: Any) -> None:
    -        pass
    -
    -    foo(a='aa')
    -
    -
    -
    -
    -def test_args_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_args_kwargs(self):
    -    @pedantic
    -    def some_method(a: int = 0, b: float = 0.0) -> float:
    -        return a * b
    -
    -    @pedantic
    -    def wrapper_method(*args: Union[int, float], **kwargs: Union[int, float]) -> float:
    -        return some_method(*args, **kwargs)
    -
    -    some_method()
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        some_method(3, 3.0)
    -    some_method(a=3, b=3.0)
    -    wrapper_method()
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        wrapper_method(3, 3.0)
    -    wrapper_method(a=3, b=3.0)
    -
    -
    -
    -
    -def test_args_kwargs_different_types(self) -
    -
    -
    - -Expand source code - -
    def test_args_kwargs_different_types(self):
    -    @pedantic
    -    def foo(*args: str, **kwds: int) -> None:
    -        print(args)
    -        print(kwds)
    -
    -    foo('a', 'b', 'c')
    -    foo(x=1, y=2)
    -    foo('', z=0)
    -
    -
    -
    -
    -def test_args_kwargs_no_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_args_kwargs_no_type_hint(self):
    -    @pedantic
    -    def method_no_type_hint(*args, **kwargs) -> None:
    -        print(args)
    -        print(kwargs)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        method_no_type_hint(a=3, b=3.0)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        method_no_type_hint()
    -
    -
    -
    -
    -def test_args_kwargs_wrong_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_args_kwargs_wrong_type_hint(self):
    -    """See: https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values"""
    -    @pedantic
    -    def wrapper_method(*args: str, **kwargs: str) -> None:
    -        print(args)
    -        print(kwargs)
    -
    -    wrapper_method()
    -    wrapper_method('hi', 'you', ':)')
    -    wrapper_method(a='hi', b='you', c=':)')
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        wrapper_method('hi', 'you', ':)', 7)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        wrapper_method(3, 3.0)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        wrapper_method(a=3, b=3.0)
    -
    - -
    -
    -def test_binary_io(self) -
    -
    -
    - -Expand source code - -
    def test_binary_io(self):
    -    @pedantic
    -    def foo(a: BinaryIO) -> None:
    -        print(a)
    -
    -    foo(a=BytesIO())
    -
    -
    -
    -
    -def test_binary_io_fail(self) -
    -
    -
    - -Expand source code - -
    def test_binary_io_fail(self):
    -    @pedantic
    -    def foo(a: TextIO) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=BytesIO())
    -
    -
    -
    -
    -def test_binary_io_real_file(self) -
    -
    -
    - -Expand source code - -
    def test_binary_io_real_file(self):
    -    @pedantic
    -    def foo(a: BinaryIO) -> None:
    -        print(a)
    -
    -    with open(file=TEST_FILE, mode='wb') as f:
    -        foo(a=f)
    -
    -
    -
    -
    -def test_bytearray_bytes(self) -
    -
    -
    - -Expand source code - -
    def test_bytearray_bytes(self):
    -    @pedantic
    -    def foo(x: bytearray) -> None:
    -        pass
    -
    -    foo(x=bytearray([1]))
    -
    -
    -
    -
    -def test_callable(self) -
    -
    -
    - -Expand source code - -
    def test_callable(self):
    -    @pedantic
    -    def foo_1(a: Callable[..., int]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Callable) -> None:
    -        print(a)
    -
    -    def some_callable() -> int:
    -        return 4
    -
    -    foo_1(a=some_callable)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_2(a=some_callable)
    -
    -
    -
    -
    -def test_callable_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_callable_bad_type(self):
    -    @pedantic
    -    def foo(a: Callable[..., int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_callable_bound_method(self) -
    -
    -
    - -Expand source code - -
    def test_callable_bound_method(self):
    -    @pedantic
    -    def foo(callback: Callable[[int], Any]) -> None:
    -        pass
    -
    -    foo(callback=Child().method)
    -
    -
    -
    -
    -def test_callable_builtin(self) -
    -
    -
    - -Expand source code - -
    def test_callable_builtin(self):
    -    @pedantic
    -    def foo(callback: types.BuiltinFunctionType) -> None:
    -        pass
    -
    -    foo(callback=[].append)
    -
    -
    -
    -
    -def test_callable_class(self) -
    -
    -
    - -Expand source code - -
    def test_callable_class(self):
    -    """
    -    Test that passing a class as a callable does not count the "self" argument "a"gainst the
    -    ones declared in the Callable specification.
    -
    -    """
    -    @pedantic
    -    def foo(a: Callable[[int, str], Any]) -> None:
    -        pass
    -
    -    class SomeClass:
    -        def __init__(self, x: int, y: str):
    -            pass
    -
    -    foo(a=SomeClass)
    -
    -

    Test that passing a class as a callable does not count the "self" argument "a"gainst the -ones declared in the Callable specification.

    -
    -
    -def test_callable_defaults(self) -
    -
    -
    - -Expand source code - -
    def test_callable_defaults(self):
    -    """
    -    Test that a callable having "too many" arguments don't raise an error if the extra
    -    arguments have default values.
    -
    -    """
    -    @pedantic
    -    def foo(callback: Callable[[int, str], Any]) -> None:
    -        pass
    -
    -    def some_callable(x: int, y: str, z: float = 1.2) -> int:
    -        pass
    -
    -    foo(callback=some_callable)
    -
    -

    Test that a callable having "too many" arguments don't raise an error if the extra -arguments have default values.

    -
    -
    -def test_callable_exact_arg_count(self) -
    -
    -
    - -Expand source code - -
    def test_callable_exact_arg_count(self):
    -    @pedantic
    -    def foo(a: Callable[[int, str], int]) -> None:
    -        pass
    -
    -    def some_callable(x: int, y: str) -> int:
    -        pass
    -
    -    foo(a=some_callable)
    -
    -
    -
    -
    -def test_callable_mandatory_kwonlyargs(self) -
    -
    -
    - -Expand source code - -
    def test_callable_mandatory_kwonlyargs(self):
    -    @pedantic
    -    def foo(a: Callable[[int, str], int]) -> None:
    -        pass
    -
    -    def some_callable(x: int, y: str, *, z: float, bar: str) -> int:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=some_callable)
    -
    -
    -
    -
    -def test_callable_no_args(self) -
    -
    -
    - -Expand source code - -
    def test_callable_no_args(self):
    -    @pedantic
    -    def f(g: Callable[[], str]) -> str:
    -        return g()
    -
    -    @pedantic
    -    def greetings() -> str:
    -        return 'hello world'
    -
    -    f(g=greetings)
    -
    -
    -
    -
    -def test_callable_nonmember(self) -
    -
    -
    - -Expand source code - -
    def test_callable_nonmember(self):
    -    class CallableClass:
    -        def __call__(self):
    -            pass
    -
    -    @pedantic_class
    -    class LocalClass:
    -        some_callable = CallableClass()
    -
    -
    -
    -
    -def test_callable_plain(self) -
    -
    -
    - -Expand source code - -
    def test_callable_plain(self):
    -    @pedantic
    -    def foo(a: Callable[..., Any]) -> None:
    -        pass
    -
    -    def callback(a):
    -        pass
    -
    -    foo(a=callback)
    -
    -
    -
    -
    -def test_callable_too_few_arguments(self) -
    -
    -
    - -Expand source code - -
    def test_callable_too_few_arguments(self):
    -    @pedantic
    -    def foo(a: Callable[[int, str], int]) -> None:
    -        pass
    -
    -    def some_callable(x: int) -> int:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=some_callable)
    -
    -
    -
    -
    -def test_callable_with_union_return(self) -
    -
    -
    - -Expand source code - -
    def test_callable_with_union_return(self):
    -    class MyClass:
    -        pass
    -
    -    @pedantic
    -    def admin_required(func: Callable[..., Union[str, MyClass]]) -> Callable[..., Union[str, MyClass]]:
    -        @wraps(func)
    -        def decorated_function(*args, **kwargs):
    -            return func(*args, **kwargs)
    -        return decorated_function
    -
    -    @admin_required
    -    @pedantic
    -    def get_server_info() -> str:
    -        return 'info'
    -
    -    get_server_info()
    -
    -
    -
    -
    -def test_callable_without_args_correct_with_lambdas(self) -
    -
    -
    - -Expand source code - -
    def test_callable_without_args_correct_with_lambdas(self):
    -    @pedantic
    -    def calc(i: Callable[[Any], Tuple[Any, ...]]) -> str:
    -        return str(i(x=' you'))
    -
    -    calc(i=lambda x: (42.0, 43, 'hi', x))
    -
    -
    -
    -
    -def test_callable_without_args_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_callable_without_args_corrected(self):
    -    @pedantic
    -    def calc(i: Callable[[Any], Tuple[Any, ...]]) -> str:
    -        return str(i(x=' you'))
    -
    -    @pedantic
    -    def arg(x: Any) -> Tuple[Any, ...]:
    -        return 42.0, 43, 'hi', x
    -    calc(i=arg)
    -
    -
    -
    -
    -def test_callable_without_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_callable_without_type_args(self):
    -    @pedantic
    -    def calc(i: Callable) -> str:
    -        return str(i(' you'))
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=lambda x: (42.0, 43, 'hi', x))
    -
    -
    -
    -
    -def test_class(self) -
    -
    -
    - -Expand source code - -
    def test_class(self):
    -    @pedantic
    -    def foo_1(a: Type[Parent]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Type[TypeVar('UnboundType')]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_3(a: Type[TypeVar('BoundType', bound=Parent)]) -> None:
    -        print(a)
    -
    -    foo_1(a=Child)
    -    foo_2(a=Child)
    -    foo_3(a=Child)
    -
    -
    -
    -
    -def test_class_any(self) -
    -
    -
    - -Expand source code - -
    def test_class_any(self):
    -    @pedantic
    -    def foo(a: Type[Any]) -> None:
    -        pass
    -
    -    foo(a=str)
    -
    -
    -
    -
    -def test_class_bad_subclass(self) -
    -
    -
    - -Expand source code - -
    def test_class_bad_subclass(self):
    -    @pedantic
    -    def foo(a: Type[Child]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=Parent)
    -
    -
    -
    -
    -def test_class_decorator(self) -
    -
    -
    - -Expand source code - -
    def test_class_decorator(self):
    -    @pedantic_class
    -    class Foo:
    -        @staticmethod
    -        def staticmethod() -> int:
    -            return 'foo'
    -
    -        @classmethod
    -        def classmethod(cls) -> int:
    -            return 'foo'
    -
    -        def method(self) -> int:
    -            return 'foo'
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        Foo.staticmethod()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        Foo.classmethod()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        Foo().method()
    -
    -
    -
    -
    -def test_class_no_type_vars(self) -
    -
    -
    - -Expand source code - -
    def test_class_no_type_vars(self):
    -    @pedantic
    -    def foo_1(a: Type) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: type) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_1(a=Child)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_2(a=Child)
    -
    -
    -
    -
    -def test_class_not_a_class(self) -
    -
    -
    - -Expand source code - -
    def test_class_not_a_class(self):
    -    @pedantic
    -    def foo(a: Type[Parent]) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1)
    -
    -
    -
    -
    -def test_collection(self) -
    -
    -
    - -Expand source code - -
    def test_collection(self):
    -    @pedantic
    -    def foo(a: Collection) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=True)
    -
    -
    -
    -
    -def test_complex(self) -
    -
    -
    - -Expand source code - -
    def test_complex(self):
    -    @pedantic
    -    def foo(a: complex) -> None:
    -        print(a)
    -
    -    foo(a=complex(1, 5))
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1.0)
    -
    -
    -
    -
    -def test_container(self) -
    -
    -
    - -Expand source code - -
    def test_container(self):
    -    @pedantic
    -    def foo(a: Container[str]) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        foo(a=value)
    -
    -
    -
    -
    -def test_container_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_container_no_type_args(self):
    -    @pedantic
    -    def foo(a: Container) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=value)
    -
    -
    -
    -
    -def test_coroutine_correct_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_coroutine_correct_return_type(self):
    -    @pedantic
    -    async def foo() -> str:
    -        return 'foo'
    -
    -    coro = foo()
    -
    -    with self.assertRaises(StopIteration):
    -        coro.send(None)
    -
    -
    -
    -
    -def test_coroutine_wrong_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_coroutine_wrong_return_type(self):
    -    @pedantic
    -    async def foo() -> str:
    -        return 1
    -
    -    coro = foo()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        coro.send(None)
    -
    -
    -
    -
    -def test_dataclass_protocol(self) -
    -
    -
    - -Expand source code - -
    def test_dataclass_protocol(self):
    -    class IsDataclass(typing.Protocol):
    -        __dataclass_fields__: ClassVar[Dict]
    -
    -    @dataclass
    -    class Foo:
    -        v: int
    -
    -    @pedantic
    -    def foo(x: IsDataclass) -> IsDataclass:
    -        return x
    -
    -    foo(x=Foo(v=42))
    -
    -
    -
    -
    -def test_dataclass_protocol_in_type(self) -
    -
    -
    - -Expand source code - -
    def test_dataclass_protocol_in_type(self):
    -    class IsDataclass(typing.Protocol):
    -        __dataclass_fields__: ClassVar[Dict]
    -
    -    @dataclass
    -    class Foo:
    -        v: int
    -
    -    @pedantic
    -    def foo(x: type[IsDataclass]) -> IsDataclass:
    -        return x
    -
    -    assert foo(x=Foo) == Foo
    -
    -
    -
    -
    -def test_dataclass_protocol_in_type_with_union(self) -
    -
    -
    - -Expand source code - -
    def test_dataclass_protocol_in_type_with_union(self):
    -    class IsDataclass(typing.Protocol):
    -        __dataclass_fields__: ClassVar[Dict]
    -
    -    @dataclass
    -    class Foo:
    -        v: int
    -
    -    @pedantic
    -    def foo(x: type[None | bool | IsDataclass]) -> IsDataclass:
    -        return x
    -
    -    assert foo(x=Foo) == Foo
    -
    -
    -
    -
    -def test_date_datetime(self) -
    -
    -
    - -Expand source code - -
    def test_date_datetime(self):
    -    @pedantic
    -    def foo(a: datetime, b: date) -> None:
    -        pass
    -
    -    foo(a=datetime(1995, 2, 5), b=date(1987, 8, 7))
    -    foo(a=datetime(1995, 2, 5), b=datetime(1987, 8, 7))
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        foo(a=date(1995, 2, 5), b=date(1987, 8, 7))
    -
    -
    -
    -
    -def test_dict(self) -
    -
    -
    - -Expand source code - -
    def test_dict(self):
    -    @pedantic
    -    def foo_1(a: Dict[str, int]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Dict) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_3(a: dict) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_4(a: dict[str, int]) -> None:
    -        print(a)
    -
    -    foo_1(a={'x': 2})
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_2(a={'x': 2})
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_3(a={'x': 2})
    -
    -    foo_4(a={'x': 2})
    -
    -
    -
    -
    -def test_dict_bad_key_type(self) -
    -
    -
    - -Expand source code - -
    def test_dict_bad_key_type(self):
    -    @pedantic
    -    def foo(a: Dict[str, int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a={1: 2})
    -
    -
    -
    -
    -def test_dict_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_dict_bad_type(self):
    -    @pedantic
    -    def foo(a: Dict[str, int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_dict_bad_value_type(self) -
    -
    -
    - -Expand source code - -
    def test_dict_bad_value_type(self):
    -    @pedantic
    -    def foo(a: Dict[str, int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a={'x': 'a'})
    -
    -
    -
    -
    -def test_double_pedantic(self) -
    -
    -
    - -Expand source code - -
    def test_double_pedantic(self):
    -    @pedantic
    -    @pedantic
    -    def f(x: int, y: float) -> Tuple[float, str]:
    -        return float(x), str(y)
    -
    -    f(x=5, y=3.14)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f(x=5.0, y=3.14)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        f(5, 3.14)
    -
    -
    -
    -
    -def test_ellipsis_in_callable_1(self) -
    -
    -
    - -Expand source code - -
    def test_ellipsis_in_callable_1(self):
    -    @pedantic
    -    def calc(i: Callable[..., int]) -> int:
    -        return i()
    -
    -    @pedantic
    -    def call() -> int:
    -        return 42
    -
    -    calc(i=call)
    -
    -
    -
    -
    -def test_ellipsis_in_callable_2(self) -
    -
    -
    - -Expand source code - -
    def test_ellipsis_in_callable_2(self):
    -    @pedantic
    -    def calc(i: Callable[..., int]) -> int:
    -        return i(x=3.14, y=5)
    -
    -    @pedantic
    -    def call(x: float, y: int) -> int:
    -        return 42
    -
    -    calc(i=call)
    -
    -
    -
    -
    -def test_ellipsis_in_callable_3(self) -
    -
    -
    - -Expand source code - -
    def test_ellipsis_in_callable_3(self):
    -    """Problem here: call to "call" misses one argument"""
    -    @pedantic
    -    def calc(i: Callable[..., int]) -> int:
    -        return i(x=3.14)
    -
    -    @pedantic
    -    def call(x: float, y: int) -> int:
    -        return 42
    -
    -    with self.assertRaises(expected_exception=PedanticException):
    -        calc(i=call)
    -
    -

    Problem here: call to "call" misses one argument

    -
    -
    -def test_empty_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_empty_tuple(self):
    -    @pedantic
    -    def foo(a: Tuple[()]) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=())
    -
    -
    -
    -
    -def test_enum(self) -
    -
    -
    - -Expand source code - -
    def test_enum(self):
    -    with self.assertRaises(PedanticTypeCheckException):
    -        @pedantic_class
    -        class MyEnum(Enum):
    -            A = 'a'
    -
    -
    -
    -
    -def test_enum_1(self) -
    -
    -
    - -Expand source code - -
    def test_enum_1(self):
    -    """Problem here: Type hint for 'a' should be MyEnum instead of MyEnum.GAMMA"""
    -    class MyEnum(Enum):
    -        ALPHA = 'startEvent'
    -        BETA = 'task'
    -        GAMMA = 'sequenceFlow'
    -
    -    class MyClass:
    -        @pedantic
    -        def operation(self, a: MyEnum.GAMMA) -> None:
    -            print(a)
    -
    -    m = MyClass()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.operation(a=MyEnum.GAMMA)
    -
    -

    Problem here: Type hint for 'a' should be MyEnum instead of MyEnum.GAMMA

    -
    -
    -def test_enum_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_enum_1_corrected(self):
    -    class MyEnum(Enum):
    -        ALPHA = 'startEvent'
    -        BETA = 'task'
    -        GAMMA = 'sequenceFlow'
    -
    -    @pedantic
    -    def operation(a: MyEnum) -> None:
    -        print(a)
    -
    -    operation(a=MyEnum.GAMMA)
    -
    -
    -
    -
    -def test_enum_aggregate(self) -
    -
    -
    - -Expand source code - -
    def test_enum_aggregate(self):
    -    T = TypeVar('T', bound=IntEnum)
    -
    -    @pedantic_class
    -    class EnumAggregate(Generic[T]):
    -        enum: ClassVar[Type[T]]
    -
    -        def __init__(self, value: Union[int, str, List[T]]) -> None:
    -            assert len(self.enum) < 10
    -
    -            if value == '':
    -                raise ValueError(f'Parameter "value" cannot be empty!')
    -
    -            if isinstance(value, list):
    -                self._value = ''.join([str(x.value) for x in value])
    -            else:
    -                self._value = str(value)
    -
    -            self._value = ''.join(sorted(self._value))  # sort characters in string
    -            self.to_list()  # check if is valid
    -
    -        def __contains__(self, item: T) -> bool:
    -            return item in self.to_list()
    -
    -        def __eq__(self, other: Union['EnumAggregate', str]) -> bool:
    -            if isinstance(other, str):
    -                return self._value == other
    -
    -            return self._value == other._value
    -
    -        def __str__(self) -> str:
    -            return self._value
    -
    -        def to_list(self) -> List[T]:
    -            return [self.enum(int(character)) for character in self._value]
    -
    -        @property
    -        def value(self) -> str:
    -            return self._value
    -
    -        @classmethod
    -        def all(cls) -> str:
    -            return ''.join([str(x.value) for x in cls.enum])
    -
    -    class Gender(IntEnum):
    -        MALE = 1
    -        FEMALE = 2
    -        DIVERS = 3
    -
    -    @pedantic_class
    -    class Genders(EnumAggregate[Gender]):
    -        enum = Gender
    -
    -    Genders(value=12)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        Genders(value=Child())
    -
    -
    -
    -
    -def test_float(self) -
    -
    -
    - -Expand source code - -
    def test_float(self):
    -    @pedantic
    -    def foo(a: float) -> None:
    -        print(a)
    -
    -    foo(a=1.5)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1)
    -
    -
    -
    -
    -def test_forward_ref(self) -
    -
    -
    - -Expand source code - -
    def test_forward_ref(self):
    -    class Conversation:
    -        pass
    -
    -    @pedantic
    -    def get_conversations() -> List['Conversation']:
    -        return [Conversation(), Conversation()]
    -
    -    get_conversations()
    -
    -
    -
    -
    -def test_generator(self) -
    -
    -
    - -Expand source code - -
    def test_generator(self):
    -    @pedantic
    -    def genfunc() -> Generator[int, str, List[str]]:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    gen = genfunc()
    -
    -    with self.assertRaises(StopIteration):
    -        value = next(gen)
    -        while True:
    -            value = gen.send(str(value))
    -            assert isinstance(value, int)
    -
    -
    -
    -
    -def test_generator_bad_return(self) -
    -
    -
    - -Expand source code - -
    def test_generator_bad_return(self):
    -    @pedantic
    -    def genfunc() -> Generator[int, str, str]:
    -        yield 1
    -        return 6
    -
    -    gen = genfunc()
    -    next(gen)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        gen.send('foo')
    -
    -
    -
    -
    -def test_generator_bad_send(self) -
    -
    -
    - -Expand source code - -
    def test_generator_bad_send(self):
    -    @pedantic
    -    def genfunc() -> Generator[int, str, None]:
    -        yield 1
    -        yield 2
    -
    -    gen = genfunc()
    -    next(gen)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        gen.send(2)
    -
    -
    -
    -
    -def test_generator_bad_yield(self) -
    -
    -
    - -Expand source code - -
    def test_generator_bad_yield(self):
    -    @pedantic
    -    def genfunc_1() -> Generator[int, str, None]:
    -        yield 'foo'
    -
    -    @pedantic
    -    def genfunc_2() -> Iterable[int]:
    -        yield 'foo'
    -
    -    @pedantic
    -    def genfunc_3() -> Iterator[int]:
    -        yield 'foo'
    -
    -    gen = genfunc_1()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        next(gen)
    -
    -    gen = genfunc_2()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        next(gen)
    -
    -    gen = genfunc_3()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        next(gen)
    -
    -
    -
    -
    -def test_generator_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_generator_no_type_args(self):
    -    @pedantic
    -    def genfunc() -> Generator:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        genfunc()
    -
    -
    -
    -
    -def test_generator_simple(self) -
    -
    -
    - -Expand source code - -
    def test_generator_simple(self):
    -    """Test that argument type checking works in a generator function too."""
    -    @pedantic
    -    def generate(a: int) -> Generator[int, int, None]:
    -        yield a
    -        yield a + 1
    -
    -    gen = generate(a=1)
    -    next(gen)
    -
    -

    Test that argument type checking works in a generator function too.

    -
    -
    -def test_generic(self) -
    -
    -
    - -Expand source code - -
    def test_generic(self):
    -    T_Foo = TypeVar('T_Foo')
    -
    -    class FooGeneric(Generic[T_Foo]):
    -        pass
    -
    -    @pedantic
    -    def foo(a: FooGeneric[str]) -> None:
    -        print(a)
    -
    -    foo(a=FooGeneric[str]())
    -
    -
    -
    -
    -def test_implicit_default_none(self) -
    -
    -
    - -Expand source code - -
    def test_implicit_default_none(self):
    -    """
    -    Test that if the default value is ``None``, a ``None`` argument can be passed.
    -
    -    """
    -    @pedantic
    -    def foo(a: Optional[str] = None) -> None:
    -        pass
    -
    -    foo()
    -
    -

    Test that if the default value is None, a None argument can be passed.

    -
    -
    -def test_inheritance_1(self) -
    -
    -
    - -Expand source code - -
    def test_inheritance_1(self):
    -    class MyClassA:
    -        pass
    -
    -    class MyClassB(MyClassA):
    -        pass
    -
    -    @pedantic
    -    def calc(a: MyClassA) -> str:
    -        return str(a)
    -
    -    calc(a=MyClassA())
    -    calc(a=MyClassB())
    -
    -
    -
    -
    -def test_inheritance_2(self) -
    -
    -
    - -Expand source code - -
    def test_inheritance_2(self):
    -    """Problem here: A is not a subtype of B"""
    -    class MyClassA:
    -        pass
    -
    -    class MyClassB(MyClassA):
    -        pass
    -
    -    @pedantic
    -    def calc(a: MyClassB) -> str:
    -        return str(a)
    -
    -    calc(a=MyClassB())
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(a=MyClassA())
    -
    -

    Problem here: A is not a subtype of B

    -
    -
    -def test_inherited_class_method(self) -
    -
    -
    - -Expand source code - -
    def test_inherited_class_method(self):
    -    @pedantic_class
    -    class Parent:
    -        @classmethod
    -        def foo(cls, x: str) -> str:
    -            return cls.__name__
    -
    -    @pedantic_class
    -    class Child(Parent):
    -        pass
    -
    -    self.assertEqual('Parent', Child.foo(x='bar'))
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        Child.foo(x=1)
    -
    -
    -
    -
    -def test_instance_method_1(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_1(self):
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: int) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    a.calc(i=42)
    -
    -
    -
    -
    -def test_instance_method_2(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_2(self):
    -    """Problem here: 'i' has no type annotation"""
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        a.calc(i=42)
    -
    -

    Problem here: 'i' has no type annotation

    -
    -
    -def test_instance_method_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_2_corrected(self):
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: int) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    a.calc(i=42)
    -
    -
    -
    -
    -def test_instance_method_3_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_3_corrected(self):
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: float) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    a.calc(i=42.0)
    -
    -
    -
    -
    -def test_instance_method_5(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_5(self):
    -    """Problem here: instance methods is not called with kwargs"""
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: int) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    a.calc(i=42)
    -
    -

    Problem here: instance methods is not called with kwargs

    -
    -
    -def test_instance_method_int_is_not_float(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_int_is_not_float(self):
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: float) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        a.calc(i=42)
    -
    -
    -
    -
    -def test_instance_method_no_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_instance_method_no_kwargs(self):
    -    class MyClassA:
    -        @pedantic
    -        def calc(self, i: int) -> str:
    -            return str(i)
    -
    -    a = MyClassA()
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        a.calc(42)
    -
    -
    -
    -
    -def test_is_subtype_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_is_subtype_tuple(self):
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        @pedantic
    -        def foo() -> Callable[[Tuple[float, str]], Tuple[int]]:
    -            def bar(a: Tuple[float]) -> Tuple[int]:
    -                return len(a[1]) + int(a[0]),
    -            return bar
    -        foo()
    -
    -
    -
    -
    -def test_is_subtype_tuple_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_is_subtype_tuple_corrected(self):
    -    @pedantic
    -    def foo() -> Callable[[Tuple[float, str]], Tuple[int]]:
    -        def bar(a: Tuple[float, str]) -> Tuple[int]:
    -            return len(a[1]) + int(a[0]),
    -        return bar
    -    foo()
    -
    -
    -
    -
    -def test_iterable(self) -
    -
    -
    - -Expand source code - -
    def test_iterable(self):
    -    @pedantic
    -    def foo(a: Iterable[str]) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        foo(a=value)
    -
    -
    -
    -
    -def test_iterable_advanced(self) -
    -
    -
    - -Expand source code - -
    def test_iterable_advanced(self):
    -    @pedantic
    -    def genfunc() -> Iterable[int]:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    gen = genfunc()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        value = next(gen)
    -        while True:
    -            value = gen.send(str(value))
    -            assert isinstance(value, int)
    -
    -
    -
    -
    -def test_iterable_advanced_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_iterable_advanced_no_type_args(self):
    -    @pedantic
    -    def genfunc() -> Iterable:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        genfunc()
    -
    -
    -
    -
    -def test_iterable_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_iterable_no_type_args(self):
    -    @pedantic
    -    def foo(a: Iterable) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=value)
    -
    -
    -
    -
    -def test_iterator(self) -
    -
    -
    - -Expand source code - -
    def test_iterator(self):
    -    @pedantic
    -    def genfunc() -> Iterator[int]:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    gen = genfunc()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        value = next(gen)
    -        while True:
    -            value = gen.send(str(value))
    -            assert isinstance(value, int)
    -
    -
    -
    -
    -def test_iterator_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_iterator_no_type_args(self):
    -    @pedantic
    -    def genfunc() -> Iterator:
    -        val1 = yield 2
    -        val2 = yield 3
    -        val3 = yield 4
    -        return [val1, val2, val3]
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        genfunc()
    -
    -
    -
    -
    -def test_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_kwargs(self):
    -    @pedantic
    -    def foo(**kwargs: int) -> None:
    -        pass
    -
    -    foo(a=1, b=2)
    -
    -
    -
    -
    -def test_kwargs_fail(self) -
    -
    -
    - -Expand source code - -
    def test_kwargs_fail(self):
    -    @pedantic
    -    def foo(**kwargs: int) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1, b='a')
    -
    -
    -
    -
    -def test_lambda_1(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_1(self):
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        return lambda x: str(x * i)
    -
    -    calc(i=42.0)(10.0)
    -
    -
    -
    -
    -def test_lambda_3(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_3(self):
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        def res(x: float) -> str:
    -            return str(x * i)
    -        return res
    -
    -    calc(i=42.0)(10.0)
    -
    -
    -
    -
    -def test_lambda_4_almost_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_4_almost_corrected(self):
    -    """Problem here: float != str"""
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        @pedantic
    -        def res(x: int) -> str:
    -            return str(x * i)
    -        return res
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=42.0)(x=10)
    -
    -

    Problem here: float != str

    -
    -
    -def test_lambda_4_almost_corrected_2(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_4_almost_corrected_2(self):
    -    @pedantic
    -    def calc(i: float) -> Callable[[int], str]:
    -        @pedantic
    -        def res(x: int) -> str:
    -            return str(x * i)
    -        return res
    -
    -    calc(i=42.0)(x=10)
    -
    -
    -
    -
    -def test_lambda_5(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_5(self):
    -    """Problem here: float != int"""
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        @pedantic
    -        def res(x: float) -> str:
    -            return str(x * i)
    -        return res
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=42.0)(x=10)
    -
    -

    Problem here: float != int

    -
    -
    -def test_lambda_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_corrected(self):
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        @pedantic
    -        def res(x: float) -> str:
    -            return str(x * i)
    -
    -        return res
    -
    -    calc(i=42.0)(x=10.0)
    -
    -
    -
    -
    -def test_lambda_int_is_not_float(self) -
    -
    -
    - -Expand source code - -
    def test_lambda_int_is_not_float(self):
    -    @pedantic
    -    def calc(i: float) -> Callable[[float], str]:
    -        def res(x: int) -> str:
    -            return str(x * i)
    -        return res
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=42.0)(x=10)
    -
    -
    -
    -
    -def test_list(self) -
    -
    -
    - -Expand source code - -
    def test_list(self):
    -    @pedantic
    -    def foo_1(a: List[int]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: List) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_3(a: list) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_4(a: list[int]) -> None:
    -        print(a)
    -
    -    foo_1(a=[1, 2])
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_2(a=[1, 2])
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_3(a=[1, 2])
    -
    -
    -    foo_4(a=[1, 2])
    -
    -
    -
    -
    -def test_list_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_list_bad_element(self):
    -    @pedantic
    -    def foo(a: List[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=[1, 2, 'bb'])
    -
    -
    -
    -
    -def test_list_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_list_bad_type(self):
    -    @pedantic
    -    def foo(a: List[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_list_of_new_type(self) -
    -
    -
    - -Expand source code - -
    def test_list_of_new_type(self):
    -    UserId = NewType('UserId', int)
    -
    -    @pedantic
    -    def get_user_name(user_ids: List[UserId]) -> str:
    -        return str(user_ids)
    -
    -    get_user_name(user_ids=[UserId(524313), UserId(42)])
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        get_user_name(user_ids=[UserId(524313), UserId(42), 430.0])
    -
    -
    -
    -
    -def test_list_without_args(self) -
    -
    -
    - -Expand source code - -
    def test_list_without_args(self):
    -    @pedantic
    -    def calc(i: List) -> Any:
    -        return [i]
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=[42.0, 43, 'hi'])
    -
    -
    -
    -
    -def test_list_without_args_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_list_without_args_corrected(self):
    -    @pedantic
    -    def calc(i: List[Any]) -> List[List[Any]]:
    -        return [i]
    -
    -    calc(i=[42.0, 43, 'hi'])
    -
    -
    -
    -
    -def test_literal(self) -
    -
    -
    - -Expand source code - -
    def test_literal(self):
    -    @pedantic
    -    def foo(a: Literal[1, True, 'x', b'y', 404]) -> None:
    -        print(a)
    -
    -    foo(a=404)
    -    foo(a=True)
    -    foo(a='x')
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=4)
    -
    -
    -
    -
    -def test_literal_illegal_value(self) -
    -
    -
    - -Expand source code - -
    def test_literal_illegal_value(self):
    -    @pedantic
    -    def foo(a: Literal[1, 1.1]) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=4)
    -
    -
    -
    -
    -def test_literal_union(self) -
    -
    -
    - -Expand source code - -
    def test_literal_union(self):
    -    @pedantic
    -    def foo(a: Union[str, Literal[1, 6, 8]]) -> None:
    -        print(a)
    -
    -    foo(a=6)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=4)
    -
    -
    -
    -
    -def test_local_class(self) -
    -
    -
    - -Expand source code - -
    def test_local_class(self):
    -    @pedantic_class
    -    class LocalClass:
    -        class Inner:
    -            pass
    -
    -        def create_inner(self) -> 'Inner':
    -            return self.Inner()
    -
    -    retval = LocalClass().create_inner()
    -    assert isinstance(retval, LocalClass.Inner)
    -
    -
    -
    -
    -def test_local_class_async(self) -
    -
    -
    - -Expand source code - -
    def test_local_class_async(self):
    -    @pedantic_class
    -    class LocalClass:
    -        class Inner:
    -            pass
    -
    -        async def create_inner(self) -> 'Inner':
    -            return self.Inner()
    -
    -    coro = LocalClass().create_inner()
    -
    -    with self.assertRaises(StopIteration):
    -        coro.send(None)
    -
    -
    -
    -
    -def test_marco(self) -
    -
    -
    - -Expand source code - -
    def test_marco(self):
    -    @pedantic_class
    -    class A:
    -        def __init__(self, val: int) -> None:
    -            self.val = val
    -
    -        def __eq__(self, other: 'A') -> bool:  # other: A and all subclasses
    -            return self.val == other.val
    -
    -    @pedantic_class
    -    class B(A):
    -        def __init__(self, val: int) -> None:
    -            super().__init__(val=val)
    -
    -    @pedantic_class
    -    class C(A):
    -        def __init__(self, val: int) -> None:
    -            super().__init__(val=val)
    -
    -    a = A(val=42)
    -    b = B(val=42)
    -    c = C(val=42)
    -
    -    assert a == b  # works
    -    assert a == c  # works
    -    assert b == c  # error
    -
    -
    -
    -
    -def test_mismatching_default_type(self) -
    -
    -
    - -Expand source code - -
    def test_mismatching_default_type(self):
    -    @pedantic
    -    def foo(a: str = 1) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo()
    -
    -
    -
    -
    -def test_missing_type_hint_1(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_1(self):
    -    """Problem here: type hint for n missed"""
    -    @pedantic
    -    def calc(n) -> float:
    -        return 42.0 * n
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)
    -
    -

    Problem here: type hint for n missed

    -
    -
    -def test_missing_type_hint_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_1_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> float:
    -        return 42.0 * n
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_missing_type_hint_2(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_2(self):
    -    """Problem here: Return type annotation missed"""
    -    @pedantic
    -    def calc(n: int):
    -        return 'Hi' + str(n)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)
    -
    -

    Problem here: Return type annotation missed

    -
    -
    -def test_missing_type_hint_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_2_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> str:
    -        return 'Hi' + str(n)
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_missing_type_hint_3(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_3(self):
    -    """Problem here: type hint for i missed"""
    -    @pedantic
    -    def calc(n: int, m: int, i) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=38)
    -
    -

    Problem here: type hint for i missed

    -
    -
    -def test_missing_type_hint_3_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_missing_type_hint_3_corrected(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_namedtuple(self) -
    -
    -
    - -Expand source code - -
    def test_namedtuple(self):
    -    Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -    @pedantic
    -    def foo(bar: Employee) -> None:
    -        print(bar)
    -
    -    foo(bar=Employee('bob', 1))
    -
    -
    -
    -
    -def test_namedtuple_huge_type_mismatch(self) -
    -
    -
    - -Expand source code - -
    def test_namedtuple_huge_type_mismatch(self):
    -    Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -    @pedantic
    -    def foo(bar: int) -> None:
    -        print(bar)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(bar=foo(bar=Employee('bob', 1)))
    -
    -
    -
    -
    -def test_namedtuple_key_mismatch(self) -
    -
    -
    - -Expand source code - -
    def test_namedtuple_key_mismatch(self):
    -    Employee1 = NamedTuple('Employee', [('name', str), ('id', int)])
    -    Employee2 = NamedTuple('Employee', [('firstname', str), ('id', int)])
    -
    -    @pedantic
    -    def foo(bar: Employee1) -> None:
    -        print(bar)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(bar=Employee2('bob', 1))
    -
    -
    -
    -
    -def test_namedtuple_type_mismatch(self) -
    -
    -
    - -Expand source code - -
    def test_namedtuple_type_mismatch(self):
    -    Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -    @pedantic
    -    def foo(bar: Employee) -> None:
    -        print(bar)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(bar=('bob', 1))
    -
    -
    -
    -
    -def test_namedtuple_wrong_field_type(self) -
    -
    -
    - -Expand source code - -
    def test_namedtuple_wrong_field_type(self):
    -    Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    -
    -    @pedantic
    -    def foo(bar: Employee) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(bar=Employee(2, 1))
    -
    -
    -
    -
    -def test_nested_type_hints_1(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_1(self):
    -    @pedantic
    -    def calc(n: int) -> List[List[float]]:
    -        return [0.0 * n]
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)
    -
    -
    -
    -
    -def test_nested_type_hints_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_1_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> List[List[float]]:
    -        return [[0.0 * n]]
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_nested_type_hints_2(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_2(self):
    -    """Problem here: int != float"""
    -    @pedantic
    -    def calc(n: int) -> List[Tuple[float, str]]:
    -        return [(n, str(n))]
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)
    -
    -

    Problem here: int != float

    -
    -
    -def test_nested_type_hints_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_2_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> List[Tuple[int, str]]:
    -        return [(n, str(n))]
    -
    -    @pedantic
    -    def calc_2(n: float) -> List[Tuple[float, str]]:
    -        return [(n, str(n))]
    -
    -    calc(n=42)
    -    calc_2(n=42.0)
    -
    -
    -
    -
    -def test_nested_type_hints_3(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_3(self):
    -    """Problem here: inner function actually returns Tuple[int, str]"""
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, str]:
    -            return n * x, str(y)
    -        return f
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)(x=3, y=3.14)
    -
    -

    Problem here: inner function actually returns Tuple[int, str]

    -
    -
    -def test_nested_type_hints_3_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_3_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[int, str]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[int, str]:
    -            return n * x, str(y)
    -
    -        return f
    -
    -    calc(n=42)(x=3, y=3.14)
    -
    -
    -
    -
    -def test_nested_type_hints_4(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_4(self):
    -    """Problem here: return type is actually float"""
    -    @pedantic
    -    def calc(n: List[List[float]]) -> int:
    -        return n[0][0]
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=[[42.0]])
    -
    -

    Problem here: return type is actually float

    -
    -
    -def test_nested_type_hints_5(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_5(self):
    -    """Problem here: Tuple[float, str] != Tuple[float, float]"""
    -
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[float, str]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, float]:
    -            return n * float(x), y
    -        return f
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42)
    -
    -

    Problem here: Tuple[float, str] != Tuple[float, float]

    -
    -
    -def test_nested_type_hints_5_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_5_corrected(self):
    -    @pedantic
    -    def calc(n: int) -> Callable[[int, float], Tuple[float, float]]:
    -        @pedantic
    -        def f(x: int, y: float) -> Tuple[float, float]:
    -            return n * float(x), y
    -        return f
    -
    -    calc(n=42)
    -
    -
    -
    -
    -def test_nested_type_hints_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_nested_type_hints_corrected(self):
    -    @pedantic
    -    def calc(n: List[List[float]]) -> int:
    -        return int(n[0][0])
    -
    -    calc(n=[[42.0]])
    -
    -
    -
    -
    -def test_new_type(self) -
    -
    -
    - -Expand source code - -
    def test_new_type(self):
    -    UserId = NewType('UserId', int)
    -
    -    @pedantic
    -    def get_user_name(user_id: UserId) -> str:
    -        return str(user_id)
    -
    -    some_id = UserId(524313)
    -    get_user_name(user_id=some_id)
    -
    -    # the following would be desirable but impossible to check at runtime:
    -    # with self.assertRaises(expected_exception=AssertionError):
    -    #     get_user_name(user_id=-1)
    -
    -
    -
    -
    -def test_newtype(self) -
    -
    -
    - -Expand source code - -
    def test_newtype(self):
    -    myint = NewType("myint", int)
    -
    -    @pedantic
    -    def foo(a: myint) -> int:
    -        return 42
    -
    -    assert foo(a=1) == 42
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a="a")
    -
    -
    -
    -
    -def test_no_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_no_kwargs(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        calc(42, 40, 38)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        calc(42, m=40, i=38)
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_none_1(self) -
    -
    -
    - -Expand source code - -
    def test_none_1(self):
    -    """Problem here: None is not accepted"""
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=None)
    -
    -

    Problem here: None is not accepted

    -
    -
    -def test_none_2(self) -
    -
    -
    - -Expand source code - -
    def test_none_2(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: Optional[int]) -> int:
    -        return n + m + i if i is not None else n + m
    -
    -    calc(n=42, m=40, i=None)
    -
    -
    -
    -
    -def test_none_3(self) -
    -
    -
    - -Expand source code - -
    def test_none_3(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: Union[int, None]) -> int:
    -        return n + m + i if i is not None else n + m
    -
    -    calc(n=42, m=40, i=None)
    -
    -
    -
    -
    -def test_none_4(self) -
    -
    -
    - -Expand source code - -
    def test_none_4(self):
    -    """Problem here: function may return None"""
    -    @pedantic
    -    def calc(n: int, m: int, i: Union[int, None]) -> int:
    -        return n + m + i if i is not None else None
    -
    -    calc(n=42, m=40, i=42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=None)
    -
    -

    Problem here: function may return None

    -
    -
    -def test_none_5(self) -
    -
    -
    - -Expand source code - -
    def test_none_5(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: Union[int, None]) -> Optional[int]:
    -        return n + m + i if i is not None else None
    -
    -    calc(n=42, m=40, i=None)
    -
    -
    -
    -
    -def test_noreturn(self) -
    -
    -
    - -Expand source code - -
    def test_noreturn(self):
    -    @pedantic
    -    def foo() -> NoReturn:
    -        pass
    -
    -    @pedantic
    -    def bar() -> NoReturn:
    -        raise ZeroDivisionError('bar')
    -
    -    with self.assertRaises(expected_exception=ZeroDivisionError):
    -        bar()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo()
    -
    -
    -
    -
    -def test_optional_args_1(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_1(self):
    -    @pedantic
    -    def calc(a: int, b: int = 42) -> int:
    -        return a + b
    -
    -    calc(a=2)
    -
    -
    -
    -
    -def test_optional_args_2(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_2(self):
    -    @pedantic
    -    def calc(a: int = 3, b: int = 42, c: float = 5.0) -> float:
    -        return a + b + c
    -
    -    calc()
    -    calc(a=1)
    -    calc(b=1)
    -    calc(c=1.0)
    -    calc(a=1, b=1)
    -    calc(a=1, c=1.0)
    -    calc(b=1, c=1.0)
    -    calc(a=1, b=1, c=1.0)
    -
    -
    -
    -
    -def test_optional_args_3(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_3(self):
    -    """Problem here: optional argument c: 5 is not a float"""
    -    @pedantic
    -    def calc(a: int = 3, b: int = 42, c: float = 5) -> float:
    -        return a + b + c
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc()
    -
    -

    Problem here: optional argument c: 5 is not a float

    -
    -
    -def test_optional_args_3_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_3_corrected(self):
    -    @pedantic
    -    def calc(a: int = 3, b: int = 42, c: float = 5.0) -> float:
    -        return a + b + c
    -
    -    calc()
    -
    -
    -
    -
    -def test_optional_args_4(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_4(self):
    -    class MyClass:
    -        @pedantic
    -        def foo(self, a: int, b: Optional[int] = 1) -> int:
    -            return a + b
    -
    -    my_class = MyClass()
    -    my_class.foo(a=10)
    -
    -
    -
    -
    -def test_optional_args_5(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_5(self):
    -    @pedantic
    -    def calc(d: Optional[Dict[int, int]] = None) -> Optional[int]:
    -        if d is None:
    -            return None
    -        return sum(d.keys())
    -
    -    calc(d=None)
    -    calc()
    -    calc(d={42: 3})
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(d={42: 3.14})
    -
    -
    -
    -
    -def test_optional_args_6(self) -
    -
    -
    - -Expand source code - -
    def test_optional_args_6(self):
    -    """"Problem here: str != int"""
    -    @pedantic
    -    def calc(d: int = 42) -> int:
    -        return int(d)
    -
    -    calc(d=99999)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(d='999999')
    -
    -

    "Problem here: str != int

    -
    -
    -def test_partial_function(self) -
    -
    -
    - -Expand source code - -
    def test_partial_function(self):
    -    @pedantic
    -    def f(a: int, b: int) -> int:
    -        return a + b
    -
    -    g = pedantic(partial(f, a=1))
    -
    -    assert f(a=2, b=3) == 5
    -    assert g(b=3) == 4
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        f(a='2', b=3)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        g(b='2')
    -
    -
    -
    -
    -def test_pedantic(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic(self):
    -    @pedantic
    -    def foo(a: int, b: str) -> str:
    -        return 'abc'
    -
    -    self.assertEqual('abc', foo(a=4, b='abc'))
    -
    -
    -
    -
    -def test_pedantic_always(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_always(self):
    -    @pedantic
    -    def foo(a: int, b: str) -> str:
    -        return 'abc'
    -
    -    self.assertEqual('abc', foo(a=4, b='abc'))
    -
    -
    -
    -
    -def test_pedantic_arguments_fail(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_arguments_fail(self):
    -    @pedantic
    -    def foo(a: int, b: str) -> str:
    -        return 'abc'
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        foo(a=4, b=5)
    -
    -
    -
    -
    -def test_pedantic_on_class(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_on_class(self):
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        @pedantic
    -        class MyClass:
    -            pass
    -        MyClass()
    -
    -
    -
    -
    -def test_pedantic_return_type_fail(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_return_type_fail(self):
    -    @pedantic
    -    def foo(a: int, b: str) -> str:
    -        return 6
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        foo(a=4, b='abc')
    -
    -
    -
    -
    -def test_pedantic_return_type_var_fail(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_return_type_var_fail(self):
    -    T = TypeVar('T', int, float)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> T:
    -        return 'a'
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=4, b=2)
    -
    -
    -
    -
    -def test_primitive_list_dict_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_primitive_list_dict_tuple(self):
    -    @pedantic
    -    def f(x: list[dict[int, tuple[float, str]]]) -> list[Any]:
    -        return x
    -
    -    f(x=[{3: (3.24, 'hi')}])
    -
    -    for value in [
    -        [{3, (3, 'hi')}],
    -        [{3: (3, 'hi')}],
    -        [{3: (3.24, 3)}],
    -        [{3: (3.24, 'hi')}, {0}],
    -    ]:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            f(x=value)
    -
    -
    -
    -
    -def test_return_generator(self) -
    -
    -
    - -Expand source code - -
    def test_return_generator(self):
    -    @pedantic
    -    def genfunc() -> Generator[int, None, None]:
    -        yield 1
    -
    -    @pedantic
    -    def foo() -> Generator[int, None, None]:
    -        return genfunc()
    -
    -    foo()
    -
    -
    -
    -
    -def test_return_type_none(self) -
    -
    -
    - -Expand source code - -
    def test_return_type_none(self):
    -    @pedantic
    -    def foo() -> None:
    -        return 'a'
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        foo()
    -
    -
    -
    -
    -def test_sequence(self) -
    -
    -
    - -Expand source code - -
    def test_sequence(self):
    -    @pedantic
    -    def foo(a: Sequence[str]) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        foo(a=value)
    -
    -
    -
    -
    -def test_sequence_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_sequence_bad_element(self):
    -    @pedantic
    -    def foo(a: Sequence[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=[1, 2, 'bb'])
    -
    -
    -
    -
    -def test_sequence_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_sequence_bad_type(self):
    -    @pedantic
    -    def foo(a: Sequence[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_sequence_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sequence_no_type_args(self):
    -    @pedantic
    -    def foo(a: Sequence) -> None:
    -        print(a)
    -
    -    for value in [('a', 'b'), ['a', 'b'], 'abc']:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=value)
    -
    -
    -
    -
    -def test_set(self) -
    -
    -
    - -Expand source code - -
    def test_set(self):
    -    @pedantic
    -    def foo_1(a: AbstractSet[int]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Set[int]) -> None:
    -        print(a)
    -
    -    for value in [set(), {6}]:
    -        foo_1(a=value)
    -        foo_2(a=value)
    -
    -
    -
    -
    -def test_set_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_set_bad_element(self):
    -    @pedantic
    -    def foo(a: Set[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a={1, 2, 'bb'})
    -
    -
    -
    -
    -def test_set_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_set_bad_type(self):
    -    @pedantic
    -    def foo(a: Set[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_set_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_set_no_type_args(self):
    -    @pedantic
    -    def foo_1(a: AbstractSet) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Set) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_3(a: set) -> None:
    -        print(a)
    -
    -    for value in [set(), {6}]:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_1(a=value)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_2(a=value)
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo_3(a=value)
    -
    -
    -
    -
    -def test_sloppy_types_dict(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_dict(self):
    -    @pedantic
    -    def operation(d: dict) -> int:
    -        return len(d.keys())
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d={1: 1, 2: 2})
    -
    -
    -
    -
    -def test_sloppy_types_dict_almost_corrected_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_dict_almost_corrected_no_type_args(self):
    -    @pedantic
    -    def operation(d: Dict) -> int:
    -        return len(d.keys())
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d={1: 1, 2: 2})
    -
    -
    -
    -
    -def test_sloppy_types_dict_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_dict_corrected(self):
    -    @pedantic
    -    def operation(d: Dict[int, int]) -> int:
    -        return len(d.keys())
    -
    -    operation(d={1: 1, 2: 2})
    -
    -
    -
    -
    -def test_sloppy_types_frozenset(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_frozenset(self):
    -    @pedantic
    -    def operation(d: frozenset) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=frozenset({1, 2, 3}))
    -
    -
    -
    -
    -def test_sloppy_types_frozenset_almost_corrected_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_frozenset_almost_corrected_no_type_args(self):
    -    @pedantic
    -    def operation(d: FrozenSet) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=frozenset({1, 2, 3}))
    -
    -
    -
    -
    -def test_sloppy_types_frozenset_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_frozenset_corrected(self):
    -    @pedantic
    -    def operation(d: FrozenSet[int]) -> int:
    -        return len(d)
    -
    -    operation(d=frozenset({1, 2, 3}))
    -
    -
    -
    -
    -def test_sloppy_types_list(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_list(self):
    -    @pedantic
    -    def operation(d: list) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=[1, 2, 3, 4])
    -
    -
    -
    -
    -def test_sloppy_types_list_almost_corrected_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_list_almost_corrected_no_type_args(self):
    -    @pedantic
    -    def operation(d: List) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=[1, 2, 3, 4])
    -
    -
    -
    -
    -def test_sloppy_types_list_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_list_corrected(self):
    -    @pedantic
    -    def operation(d: List[int]) -> int:
    -        return len(d)
    -
    -    operation(d=[1, 2, 3, 4])
    -
    -
    -
    -
    -def test_sloppy_types_set(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_set(self):
    -    @pedantic
    -    def operation(d: set) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d={1, 2, 3})
    -
    -
    -
    -
    -def test_sloppy_types_set_almost_corrected_to_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_set_almost_corrected_to_type_args(self):
    -    @pedantic
    -    def operation(d: Set) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d={1, 2, 3})
    -
    -
    -
    -
    -def test_sloppy_types_set_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_set_corrected(self):
    -    @pedantic
    -    def operation(d: Set[int]) -> int:
    -        return len(d)
    -
    -    operation(d={1, 2, 3})
    -
    -
    -
    -
    -def test_sloppy_types_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_tuple(self):
    -    @pedantic
    -    def operation(d: tuple) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=(1, 2, 3))
    -
    -
    -
    -
    -def test_sloppy_types_tuple_almost_corrected_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_tuple_almost_corrected_no_type_args(self):
    -    @pedantic
    -    def operation(d: Tuple) -> int:
    -        return len(d)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        operation(d=(1, 2, 3))
    -
    -
    -
    -
    -def test_sloppy_types_tuple_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_sloppy_types_tuple_corrected(self):
    -    @pedantic
    -    def operation(d: Tuple[int, int, int]) -> int:
    -        return len(d)
    -
    -    operation(d=(1, 2, 3))
    -
    -
    -
    -
    -def test_text_io(self) -
    -
    -
    - -Expand source code - -
    def test_text_io(self):
    -    @pedantic
    -    def foo(a: TextIO) -> None:
    -        print(a)
    -
    -    foo(a=StringIO())
    -
    -
    -
    -
    -def test_text_io_fail(self) -
    -
    -
    - -Expand source code - -
    def test_text_io_fail(self):
    -    @pedantic
    -    def foo(a: BinaryIO) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=StringIO())
    -
    -
    -
    -
    -def test_text_io_real_file(self) -
    -
    -
    - -Expand source code - -
    def test_text_io_real_file(self):
    -    @pedantic
    -    def foo(a: TextIO) -> None:
    -        print(a)
    -
    -    with open(file=TEST_FILE, mode='w') as f:
    -        foo(a=f)
    -
    -
    -
    -
    -def test_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_tuple(self):
    -    @pedantic
    -    def foo_1(a: Tuple[int, int]) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: Tuple[int, ...]) -> None:
    -        print(a)
    -
    -    foo_1(a=(1, 2))
    -    foo_2(a=(1, 2))
    -
    -
    -
    -
    -def test_tuple_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_bad_element(self):
    -    @pedantic
    -    def foo(a: Tuple[int, str]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=(1, 2))
    -
    -
    -
    -
    -def test_tuple_bad_type(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_bad_type(self):
    -    @pedantic
    -    def foo(a: Tuple[int]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=5)
    -
    -
    -
    -
    -def test_tuple_ellipsis_bad_element(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_ellipsis_bad_element(self):
    -    @pedantic
    -    def foo(a: Tuple[int, ...]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=(1, 2, 'blah'))
    -
    -
    -
    -
    -def test_tuple_no_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_no_type_args(self):
    -    @pedantic
    -    def foo_1(a: Tuple) -> None:
    -        print(a)
    -
    -    @pedantic
    -    def foo_2(a: tuple) -> None:
    -        print(a)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_1(a=(1, 2))
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo_2(a=(1, 2))
    -
    -
    -
    -
    -def test_tuple_too_few_elements(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_too_few_elements(self):
    -    @pedantic
    -    def foo(a: Tuple[int, str]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=(1,))
    -
    -
    -
    -
    -def test_tuple_too_many_elements(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_too_many_elements(self):
    -    @pedantic
    -    def foo(a: Tuple[int, str]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=(1, 'aa', 2))
    -
    -
    -
    -
    -def test_tuple_without_args_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_without_args_corrected(self):
    -    @pedantic
    -    def calc(i: Tuple[Any, ...]) -> str:
    -        return str(i)
    -
    -    calc(i=(42.0, 43, 'hi'))
    -
    -
    -
    -
    -def test_tuple_without_type_args(self) -
    -
    -
    - -Expand source code - -
    def test_tuple_without_type_args(self):
    -    @pedantic
    -    def calc(i: Tuple) -> str:
    -        return str(i)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(i=(42.0, 43, 'hi'))
    -
    -
    -
    -
    -def test_type_list_but_got_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_type_list_but_got_tuple(self):
    -    @pedantic
    -    def calc(ls: List[Any]) -> int:
    -        return len(ls)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(ls=(1, 2, 3))
    -
    -
    -
    -
    -def test_type_list_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_type_list_corrected(self):
    -    @pedantic
    -    def calc(ls: Tuple[Any, ...]) -> int:
    -        return len(ls)
    -
    -    calc(ls=(1, 2, 3))
    -
    -
    -
    -
    -def test_type_var(self) -
    -
    -
    - -Expand source code - -
    def test_type_var(self):
    -    T = TypeVar('T')
    -
    -    @pedantic
    -    def first(ls: List[T]) -> T:
    -        return ls[0]
    -
    -    first(ls=[1, 2, 3])
    -
    -
    -
    -
    -def test_type_var_bound_fail(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_bound_fail(self):
    -    T = TypeVar('T', bound=Child)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=Parent(), b=Parent())
    -
    -
    -
    -
    -def test_type_var_constraints(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_constraints(self):
    -    T = TypeVar('T', int, str)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    for values in [
    -        {'a': 6, 'b': 7},
    -        {'a': 'aa', 'b': "bb"},
    -    ]:
    -        foo(**values)
    -
    -
    -
    -
    -def test_type_var_constraints_fail_typing_type(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_constraints_fail_typing_type(self):
    -    T = TypeVar('T', int, Collection)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a='aa', b='bb')
    -
    -
    -
    -
    -def test_type_var_contravariant(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_contravariant(self):
    -    T = TypeVar('T', contravariant=True)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    foo(a=Child(), b=Parent())
    -
    -
    -
    -
    -def test_type_var_contravariant_fail(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_contravariant_fail(self):
    -    T = TypeVar('T', contravariant=True)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeVarMismatchException):
    -        foo(a=Parent(), b=Child())
    -
    -
    -
    -
    -def test_type_var_covariant(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_covariant(self):
    -    T = TypeVar('T', covariant=True)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    foo(a=Parent(), b=Child())
    -
    -
    -
    -
    -def test_type_var_covariant_fail(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_covariant_fail(self):
    -    T = TypeVar('T', covariant=True)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeVarMismatchException):
    -        foo(a=Child(), b=Parent())
    -
    -
    -
    -
    -def test_type_var_forward_ref_bound(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_forward_ref_bound(self):
    -    TBound = TypeVar('TBound', bound='Parent')
    -
    -    @pedantic
    -    def func(x: TBound) -> None:
    -        pass
    -
    -    func(x=Parent())
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        func(x='foo')
    -
    -
    -
    -
    -def test_type_var_invariant_fail(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_invariant_fail(self):
    -    T = TypeVar('T', int, str)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=2, b=3.6)
    -
    -
    -
    -
    -def test_type_var_wrong(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_wrong(self):
    -    T = TypeVar('T')
    -
    -    @pedantic
    -    def first(ls: List[T]) -> T:
    -        return str(ls[0])
    -
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        first(ls=[1, 2, 3])
    -
    -
    -
    -
    -def test_type_var_wrong_sequence(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_wrong_sequence(self):
    -    T = TypeVar('T')
    -
    -    @pedantic
    -    def first(ls: Sequence[T]) -> T:
    -        return str(ls[0])
    -
    -    with self.assertRaises(expected_exception=PedanticTypeVarMismatchException):
    -        first(ls=[1, 2, 3])
    -
    -
    -
    -
    -def test_typevar_bound(self) -
    -
    -
    - -Expand source code - -
    def test_typevar_bound(self):
    -    T = TypeVar('T', bound=Parent)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    foo(a=Child(), b=Child())
    -
    -
    -
    -
    -def test_typevar_constraints_fail(self) -
    -
    -
    - -Expand source code - -
    def test_typevar_constraints_fail(self):
    -    T = TypeVar('T', int, str)
    -
    -    @pedantic
    -    def foo(a: T, b: T) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=2.5, b='aa')
    -
    -
    -
    -
    -def test_union(self) -
    -
    -
    - -Expand source code - -
    def test_union(self):
    -    @pedantic
    -    def foo(a: Union[str, int]) -> None:
    -        pass
    -
    -    for value in [6, 'xa']:
    -        foo(a=value)
    -
    -
    -
    -
    -def test_union_fail(self) -
    -
    -
    - -Expand source code - -
    def test_union_fail(self):
    -    @pedantic
    -    def foo(a: Union[str, int]) -> None:
    -        pass
    -
    -    for value in [5.6, b'xa']:
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo(a=value)
    -
    -
    -
    -
    -def test_union_new_syntax(self) -
    -
    -
    - -Expand source code - -
    def test_union_new_syntax(self):
    -    @pedantic
    -    def foo(a: str | int) -> None:
    -        pass
    -
    -    for value in [6, 'xa']:
    -        foo(a=value)
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1.7)
    -
    -
    -
    -
    -def test_union_typing_type(self) -
    -
    -
    - -Expand source code - -
    def test_union_typing_type(self):
    -    @pedantic
    -    def foo(a: Union[str, Collection]) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=1)
    -
    -
    -
    -
    -def test_varargs(self) -
    -
    -
    - -Expand source code - -
    def test_varargs(self):
    -    @pedantic
    -    def foo(*args: int) -> None:
    -        pass
    -
    -    foo(1, 2)
    -
    -
    -
    -
    -def test_varargs_fail(self) -
    -
    -
    - -Expand source code - -
    def test_varargs_fail(self):
    -    @pedantic
    -    def foo(*args: int) -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(1, 'a')
    -
    -
    -
    -
    -def test_wrapped_function(self) -
    -
    -
    - -Expand source code - -
    def test_wrapped_function(self):
    -    def decorator(func):
    -        @wraps(func)
    -        def wrapper(*args, **kwargs):
    -            return func(*args, **kwargs)
    -        return wrapper
    -
    -    @pedantic
    -    @decorator
    -    def foo(a: 'Child') -> None:
    -        pass
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo(a=Parent())
    -
    -
    -
    -
    -def test_wrapped_generator_no_return_type_annotation(self) -
    -
    -
    - -Expand source code - -
    def test_wrapped_generator_no_return_type_annotation(self):
    -    """Test that return type checking works in a generator function too."""
    -    @pedantic
    -    def generate(a: int) -> Generator[int, int, None]:
    -        yield a
    -        yield a + 1
    -
    -    gen = generate(a=1)
    -    next(gen)
    -
    -

    Test that return type checking works in a generator function too.

    -
    -
    -def test_wrong_type_hint_1(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_1(self):
    -    """Problem here: str != int"""
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> str:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=38)
    -
    -

    Problem here: str != int

    -
    -
    -def test_wrong_type_hint_1_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_1_corrected(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> str:
    -        return str(n + m + i)
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_wrong_type_hint_2(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_2(self):
    -    """Problem here: str != int"""
    -    @pedantic
    -    def calc(n: int, m: int, i: str) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=38)
    -
    -

    Problem here: str != int

    -
    -
    -def test_wrong_type_hint_2_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_2_corrected(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: str) -> int:
    -        return n + m + int(i)
    -
    -    calc(n=42, m=40, i='38')
    -
    -
    -
    -
    -def test_wrong_type_hint_3(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_3(self):
    -    """Problem here: None != int"""
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> None:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=38)
    -
    -

    Problem here: None != int

    -
    -
    -def test_wrong_type_hint_4(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_4(self):
    -    """Problem here: None != int"""
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> int:
    -        print(n + m + i)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        calc(n=42, m=40, i=38)
    -
    -

    Problem here: None != int

    -
    -
    -def test_wrong_type_hint_4_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_4_corrected(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -def test_wrong_type_hint_corrected(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_type_hint_corrected(self):
    -    @pedantic
    -    def calc(n: int, m: int, i: int) -> None:
    -        print(n + m + i)
    -
    -    calc(n=42, m=40, i=38)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_pedantic_async.html b/docs/pedantic/tests/tests_pedantic_async.html deleted file mode 100644 index cfc9dea..0000000 --- a/docs/pedantic/tests/tests_pedantic_async.html +++ /dev/null @@ -1,269 +0,0 @@ - - - - - - -pedantic.tests.tests_pedantic_async API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_pedantic_async

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestPedanticAsyncio -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestPedanticAsyncio(unittest.IsolatedAsyncioTestCase):
    -    async def test_coroutine_correct_return_type(self):
    -        @pedantic
    -        async def foo() -> str:
    -            await asyncio.sleep(0)
    -            return 'foo'
    -
    -        await foo()
    -
    -    async def test_coroutine_wrong_return_type(self):
    -        @pedantic
    -        async def foo() -> str:
    -            await asyncio.sleep(0)
    -            return 1
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            await foo()
    -
    -    async def test_coroutine_wrong_argument_type(self):
    -        @pedantic
    -        async def foo(x: int) -> int:
    -            await asyncio.sleep(0)
    -            return 1 + x
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            await foo(x=4.5)
    -
    -    async def test_static_async(self):
    -        @pedantic_class
    -        class Foo:
    -            @staticmethod
    -            async def staticmethod() -> int:
    -                await asyncio.sleep(0)
    -                return 'foo'
    -
    -            @classmethod
    -            async def classmethod(cls) -> int:
    -                await asyncio.sleep(0)
    -                return 'foo'
    -
    -            async def method(self) -> int:
    -                await asyncio.sleep(0)
    -                return 'foo'
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            await Foo.staticmethod()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            await Foo.classmethod()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            await Foo().method()
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.async_case.IsolatedAsyncioTestCase
    • -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -async def test_coroutine_correct_return_type(self) -
    -
    -
    - -Expand source code - -
    async def test_coroutine_correct_return_type(self):
    -    @pedantic
    -    async def foo() -> str:
    -        await asyncio.sleep(0)
    -        return 'foo'
    -
    -    await foo()
    -
    -
    -
    -
    -async def test_coroutine_wrong_argument_type(self) -
    -
    -
    - -Expand source code - -
    async def test_coroutine_wrong_argument_type(self):
    -    @pedantic
    -    async def foo(x: int) -> int:
    -        await asyncio.sleep(0)
    -        return 1 + x
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        await foo(x=4.5)
    -
    -
    -
    -
    -async def test_coroutine_wrong_return_type(self) -
    -
    -
    - -Expand source code - -
    async def test_coroutine_wrong_return_type(self):
    -    @pedantic
    -    async def foo() -> str:
    -        await asyncio.sleep(0)
    -        return 1
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        await foo()
    -
    -
    -
    -
    -async def test_static_async(self) -
    -
    -
    - -Expand source code - -
    async def test_static_async(self):
    -    @pedantic_class
    -    class Foo:
    -        @staticmethod
    -        async def staticmethod() -> int:
    -            await asyncio.sleep(0)
    -            return 'foo'
    -
    -        @classmethod
    -        async def classmethod(cls) -> int:
    -            await asyncio.sleep(0)
    -            return 'foo'
    -
    -        async def method(self) -> int:
    -            await asyncio.sleep(0)
    -            return 'foo'
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        await Foo.staticmethod()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        await Foo.classmethod()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        await Foo().method()
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_pedantic_class.html b/docs/pedantic/tests/tests_pedantic_class.html deleted file mode 100644 index b2a69f0..0000000 --- a/docs/pedantic/tests/tests_pedantic_class.html +++ /dev/null @@ -1,1511 +0,0 @@ - - - - - - -pedantic.tests.tests_pedantic_class API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_pedantic_class

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestPedanticClass -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestPedanticClass(unittest.TestCase):
    -    def tearDown(self) -> None:
    -        enable_pedantic()
    -
    -    def test_constructor(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -        MyClass(a=42)
    -
    -    def test_constructor_with_list(self):
    -        class Foo(IntEnum):
    -            A = 1
    -            B = 2
    -
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, b: int, a: List[Foo]) -> None:
    -                self.a = a
    -                self.b = b
    -
    -        MyClass(b=42, a=[Foo.A, Foo.B])
    -
    -    def test_constructor_param_without_type_hint(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a) -> None:
    -                self.a = a
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass(a=42)
    -
    -    def test_constructor_without_return_type(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int):
    -                self.a = a
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass(a=42)
    -
    -    def test_constructor_wrong_return_type(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int) -> int:
    -                self.a = a
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass(a=42)
    -
    -    def test_constructor_must_be_called_with_kwargs(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            MyClass(42)
    -
    -    def test_multiple_methods(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            def calc(self, b: int) -> int:
    -                return self.a - b
    -
    -            def print(self, s: str) -> None:
    -                print(f'{self.a} and {s}')
    -
    -        m = MyClass(a=5)
    -        m.calc(b=42)
    -        m.print(s='Hi')
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.calc(45)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.calc(b=45.0)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.print('Hi')
    -
    -    def test_multiple_methods_with_missing_and_wrong_type_hints(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            def calc(self, b: int) -> float:
    -                return self.a - b
    -
    -            def dream(self, b) -> int:
    -                return self.a * b
    -
    -            def print(self, s: str):
    -                print(f'{self.a} and {s}')
    -
    -        m = MyClass(a=5)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.calc(b=42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.print(s='Hi')
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.dream(b=2)
    -
    -    def test_type_annotation_string(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                self.s = s
    -
    -            @staticmethod
    -            def generator() -> 'MyClass':
    -                return MyClass(s='generated')
    -
    -        MyClass.generator()
    -
    -    def test_typo_in_type_annotation_string(self):
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                self.s = s
    -
    -            @staticmethod
    -            def generator() -> 'MyClas':
    -                return MyClass(s='generated')
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.generator()
    -
    -    def test_overriding_contains(self):
    -        @pedantic_class
    -        class MyClass(list):
    -            def __contains__(self, item: int) -> bool:
    -                return True
    -
    -        m = MyClass()
    -        print(42 in m)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            print('something' in m)
    -
    -    def test_type_annotation_string_typo(self):
    -        @pedantic_class
    -        class MyClass:
    -            def compare(self, other: 'MyClas') -> bool:
    -                return self == other
    -
    -            def fixed_compare(self, other: 'MyClass') -> bool:
    -                return self == other
    -
    -        m = MyClass()
    -        m.fixed_compare(other=m)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.compare(other=m)
    -
    -    def test_docstring_not_required(self):
    -        @pedantic_class
    -        class Foo:
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            def bunk(self) -> int:
    -                '''
    -                Function with correct docstring. Yes, single-quoted docstrings are allowed too.
    -                Returns:
    -                    int: 42
    -                '''
    -                return self.a
    -
    -        foo = Foo(a=10)
    -        foo.bunk()
    -
    -    def test_overrides(self):
    -        @pedantic_class
    -        class Abstract:
    -            def func(self, b: str) -> str:
    -                pass
    -
    -            def bunk(self) -> int:
    -                pass
    -
    -        @pedantic_class
    -        class Foo(Abstract):
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            @overrides(Abstract)
    -            def func(self, b: str) -> str:
    -                return b
    -
    -            @overrides(Abstract)
    -            def bunk(self) -> int:
    -                return 42
    -
    -        f = Foo(a=42)
    -        f.func(b='Hi')
    -        f.bunk()
    -
    -    def test_overrides_abc(self):
    -        @pedantic_class
    -        class Abstract(ABC):
    -            @abstractmethod
    -            def func(self, b: str) -> str:
    -                pass
    -
    -            @abstractmethod
    -            def bunk(self) -> int:
    -                pass
    -
    -        @pedantic_class
    -        class Foo(Abstract):
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            @overrides(Abstract)
    -            def func(self, b: str) -> str:
    -                return b
    -
    -            @overrides(Abstract)
    -            def bunk(self) -> int:
    -                return 42
    -
    -        f = Foo(a=42)
    -        f.func(b='Hi')
    -        f.bunk()
    -
    -    def test_overrides_with_type_errors_and_call_by_args3(self):
    -        @pedantic_class
    -        class Abstract:
    -            def func(self, b: str) -> str:
    -                pass
    -
    -            def bunk(self) -> int:
    -                pass
    -
    -        @pedantic_class
    -        class Foo(Abstract):
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            @overrides(Abstract)
    -            def func(self, b: str) -> str:
    -                return b
    -
    -            @overrides(Abstract)
    -            def bunk(self) -> int:
    -                return self.a
    -
    -        f = Foo(a=42)
    -        f.func(b='Hi')
    -        f.bunk()
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            f.func('Hi')
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo(a=3.1415)
    -        f.a = 3.145
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f.bunk()
    -
    -    def test_overrides_goes_wrong(self):
    -        @pedantic_class
    -        class Parent:
    -            def func(self, b: str) -> str:
    -                return b + b + b
    -
    -            def bunk(self) -> int:
    -                return 42
    -
    -        with self.assertRaises(expected_exception=PedanticOverrideException):
    -            @pedantic_class
    -            class Foo(Parent):
    -                def __init__(self, a: int) -> None:
    -                    self.a = a
    -
    -                @overrides(Parent)
    -                def funcy(self, b: str) -> str:
    -                    return b
    -
    -                @overrides(Parent)
    -                def bunk(self) -> int:
    -                    return self.a
    -
    -            f = Foo(a=40002)
    -            f.func(b='Hi')
    -            f.bunk()
    -
    -        p = Parent()
    -        p.func(b='Hi')
    -        p.bunk()
    -
    -    def test_static_method_with_sloppy_type_annotation(self):
    -        @pedantic_class
    -        class MyStaticClass:
    -            @staticmethod
    -            def double_func(a: int) -> int:
    -                x, y = MyStaticClass.static_bar()
    -                return x
    -
    -            @staticmethod
    -            def static_bar() -> (int, int):  # this is wrong. Correct would be Tuple[int, int]
    -                return 0, 1
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            print(MyStaticClass.double_func(a=0))
    -
    -    def test_property(self):
    -        @pedantic_class
    -        class MyClass(object):
    -            def __init__(self, some_arg: Any) -> None:
    -                self._some_attribute = some_arg
    -
    -            @property
    -            def some_attribute(self) -> int:
    -                return self._some_attribute
    -
    -            @some_attribute.setter
    -            def some_attribute(self, value: str) -> None:
    -                self._some_attribute = value
    -
    -            def calc(self, value: float) -> float:
    -                return 2 * value
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            MyClass(42)
    -
    -        m = MyClass(some_arg=42)
    -        self.assertEqual(m.some_attribute, 42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_attribute = 100
    -        self.assertEqual(m.some_attribute, 42)
    -        m.some_attribute = '100'
    -        self.assertEqual(m._some_attribute, '100')
    -        m.calc(value=42.0)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            print(m.some_attribute)
    -
    -    def test_property_getter_and_setter_misses_type_hints(self):
    -        @pedantic_class
    -        class MyClass(object):
    -            def __init__(self, some_arg: int) -> None:
    -                self._some_attribute = some_arg
    -
    -            @property
    -            def some_attribute(self):
    -                return self._some_attribute
    -
    -            @some_attribute.setter
    -            def some_attribute(self, value: int):
    -                self._some_attribute = value
    -
    -            def calc(self, value: float) -> float:
    -                return 2 * value
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            MyClass(42)
    -
    -        m = MyClass(some_arg=42)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.some_attribute = 100
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            print(m.some_attribute)
    -        m.calc(value=42.0)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.calc(value=42)
    -
    -    def test_default_constructor(self):
    -        @pedantic_class
    -        class MyClass:
    -            def fun(self) -> int:
    -                return 42
    -        m = MyClass()
    -        m.fun()
    -
    -    def test_optional_callable(self):
    -        @pedantic_class
    -        class SemanticSimilarity:
    -            def __init__(self, post_processing: bool = True, val: Optional[Callable[[float], float]] = None) -> None:
    -                if post_processing is None:
    -                    self.post_processing = val
    -                else:
    -                    self.post_processing = lambda x: x
    -
    -        SemanticSimilarity()
    -
    -    def test_optional_lambda(self):
    -        @pedantic_class
    -        class SemanticSimilarity:
    -            def __init__(self, val: Callable[[float], float] = lambda x: x) -> None:
    -                self.post_processing = val
    -
    -        SemanticSimilarity()
    -
    -    def test_class_method_type_annotation_missing(self):
    -        @pedantic_class
    -        class MyClass:
    -            @classmethod
    -            def do(cls):
    -                print('i did something')
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.do()
    -
    -    def test_class_method_type_annotation(self):
    -        @pedantic_class
    -        class MyClass:
    -            @classmethod
    -            def do(cls) -> None:
    -                print('i did something')
    -
    -            @classmethod
    -            def calc(cls, x: Union[int, float]) -> int:
    -                return x * x
    -
    -        MyClass.do()
    -        MyClass.calc(x=5)
    -        m = MyClass()
    -        m.do()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.calc(5)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.calc(x=5.1)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            MyClass.calc('hi')
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.calc(5)
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            m.calc(x=5.1)
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            m.calc('hi')
    -
    -    def test_dataclass_inside(self):
    -        """Pedantic cannot be used on dataclasses."""
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            @pedantic_class
    -            @dataclass
    -            class MyClass:
    -                name: str
    -                unit_price: float
    -                quantity_on_hand: int = 0
    -
    -    def test_dataclass_outside(self):
    -        """Pedantic cannot check the constructor of dataclasses"""
    -
    -        @dataclass
    -        @pedantic_class
    -        class MyClass:
    -            name: str
    -            unit_price: float
    -            quantity_on_hand: int = 0
    -
    -            def total_cost(self) -> int:
    -                return self.unit_price * self.quantity_on_hand
    -
    -        MyClass(name='name', unit_price=5.1)
    -        a = MyClass(name='name', unit_price=5.0, quantity_on_hand=42)
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            a.total_cost()
    -
    -    def test_class_decorator_static_class_method(self):
    -        @pedantic_class
    -        class Foo:
    -            @staticmethod
    -            def staticmethod() -> int:
    -                return 'foo'
    -
    -            @classmethod
    -            def classmethod(cls) -> int:
    -                return 'foo'
    -
    -            def method(self) -> int:
    -                return 'foo'
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo.staticmethod()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo.classmethod()
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo().method()
    -
    -    def test_pedantic_class_disable_pedantic(self):
    -        disable_pedantic()
    -
    -        @pedantic_class
    -        class MyClass:
    -            def __init__(self, pw, **kwargs):
    -                self._validate_str_len(new_values=kwargs)
    -
    -            @staticmethod
    -            def _validate_str_len(new_values: Dict[str, Any]) -> None:
    -                return 42
    -
    -            def method(pw, **kwargs):
    -                MyClass._validate_str_len(new_values=kwargs)
    -
    -        MyClass._validate_str_len(None)
    -        MyClass._validate_str_len(new_values={1: 1, 2: 2})
    -        MyClass(name='hi', age=12, pw='123')
    -
    -    def test_disable_pedantic_2(self):
    -        """ https://github.com/LostInDarkMath/pedantic-python-decorators/issues/37 """
    -
    -        disable_pedantic()
    -
    -        @pedantic_class
    -        class Foo:
    -            def __init__(self) -> None:
    -                self._value = 42
    -
    -            def do(self) -> None:
    -                print(self.bar(value=self._value))
    -
    -            @staticmethod
    -            def bar(value: int) -> int:
    -                return value + 75
    -
    -        f = Foo()
    -        f.do()
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def tearDown(self) ‑> None -
    -
    -
    - -Expand source code - -
    def tearDown(self) -> None:
    -    enable_pedantic()
    -
    -

    Hook method for deconstructing the test fixture after testing it.

    -
    -
    -def test_class_decorator_static_class_method(self) -
    -
    -
    - -Expand source code - -
    def test_class_decorator_static_class_method(self):
    -    @pedantic_class
    -    class Foo:
    -        @staticmethod
    -        def staticmethod() -> int:
    -            return 'foo'
    -
    -        @classmethod
    -        def classmethod(cls) -> int:
    -            return 'foo'
    -
    -        def method(self) -> int:
    -            return 'foo'
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo.staticmethod()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo.classmethod()
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo().method()
    -
    -
    -
    -
    -def test_class_method_type_annotation(self) -
    -
    -
    - -Expand source code - -
    def test_class_method_type_annotation(self):
    -    @pedantic_class
    -    class MyClass:
    -        @classmethod
    -        def do(cls) -> None:
    -            print('i did something')
    -
    -        @classmethod
    -        def calc(cls, x: Union[int, float]) -> int:
    -            return x * x
    -
    -    MyClass.do()
    -    MyClass.calc(x=5)
    -    m = MyClass()
    -    m.do()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.calc(5)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.calc(x=5.1)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.calc('hi')
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.calc(5)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.calc(x=5.1)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.calc('hi')
    -
    -
    -
    -
    -def test_class_method_type_annotation_missing(self) -
    -
    -
    - -Expand source code - -
    def test_class_method_type_annotation_missing(self):
    -    @pedantic_class
    -    class MyClass:
    -        @classmethod
    -        def do(cls):
    -            print('i did something')
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.do()
    -
    -
    -
    -
    -def test_constructor(self) -
    -
    -
    - -Expand source code - -
    def test_constructor(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -    MyClass(a=42)
    -
    -
    -
    -
    -def test_constructor_must_be_called_with_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_constructor_must_be_called_with_kwargs(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        MyClass(42)
    -
    -
    -
    -
    -def test_constructor_param_without_type_hint(self) -
    -
    -
    - -Expand source code - -
    def test_constructor_param_without_type_hint(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a) -> None:
    -            self.a = a
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass(a=42)
    -
    -
    -
    -
    -def test_constructor_with_list(self) -
    -
    -
    - -Expand source code - -
    def test_constructor_with_list(self):
    -    class Foo(IntEnum):
    -        A = 1
    -        B = 2
    -
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, b: int, a: List[Foo]) -> None:
    -            self.a = a
    -            self.b = b
    -
    -    MyClass(b=42, a=[Foo.A, Foo.B])
    -
    -
    -
    -
    -def test_constructor_without_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_constructor_without_return_type(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int):
    -            self.a = a
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass(a=42)
    -
    -
    -
    -
    -def test_constructor_wrong_return_type(self) -
    -
    -
    - -Expand source code - -
    def test_constructor_wrong_return_type(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int) -> int:
    -            self.a = a
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass(a=42)
    -
    -
    -
    -
    -def test_dataclass_inside(self) -
    -
    -
    - -Expand source code - -
    def test_dataclass_inside(self):
    -    """Pedantic cannot be used on dataclasses."""
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        @pedantic_class
    -        @dataclass
    -        class MyClass:
    -            name: str
    -            unit_price: float
    -            quantity_on_hand: int = 0
    -
    -

    Pedantic cannot be used on dataclasses.

    -
    -
    -def test_dataclass_outside(self) -
    -
    -
    - -Expand source code - -
    def test_dataclass_outside(self):
    -    """Pedantic cannot check the constructor of dataclasses"""
    -
    -    @dataclass
    -    @pedantic_class
    -    class MyClass:
    -        name: str
    -        unit_price: float
    -        quantity_on_hand: int = 0
    -
    -        def total_cost(self) -> int:
    -            return self.unit_price * self.quantity_on_hand
    -
    -    MyClass(name='name', unit_price=5.1)
    -    a = MyClass(name='name', unit_price=5.0, quantity_on_hand=42)
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        a.total_cost()
    -
    -

    Pedantic cannot check the constructor of dataclasses

    -
    -
    -def test_default_constructor(self) -
    -
    -
    - -Expand source code - -
    def test_default_constructor(self):
    -    @pedantic_class
    -    class MyClass:
    -        def fun(self) -> int:
    -            return 42
    -    m = MyClass()
    -    m.fun()
    -
    -
    -
    -
    -def test_disable_pedantic_2(self) -
    -
    -
    - -Expand source code - -
    def test_disable_pedantic_2(self):
    -    """ https://github.com/LostInDarkMath/pedantic-python-decorators/issues/37 """
    -
    -    disable_pedantic()
    -
    -    @pedantic_class
    -    class Foo:
    -        def __init__(self) -> None:
    -            self._value = 42
    -
    -        def do(self) -> None:
    -            print(self.bar(value=self._value))
    -
    -        @staticmethod
    -        def bar(value: int) -> int:
    -            return value + 75
    -
    -    f = Foo()
    -    f.do()
    -
    - -
    -
    -def test_docstring_not_required(self) -
    -
    -
    - -Expand source code - -
    def test_docstring_not_required(self):
    -    @pedantic_class
    -    class Foo:
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        def bunk(self) -> int:
    -            '''
    -            Function with correct docstring. Yes, single-quoted docstrings are allowed too.
    -            Returns:
    -                int: 42
    -            '''
    -            return self.a
    -
    -    foo = Foo(a=10)
    -    foo.bunk()
    -
    -
    -
    -
    -def test_multiple_methods(self) -
    -
    -
    - -Expand source code - -
    def test_multiple_methods(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        def calc(self, b: int) -> int:
    -            return self.a - b
    -
    -        def print(self, s: str) -> None:
    -            print(f'{self.a} and {s}')
    -
    -    m = MyClass(a=5)
    -    m.calc(b=42)
    -    m.print(s='Hi')
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.calc(45)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.calc(b=45.0)
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        m.print('Hi')
    -
    -
    -
    -
    -def test_multiple_methods_with_missing_and_wrong_type_hints(self) -
    -
    -
    - -Expand source code - -
    def test_multiple_methods_with_missing_and_wrong_type_hints(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        def calc(self, b: int) -> float:
    -            return self.a - b
    -
    -        def dream(self, b) -> int:
    -            return self.a * b
    -
    -        def print(self, s: str):
    -            print(f'{self.a} and {s}')
    -
    -    m = MyClass(a=5)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.calc(b=42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.print(s='Hi')
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.dream(b=2)
    -
    -
    -
    -
    -def test_optional_callable(self) -
    -
    -
    - -Expand source code - -
    def test_optional_callable(self):
    -    @pedantic_class
    -    class SemanticSimilarity:
    -        def __init__(self, post_processing: bool = True, val: Optional[Callable[[float], float]] = None) -> None:
    -            if post_processing is None:
    -                self.post_processing = val
    -            else:
    -                self.post_processing = lambda x: x
    -
    -    SemanticSimilarity()
    -
    -
    -
    -
    -def test_optional_lambda(self) -
    -
    -
    - -Expand source code - -
    def test_optional_lambda(self):
    -    @pedantic_class
    -    class SemanticSimilarity:
    -        def __init__(self, val: Callable[[float], float] = lambda x: x) -> None:
    -            self.post_processing = val
    -
    -    SemanticSimilarity()
    -
    -
    -
    -
    -def test_overrides(self) -
    -
    -
    - -Expand source code - -
    def test_overrides(self):
    -    @pedantic_class
    -    class Abstract:
    -        def func(self, b: str) -> str:
    -            pass
    -
    -        def bunk(self) -> int:
    -            pass
    -
    -    @pedantic_class
    -    class Foo(Abstract):
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        @overrides(Abstract)
    -        def func(self, b: str) -> str:
    -            return b
    -
    -        @overrides(Abstract)
    -        def bunk(self) -> int:
    -            return 42
    -
    -    f = Foo(a=42)
    -    f.func(b='Hi')
    -    f.bunk()
    -
    -
    -
    -
    -def test_overrides_abc(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_abc(self):
    -    @pedantic_class
    -    class Abstract(ABC):
    -        @abstractmethod
    -        def func(self, b: str) -> str:
    -            pass
    -
    -        @abstractmethod
    -        def bunk(self) -> int:
    -            pass
    -
    -    @pedantic_class
    -    class Foo(Abstract):
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        @overrides(Abstract)
    -        def func(self, b: str) -> str:
    -            return b
    -
    -        @overrides(Abstract)
    -        def bunk(self) -> int:
    -            return 42
    -
    -    f = Foo(a=42)
    -    f.func(b='Hi')
    -    f.bunk()
    -
    -
    -
    -
    -def test_overrides_goes_wrong(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_goes_wrong(self):
    -    @pedantic_class
    -    class Parent:
    -        def func(self, b: str) -> str:
    -            return b + b + b
    -
    -        def bunk(self) -> int:
    -            return 42
    -
    -    with self.assertRaises(expected_exception=PedanticOverrideException):
    -        @pedantic_class
    -        class Foo(Parent):
    -            def __init__(self, a: int) -> None:
    -                self.a = a
    -
    -            @overrides(Parent)
    -            def funcy(self, b: str) -> str:
    -                return b
    -
    -            @overrides(Parent)
    -            def bunk(self) -> int:
    -                return self.a
    -
    -        f = Foo(a=40002)
    -        f.func(b='Hi')
    -        f.bunk()
    -
    -    p = Parent()
    -    p.func(b='Hi')
    -    p.bunk()
    -
    -
    -
    -
    -def test_overrides_with_type_errors_and_call_by_args3(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_with_type_errors_and_call_by_args3(self):
    -    @pedantic_class
    -    class Abstract:
    -        def func(self, b: str) -> str:
    -            pass
    -
    -        def bunk(self) -> int:
    -            pass
    -
    -    @pedantic_class
    -    class Foo(Abstract):
    -        def __init__(self, a: int) -> None:
    -            self.a = a
    -
    -        @overrides(Abstract)
    -        def func(self, b: str) -> str:
    -            return b
    -
    -        @overrides(Abstract)
    -        def bunk(self) -> int:
    -            return self.a
    -
    -    f = Foo(a=42)
    -    f.func(b='Hi')
    -    f.bunk()
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        f.func('Hi')
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo(a=3.1415)
    -    f.a = 3.145
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f.bunk()
    -
    -
    -
    -
    -def test_overriding_contains(self) -
    -
    -
    - -Expand source code - -
    def test_overriding_contains(self):
    -    @pedantic_class
    -    class MyClass(list):
    -        def __contains__(self, item: int) -> bool:
    -            return True
    -
    -    m = MyClass()
    -    print(42 in m)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        print('something' in m)
    -
    -
    -
    -
    -def test_pedantic_class_disable_pedantic(self) -
    -
    -
    - -Expand source code - -
    def test_pedantic_class_disable_pedantic(self):
    -    disable_pedantic()
    -
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, pw, **kwargs):
    -            self._validate_str_len(new_values=kwargs)
    -
    -        @staticmethod
    -        def _validate_str_len(new_values: Dict[str, Any]) -> None:
    -            return 42
    -
    -        def method(pw, **kwargs):
    -            MyClass._validate_str_len(new_values=kwargs)
    -
    -    MyClass._validate_str_len(None)
    -    MyClass._validate_str_len(new_values={1: 1, 2: 2})
    -    MyClass(name='hi', age=12, pw='123')
    -
    -
    -
    -
    -def test_property(self) -
    -
    -
    - -Expand source code - -
    def test_property(self):
    -    @pedantic_class
    -    class MyClass(object):
    -        def __init__(self, some_arg: Any) -> None:
    -            self._some_attribute = some_arg
    -
    -        @property
    -        def some_attribute(self) -> int:
    -            return self._some_attribute
    -
    -        @some_attribute.setter
    -        def some_attribute(self, value: str) -> None:
    -            self._some_attribute = value
    -
    -        def calc(self, value: float) -> float:
    -            return 2 * value
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        MyClass(42)
    -
    -    m = MyClass(some_arg=42)
    -    self.assertEqual(m.some_attribute, 42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_attribute = 100
    -    self.assertEqual(m.some_attribute, 42)
    -    m.some_attribute = '100'
    -    self.assertEqual(m._some_attribute, '100')
    -    m.calc(value=42.0)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        print(m.some_attribute)
    -
    -
    -
    -
    -def test_property_getter_and_setter_misses_type_hints(self) -
    -
    -
    - -Expand source code - -
    def test_property_getter_and_setter_misses_type_hints(self):
    -    @pedantic_class
    -    class MyClass(object):
    -        def __init__(self, some_arg: int) -> None:
    -            self._some_attribute = some_arg
    -
    -        @property
    -        def some_attribute(self):
    -            return self._some_attribute
    -
    -        @some_attribute.setter
    -        def some_attribute(self, value: int):
    -            self._some_attribute = value
    -
    -        def calc(self, value: float) -> float:
    -            return 2 * value
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        MyClass(42)
    -
    -    m = MyClass(some_arg=42)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.some_attribute = 100
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        print(m.some_attribute)
    -    m.calc(value=42.0)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.calc(value=42)
    -
    -
    -
    -
    -def test_static_method_with_sloppy_type_annotation(self) -
    -
    -
    - -Expand source code - -
    def test_static_method_with_sloppy_type_annotation(self):
    -    @pedantic_class
    -    class MyStaticClass:
    -        @staticmethod
    -        def double_func(a: int) -> int:
    -            x, y = MyStaticClass.static_bar()
    -            return x
    -
    -        @staticmethod
    -        def static_bar() -> (int, int):  # this is wrong. Correct would be Tuple[int, int]
    -            return 0, 1
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        print(MyStaticClass.double_func(a=0))
    -
    -
    -
    -
    -def test_type_annotation_string(self) -
    -
    -
    - -Expand source code - -
    def test_type_annotation_string(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, s: str) -> None:
    -            self.s = s
    -
    -        @staticmethod
    -        def generator() -> 'MyClass':
    -            return MyClass(s='generated')
    -
    -    MyClass.generator()
    -
    -
    -
    -
    -def test_type_annotation_string_typo(self) -
    -
    -
    - -Expand source code - -
    def test_type_annotation_string_typo(self):
    -    @pedantic_class
    -    class MyClass:
    -        def compare(self, other: 'MyClas') -> bool:
    -            return self == other
    -
    -        def fixed_compare(self, other: 'MyClass') -> bool:
    -            return self == other
    -
    -    m = MyClass()
    -    m.fixed_compare(other=m)
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        m.compare(other=m)
    -
    -
    -
    -
    -def test_typo_in_type_annotation_string(self) -
    -
    -
    - -Expand source code - -
    def test_typo_in_type_annotation_string(self):
    -    @pedantic_class
    -    class MyClass:
    -        def __init__(self, s: str) -> None:
    -            self.s = s
    -
    -        @staticmethod
    -        def generator() -> 'MyClas':
    -            return MyClass(s='generated')
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        MyClass.generator()
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_pedantic_class_docstring.html b/docs/pedantic/tests/tests_pedantic_class_docstring.html deleted file mode 100644 index 5df0835..0000000 --- a/docs/pedantic/tests/tests_pedantic_class_docstring.html +++ /dev/null @@ -1,317 +0,0 @@ - - - - - - -pedantic.tests.tests_pedantic_class_docstring API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_pedantic_class_docstring

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestPedanticClassDocstring -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestPedanticClassDocstring(unittest.TestCase):
    -    def test_require_docstring(self):
    -        @pedantic_class_require_docstring
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                """Constructor
    -
    -                Args:
    -                    s (str): name
    -                """
    -                self.s = s
    -
    -            def double(self, b: int) -> str:
    -                """some method
    -
    -                Args:
    -                    b (int): magic number
    -
    -                Returns:
    -                    str: cool stuff
    -
    -                """
    -                return self.s + str(b)
    -
    -            @staticmethod
    -            def generator() -> 'MyClass':
    -                """Static
    -
    -                Returns:
    -                    MyClass: instance
    -                """
    -                return MyClass(s='generated')
    -
    -        m = MyClass.generator()
    -        m.double(b=42)
    -
    -    def test_typo_docstring(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_class_require_docstring
    -            class MyClass:
    -                def __init__(self, s: str) -> None:
    -                    """Constructor
    -
    -                    Args:
    -                        s (str): name
    -                    """
    -                    self.s = s
    -
    -                @staticmethod
    -                def generator() -> 'MyClass':
    -                    """Static
    -
    -                    Returns:
    -                        MyClas: instance
    -                    """
    -                    return MyClass(s='generated')
    -
    -    def test_wrong_docstring(self):
    -        with self.assertRaises(expected_exception=PedanticDocstringException):
    -            @pedantic_class_require_docstring
    -            class MyClass:
    -                def __init__(self, s: str) -> None:
    -                    """Constructor
    -
    -                    Args:
    -                        s (str): name
    -                    """
    -                    self.s = s
    -
    -                def double(self, b: int) -> str:
    -                    """some method
    -
    -                    Args:
    -                        b (float): magic number
    -
    -                    Returns:
    -                        str: cool stuff
    -
    -                    """
    -                    return self.s + str(b)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_require_docstring(self) -
    -
    -
    - -Expand source code - -
    def test_require_docstring(self):
    -    @pedantic_class_require_docstring
    -    class MyClass:
    -        def __init__(self, s: str) -> None:
    -            """Constructor
    -
    -            Args:
    -                s (str): name
    -            """
    -            self.s = s
    -
    -        def double(self, b: int) -> str:
    -            """some method
    -
    -            Args:
    -                b (int): magic number
    -
    -            Returns:
    -                str: cool stuff
    -
    -            """
    -            return self.s + str(b)
    -
    -        @staticmethod
    -        def generator() -> 'MyClass':
    -            """Static
    -
    -            Returns:
    -                MyClass: instance
    -            """
    -            return MyClass(s='generated')
    -
    -    m = MyClass.generator()
    -    m.double(b=42)
    -
    -
    -
    -
    -def test_typo_docstring(self) -
    -
    -
    - -Expand source code - -
    def test_typo_docstring(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_class_require_docstring
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                """Constructor
    -
    -                Args:
    -                    s (str): name
    -                """
    -                self.s = s
    -
    -            @staticmethod
    -            def generator() -> 'MyClass':
    -                """Static
    -
    -                Returns:
    -                    MyClas: instance
    -                """
    -                return MyClass(s='generated')
    -
    -
    -
    -
    -def test_wrong_docstring(self) -
    -
    -
    - -Expand source code - -
    def test_wrong_docstring(self):
    -    with self.assertRaises(expected_exception=PedanticDocstringException):
    -        @pedantic_class_require_docstring
    -        class MyClass:
    -            def __init__(self, s: str) -> None:
    -                """Constructor
    -
    -                Args:
    -                    s (str): name
    -                """
    -                self.s = s
    -
    -            def double(self, b: int) -> str:
    -                """some method
    -
    -                Args:
    -                    b (float): magic number
    -
    -                Returns:
    -                    str: cool stuff
    -
    -                """
    -                return self.s + str(b)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_pedantic_python_311.html b/docs/pedantic/tests/tests_pedantic_python_311.html deleted file mode 100644 index da2d495..0000000 --- a/docs/pedantic/tests/tests_pedantic_python_311.html +++ /dev/null @@ -1,423 +0,0 @@ - - - - - - -pedantic.tests.tests_pedantic_python_311 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_pedantic_python_311

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestPedanticPython311AddedStuff -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestPedanticPython311AddedStuff(unittest.TestCase):
    -    def test_typing_never(self):
    -        from typing import Never
    -
    -        @pedantic
    -        def never_call_me(arg: Never) -> None:
    -            pass
    -
    -        @pedantic
    -        def foo() -> Never:
    -            pass
    -
    -        @pedantic
    -        def bar() -> Never:
    -            raise ZeroDivisionError('bar')
    -
    -        with self.assertRaises(expected_exception=ZeroDivisionError):
    -            bar()
    -
    -        with self.assertRaises(PedanticTypeCheckException):
    -            foo()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -            never_call_me(arg='42')
    -
    -    def test_literal_string(self):
    -        from typing import LiteralString
    -
    -        @pedantic
    -        def foo(s: LiteralString) -> None:
    -            pass
    -
    -        foo(s='Hi')
    -        foo(s=2 * 'Hi')
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            foo(s=3)
    -
    -    def test_self_type(self):
    -        from typing import Self
    -
    -        class Bar:
    -            pass
    -
    -        @pedantic_class
    -        class Foo:
    -            def f(self) -> Self:
    -                return self
    -
    -            @staticmethod
    -            def g() -> Self:
    -                return Foo()
    -
    -            @classmethod
    -            def h(cls) -> Self:
    -                return cls()
    -
    -            def f_2(self) -> Self:
    -                return Bar()
    -
    -            @staticmethod
    -            def g_2() -> Self:
    -                return Bar()
    -
    -            @classmethod
    -            def h_2(cls) -> Self:
    -                return Bar()
    -
    -        f = Foo()
    -        assert f.f() == f
    -        f.g()
    -        f.h()
    -        Foo.g()
    -        Foo.h()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f.f_2()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f.g_2()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f.h_2()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo.g_2()
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            Foo.h_2()
    -
    -    def test_using_self_type_annotation_outside_class(self):
    -        from typing import Self
    -
    -        @pedantic
    -        def f() -> Self:
    -            return 'hi'
    -
    -        with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -            f()
    -
    -    def test_type_var_tuple(self):
    -        from typing import TypeVarTuple, Generic
    -
    -        Ts = TypeVarTuple('Ts')
    -
    -        @pedantic_class
    -        class Array(Generic[*Ts]):
    -            def __init__(self, *args: *Ts) -> None:
    -                self._values = args
    -
    -        @pedantic
    -        def add_dimension(a: Array[*Ts], value: int) -> Array[int, *Ts]:
    -            return Array[int, *Ts](value, *a._values)
    -
    -        array = Array[int, float](42, 3.4)
    -        array_2 = Array[bool, int, float, str](True, 4, 3.4, 'hi')
    -        extended_array = add_dimension(a=array, value=42)
    -        assert extended_array._values == (42, 42, 3.4)
    -
    -        # this is too complicated at the moment
    -        # with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        #     Array[int, float](4.2, 3.4)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_literal_string(self) -
    -
    -
    - -Expand source code - -
    def test_literal_string(self):
    -    from typing import LiteralString
    -
    -    @pedantic
    -    def foo(s: LiteralString) -> None:
    -        pass
    -
    -    foo(s='Hi')
    -    foo(s=2 * 'Hi')
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        foo(s=3)
    -
    -
    -
    -
    -def test_self_type(self) -
    -
    -
    - -Expand source code - -
    def test_self_type(self):
    -    from typing import Self
    -
    -    class Bar:
    -        pass
    -
    -    @pedantic_class
    -    class Foo:
    -        def f(self) -> Self:
    -            return self
    -
    -        @staticmethod
    -        def g() -> Self:
    -            return Foo()
    -
    -        @classmethod
    -        def h(cls) -> Self:
    -            return cls()
    -
    -        def f_2(self) -> Self:
    -            return Bar()
    -
    -        @staticmethod
    -        def g_2() -> Self:
    -            return Bar()
    -
    -        @classmethod
    -        def h_2(cls) -> Self:
    -            return Bar()
    -
    -    f = Foo()
    -    assert f.f() == f
    -    f.g()
    -    f.h()
    -    Foo.g()
    -    Foo.h()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f.f_2()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f.g_2()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f.h_2()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo.g_2()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        Foo.h_2()
    -
    -
    -
    -
    -def test_type_var_tuple(self) -
    -
    -
    - -Expand source code - -
    def test_type_var_tuple(self):
    -    from typing import TypeVarTuple, Generic
    -
    -    Ts = TypeVarTuple('Ts')
    -
    -    @pedantic_class
    -    class Array(Generic[*Ts]):
    -        def __init__(self, *args: *Ts) -> None:
    -            self._values = args
    -
    -    @pedantic
    -    def add_dimension(a: Array[*Ts], value: int) -> Array[int, *Ts]:
    -        return Array[int, *Ts](value, *a._values)
    -
    -    array = Array[int, float](42, 3.4)
    -    array_2 = Array[bool, int, float, str](True, 4, 3.4, 'hi')
    -    extended_array = add_dimension(a=array, value=42)
    -    assert extended_array._values == (42, 42, 3.4)
    -
    -    # this is too complicated at the moment
    -    # with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -    #     Array[int, float](4.2, 3.4)
    -
    -
    -
    -
    -def test_typing_never(self) -
    -
    -
    - -Expand source code - -
    def test_typing_never(self):
    -    from typing import Never
    -
    -    @pedantic
    -    def never_call_me(arg: Never) -> None:
    -        pass
    -
    -    @pedantic
    -    def foo() -> Never:
    -        pass
    -
    -    @pedantic
    -    def bar() -> Never:
    -        raise ZeroDivisionError('bar')
    -
    -    with self.assertRaises(expected_exception=ZeroDivisionError):
    -        bar()
    -
    -    with self.assertRaises(PedanticTypeCheckException):
    -        foo()
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException) as exc:
    -        never_call_me(arg='42')
    -
    -
    -
    -
    -def test_using_self_type_annotation_outside_class(self) -
    -
    -
    - -Expand source code - -
    def test_using_self_type_annotation_outside_class(self):
    -    from typing import Self
    -
    -    @pedantic
    -    def f() -> Self:
    -        return 'hi'
    -
    -    with self.assertRaises(expected_exception=PedanticTypeCheckException):
    -        f()
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_require_kwargs.html b/docs/pedantic/tests/tests_require_kwargs.html deleted file mode 100644 index 425e0c5..0000000 --- a/docs/pedantic/tests/tests_require_kwargs.html +++ /dev/null @@ -1,204 +0,0 @@ - - - - - - -pedantic.tests.tests_require_kwargs API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_require_kwargs

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestRequireKwargs -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestRequireKwargs(unittest.TestCase):
    -
    -    def test_kwargs(self):
    -        @require_kwargs
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        calc(n=1, m=2, i=3)
    -
    -    def test_no_kwargs_1(self):
    -        @require_kwargs
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            calc(1, m=2, i=3)
    -
    -    def test_no_kwargs_2(self):
    -        @require_kwargs
    -        def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            calc(1, 2, 3)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_kwargs(self) -
    -
    -
    - -Expand source code - -
    def test_kwargs(self):
    -    @require_kwargs
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    calc(n=1, m=2, i=3)
    -
    -
    -
    -
    -def test_no_kwargs_1(self) -
    -
    -
    - -Expand source code - -
    def test_no_kwargs_1(self):
    -    @require_kwargs
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        calc(1, m=2, i=3)
    -
    -
    -
    -
    -def test_no_kwargs_2(self) -
    -
    -
    - -Expand source code - -
    def test_no_kwargs_2(self):
    -    @require_kwargs
    -    def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        calc(1, 2, 3)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/tests_small_method_decorators.html b/docs/pedantic/tests/tests_small_method_decorators.html deleted file mode 100644 index cf2fec7..0000000 --- a/docs/pedantic/tests/tests_small_method_decorators.html +++ /dev/null @@ -1,988 +0,0 @@ - - - - - - -pedantic.tests.tests_small_method_decorators API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.tests_small_method_decorators

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class AsyncSmallDecoratorTests -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class AsyncSmallDecoratorTests(IsolatedAsyncioTestCase):
    -    async def test_overrides_async_instance_method(self) -> None:
    -        class MyClassA:
    -            async def operation(self): pass
    -
    -        class MyClassB(MyClassA):
    -            @overrides(MyClassA)
    -            async def operation(self):
    -                await asyncio.sleep(0)
    -                return 42
    -
    -        b = MyClassB()
    -        await b.operation()
    -
    -    async def test_overrides_parent_has_no_such_method_async(self):
    -        class MyClassA:
    -            pass
    -
    -        with self.assertRaises(expected_exception=PedanticOverrideException):
    -            class MyClassB(MyClassA):
    -                @overrides(MyClassA)
    -                async def operation(self): return 42
    -
    -    async def test_count_calls_async(self):
    -        @count_calls
    -        async def operation(i: int) -> str:
    -            await asyncio.sleep(0)
    -            return str(i)
    -
    -        res = await operation(42)
    -        self.assertEqual('42', res)
    -
    -    async def test_trace_async(self):
    -        async def some_method(x, y):
    -            await asyncio.sleep(0)
    -            return x + y
    -
    -        traced_method = trace(some_method)
    -        self.assertEqual(await some_method(42, 99), await traced_method(42, 99))
    -
    -    async def test_trace_if_returns_async(self):
    -        async def some_method(x, y):
    -            await asyncio.sleep(0)
    -            return x + y
    -
    -        traced_method = trace_if_returns(100)(some_method)
    -        self.assertEqual(await some_method(42, 99), await traced_method(42, 99))
    -        self.assertEqual(await some_method(42, 58), await traced_method(42, 58))
    -
    -    async def test_timer_async(self):
    -        @timer
    -        async def operation(i: int) -> str:
    -            await asyncio.sleep(0.05)
    -            return str(i)
    -
    -        await operation(42)
    -
    -    async def test_deprecated_async(self):
    -        @deprecated
    -        async def old_method(i: int) -> str:
    -            return str(i)
    -
    -        with warnings.catch_warnings(record=True) as w:
    -            warnings.simplefilter("always")
    -            await old_method(42)
    -            assert len(w) == 1
    -            assert issubclass(w[-1].category, DeprecationWarning)
    -            assert "deprecated" in str(w[-1].message)
    -
    -    async def test_does_same_as_function_async(self):
    -        async def some_method(x, y, z):
    -            await asyncio.sleep(0)
    -            return x * (y + z)
    -
    -        @does_same_as_function(some_method)
    -        async def other_method(x, y, z):
    -            await asyncio.sleep(0)
    -            return x * y + x * z
    -
    -        await other_method(1, 2, 3)
    -        await other_method(4, 5, 6)
    -
    -    async def test_does_same_as_function_async_and_sync(self):
    -        def some_method(x, y, z):
    -            return x * (y + z)
    -
    -        @does_same_as_function(some_method)
    -        async def other_method(x, y, z):
    -            await asyncio.sleep(0)
    -            return x * y + x * z
    -
    -        await other_method(1, 2, 3)
    -        await other_method(4, 5, 6)
    -
    -    async def test_does_same_as_function_wrong(self):
    -        async def some_method(x, y, z):
    -            await asyncio.sleep(0)
    -            return x * (y + z)
    -
    -        @does_same_as_function(some_method)
    -        async def other_method(x, y, z):
    -            await asyncio.sleep(0)
    -            return x * y + z
    -
    -        await other_method(0, 2, 0)
    -
    -        with self.assertRaises(expected_exception=AssertionError):
    -            await other_method(4, 5, 6)
    -
    -    async def test_mock_async(self) -> None:
    -        @mock(return_value=42)
    -        async def my_function(a, b, c): return a + b + c
    -
    -        assert await my_function(1, 2, 3) == 42
    -        assert await my_function(100, 200, 300) == 42
    -
    -    async def test_require_kwargs(self):
    -        @require_kwargs
    -        async def calc(n: int, m: int, i: int) -> int:
    -            return n + m + i
    -
    -        await calc(n=1, m=2, i=3)
    -
    -        with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -            await calc(1, m=2, i=3)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.async_case.IsolatedAsyncioTestCase
    • -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -async def test_count_calls_async(self) -
    -
    -
    - -Expand source code - -
    async def test_count_calls_async(self):
    -    @count_calls
    -    async def operation(i: int) -> str:
    -        await asyncio.sleep(0)
    -        return str(i)
    -
    -    res = await operation(42)
    -    self.assertEqual('42', res)
    -
    -
    -
    -
    -async def test_deprecated_async(self) -
    -
    -
    - -Expand source code - -
    async def test_deprecated_async(self):
    -    @deprecated
    -    async def old_method(i: int) -> str:
    -        return str(i)
    -
    -    with warnings.catch_warnings(record=True) as w:
    -        warnings.simplefilter("always")
    -        await old_method(42)
    -        assert len(w) == 1
    -        assert issubclass(w[-1].category, DeprecationWarning)
    -        assert "deprecated" in str(w[-1].message)
    -
    -
    -
    -
    -async def test_does_same_as_function_async(self) -
    -
    -
    - -Expand source code - -
    async def test_does_same_as_function_async(self):
    -    async def some_method(x, y, z):
    -        await asyncio.sleep(0)
    -        return x * (y + z)
    -
    -    @does_same_as_function(some_method)
    -    async def other_method(x, y, z):
    -        await asyncio.sleep(0)
    -        return x * y + x * z
    -
    -    await other_method(1, 2, 3)
    -    await other_method(4, 5, 6)
    -
    -
    -
    -
    -async def test_does_same_as_function_async_and_sync(self) -
    -
    -
    - -Expand source code - -
    async def test_does_same_as_function_async_and_sync(self):
    -    def some_method(x, y, z):
    -        return x * (y + z)
    -
    -    @does_same_as_function(some_method)
    -    async def other_method(x, y, z):
    -        await asyncio.sleep(0)
    -        return x * y + x * z
    -
    -    await other_method(1, 2, 3)
    -    await other_method(4, 5, 6)
    -
    -
    -
    -
    -async def test_does_same_as_function_wrong(self) -
    -
    -
    - -Expand source code - -
    async def test_does_same_as_function_wrong(self):
    -    async def some_method(x, y, z):
    -        await asyncio.sleep(0)
    -        return x * (y + z)
    -
    -    @does_same_as_function(some_method)
    -    async def other_method(x, y, z):
    -        await asyncio.sleep(0)
    -        return x * y + z
    -
    -    await other_method(0, 2, 0)
    -
    -    with self.assertRaises(expected_exception=AssertionError):
    -        await other_method(4, 5, 6)
    -
    -
    -
    -
    -async def test_mock_async(self) ‑> None -
    -
    -
    - -Expand source code - -
    async def test_mock_async(self) -> None:
    -    @mock(return_value=42)
    -    async def my_function(a, b, c): return a + b + c
    -
    -    assert await my_function(1, 2, 3) == 42
    -    assert await my_function(100, 200, 300) == 42
    -
    -
    -
    -
    -async def test_overrides_async_instance_method(self) ‑> None -
    -
    -
    - -Expand source code - -
    async def test_overrides_async_instance_method(self) -> None:
    -    class MyClassA:
    -        async def operation(self): pass
    -
    -    class MyClassB(MyClassA):
    -        @overrides(MyClassA)
    -        async def operation(self):
    -            await asyncio.sleep(0)
    -            return 42
    -
    -    b = MyClassB()
    -    await b.operation()
    -
    -
    -
    -
    -async def test_overrides_parent_has_no_such_method_async(self) -
    -
    -
    - -Expand source code - -
    async def test_overrides_parent_has_no_such_method_async(self):
    -    class MyClassA:
    -        pass
    -
    -    with self.assertRaises(expected_exception=PedanticOverrideException):
    -        class MyClassB(MyClassA):
    -            @overrides(MyClassA)
    -            async def operation(self): return 42
    -
    -
    -
    -
    -async def test_require_kwargs(self) -
    -
    -
    - -Expand source code - -
    async def test_require_kwargs(self):
    -    @require_kwargs
    -    async def calc(n: int, m: int, i: int) -> int:
    -        return n + m + i
    -
    -    await calc(n=1, m=2, i=3)
    -
    -    with self.assertRaises(expected_exception=PedanticCallWithArgsException):
    -        await calc(1, m=2, i=3)
    -
    -
    -
    -
    -async def test_timer_async(self) -
    -
    -
    - -Expand source code - -
    async def test_timer_async(self):
    -    @timer
    -    async def operation(i: int) -> str:
    -        await asyncio.sleep(0.05)
    -        return str(i)
    -
    -    await operation(42)
    -
    -
    -
    -
    -async def test_trace_async(self) -
    -
    -
    - -Expand source code - -
    async def test_trace_async(self):
    -    async def some_method(x, y):
    -        await asyncio.sleep(0)
    -        return x + y
    -
    -    traced_method = trace(some_method)
    -    self.assertEqual(await some_method(42, 99), await traced_method(42, 99))
    -
    -
    -
    -
    -async def test_trace_if_returns_async(self) -
    -
    -
    - -Expand source code - -
    async def test_trace_if_returns_async(self):
    -    async def some_method(x, y):
    -        await asyncio.sleep(0)
    -        return x + y
    -
    -    traced_method = trace_if_returns(100)(some_method)
    -    self.assertEqual(await some_method(42, 99), await traced_method(42, 99))
    -    self.assertEqual(await some_method(42, 58), await traced_method(42, 58))
    -
    -
    -
    -
    -
    -
    -class TestSmallDecoratorMethods -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestSmallDecoratorMethods(unittest.TestCase):
    -    def test_overrides_parent_has_no_such_method(self):
    -        class MyClassA:
    -            pass
    -
    -        with self.assertRaises(expected_exception=PedanticOverrideException):
    -            class MyClassB(MyClassA):
    -                @overrides(MyClassA)
    -                def operation(self): pass
    -
    -    def test_overrides_all_good(self):
    -        class MyClassA:
    -            def operation(self): pass
    -
    -        class MyClassB(MyClassA):
    -            @overrides(MyClassA)
    -            def operation(self):
    -                return 42
    -
    -        b = MyClassB()
    -        b.operation()
    -
    -    def test_overrides_static_method(self):
    -        class MyClassA:
    -            @staticmethod
    -            def operation(): pass
    -
    -        class MyClassB(MyClassA):
    -            @staticmethod
    -            @overrides(MyClassA)
    -            def operation():
    -                return 42
    -
    -        b = MyClassB()
    -        self.assertEqual(b.operation(), 42)
    -        self.assertEqual(MyClassB.operation(), 42)
    -
    -    def test_overrides_below_property(self):
    -        class MyClassA:
    -            @property
    -            @abstractmethod
    -            def operation(self): pass
    -
    -        class MyClassB(MyClassA):
    -            @property
    -            @overrides(MyClassA)   # Note: it does not work the other way around
    -            def operation(self):
    -                return 43
    -
    -        b = MyClassB()
    -        self.assertEqual(b.operation, 43)
    -
    -    def test_overrides_function(self):
    -        class MyClassA:
    -            pass
    -
    -        with self.assertRaises(expected_exception=PedanticOverrideException):
    -            @overrides(MyClassA)
    -            def operation(): return 42
    -
    -    def test_deprecated_1(self):
    -        @deprecated
    -        def old_method(i: int) -> str: return str(i)
    -
    -        with warnings.catch_warnings(record=True) as w:
    -            warnings.simplefilter("always")
    -            old_method(42)
    -            assert len(w) == 1
    -            assert issubclass(w[-1].category, DeprecationWarning)
    -            assert "deprecated" in str(w[-1].message)
    -
    -    def test_deprecated_2(self):
    -        def old_method(i: int) -> str:
    -            return str(i)
    -
    -        with warnings.catch_warnings(record=True) as w:
    -            warnings.simplefilter("always")
    -            old_method(42)
    -            assert not len(w) == 1
    -
    -    def test_unimplemented(self):
    -        @unimplemented
    -        def dirt(i: int) -> str:
    -            return str(i)
    -
    -        with self.assertRaises(expected_exception=NotImplementedException):
    -            dirt(42)
    -
    -    def test_timer(self):
    -        @timer
    -        def operation(i: int) -> str:
    -            return str(i)
    -
    -        operation(42)
    -
    -    def test_count_calls(self):
    -        @count_calls
    -        def operation(i: int) -> str:
    -            return str(i)
    -
    -        operation(42)
    -
    -    def test_trace(self):
    -        def some_method(x, y):
    -            return x + y
    -
    -        traced_method = trace(some_method)
    -        self.assertEqual(some_method(42, 99), traced_method(42, 99))
    -
    -    def test_trace_if_returns(self):
    -        def some_method(x, y):
    -            return x + y
    -        traced_method = trace_if_returns(100)(some_method)
    -        self.assertEqual(some_method(42, 99), traced_method(42, 99))
    -        self.assertEqual(some_method(42, 58), traced_method(42, 58))
    -
    -    def test_does_same_as_function(self):
    -        def some_method(x, y, z):
    -            return x * (y + z)
    -
    -        @does_same_as_function(some_method)
    -        def other_method(x, y, z):
    -            return x * y + x * z
    -
    -        other_method(1, 2, 3)
    -        other_method(4, 5, 6)
    -
    -    def test_does_same_as_function_wrong(self):
    -        def some_method(x, y, z):
    -            return x * (y + z)
    -
    -        @does_same_as_function(some_method)
    -        def other_method(x, y, z):
    -            return x * y + z
    -
    -        other_method(0, 2, 0)
    -        with self.assertRaises(expected_exception=AssertionError):
    -            other_method(4, 5, 6)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_count_calls(self) -
    -
    -
    - -Expand source code - -
    def test_count_calls(self):
    -    @count_calls
    -    def operation(i: int) -> str:
    -        return str(i)
    -
    -    operation(42)
    -
    -
    -
    -
    -def test_deprecated_1(self) -
    -
    -
    - -Expand source code - -
    def test_deprecated_1(self):
    -    @deprecated
    -    def old_method(i: int) -> str: return str(i)
    -
    -    with warnings.catch_warnings(record=True) as w:
    -        warnings.simplefilter("always")
    -        old_method(42)
    -        assert len(w) == 1
    -        assert issubclass(w[-1].category, DeprecationWarning)
    -        assert "deprecated" in str(w[-1].message)
    -
    -
    -
    -
    -def test_deprecated_2(self) -
    -
    -
    - -Expand source code - -
    def test_deprecated_2(self):
    -    def old_method(i: int) -> str:
    -        return str(i)
    -
    -    with warnings.catch_warnings(record=True) as w:
    -        warnings.simplefilter("always")
    -        old_method(42)
    -        assert not len(w) == 1
    -
    -
    -
    -
    -def test_does_same_as_function(self) -
    -
    -
    - -Expand source code - -
    def test_does_same_as_function(self):
    -    def some_method(x, y, z):
    -        return x * (y + z)
    -
    -    @does_same_as_function(some_method)
    -    def other_method(x, y, z):
    -        return x * y + x * z
    -
    -    other_method(1, 2, 3)
    -    other_method(4, 5, 6)
    -
    -
    -
    -
    -def test_does_same_as_function_wrong(self) -
    -
    -
    - -Expand source code - -
    def test_does_same_as_function_wrong(self):
    -    def some_method(x, y, z):
    -        return x * (y + z)
    -
    -    @does_same_as_function(some_method)
    -    def other_method(x, y, z):
    -        return x * y + z
    -
    -    other_method(0, 2, 0)
    -    with self.assertRaises(expected_exception=AssertionError):
    -        other_method(4, 5, 6)
    -
    -
    -
    -
    -def test_overrides_all_good(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_all_good(self):
    -    class MyClassA:
    -        def operation(self): pass
    -
    -    class MyClassB(MyClassA):
    -        @overrides(MyClassA)
    -        def operation(self):
    -            return 42
    -
    -    b = MyClassB()
    -    b.operation()
    -
    -
    -
    -
    -def test_overrides_below_property(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_below_property(self):
    -    class MyClassA:
    -        @property
    -        @abstractmethod
    -        def operation(self): pass
    -
    -    class MyClassB(MyClassA):
    -        @property
    -        @overrides(MyClassA)   # Note: it does not work the other way around
    -        def operation(self):
    -            return 43
    -
    -    b = MyClassB()
    -    self.assertEqual(b.operation, 43)
    -
    -
    -
    -
    -def test_overrides_function(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_function(self):
    -    class MyClassA:
    -        pass
    -
    -    with self.assertRaises(expected_exception=PedanticOverrideException):
    -        @overrides(MyClassA)
    -        def operation(): return 42
    -
    -
    -
    -
    -def test_overrides_parent_has_no_such_method(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_parent_has_no_such_method(self):
    -    class MyClassA:
    -        pass
    -
    -    with self.assertRaises(expected_exception=PedanticOverrideException):
    -        class MyClassB(MyClassA):
    -            @overrides(MyClassA)
    -            def operation(self): pass
    -
    -
    -
    -
    -def test_overrides_static_method(self) -
    -
    -
    - -Expand source code - -
    def test_overrides_static_method(self):
    -    class MyClassA:
    -        @staticmethod
    -        def operation(): pass
    -
    -    class MyClassB(MyClassA):
    -        @staticmethod
    -        @overrides(MyClassA)
    -        def operation():
    -            return 42
    -
    -    b = MyClassB()
    -    self.assertEqual(b.operation(), 42)
    -    self.assertEqual(MyClassB.operation(), 42)
    -
    -
    -
    -
    -def test_timer(self) -
    -
    -
    - -Expand source code - -
    def test_timer(self):
    -    @timer
    -    def operation(i: int) -> str:
    -        return str(i)
    -
    -    operation(42)
    -
    -
    -
    -
    -def test_trace(self) -
    -
    -
    - -Expand source code - -
    def test_trace(self):
    -    def some_method(x, y):
    -        return x + y
    -
    -    traced_method = trace(some_method)
    -    self.assertEqual(some_method(42, 99), traced_method(42, 99))
    -
    -
    -
    -
    -def test_trace_if_returns(self) -
    -
    -
    - -Expand source code - -
    def test_trace_if_returns(self):
    -    def some_method(x, y):
    -        return x + y
    -    traced_method = trace_if_returns(100)(some_method)
    -    self.assertEqual(some_method(42, 99), traced_method(42, 99))
    -    self.assertEqual(some_method(42, 58), traced_method(42, 58))
    -
    -
    -
    -
    -def test_unimplemented(self) -
    -
    -
    - -Expand source code - -
    def test_unimplemented(self):
    -    @unimplemented
    -    def dirt(i: int) -> str:
    -        return str(i)
    -
    -    with self.assertRaises(expected_exception=NotImplementedException):
    -        dirt(42)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/index.html b/docs/pedantic/tests/validate/index.html deleted file mode 100644 index 4fd012f..0000000 --- a/docs/pedantic/tests/validate/index.html +++ /dev/null @@ -1,158 +0,0 @@ - - - - - - -pedantic.tests.validate API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate

    -
    -
    -
    -
    -

    Sub-modules

    -
    -
    pedantic.tests.validate.test_convert_value
    -
    -
    -
    -
    pedantic.tests.validate.test_datetime_isoformat
    -
    -
    -
    -
    pedantic.tests.validate.test_flask_parameters
    -
    -
    -
    -
    pedantic.tests.validate.test_parameter_environment_variable
    -
    -
    -
    -
    pedantic.tests.validate.test_validate
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_composite
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_datetime_unix_timestamp
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_email
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_for_each
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_is_enum
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_is_uuid
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_match_pattern
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_max
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_max_length
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_min
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_min_length
    -
    -
    -
    -
    pedantic.tests.validate.test_validator_not_empty
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_convert_value.html b/docs/pedantic/tests/validate/test_convert_value.html deleted file mode 100644 index 484efbc..0000000 --- a/docs/pedantic/tests/validate/test_convert_value.html +++ /dev/null @@ -1,273 +0,0 @@ - - - - - - -pedantic.tests.validate.test_convert_value API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_convert_value

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestConvertValue -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestConvertValue(TestCase):
    -    def test_convert_to_bool(self):
    -        for value in [True, 1, '1', '  1 ', '  tRuE  ', 'TRUE']:
    -            self.assertTrue(convert_value(value=value, target_type=bool))
    -
    -        for value in [False, 0, '0', '  0 ', '  fAlSe  ', 'FALSE']:
    -            self.assertFalse(convert_value(value=value, target_type=bool))
    -
    -        for value in ['alse', 0.1, '0.2', '  0000 ', 'Talse', 'Frue', 42]:
    -            with self.assertRaises(expected_exception=ConversionError):
    -                self.assertFalse(convert_value(value=value, target_type=bool))
    -
    -    def test_convert_to_int(self):
    -        for value in range(-4, 4):
    -            self.assertEqual(value, convert_value(value=value, target_type=int))
    -
    -        self.assertEqual(42, convert_value(value='42', target_type=int))
    -        self.assertEqual(0, convert_value(value='  0000 ', target_type=int))
    -
    -        for value in ['alse', 'Talse', 'Frue', 0.2, '0.2']:
    -            with self.assertRaises(expected_exception=ConversionError):
    -                self.assertFalse(convert_value(value=value, target_type=int))
    -
    -    def test_convert_to_float(self):
    -        for value in range(-4, 4):
    -            self.assertEqual(value, convert_value(value=value, target_type=float))
    -
    -        self.assertEqual(0.2, convert_value(value=0.2, target_type=float))
    -        self.assertEqual(0.2, convert_value(value='0.2', target_type=float))
    -        self.assertEqual(42, convert_value(value='42', target_type=float))
    -        self.assertEqual(0, convert_value(value='  0000 ', target_type=float))
    -
    -        for value in ['alse', 'Talse', 'Frue']:
    -            with self.assertRaises(expected_exception=ConversionError):
    -                self.assertFalse(convert_value(value=value, target_type=float))
    -
    -    def test_convert_to_list(self):
    -        for value in [[], [1], ['1', '  1 '], ['  tRuE  ', 'TRUE']]:
    -            self.assertEqual(value, convert_value(value=value, target_type=list))
    -
    -        self.assertEqual(['1', '2', '3'], convert_value(value='1,2,3', target_type=list))
    -
    -    def test_convert_to_dict(self):
    -        for value in [{}, {1: 2}, {'1': '  1 '}, {1: '  tRuE  ', 2: 'TRUE'}]:
    -            self.assertEqual(value, convert_value(value=value, target_type=dict))
    -
    -        self.assertEqual({'1': '1', '2': '4', '3': '7'}, convert_value(value='1:1,2:4,3:7', target_type=dict))
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_convert_to_bool(self) -
    -
    -
    - -Expand source code - -
    def test_convert_to_bool(self):
    -    for value in [True, 1, '1', '  1 ', '  tRuE  ', 'TRUE']:
    -        self.assertTrue(convert_value(value=value, target_type=bool))
    -
    -    for value in [False, 0, '0', '  0 ', '  fAlSe  ', 'FALSE']:
    -        self.assertFalse(convert_value(value=value, target_type=bool))
    -
    -    for value in ['alse', 0.1, '0.2', '  0000 ', 'Talse', 'Frue', 42]:
    -        with self.assertRaises(expected_exception=ConversionError):
    -            self.assertFalse(convert_value(value=value, target_type=bool))
    -
    -
    -
    -
    -def test_convert_to_dict(self) -
    -
    -
    - -Expand source code - -
    def test_convert_to_dict(self):
    -    for value in [{}, {1: 2}, {'1': '  1 '}, {1: '  tRuE  ', 2: 'TRUE'}]:
    -        self.assertEqual(value, convert_value(value=value, target_type=dict))
    -
    -    self.assertEqual({'1': '1', '2': '4', '3': '7'}, convert_value(value='1:1,2:4,3:7', target_type=dict))
    -
    -
    -
    -
    -def test_convert_to_float(self) -
    -
    -
    - -Expand source code - -
    def test_convert_to_float(self):
    -    for value in range(-4, 4):
    -        self.assertEqual(value, convert_value(value=value, target_type=float))
    -
    -    self.assertEqual(0.2, convert_value(value=0.2, target_type=float))
    -    self.assertEqual(0.2, convert_value(value='0.2', target_type=float))
    -    self.assertEqual(42, convert_value(value='42', target_type=float))
    -    self.assertEqual(0, convert_value(value='  0000 ', target_type=float))
    -
    -    for value in ['alse', 'Talse', 'Frue']:
    -        with self.assertRaises(expected_exception=ConversionError):
    -            self.assertFalse(convert_value(value=value, target_type=float))
    -
    -
    -
    -
    -def test_convert_to_int(self) -
    -
    -
    - -Expand source code - -
    def test_convert_to_int(self):
    -    for value in range(-4, 4):
    -        self.assertEqual(value, convert_value(value=value, target_type=int))
    -
    -    self.assertEqual(42, convert_value(value='42', target_type=int))
    -    self.assertEqual(0, convert_value(value='  0000 ', target_type=int))
    -
    -    for value in ['alse', 'Talse', 'Frue', 0.2, '0.2']:
    -        with self.assertRaises(expected_exception=ConversionError):
    -            self.assertFalse(convert_value(value=value, target_type=int))
    -
    -
    -
    -
    -def test_convert_to_list(self) -
    -
    -
    - -Expand source code - -
    def test_convert_to_list(self):
    -    for value in [[], [1], ['1', '  1 '], ['  tRuE  ', 'TRUE']]:
    -        self.assertEqual(value, convert_value(value=value, target_type=list))
    -
    -    self.assertEqual(['1', '2', '3'], convert_value(value='1,2,3', target_type=list))
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_datetime_isoformat.html b/docs/pedantic/tests/validate/test_datetime_isoformat.html deleted file mode 100644 index 982bd9e..0000000 --- a/docs/pedantic/tests/validate/test_datetime_isoformat.html +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - -pedantic.tests.validate.test_datetime_isoformat API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_datetime_isoformat

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorDatetimeIsoformat -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorDatetimeIsoformat(TestCase):
    -    def test_validator_datetime_isoformat(self) -> None:
    -        @validate(Parameter(name='x', validators=[DatetimeIsoFormat()]))
    -        def foo(x):
    -            return x
    -
    -        now = datetime.now()
    -        self.assertTrue(abs((now - foo(now.isoformat()) < timedelta(milliseconds=1))))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo('12.12.2020')
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo('invalid')
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_datetime_isoformat(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_datetime_isoformat(self) -> None:
    -    @validate(Parameter(name='x', validators=[DatetimeIsoFormat()]))
    -    def foo(x):
    -        return x
    -
    -    now = datetime.now()
    -    self.assertTrue(abs((now - foo(now.isoformat()) < timedelta(milliseconds=1))))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo('12.12.2020')
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo('invalid')
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_flask_parameters.html b/docs/pedantic/tests/validate/test_flask_parameters.html deleted file mode 100644 index 7e046e9..0000000 --- a/docs/pedantic/tests/validate/test_flask_parameters.html +++ /dev/null @@ -1,1531 +0,0 @@ - - - - - - -pedantic.tests.validate.test_flask_parameters API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_flask_parameters

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestFlaskParameters -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestFlaskParameters(TestCase):
    -    def test_validator_flask_json(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(
    -            FlaskJsonParameter(name='key', validators=[NotEmpty()]),
    -        )
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.route('/required')
    -        @validate(
    -            FlaskJsonParameter(name='required', required=True),
    -            FlaskJsonParameter(name='not_required', required=False),
    -            FlaskJsonParameter(name='not_required_with_default', required=False, default=42),
    -        )
    -        def required_params(required, not_required, not_required_with_default) -> Response:
    -            return jsonify({
    -                'required': required,
    -                'not_required': not_required,
    -                'not_required_with_default': not_required_with_default,
    -            })
    -
    -        @app.route('/types')
    -        @validate(
    -            FlaskJsonParameter(name='bool_param', value_type=bool),
    -            FlaskJsonParameter(name='int_param', value_type=int),
    -            FlaskJsonParameter(name='float_param', value_type=float),
    -            FlaskJsonParameter(name='str_param', value_type=str),
    -            FlaskJsonParameter(name='list_param', value_type=list),
    -            FlaskJsonParameter(name='dict_param', value_type=dict),
    -        )
    -        def different_types(
    -                bool_param,
    -                int_param,
    -                float_param,
    -                str_param,
    -                list_param,
    -                dict_param,
    -        ) -> Response:
    -            return jsonify({
    -                'bool_param': bool_param,
    -                'int_param': int_param,
    -                'float_param': float_param,
    -                'str_param': str_param,
    -                'list_param': list_param,
    -                'dict_param': dict_param,
    -            })
    -
    -        @app.route('/args')
    -        @validate(
    -            FlaskJsonParameter(name='a', validators=[NotEmpty()]),
    -            FlaskJsonParameter(name='b', validators=[NotEmpty()]),
    -            return_as=ReturnAs.ARGS,
    -        )
    -        def names_do_not_need_to_match(my_key: str, another: str) -> Response:
    -            return jsonify({
    -                'my_key': my_key,
    -                'another': another,
    -            })
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        @app.errorhandler(TooManyArguments)
    -        def handle_validation_error(exception: TooManyArguments) -> Response:
    -            print(str(exception))
    -            response = jsonify(str(exception))
    -            response.status_code = TOO_MANY_ARGS
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/', data=json.dumps({'key': '  hello world  '}), content_type=JSON)
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/', data=json.dumps({'key': '  '}), content_type=JSON)
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -                ExceptionDictKey.VALUE: '  ',
    -                ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -            data = {
    -                'key': '  hello world  ',
    -                'required': '1',
    -            }
    -            res = client.get('/', data=json.dumps(data), content_type=JSON)
    -            self.assertEqual(TOO_MANY_ARGS, res.status_code)
    -            self.assertEqual("Got unexpected arguments: ['required']", res.json)
    -
    -    def test_validator_flask_form_data(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', validators=[NotEmpty()]))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/', data={'key': '  hello world  '})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/', data={'key': '  '})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -                ExceptionDictKey.VALUE: '  ',
    -                ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_validator_flask_header(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskHeaderParameter(name='key', validators=[NotEmpty()]))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(InvalidHeader)
    -        def handle_validation_error(exception: InvalidHeader) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/', headers={'key': '  hello world  '}, data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/', headers={'key': '  '}, data={})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALUE: '  ',
    -                ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -                ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_validator_flask_header_optional_parameter(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskHeaderParameter(name='key', validators=[NotEmpty()], required=False))
    -        def hello_world(key: str = None) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get('/', headers={'key': '  hello world  '}, data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/', headers={}, data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual(None, res.json)
    -
    -    def test_validator_flask_get(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskGetParameter(name='key', value_type=str, validators=[NotEmpty()]))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/?key=hello_world', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello_world', res.json)
    -
    -            res = client.get('/?key=hello world', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/?key= ', data={})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -                ExceptionDictKey.VALUE: ' ',
    -                ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_validator_flask_get_multiple_values_for_same_key(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskGetParameter(name='key', value_type=list, validators=[NotEmpty()]))
    -        def hello_world(key: List[str]) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get('/?key=hello&key=world', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual(['hello', 'world'], res.json)
    -
    -    def test_validator_flask_path(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/<string:key>')
    -        @validate(FlaskPathParameter(name='key', validators=[NotEmpty()]))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/hello_world', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello_world', res.json)
    -
    -            res = client.get('/hello world', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('hello world', res.json)
    -
    -            res = client.get('/   ', data={})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -                ExceptionDictKey.VALUE: '   ',
    -                ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_invalid_value_type(self) -> None:
    -        app = Flask(__name__)
    -
    -        with self.assertRaises(expected_exception=AssertionError):
    -            @app.route('/')
    -            @validate(FlaskFormParameter(name='key', value_type=tuple))
    -            def hello_world(key: str) -> Response:
    -                return jsonify(key)
    -
    -    def test_wrong_name(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='k', value_type=str))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ValidateException)
    -        def handle_validation_error(exception: ValidateException) -> Response:
    -            print(str(exception))
    -            response = jsonify(str(exception))
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get(data={'key': 'k'})
    -            self.assertEqual(INVALID, res.status_code)
    -            self.assertIn('Value for parameter k is required.', res.json)
    -
    -    def test_default_value(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', value_type=str, default='42'))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get(data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('42', res.json)
    -
    -    def test_not_required_allows_none_kwargs_without_none(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', value_type=str, required=False),
    -                  return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -        def hello_world(key: str = 'it works') -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get(data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('it works', res.json)
    -
    -    def test_not_required_allows_none_kwargs_with_none(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', value_type=str, required=False, default=None),
    -                  return_as=ReturnAs.KWARGS_WITH_NONE)
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get(data={'key': None})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual(None, res.json)
    -
    -    def test_not_required_with_default(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', value_type=str, required=False, default='42'))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get(data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('42', res.json)
    -
    -    def test_validator_flask_path_type_conversion(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/<string:key>')
    -        @validate(FlaskPathParameter(name='key', value_type=int, validators=[Min(42)]))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/42', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual(42, res.json)
    -
    -            res = client.get('/42f', data={})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: None,
    -                ExceptionDictKey.VALUE: '42f',
    -                ExceptionDictKey.MESSAGE: "Value 42f cannot be converted to <class 'int'>.",
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_validator_flask_json_parameter_does_not_get_json(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskJsonParameter(name='key'))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            print(str(exception))
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get('/', data={})
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.VALIDATOR: None,
    -                ExceptionDictKey.VALUE: 'None',
    -                ExceptionDictKey.MESSAGE: 'Value for parameter key is required.',
    -                ExceptionDictKey.PARAMETER: 'key',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_validator_flask_json_parameter_does_not_get_json_but_default(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskJsonParameter(name='key', default='42'))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -        with app.test_client() as client:
    -            res = client.get('/', data={})
    -            self.assertEqual(OK, res.status_code)
    -            self.assertEqual('42', res.json)
    -
    -    def test_too_many_arguments(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/')
    -        @validate(FlaskJsonParameter(name='k', value_type=str))
    -        def hello_world(**kwargs) -> Response:
    -            return jsonify(str(kwargs))
    -
    -        @app.errorhandler(TooManyArguments)
    -        def handle_validation_error(exception: TooManyArguments) -> Response:
    -            print(str(exception))
    -            response = jsonify(str(exception))
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get(data=json.dumps({'k': 'k', 'a': 1}), content_type=JSON)
    -            self.assertEqual(INVALID, res.status_code)
    -            self.assertEqual("Got unexpected arguments: ['a']", res.json)
    -
    -    def test_exception_for_required_parameter(self) -> None:
    -        app = Flask(__name__)
    -        key = 'PASSWORD'
    -
    -        @app.route('/')
    -        @validate(FlaskJsonParameter(name=key, value_type=str))
    -        def hello_world(**kwargs) -> Response:
    -            return jsonify(str(kwargs))
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            reason = 'required' if 'required' in exception.message else 'invalid'
    -            response = jsonify({exception.parameter_name: [{'KEY': reason}]})
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get(data=json.dumps({}), content_type=JSON)
    -            self.assertEqual(INVALID, res.status_code)
    -            self.assertEqual({key: [{'KEY': 'required'}]}, res.json)
    -
    -    def test_async_endpoints(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/<int:k>')
    -        @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]))
    -        async def hello_world(k) -> Response:
    -            return jsonify(str(k))
    -
    -        @app.route('/foo/<int:k>')
    -        @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]), return_as=ReturnAs.ARGS)
    -        async def return_args(k) -> Response:
    -            return jsonify(str(k))
    -
    -        @app.route('/bar/<int:k>')
    -        @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]),
    -                  return_as=ReturnAs.KWARGS_WITH_NONE)
    -        async def return_kwargs_with_none(k) -> Response:
    -            return jsonify(str(k))
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            res = client.get(path=f'/45')
    -            self.assertEqual(OK, res.status_code)
    -
    -            res = client.get(path=f'/foo/45')
    -            self.assertEqual(OK, res.status_code)
    -
    -            res = client.get(path=f'/bar/45')
    -            self.assertEqual(OK, res.status_code)
    -
    -            res = client.get(path=f'/41')
    -            self.assertEqual(INVALID, res.status_code)
    -            expected = {
    -                ExceptionDictKey.MESSAGE: 'smaller then allowed: 41 is not >= 42',
    -                ExceptionDictKey.PARAMETER: 'k',
    -                ExceptionDictKey.VALIDATOR: 'Min',
    -                ExceptionDictKey.VALUE: '41',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_json_parameter_with_default_value(self) -> None:
    -        app = Flask(__name__)
    -
    -        @app.route('/testing/message/<string:email>', methods=['POST'])
    -        @validate(
    -            FlaskPathParameter(name='email', value_type=str, validators=[Email()]),
    -            FlaskJsonParameter(name='content', value_type=str, default='this is a fake message', required=False),
    -        )
    -        def testing_send_system_message(email: str, content: str) -> Response:
    -            return jsonify({'email': email, 'content': content})
    -
    -        with app.test_client() as client:
    -            res = client.post(path=f'/testing/message/adam@eva.de')
    -            self.assertEqual(OK, res.status_code)
    -            expected = {
    -                'email': 'adam@eva.de',
    -                'content': 'this is a fake message',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -            res = client.post(path=f'/testing/message/adam@eva.de', json={'content': 'hello world'})
    -            self.assertEqual(OK, res.status_code)
    -            expected = {
    -                'email': 'adam@eva.de',
    -                'content': 'hello world',
    -            }
    -            self.assertEqual(expected, res.json)
    -
    -    def test_generic_deserializer(self) -> None:
    -        @dataclass(frozen=True)
    -        class User(Deserializable):
    -            firstname: str
    -            lastname: str
    -            age: int
    -
    -            @staticmethod
    -            @overrides(Deserializable)
    -            def from_json(data: Dict[str, Any]) -> 'User':
    -                return User(
    -                    firstname=data['firstname'],
    -                    lastname=data['lastname'],
    -                    age=Min(value=18).validate_param(value=int(data['age']), parameter_name='age'),
    -                )
    -
    -        app = Flask(__name__)
    -
    -        @app.route('/foo', methods=['POST'])
    -        @validate(
    -            GenericFlaskDeserializer(name='user', cls=User, catch_exception=True),
    -        )
    -        def the_generic_approach(user: User) -> Response:
    -            return jsonify({'name': user.firstname})
    -
    -        @app.route('/bar', methods=['POST'])
    -        @validate(
    -            GenericFlaskDeserializer(name='user', cls=User, catch_exception=False),
    -        )
    -        def do_not_catch(user: User) -> Response:
    -            return jsonify({'name': user.firstname})
    -
    -        @app.errorhandler(ParameterException)
    -        def handle_validation_error(exception: ParameterException) -> Response:
    -            response = jsonify(exception.to_dict)
    -            response.status_code = INVALID
    -            return response
    -
    -        with app.test_client() as client:
    -            data = {
    -                'firstname': 'Albert',
    -                'lastname': 'Einstein',
    -                'age': '56',
    -            }
    -            res = client.post(path=f'/foo', json=data)
    -            assert res.status_code == 200
    -            assert res.json == {'name': 'Albert'}
    -
    -            data.pop('age')
    -            res = client.post(path=f'/foo', json=data)
    -            assert res.status_code == 422
    -
    -            res = client.post(path=f'/bar', json=data)
    -            assert res.status_code == 500
    -
    -            data['age'] = '16'
    -            res = client.post(path=f'/foo', json=data)
    -            assert res.status_code == 422
    -            expected = {
    -                ExceptionDictKey.MESSAGE: 'smaller then allowed: 16 is not >= 18',
    -                ExceptionDictKey.PARAMETER: 'age',
    -                ExceptionDictKey.VALIDATOR: 'Min',
    -                ExceptionDictKey.VALUE: '16',
    -            }
    -            assert res.json == expected
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_async_endpoints(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_async_endpoints(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/<int:k>')
    -    @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]))
    -    async def hello_world(k) -> Response:
    -        return jsonify(str(k))
    -
    -    @app.route('/foo/<int:k>')
    -    @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]), return_as=ReturnAs.ARGS)
    -    async def return_args(k) -> Response:
    -        return jsonify(str(k))
    -
    -    @app.route('/bar/<int:k>')
    -    @validate(FlaskPathParameter(name='k', value_type=int, validators=[Min(42)]),
    -              return_as=ReturnAs.KWARGS_WITH_NONE)
    -    async def return_kwargs_with_none(k) -> Response:
    -        return jsonify(str(k))
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get(path=f'/45')
    -        self.assertEqual(OK, res.status_code)
    -
    -        res = client.get(path=f'/foo/45')
    -        self.assertEqual(OK, res.status_code)
    -
    -        res = client.get(path=f'/bar/45')
    -        self.assertEqual(OK, res.status_code)
    -
    -        res = client.get(path=f'/41')
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.MESSAGE: 'smaller then allowed: 41 is not >= 42',
    -            ExceptionDictKey.PARAMETER: 'k',
    -            ExceptionDictKey.VALIDATOR: 'Min',
    -            ExceptionDictKey.VALUE: '41',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_default_value(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_default_value(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='key', value_type=str, default='42'))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get(data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('42', res.json)
    -
    -
    -
    -
    -def test_exception_for_required_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_exception_for_required_parameter(self) -> None:
    -    app = Flask(__name__)
    -    key = 'PASSWORD'
    -
    -    @app.route('/')
    -    @validate(FlaskJsonParameter(name=key, value_type=str))
    -    def hello_world(**kwargs) -> Response:
    -        return jsonify(str(kwargs))
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        reason = 'required' if 'required' in exception.message else 'invalid'
    -        response = jsonify({exception.parameter_name: [{'KEY': reason}]})
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get(data=json.dumps({}), content_type=JSON)
    -        self.assertEqual(INVALID, res.status_code)
    -        self.assertEqual({key: [{'KEY': 'required'}]}, res.json)
    -
    -
    -
    -
    -def test_generic_deserializer(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_generic_deserializer(self) -> None:
    -    @dataclass(frozen=True)
    -    class User(Deserializable):
    -        firstname: str
    -        lastname: str
    -        age: int
    -
    -        @staticmethod
    -        @overrides(Deserializable)
    -        def from_json(data: Dict[str, Any]) -> 'User':
    -            return User(
    -                firstname=data['firstname'],
    -                lastname=data['lastname'],
    -                age=Min(value=18).validate_param(value=int(data['age']), parameter_name='age'),
    -            )
    -
    -    app = Flask(__name__)
    -
    -    @app.route('/foo', methods=['POST'])
    -    @validate(
    -        GenericFlaskDeserializer(name='user', cls=User, catch_exception=True),
    -    )
    -    def the_generic_approach(user: User) -> Response:
    -        return jsonify({'name': user.firstname})
    -
    -    @app.route('/bar', methods=['POST'])
    -    @validate(
    -        GenericFlaskDeserializer(name='user', cls=User, catch_exception=False),
    -    )
    -    def do_not_catch(user: User) -> Response:
    -        return jsonify({'name': user.firstname})
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        data = {
    -            'firstname': 'Albert',
    -            'lastname': 'Einstein',
    -            'age': '56',
    -        }
    -        res = client.post(path=f'/foo', json=data)
    -        assert res.status_code == 200
    -        assert res.json == {'name': 'Albert'}
    -
    -        data.pop('age')
    -        res = client.post(path=f'/foo', json=data)
    -        assert res.status_code == 422
    -
    -        res = client.post(path=f'/bar', json=data)
    -        assert res.status_code == 500
    -
    -        data['age'] = '16'
    -        res = client.post(path=f'/foo', json=data)
    -        assert res.status_code == 422
    -        expected = {
    -            ExceptionDictKey.MESSAGE: 'smaller then allowed: 16 is not >= 18',
    -            ExceptionDictKey.PARAMETER: 'age',
    -            ExceptionDictKey.VALIDATOR: 'Min',
    -            ExceptionDictKey.VALUE: '16',
    -        }
    -        assert res.json == expected
    -
    -
    -
    -
    -def test_invalid_value_type(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_invalid_value_type(self) -> None:
    -    app = Flask(__name__)
    -
    -    with self.assertRaises(expected_exception=AssertionError):
    -        @app.route('/')
    -        @validate(FlaskFormParameter(name='key', value_type=tuple))
    -        def hello_world(key: str) -> Response:
    -            return jsonify(key)
    -
    -
    -
    -
    -def test_json_parameter_with_default_value(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_json_parameter_with_default_value(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/testing/message/<string:email>', methods=['POST'])
    -    @validate(
    -        FlaskPathParameter(name='email', value_type=str, validators=[Email()]),
    -        FlaskJsonParameter(name='content', value_type=str, default='this is a fake message', required=False),
    -    )
    -    def testing_send_system_message(email: str, content: str) -> Response:
    -        return jsonify({'email': email, 'content': content})
    -
    -    with app.test_client() as client:
    -        res = client.post(path=f'/testing/message/adam@eva.de')
    -        self.assertEqual(OK, res.status_code)
    -        expected = {
    -            'email': 'adam@eva.de',
    -            'content': 'this is a fake message',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -        res = client.post(path=f'/testing/message/adam@eva.de', json={'content': 'hello world'})
    -        self.assertEqual(OK, res.status_code)
    -        expected = {
    -            'email': 'adam@eva.de',
    -            'content': 'hello world',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_not_required_allows_none_kwargs_with_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_not_required_allows_none_kwargs_with_none(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='key', value_type=str, required=False, default=None),
    -              return_as=ReturnAs.KWARGS_WITH_NONE)
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get(data={'key': None})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual(None, res.json)
    -
    -
    -
    -
    -def test_not_required_allows_none_kwargs_without_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_not_required_allows_none_kwargs_without_none(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='key', value_type=str, required=False),
    -              return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -    def hello_world(key: str = 'it works') -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get(data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('it works', res.json)
    -
    -
    -
    -
    -def test_not_required_with_default(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_not_required_with_default(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='key', value_type=str, required=False, default='42'))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get(data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('42', res.json)
    -
    -
    -
    -
    -def test_too_many_arguments(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_too_many_arguments(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskJsonParameter(name='k', value_type=str))
    -    def hello_world(**kwargs) -> Response:
    -        return jsonify(str(kwargs))
    -
    -    @app.errorhandler(TooManyArguments)
    -    def handle_validation_error(exception: TooManyArguments) -> Response:
    -        print(str(exception))
    -        response = jsonify(str(exception))
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get(data=json.dumps({'k': 'k', 'a': 1}), content_type=JSON)
    -        self.assertEqual(INVALID, res.status_code)
    -        self.assertEqual("Got unexpected arguments: ['a']", res.json)
    -
    -
    -
    -
    -def test_validator_flask_form_data(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_form_data(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='key', validators=[NotEmpty()]))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/', data={'key': '  hello world  '})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/', data={'key': '  '})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -            ExceptionDictKey.VALUE: '  ',
    -            ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_validator_flask_get(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_get(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskGetParameter(name='key', value_type=str, validators=[NotEmpty()]))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/?key=hello_world', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello_world', res.json)
    -
    -        res = client.get('/?key=hello world', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/?key= ', data={})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -            ExceptionDictKey.VALUE: ' ',
    -            ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_validator_flask_get_multiple_values_for_same_key(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_get_multiple_values_for_same_key(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskGetParameter(name='key', value_type=list, validators=[NotEmpty()]))
    -    def hello_world(key: List[str]) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get('/?key=hello&key=world', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual(['hello', 'world'], res.json)
    -
    -
    -
    -
    -def test_validator_flask_header(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_header(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskHeaderParameter(name='key', validators=[NotEmpty()]))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(InvalidHeader)
    -    def handle_validation_error(exception: InvalidHeader) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/', headers={'key': '  hello world  '}, data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/', headers={'key': '  '}, data={})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALUE: '  ',
    -            ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -            ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_validator_flask_header_optional_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_header_optional_parameter(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskHeaderParameter(name='key', validators=[NotEmpty()], required=False))
    -    def hello_world(key: str = None) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get('/', headers={'key': '  hello world  '}, data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/', headers={}, data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual(None, res.json)
    -
    -
    -
    -
    -def test_validator_flask_json(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_json(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(
    -        FlaskJsonParameter(name='key', validators=[NotEmpty()]),
    -    )
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.route('/required')
    -    @validate(
    -        FlaskJsonParameter(name='required', required=True),
    -        FlaskJsonParameter(name='not_required', required=False),
    -        FlaskJsonParameter(name='not_required_with_default', required=False, default=42),
    -    )
    -    def required_params(required, not_required, not_required_with_default) -> Response:
    -        return jsonify({
    -            'required': required,
    -            'not_required': not_required,
    -            'not_required_with_default': not_required_with_default,
    -        })
    -
    -    @app.route('/types')
    -    @validate(
    -        FlaskJsonParameter(name='bool_param', value_type=bool),
    -        FlaskJsonParameter(name='int_param', value_type=int),
    -        FlaskJsonParameter(name='float_param', value_type=float),
    -        FlaskJsonParameter(name='str_param', value_type=str),
    -        FlaskJsonParameter(name='list_param', value_type=list),
    -        FlaskJsonParameter(name='dict_param', value_type=dict),
    -    )
    -    def different_types(
    -            bool_param,
    -            int_param,
    -            float_param,
    -            str_param,
    -            list_param,
    -            dict_param,
    -    ) -> Response:
    -        return jsonify({
    -            'bool_param': bool_param,
    -            'int_param': int_param,
    -            'float_param': float_param,
    -            'str_param': str_param,
    -            'list_param': list_param,
    -            'dict_param': dict_param,
    -        })
    -
    -    @app.route('/args')
    -    @validate(
    -        FlaskJsonParameter(name='a', validators=[NotEmpty()]),
    -        FlaskJsonParameter(name='b', validators=[NotEmpty()]),
    -        return_as=ReturnAs.ARGS,
    -    )
    -    def names_do_not_need_to_match(my_key: str, another: str) -> Response:
    -        return jsonify({
    -            'my_key': my_key,
    -            'another': another,
    -        })
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    @app.errorhandler(TooManyArguments)
    -    def handle_validation_error(exception: TooManyArguments) -> Response:
    -        print(str(exception))
    -        response = jsonify(str(exception))
    -        response.status_code = TOO_MANY_ARGS
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/', data=json.dumps({'key': '  hello world  '}), content_type=JSON)
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/', data=json.dumps({'key': '  '}), content_type=JSON)
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -            ExceptionDictKey.VALUE: '  ',
    -            ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -        data = {
    -            'key': '  hello world  ',
    -            'required': '1',
    -        }
    -        res = client.get('/', data=json.dumps(data), content_type=JSON)
    -        self.assertEqual(TOO_MANY_ARGS, res.status_code)
    -        self.assertEqual("Got unexpected arguments: ['required']", res.json)
    -
    -
    -
    -
    -def test_validator_flask_json_parameter_does_not_get_json(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_json_parameter_does_not_get_json(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskJsonParameter(name='key'))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/', data={})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: None,
    -            ExceptionDictKey.VALUE: 'None',
    -            ExceptionDictKey.MESSAGE: 'Value for parameter key is required.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_validator_flask_json_parameter_does_not_get_json_but_default(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_json_parameter_does_not_get_json_but_default(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskJsonParameter(name='key', default='42'))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    with app.test_client() as client:
    -        res = client.get('/', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('42', res.json)
    -
    -
    -
    -
    -def test_validator_flask_path(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_path(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/<string:key>')
    -    @validate(FlaskPathParameter(name='key', validators=[NotEmpty()]))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/hello_world', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello_world', res.json)
    -
    -        res = client.get('/hello world', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual('hello world', res.json)
    -
    -        res = client.get('/   ', data={})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: 'NotEmpty',
    -            ExceptionDictKey.VALUE: '   ',
    -            ExceptionDictKey.MESSAGE: 'Got empty String which is invalid.',
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_validator_flask_path_type_conversion(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_flask_path_type_conversion(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/<string:key>')
    -    @validate(FlaskPathParameter(name='key', value_type=int, validators=[Min(42)]))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ParameterException)
    -    def handle_validation_error(exception: ParameterException) -> Response:
    -        print(str(exception))
    -        response = jsonify(exception.to_dict)
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get('/42', data={})
    -        self.assertEqual(OK, res.status_code)
    -        self.assertEqual(42, res.json)
    -
    -        res = client.get('/42f', data={})
    -        self.assertEqual(INVALID, res.status_code)
    -        expected = {
    -            ExceptionDictKey.VALIDATOR: None,
    -            ExceptionDictKey.VALUE: '42f',
    -            ExceptionDictKey.MESSAGE: "Value 42f cannot be converted to <class 'int'>.",
    -            ExceptionDictKey.PARAMETER: 'key',
    -        }
    -        self.assertEqual(expected, res.json)
    -
    -
    -
    -
    -def test_wrong_name(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_wrong_name(self) -> None:
    -    app = Flask(__name__)
    -
    -    @app.route('/')
    -    @validate(FlaskFormParameter(name='k', value_type=str))
    -    def hello_world(key: str) -> Response:
    -        return jsonify(key)
    -
    -    @app.errorhandler(ValidateException)
    -    def handle_validation_error(exception: ValidateException) -> Response:
    -        print(str(exception))
    -        response = jsonify(str(exception))
    -        response.status_code = INVALID
    -        return response
    -
    -    with app.test_client() as client:
    -        res = client.get(data={'key': 'k'})
    -        self.assertEqual(INVALID, res.status_code)
    -        self.assertIn('Value for parameter k is required.', res.json)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_parameter_environment_variable.html b/docs/pedantic/tests/validate/test_parameter_environment_variable.html deleted file mode 100644 index 9653e5f..0000000 --- a/docs/pedantic/tests/validate/test_parameter_environment_variable.html +++ /dev/null @@ -1,377 +0,0 @@ - - - - - - -pedantic.tests.validate.test_parameter_environment_variable API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_parameter_environment_variable

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestParameterEnvironmentVariable -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestParameterEnvironmentVariable(TestCase):
    -    def setUp(self) -> None:
    -        if 'foo' in os.environ:
    -            del os.environ['foo']
    -
    -    def test_parameter_environment_variable_str(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo', value_type=str))
    -        def bar(foo):
    -            return foo
    -
    -        os.environ['foo'] = '42'
    -        self.assertEqual('42', bar())
    -
    -    def test_parameter_environment_variable_int(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo', value_type=int))
    -        def bar(foo):
    -            return foo
    -
    -        os.environ['foo'] = '42'
    -        self.assertEqual(42, bar())
    -
    -    def test_parameter_environment_variable_float(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo', value_type=float))
    -        def bar(foo):
    -            return foo
    -
    -        os.environ['foo'] = '42.7'
    -        self.assertEqual(42.7, bar())
    -
    -    def test_parameter_environment_variable_bool(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo', value_type=bool))
    -        def bar(foo):
    -            return foo
    -
    -        for value in ['true', 'True', 'TRUE']:
    -            os.environ['foo'] = value
    -            self.assertTrue(bar())
    -
    -        for value in ['false', 'False', 'FALSE']:
    -            os.environ['foo'] = value
    -            self.assertFalse(bar())
    -
    -        for value in ['invalid', 'frue', 'talse']:
    -            os.environ['foo'] = value
    -
    -            with self.assertRaises(expected_exception=ParameterException):
    -                bar()
    -
    -    def test_parameter_environment_variable_not_set(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo'))
    -        def bar(foo):
    -            return foo
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            bar()
    -
    -    def test_invalid_value_type(self) -> None:
    -        with self.assertRaises(expected_exception=AssertionError):
    -            @validate(EnvironmentVariableParameter(name='foo', value_type=dict))
    -            def bar(foo):
    -                return foo
    -
    -    def test_parameter_environment_variable_different_name(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo', env_var_name='fuu', value_type=str))
    -        def bar(foo):
    -            return foo
    -
    -        os.environ['fuu'] = '42'
    -        self.assertEqual('42', bar())
    -
    -    def test_two_parameters(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='a'), strict=False)
    -        def foo(a: float, b: int):
    -            print(f'{a} and {b}')
    -
    -        os.environ['a'] = '42'
    -        foo(b=42)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def setUp(self) ‑> None -
    -
    -
    - -Expand source code - -
    def setUp(self) -> None:
    -    if 'foo' in os.environ:
    -        del os.environ['foo']
    -
    -

    Hook method for setting up the test fixture before exercising it.

    -
    -
    -def test_invalid_value_type(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_invalid_value_type(self) -> None:
    -    with self.assertRaises(expected_exception=AssertionError):
    -        @validate(EnvironmentVariableParameter(name='foo', value_type=dict))
    -        def bar(foo):
    -            return foo
    -
    -
    -
    -
    -def test_parameter_environment_variable_bool(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_bool(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo', value_type=bool))
    -    def bar(foo):
    -        return foo
    -
    -    for value in ['true', 'True', 'TRUE']:
    -        os.environ['foo'] = value
    -        self.assertTrue(bar())
    -
    -    for value in ['false', 'False', 'FALSE']:
    -        os.environ['foo'] = value
    -        self.assertFalse(bar())
    -
    -    for value in ['invalid', 'frue', 'talse']:
    -        os.environ['foo'] = value
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            bar()
    -
    -
    -
    -
    -def test_parameter_environment_variable_different_name(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_different_name(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo', env_var_name='fuu', value_type=str))
    -    def bar(foo):
    -        return foo
    -
    -    os.environ['fuu'] = '42'
    -    self.assertEqual('42', bar())
    -
    -
    -
    -
    -def test_parameter_environment_variable_float(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_float(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo', value_type=float))
    -    def bar(foo):
    -        return foo
    -
    -    os.environ['foo'] = '42.7'
    -    self.assertEqual(42.7, bar())
    -
    -
    -
    -
    -def test_parameter_environment_variable_int(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_int(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo', value_type=int))
    -    def bar(foo):
    -        return foo
    -
    -    os.environ['foo'] = '42'
    -    self.assertEqual(42, bar())
    -
    -
    -
    -
    -def test_parameter_environment_variable_not_set(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_not_set(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo'))
    -    def bar(foo):
    -        return foo
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        bar()
    -
    -
    -
    -
    -def test_parameter_environment_variable_str(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_parameter_environment_variable_str(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo', value_type=str))
    -    def bar(foo):
    -        return foo
    -
    -    os.environ['foo'] = '42'
    -    self.assertEqual('42', bar())
    -
    -
    -
    -
    -def test_two_parameters(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_two_parameters(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='a'), strict=False)
    -    def foo(a: float, b: int):
    -        print(f'{a} and {b}')
    -
    -    os.environ['a'] = '42'
    -    foo(b=42)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validate.html b/docs/pedantic/tests/validate/test_validate.html deleted file mode 100644 index 878e0bc..0000000 --- a/docs/pedantic/tests/validate/test_validate.html +++ /dev/null @@ -1,1374 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validate API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validate

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class AsyncValidateTests -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class AsyncValidateTests(IsolatedAsyncioTestCase):
    -    async def test_async_instance_method(self) -> None:
    -        class Foo:
    -            @validate(Parameter(name='k', value_type=int, validators=[Min(42)]),
    -                      return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -            async def bar(self, k):
    -                return k
    -
    -            @validate(Parameter(name='k', value_type=int, validators=[Min(42)]), return_as=ReturnAs.ARGS)
    -            async def bar_2(self, k):
    -                return k
    -
    -        f = Foo()
    -        res = await f.bar(k=42)
    -        self.assertEqual(42, res)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            await f.bar(k=41)
    -
    -        res = await f.bar_2(k=42)
    -        self.assertEqual(42, res)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            await f.bar_2(k=41)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.async_case.IsolatedAsyncioTestCase
    • -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -async def test_async_instance_method(self) ‑> None -
    -
    -
    - -Expand source code - -
    async def test_async_instance_method(self) -> None:
    -    class Foo:
    -        @validate(Parameter(name='k', value_type=int, validators=[Min(42)]),
    -                  return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -        async def bar(self, k):
    -            return k
    -
    -        @validate(Parameter(name='k', value_type=int, validators=[Min(42)]), return_as=ReturnAs.ARGS)
    -        async def bar_2(self, k):
    -            return k
    -
    -    f = Foo()
    -    res = await f.bar(k=42)
    -    self.assertEqual(42, res)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        await f.bar(k=41)
    -
    -    res = await f.bar_2(k=42)
    -    self.assertEqual(42, res)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        await f.bar_2(k=41)
    -
    -
    -
    -
    -
    -
    -class TestValidate -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidate(TestCase):
    -    def setUp(self) -> None:
    -        if 'foo' in os.environ:
    -            del os.environ['foo']
    -
    -    def test_single_validator(self) -> None:
    -        validator = MaxLength(3)
    -        converted_value = validator.validate(value='hed')
    -        self.assertEqual(converted_value, 'hed')
    -
    -        with self.assertRaises(expected_exception=ValidatorException) as ex:
    -            validator.validate(value='hello world')
    -
    -        expected_error_msg = 'MaxLength: hello world is too long with length 11. Value: hello world'
    -        self.assertEqual(expected_error_msg, str(ex.exception))
    -
    -    def test_single_parameter(self) -> None:
    -        parameter = Parameter(name='x', validators=[MaxLength(3)])
    -        converted_value = parameter.validate(value='hed')
    -        self.assertEqual(converted_value, 'hed')
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            parameter.validate(value='hello world')
    -
    -    def test_multiple_parameters(self) -> None:
    -        @validate(
    -            Parameter(name='a', validators=[Min(3)]),
    -            Parameter(name='b', validators=[Max(3)]),
    -            Parameter(name='c', validators=[Max(43)]),
    -        )
    -        def bar(a, b, c):
    -            return a + b + c
    -
    -        self.assertEqual(11, bar(3, 3, 5))
    -        self.assertEqual(11, bar(a=3, b=3, c=5))
    -
    -    def test_validate_args(self):
    -        @validate(
    -            Parameter(name='a', validators=[Min(42, include_boundary=False)]),
    -            Parameter(name='b', validators=[Min(42, include_boundary=False)]),
    -            Parameter(name='c', validators=[Min(42, include_boundary=False)]),
    -        )
    -        def some_calculation(a, b, c):
    -            return a + b + c
    -
    -        some_calculation(43, 45, 50)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(30, 40, 50)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            some_calculation(c=30, a=40, b=50)
    -
    -    def test_validate_instance_method(self):
    -        class MyClass:
    -            @validate(
    -                Parameter(name='x', validators=[Min(1)]),
    -            )
    -            def some_calculation(self, x: int) -> int:
    -                return x
    -
    -            @validate(
    -                Parameter(name='x', validators=[Min(1)]),
    -                return_as=ReturnAs.KWARGS_WITHOUT_NONE,
    -            )
    -            def some_calculation_2(self, x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(1)
    -        m.some_calculation(42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(0)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(-42)
    -
    -        m.some_calculation_2(1)
    -        m.some_calculation_2(42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation_2(0)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation_2(-42)
    -
    -    def test_validate_static_method(self):
    -        """ The @staticmethod decorator have to be ABOVE the @validate decorator. """
    -
    -        class MyClass:
    -            @staticmethod
    -            @validate(
    -                Parameter(name='x', validators=[Min(1)]),
    -            )
    -            def some_calculation(x: int) -> int:
    -                return x
    -
    -        m = MyClass()
    -        m.some_calculation(1)
    -        m.some_calculation(42)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(0)
    -        with self.assertRaises(expected_exception=ParameterException):
    -            m.some_calculation(-42)
    -
    -    def test_less_parameter_than_arguments(self):
    -        @validate(
    -            Parameter(name='b'),
    -            strict=False,
    -        )
    -        def some_calculation(a, b, c):
    -            return a + b + c
    -
    -        some_calculation(43, 0, -50)
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            some_calculation(30, None, 50)
    -
    -    def test_empty_parameter_kwargs_with_none(self):
    -        @validate(
    -            Parameter(name='a', required=False),
    -            Parameter(name='b', required=True),
    -            Parameter(name='c', required=False),
    -            return_as=ReturnAs.KWARGS_WITH_NONE
    -        )
    -        def some_calculation(a, b, c):
    -            return str(a) + str(b) + str(c)
    -
    -        self.assertEqual('430-50', some_calculation(43, 0, -50))
    -        self.assertEqual('None0None', some_calculation(None, 0, None))
    -
    -    def test_empty_parameter_kwargs_without_none(self):
    -        @validate(
    -            Parameter(name='a', required=False),
    -            Parameter(name='b', required=True),
    -            Parameter(name='c', required=False),
    -            return_as=ReturnAs.KWARGS_WITHOUT_NONE
    -        )
    -        def some_calculation(a: Optional[int] = 1, b: Optional[int] = 2, c:  Optional[int] = 3):
    -            return str(a) + str(b) + str(c)
    -
    -        self.assertEqual('430-50', some_calculation(43, 0, -50))
    -        self.assertEqual('103', some_calculation(None, 0, None))
    -
    -    def test_required(self):
    -        @validate(
    -            Parameter(name='a', required=True),
    -            Parameter(name='b', required=True),
    -            Parameter(name='c', required=True),
    -        )
    -        def some_calculation(a, b, c):
    -            return a + b + c
    -
    -        some_calculation(43, 0, -50)
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            some_calculation(30, None, 50)
    -
    -    def test_call_with_args(self):
    -        @validate(
    -            Parameter(name='x', validators=[Min(1)]),
    -        )
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -        some_calculation(42)
    -
    -    def test_external_parameter_accepts_value_when_given(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo'))
    -        def bar(foo):
    -            return foo
    -
    -        self.assertEqual('42', bar('42'))
    -        self.assertEqual('42', bar(foo='42'))
    -
    -    def test_external_parameter_ignores_value_when_given(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo'), ignore_input=True)
    -        def bar(foo):
    -            return foo
    -
    -        os.environ['foo'] = '1'
    -
    -        self.assertEqual('1', bar('42'))
    -        self.assertEqual('1', bar(foo='42'))
    -
    -    def test_external_parameter_mixed_with_normal_parameter(self) -> None:
    -        @validate(
    -            EnvironmentVariableParameter(name='foo'),
    -            Parameter(name='footer'),
    -            return_as=ReturnAs.KWARGS_WITHOUT_NONE,
    -        )
    -        def bar(foo, footer):
    -            return foo, footer
    -
    -        self.assertEqual(('42', 3), bar('42', 3))
    -
    -        os.environ['foo'] = '42'
    -        self.assertEqual(('42', 3), bar(footer=3))
    -
    -    def test_too_many_arguments(self) -> None:
    -        @validate(
    -            Parameter(name='x'),
    -        )
    -        def bar(x):
    -            return x
    -
    -        self.assertEqual(42, bar(42))
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            bar(42, 43)
    -
    -    def test_unexpected_parameter_strict(self) -> None:
    -        @validate(Parameter(name='y'))
    -        def bar(x):
    -            return x
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            bar(42)
    -        with self.assertRaises(expected_exception=ValidateException):
    -            bar(x=42)
    -
    -    def test_unexpected_parameter_not_strict(self) -> None:
    -        @validate(Parameter(name='y'), strict=False)
    -        def bar(x):
    -            return x
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            self.assertEqual(42, bar(42))
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            self.assertEqual(42, bar(x=42))
    -
    -    def test_unexpected_parameter_not_strict_external(self) -> None:
    -        @validate(EnvironmentVariableParameter(name='foo'))
    -        def bar(x):
    -            return x
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            self.assertEqual(42, bar(42))
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            self.assertEqual(42, bar(x=42))
    -
    -    def test_return_as_simple(self) -> None:
    -        @validate(Parameter(name='x'), return_as=ReturnAs.ARGS)
    -        def bar(x):
    -            return x
    -
    -        self.assertEqual(42, bar(42))
    -        self.assertEqual(42, bar(x=42))
    -
    -    def test_return_as_args(self) -> None:
    -        @validate(Parameter(name='x'), return_as=ReturnAs.ARGS)
    -        def bar(*args, **kwargs):
    -            return args, kwargs
    -
    -        self.assertEqual(((42,), {}), bar(42))
    -        self.assertEqual(((42,), {}), bar(x=42))
    -
    -    def test_return_as_kwargs_with_none(self) -> None:
    -        @validate(Parameter(name='x'), return_as=ReturnAs.KWARGS_WITH_NONE)
    -        def bar(*args, **kwargs):
    -            return args, kwargs
    -
    -        self.assertEqual(((), {'x': 42}), bar(42))
    -        self.assertEqual(((), {'x': 42}), bar(x=42))
    -
    -    def test_return_as_kwargs_without_none(self) -> None:
    -        @validate(Parameter(name='x'), return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -        def bar(*args, **kwargs):
    -            return args, kwargs
    -
    -        self.assertEqual(((), {'x': 42}), bar(42))
    -        self.assertEqual(((), {'x': 42}), bar(x=42))
    -
    -    def test_return_as_args_advanced(self) -> None:
    -        @validate(
    -            Parameter(name='a'),
    -            Parameter(name='b'),
    -            Parameter(name='c'),
    -            return_as=ReturnAs.ARGS,
    -        )
    -        def bar(a, b, *args, **kwargs):
    -            return a, b, args, kwargs
    -
    -        bar(a=1, b=3, c=42)
    -        bar(1, 3, 4)
    -        bar(1, 3, c=4)
    -
    -    def test_return_as_args_advanced_different_order(self) -> None:
    -        @validate(
    -            Parameter(name='c'),
    -            Parameter(name='a'),
    -            Parameter(name='b'),
    -            return_as=ReturnAs.ARGS,
    -        )
    -        def bar(a, b, *args, **kwargs):
    -            return a, b, args, kwargs
    -
    -        self.assertEqual((1, 3, (42,), {}), bar(a=1, b=3, c=42))
    -        self.assertEqual((1, 3, (42,), {}), bar(1, 3, 42))
    -        self.assertEqual((42, 1, (3,), {}), bar(1, 3, c=42))
    -
    -    def test_return_multiple_args(self) -> None:
    -        @validate(
    -            Parameter(name='c'),
    -            Parameter(name='a'),
    -            Parameter(name='b'),
    -            return_as=ReturnAs.KWARGS_WITH_NONE,
    -        )
    -        def bar(*args, **kwargs):
    -            return args, kwargs
    -
    -        self.assertEqual(((), {'a': 1, 'b': 3, 'c': 42}), bar(a=1, b=3, c=42))
    -        self.assertEqual(((), {'a': 3, 'b': 42, 'c': 1}), bar(1, 3, 42))
    -        self.assertEqual(((), {'a': 1, 'b': 3, 'c': 42}), bar(1, 3, c=42))
    -
    -    def test_none_is_not_validated_if_not_required_kwargs_with_none(self) -> None:
    -        @validate(Parameter(name='a', validators=[Email()], required=False), return_as=ReturnAs.KWARGS_WITH_NONE)
    -        def bar(a: Optional[str]):
    -            return a
    -
    -        self.assertIsNone(bar(a=None))
    -        self.assertIsNone(bar(None))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            bar('no_email')
    -
    -    def test_none_is_not_validated_if_not_required_kwargs_without_none(self) -> None:
    -        @validate(Parameter(name='a', validators=[Email()], required=False), return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -        def bar(a: Optional[str] = None):
    -            return a
    -
    -        self.assertIsNone(bar(a=None))
    -        self.assertIsNone(bar(None))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            bar('no_email')
    -
    -    def test_allow_renaming_of_parameter_of_custom_validator(self) -> None:
    -        class MyCustomValidator(Validator):
    -            def validate(self, i_renamed_this_arg: Any) -> Any:
    -                return i_renamed_this_arg
    -
    -        @validate(Parameter(name='a', validators=[MyCustomValidator()]))
    -        def bar(a: int):
    -            return a
    -
    -        self.assertEqual(42, bar(42))
    -        self.assertEqual(42, bar(a=42))
    -
    -    def test_none_is_removed_for_not_required_parameter(self) -> None:
    -        @validate(Parameter(name='a', required=False))
    -        def bar(a: int = 42):
    -            return a
    -
    -        self.assertEqual(42, bar())
    -        self.assertEqual(2, bar(a=2))
    -        self.assertEqual(2, bar(2))
    -
    -    def test_default_value_is_not_validated_internal_parameter(self) -> None:
    -        t = datetime(year=2021, month=11, day=24)
    -        unix_timestamp = (t - datetime(year=1970, month=1, day=1)).total_seconds()
    -
    -        @validate(Parameter(name='a', required=False, default=t, validators=[DateTimeUnixTimestamp()]))
    -        def bar(a: datetime) -> datetime:
    -            return a
    -
    -        self.assertEqual(t, bar(a=unix_timestamp))
    -        self.assertEqual(t, bar())
    -
    -    def test_no_default_value(self) -> None:
    -        @validate(Parameter(name='a', required=False))
    -        def bar(a: datetime) -> datetime:
    -            return a
    -
    -        with self.assertRaises(expected_exception=ValidateException):
    -            bar()
    -
    -    def test_default_value_is_not_validated_external_parameter(self) -> None:
    -        t = datetime(year=2021, month=11, day=24)
    -
    -        if 'a' in os.environ:
    -            del os.environ['a']
    -
    -        @validate(EnvironmentVariableParameter(name='a', default=t, validators=[DateTimeUnixTimestamp()], required=False))
    -        def bar(a: datetime) -> datetime:
    -            return a
    -
    -        self.assertEqual(t, bar())
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def setUp(self) ‑> None -
    -
    -
    - -Expand source code - -
    def setUp(self) -> None:
    -    if 'foo' in os.environ:
    -        del os.environ['foo']
    -
    -

    Hook method for setting up the test fixture before exercising it.

    -
    -
    -def test_allow_renaming_of_parameter_of_custom_validator(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_allow_renaming_of_parameter_of_custom_validator(self) -> None:
    -    class MyCustomValidator(Validator):
    -        def validate(self, i_renamed_this_arg: Any) -> Any:
    -            return i_renamed_this_arg
    -
    -    @validate(Parameter(name='a', validators=[MyCustomValidator()]))
    -    def bar(a: int):
    -        return a
    -
    -    self.assertEqual(42, bar(42))
    -    self.assertEqual(42, bar(a=42))
    -
    -
    -
    -
    -def test_call_with_args(self) -
    -
    -
    - -Expand source code - -
    def test_call_with_args(self):
    -    @validate(
    -        Parameter(name='x', validators=[Min(1)]),
    -    )
    -    def some_calculation(x: int) -> int:
    -        return x
    -
    -    some_calculation(42)
    -
    -
    -
    -
    -def test_default_value_is_not_validated_external_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_default_value_is_not_validated_external_parameter(self) -> None:
    -    t = datetime(year=2021, month=11, day=24)
    -
    -    if 'a' in os.environ:
    -        del os.environ['a']
    -
    -    @validate(EnvironmentVariableParameter(name='a', default=t, validators=[DateTimeUnixTimestamp()], required=False))
    -    def bar(a: datetime) -> datetime:
    -        return a
    -
    -    self.assertEqual(t, bar())
    -
    -
    -
    -
    -def test_default_value_is_not_validated_internal_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_default_value_is_not_validated_internal_parameter(self) -> None:
    -    t = datetime(year=2021, month=11, day=24)
    -    unix_timestamp = (t - datetime(year=1970, month=1, day=1)).total_seconds()
    -
    -    @validate(Parameter(name='a', required=False, default=t, validators=[DateTimeUnixTimestamp()]))
    -    def bar(a: datetime) -> datetime:
    -        return a
    -
    -    self.assertEqual(t, bar(a=unix_timestamp))
    -    self.assertEqual(t, bar())
    -
    -
    -
    -
    -def test_empty_parameter_kwargs_with_none(self) -
    -
    -
    - -Expand source code - -
    def test_empty_parameter_kwargs_with_none(self):
    -    @validate(
    -        Parameter(name='a', required=False),
    -        Parameter(name='b', required=True),
    -        Parameter(name='c', required=False),
    -        return_as=ReturnAs.KWARGS_WITH_NONE
    -    )
    -    def some_calculation(a, b, c):
    -        return str(a) + str(b) + str(c)
    -
    -    self.assertEqual('430-50', some_calculation(43, 0, -50))
    -    self.assertEqual('None0None', some_calculation(None, 0, None))
    -
    -
    -
    -
    -def test_empty_parameter_kwargs_without_none(self) -
    -
    -
    - -Expand source code - -
    def test_empty_parameter_kwargs_without_none(self):
    -    @validate(
    -        Parameter(name='a', required=False),
    -        Parameter(name='b', required=True),
    -        Parameter(name='c', required=False),
    -        return_as=ReturnAs.KWARGS_WITHOUT_NONE
    -    )
    -    def some_calculation(a: Optional[int] = 1, b: Optional[int] = 2, c:  Optional[int] = 3):
    -        return str(a) + str(b) + str(c)
    -
    -    self.assertEqual('430-50', some_calculation(43, 0, -50))
    -    self.assertEqual('103', some_calculation(None, 0, None))
    -
    -
    -
    -
    -def test_external_parameter_accepts_value_when_given(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_external_parameter_accepts_value_when_given(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo'))
    -    def bar(foo):
    -        return foo
    -
    -    self.assertEqual('42', bar('42'))
    -    self.assertEqual('42', bar(foo='42'))
    -
    -
    -
    -
    -def test_external_parameter_ignores_value_when_given(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_external_parameter_ignores_value_when_given(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo'), ignore_input=True)
    -    def bar(foo):
    -        return foo
    -
    -    os.environ['foo'] = '1'
    -
    -    self.assertEqual('1', bar('42'))
    -    self.assertEqual('1', bar(foo='42'))
    -
    -
    -
    -
    -def test_external_parameter_mixed_with_normal_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_external_parameter_mixed_with_normal_parameter(self) -> None:
    -    @validate(
    -        EnvironmentVariableParameter(name='foo'),
    -        Parameter(name='footer'),
    -        return_as=ReturnAs.KWARGS_WITHOUT_NONE,
    -    )
    -    def bar(foo, footer):
    -        return foo, footer
    -
    -    self.assertEqual(('42', 3), bar('42', 3))
    -
    -    os.environ['foo'] = '42'
    -    self.assertEqual(('42', 3), bar(footer=3))
    -
    -
    -
    -
    -def test_less_parameter_than_arguments(self) -
    -
    -
    - -Expand source code - -
    def test_less_parameter_than_arguments(self):
    -    @validate(
    -        Parameter(name='b'),
    -        strict=False,
    -    )
    -    def some_calculation(a, b, c):
    -        return a + b + c
    -
    -    some_calculation(43, 0, -50)
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        some_calculation(30, None, 50)
    -
    -
    -
    -
    -def test_multiple_parameters(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_multiple_parameters(self) -> None:
    -    @validate(
    -        Parameter(name='a', validators=[Min(3)]),
    -        Parameter(name='b', validators=[Max(3)]),
    -        Parameter(name='c', validators=[Max(43)]),
    -    )
    -    def bar(a, b, c):
    -        return a + b + c
    -
    -    self.assertEqual(11, bar(3, 3, 5))
    -    self.assertEqual(11, bar(a=3, b=3, c=5))
    -
    -
    -
    -
    -def test_no_default_value(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_no_default_value(self) -> None:
    -    @validate(Parameter(name='a', required=False))
    -    def bar(a: datetime) -> datetime:
    -        return a
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        bar()
    -
    -
    -
    -
    -def test_none_is_not_validated_if_not_required_kwargs_with_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_none_is_not_validated_if_not_required_kwargs_with_none(self) -> None:
    -    @validate(Parameter(name='a', validators=[Email()], required=False), return_as=ReturnAs.KWARGS_WITH_NONE)
    -    def bar(a: Optional[str]):
    -        return a
    -
    -    self.assertIsNone(bar(a=None))
    -    self.assertIsNone(bar(None))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        bar('no_email')
    -
    -
    -
    -
    -def test_none_is_not_validated_if_not_required_kwargs_without_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_none_is_not_validated_if_not_required_kwargs_without_none(self) -> None:
    -    @validate(Parameter(name='a', validators=[Email()], required=False), return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -    def bar(a: Optional[str] = None):
    -        return a
    -
    -    self.assertIsNone(bar(a=None))
    -    self.assertIsNone(bar(None))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        bar('no_email')
    -
    -
    -
    -
    -def test_none_is_removed_for_not_required_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_none_is_removed_for_not_required_parameter(self) -> None:
    -    @validate(Parameter(name='a', required=False))
    -    def bar(a: int = 42):
    -        return a
    -
    -    self.assertEqual(42, bar())
    -    self.assertEqual(2, bar(a=2))
    -    self.assertEqual(2, bar(2))
    -
    -
    -
    -
    -def test_required(self) -
    -
    -
    - -Expand source code - -
    def test_required(self):
    -    @validate(
    -        Parameter(name='a', required=True),
    -        Parameter(name='b', required=True),
    -        Parameter(name='c', required=True),
    -    )
    -    def some_calculation(a, b, c):
    -        return a + b + c
    -
    -    some_calculation(43, 0, -50)
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        some_calculation(30, None, 50)
    -
    -
    -
    -
    -def test_return_as_args(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_args(self) -> None:
    -    @validate(Parameter(name='x'), return_as=ReturnAs.ARGS)
    -    def bar(*args, **kwargs):
    -        return args, kwargs
    -
    -    self.assertEqual(((42,), {}), bar(42))
    -    self.assertEqual(((42,), {}), bar(x=42))
    -
    -
    -
    -
    -def test_return_as_args_advanced(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_args_advanced(self) -> None:
    -    @validate(
    -        Parameter(name='a'),
    -        Parameter(name='b'),
    -        Parameter(name='c'),
    -        return_as=ReturnAs.ARGS,
    -    )
    -    def bar(a, b, *args, **kwargs):
    -        return a, b, args, kwargs
    -
    -    bar(a=1, b=3, c=42)
    -    bar(1, 3, 4)
    -    bar(1, 3, c=4)
    -
    -
    -
    -
    -def test_return_as_args_advanced_different_order(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_args_advanced_different_order(self) -> None:
    -    @validate(
    -        Parameter(name='c'),
    -        Parameter(name='a'),
    -        Parameter(name='b'),
    -        return_as=ReturnAs.ARGS,
    -    )
    -    def bar(a, b, *args, **kwargs):
    -        return a, b, args, kwargs
    -
    -    self.assertEqual((1, 3, (42,), {}), bar(a=1, b=3, c=42))
    -    self.assertEqual((1, 3, (42,), {}), bar(1, 3, 42))
    -    self.assertEqual((42, 1, (3,), {}), bar(1, 3, c=42))
    -
    -
    -
    -
    -def test_return_as_kwargs_with_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_kwargs_with_none(self) -> None:
    -    @validate(Parameter(name='x'), return_as=ReturnAs.KWARGS_WITH_NONE)
    -    def bar(*args, **kwargs):
    -        return args, kwargs
    -
    -    self.assertEqual(((), {'x': 42}), bar(42))
    -    self.assertEqual(((), {'x': 42}), bar(x=42))
    -
    -
    -
    -
    -def test_return_as_kwargs_without_none(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_kwargs_without_none(self) -> None:
    -    @validate(Parameter(name='x'), return_as=ReturnAs.KWARGS_WITHOUT_NONE)
    -    def bar(*args, **kwargs):
    -        return args, kwargs
    -
    -    self.assertEqual(((), {'x': 42}), bar(42))
    -    self.assertEqual(((), {'x': 42}), bar(x=42))
    -
    -
    -
    -
    -def test_return_as_simple(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_as_simple(self) -> None:
    -    @validate(Parameter(name='x'), return_as=ReturnAs.ARGS)
    -    def bar(x):
    -        return x
    -
    -    self.assertEqual(42, bar(42))
    -    self.assertEqual(42, bar(x=42))
    -
    -
    -
    -
    -def test_return_multiple_args(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_return_multiple_args(self) -> None:
    -    @validate(
    -        Parameter(name='c'),
    -        Parameter(name='a'),
    -        Parameter(name='b'),
    -        return_as=ReturnAs.KWARGS_WITH_NONE,
    -    )
    -    def bar(*args, **kwargs):
    -        return args, kwargs
    -
    -    self.assertEqual(((), {'a': 1, 'b': 3, 'c': 42}), bar(a=1, b=3, c=42))
    -    self.assertEqual(((), {'a': 3, 'b': 42, 'c': 1}), bar(1, 3, 42))
    -    self.assertEqual(((), {'a': 1, 'b': 3, 'c': 42}), bar(1, 3, c=42))
    -
    -
    -
    -
    -def test_single_parameter(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_single_parameter(self) -> None:
    -    parameter = Parameter(name='x', validators=[MaxLength(3)])
    -    converted_value = parameter.validate(value='hed')
    -    self.assertEqual(converted_value, 'hed')
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        parameter.validate(value='hello world')
    -
    -
    -
    -
    -def test_single_validator(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_single_validator(self) -> None:
    -    validator = MaxLength(3)
    -    converted_value = validator.validate(value='hed')
    -    self.assertEqual(converted_value, 'hed')
    -
    -    with self.assertRaises(expected_exception=ValidatorException) as ex:
    -        validator.validate(value='hello world')
    -
    -    expected_error_msg = 'MaxLength: hello world is too long with length 11. Value: hello world'
    -    self.assertEqual(expected_error_msg, str(ex.exception))
    -
    -
    -
    -
    -def test_too_many_arguments(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_too_many_arguments(self) -> None:
    -    @validate(
    -        Parameter(name='x'),
    -    )
    -    def bar(x):
    -        return x
    -
    -    self.assertEqual(42, bar(42))
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        bar(42, 43)
    -
    -
    -
    -
    -def test_unexpected_parameter_not_strict(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_unexpected_parameter_not_strict(self) -> None:
    -    @validate(Parameter(name='y'), strict=False)
    -    def bar(x):
    -        return x
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        self.assertEqual(42, bar(42))
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        self.assertEqual(42, bar(x=42))
    -
    -
    -
    -
    -def test_unexpected_parameter_not_strict_external(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_unexpected_parameter_not_strict_external(self) -> None:
    -    @validate(EnvironmentVariableParameter(name='foo'))
    -    def bar(x):
    -        return x
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        self.assertEqual(42, bar(42))
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        self.assertEqual(42, bar(x=42))
    -
    -
    -
    -
    -def test_unexpected_parameter_strict(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_unexpected_parameter_strict(self) -> None:
    -    @validate(Parameter(name='y'))
    -    def bar(x):
    -        return x
    -
    -    with self.assertRaises(expected_exception=ValidateException):
    -        bar(42)
    -    with self.assertRaises(expected_exception=ValidateException):
    -        bar(x=42)
    -
    -
    -
    -
    -def test_validate_args(self) -
    -
    -
    - -Expand source code - -
    def test_validate_args(self):
    -    @validate(
    -        Parameter(name='a', validators=[Min(42, include_boundary=False)]),
    -        Parameter(name='b', validators=[Min(42, include_boundary=False)]),
    -        Parameter(name='c', validators=[Min(42, include_boundary=False)]),
    -    )
    -    def some_calculation(a, b, c):
    -        return a + b + c
    -
    -    some_calculation(43, 45, 50)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(30, 40, 50)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        some_calculation(c=30, a=40, b=50)
    -
    -
    -
    -
    -def test_validate_instance_method(self) -
    -
    -
    - -Expand source code - -
    def test_validate_instance_method(self):
    -    class MyClass:
    -        @validate(
    -            Parameter(name='x', validators=[Min(1)]),
    -        )
    -        def some_calculation(self, x: int) -> int:
    -            return x
    -
    -        @validate(
    -            Parameter(name='x', validators=[Min(1)]),
    -            return_as=ReturnAs.KWARGS_WITHOUT_NONE,
    -        )
    -        def some_calculation_2(self, x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(1)
    -    m.some_calculation(42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(0)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(-42)
    -
    -    m.some_calculation_2(1)
    -    m.some_calculation_2(42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation_2(0)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation_2(-42)
    -
    -
    -
    -
    -def test_validate_static_method(self) -
    -
    -
    - -Expand source code - -
    def test_validate_static_method(self):
    -    """ The @staticmethod decorator have to be ABOVE the @validate decorator. """
    -
    -    class MyClass:
    -        @staticmethod
    -        @validate(
    -            Parameter(name='x', validators=[Min(1)]),
    -        )
    -        def some_calculation(x: int) -> int:
    -            return x
    -
    -    m = MyClass()
    -    m.some_calculation(1)
    -    m.some_calculation(42)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(0)
    -    with self.assertRaises(expected_exception=ParameterException):
    -        m.some_calculation(-42)
    -
    -

    The @staticmethod decorator have to be ABOVE the @validate decorator.

    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_composite.html b/docs/pedantic/tests/validate/test_validator_composite.html deleted file mode 100644 index ac4f3c8..0000000 --- a/docs/pedantic/tests/validate/test_validator_composite.html +++ /dev/null @@ -1,165 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_composite API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_composite

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorComposite -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorComposite(TestCase):
    -    def test_validator_composite(self) -> None:
    -        @validate(Parameter(name='x', validators=[Composite([Min(3), Max(5)])]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(3, foo(3))
    -        self.assertEqual(4, foo(4))
    -        self.assertEqual(5, foo(5))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(5.0001)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(2.9999)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_composite(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_composite(self) -> None:
    -    @validate(Parameter(name='x', validators=[Composite([Min(3), Max(5)])]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(3, foo(3))
    -    self.assertEqual(4, foo(4))
    -    self.assertEqual(5, foo(5))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(5.0001)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(2.9999)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_datetime_unix_timestamp.html b/docs/pedantic/tests/validate/test_validator_datetime_unix_timestamp.html deleted file mode 100644 index b666eb9..0000000 --- a/docs/pedantic/tests/validate/test_validator_datetime_unix_timestamp.html +++ /dev/null @@ -1,179 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_datetime_unix_timestamp API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_datetime_unix_timestamp

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorDatetimeUnixTimestamp -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorDatetimeUnixTimestamp(TestCase):
    -    def test_validator_datetime_unix_timestamp(self) -> None:
    -        @validate(Parameter(name='x', validators=[DateTimeUnixTimestamp()]))
    -        def foo(x):
    -            return x
    -
    -        now = datetime.now()
    -        unix_timestamp = (now - datetime(year=1970, month=1, day=1)).total_seconds()
    -        self.assertEqual(now, foo(unix_timestamp))
    -        self.assertEqual(now, foo(str(unix_timestamp)))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo('12.12.2020')
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo('invalid')
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo({'a': 1})
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(unix_timestamp * 1000)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_datetime_unix_timestamp(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_datetime_unix_timestamp(self) -> None:
    -    @validate(Parameter(name='x', validators=[DateTimeUnixTimestamp()]))
    -    def foo(x):
    -        return x
    -
    -    now = datetime.now()
    -    unix_timestamp = (now - datetime(year=1970, month=1, day=1)).total_seconds()
    -    self.assertEqual(now, foo(unix_timestamp))
    -    self.assertEqual(now, foo(str(unix_timestamp)))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo('12.12.2020')
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo('invalid')
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo({'a': 1})
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(unix_timestamp * 1000)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_email.html b/docs/pedantic/tests/validate/test_validator_email.html deleted file mode 100644 index bd1cd69..0000000 --- a/docs/pedantic/tests/validate/test_validator_email.html +++ /dev/null @@ -1,186 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_email API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_email

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorEmail -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorEmail(TestCase):
    -    def test_validator_email(self) -> None:
    -        @validate(Parameter(name='x', validators=[Email()]))
    -        def foo(x):
    -            return x
    -
    -        for value in ['fred@web.de', 'genial@gmail.com', 'test@test.co.uk']:
    -            self.assertEqual(value, foo(value))
    -
    -        for value in ['fred', 'fred@web', 'fred@w@eb.de', 'fred@@web.de', 'invalid@invalid']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -    def test_validator_email_converts_to_lower_case(self) -> None:
    -        @validate(Parameter(name='x', validators=[Email(post_processor=lambda x: x.lower())]))
    -        def foo(x):
    -            return x
    -
    -        for value in ['Fred@Web.de', 'GENIAL@GMAIL.com', 'test@test.CO.UK']:
    -            self.assertEqual(value.lower(), foo(value))
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_email(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_email(self) -> None:
    -    @validate(Parameter(name='x', validators=[Email()]))
    -    def foo(x):
    -        return x
    -
    -    for value in ['fred@web.de', 'genial@gmail.com', 'test@test.co.uk']:
    -        self.assertEqual(value, foo(value))
    -
    -    for value in ['fred', 'fred@web', 'fred@w@eb.de', 'fred@@web.de', 'invalid@invalid']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -def test_validator_email_converts_to_lower_case(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_email_converts_to_lower_case(self) -> None:
    -    @validate(Parameter(name='x', validators=[Email(post_processor=lambda x: x.lower())]))
    -    def foo(x):
    -        return x
    -
    -    for value in ['Fred@Web.de', 'GENIAL@GMAIL.com', 'test@test.CO.UK']:
    -        self.assertEqual(value.lower(), foo(value))
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_for_each.html b/docs/pedantic/tests/validate/test_validator_for_each.html deleted file mode 100644 index 8b4f3e2..0000000 --- a/docs/pedantic/tests/validate/test_validator_for_each.html +++ /dev/null @@ -1,190 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_for_each API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_for_each

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorForEach -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorForEach(TestCase):
    -    def test_validator_for_each_single_child(self) -> None:
    -        @validate(Parameter(name='x', validators=[ForEach(Min(3))]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual([3, 4, 5], foo([3, 4, 5]))
    -
    -        for value in [42, [3, 2, 5]]:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -    def test_validator_for_each_multiple_children(self) -> None:
    -        @validate(Parameter(name='x', validators=[ForEach([Min(3), Max(4)])]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual([3, 4], foo([3, 4]))
    -
    -        for value in [42, [3, 2, 5]]:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_for_each_multiple_children(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_for_each_multiple_children(self) -> None:
    -    @validate(Parameter(name='x', validators=[ForEach([Min(3), Max(4)])]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual([3, 4], foo([3, 4]))
    -
    -    for value in [42, [3, 2, 5]]:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -def test_validator_for_each_single_child(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_for_each_single_child(self) -> None:
    -    @validate(Parameter(name='x', validators=[ForEach(Min(3))]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual([3, 4, 5], foo([3, 4, 5]))
    -
    -    for value in [42, [3, 2, 5]]:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_is_enum.html b/docs/pedantic/tests/validate/test_validator_is_enum.html deleted file mode 100644 index e6ad9f7..0000000 --- a/docs/pedantic/tests/validate/test_validator_is_enum.html +++ /dev/null @@ -1,415 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_is_enum API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_is_enum

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class MyEnum -(*args, **kwds) -
    -
    -
    - -Expand source code - -
    class MyEnum(Enum):
    -    RED = 'RED'
    -    BLUE = 'BLUE'
    -
    -

    Create a collection of name/value pairs.

    -

    Example enumeration:

    -
    >>> class Color(Enum):
    -...     RED = 1
    -...     BLUE = 2
    -...     GREEN = 3
    -
    -

    Access them by:

    -
      -
    • attribute access:
    • -
    -
    -
    -
    -

    Color.RED -

    -
    -
    -
    -
      -
    • value lookup:
    • -
    -
    -
    -
    -

    Color(1) -

    -
    -
    -
    -
      -
    • name lookup:
    • -
    -
    -
    -
    -

    Color['RED'] -

    -
    -
    -
    -

    Enumerations can be iterated over, and know how many members they have:

    -
    >>> len(Color)
    -3
    -
    -
    >>> list(Color)
    -[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
    -
    -

    Methods can be added to enumerations, and members can have their own -attributes – see the documentation for details.

    -

    Ancestors

    -
      -
    • enum.Enum
    • -
    -

    Class variables

    -
    -
    var BLUE
    -
    -

    The type of the None singleton.

    -
    -
    var RED
    -
    -

    The type of the None singleton.

    -
    -
    -
    -
    -class MyIntEnum -(*args, **kwds) -
    -
    -
    - -Expand source code - -
    class MyIntEnum(IntEnum):
    -    RED = 1
    -    BLUE = 2
    -
    -

    Enum where members are also (and must be) ints

    -

    Ancestors

    -
      -
    • enum.IntEnum
    • -
    • builtins.int
    • -
    • enum.ReprEnum
    • -
    • enum.Enum
    • -
    -

    Class variables

    -
    -
    var BLUE
    -
    -

    The type of the None singleton.

    -
    -
    var RED
    -
    -

    The type of the None singleton.

    -
    -
    -
    -
    -class TestValidatorIsEnum -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorIsEnum(TestCase):
    -    def test_validator_is_enum_convert_true(self) -> None:
    -        @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=True)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(MyEnum.RED, foo('RED'))
    -        self.assertEqual(MyEnum.BLUE, foo('BLUE'))
    -
    -        for value in ['fred', 1, 'GREEN']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -    def test_validator_is_enum_int_enum_convert_true(self) -> None:
    -        @validate(Parameter(name='x', validators=[IsEnum(MyIntEnum, convert=True)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(MyIntEnum.RED, foo('1'))
    -        self.assertEqual(MyIntEnum.BLUE, foo('2'))
    -        self.assertEqual(MyIntEnum.RED, foo(1))
    -        self.assertEqual(MyIntEnum.BLUE, foo(2))
    -
    -        for value in ['fred', 3, 'GREEN']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -    def test_validator_is_enum_convert_false(self) -> None:
    -        @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual('RED', foo('RED'))
    -        self.assertEqual('BLUE', foo('BLUE'))
    -
    -        for value in ['fred', 1, 'GREEN']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -    def test_validator_is_enum_to_upper_case(self) -> None:
    -        @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual('RED', foo('red'))
    -        self.assertEqual('BLUE', foo('blue'))
    -        self.assertEqual('BLUE', foo('bLUe'))
    -
    -    def test_validator_is_enum_to_upper_case_disabled(self) -> None:
    -        @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False, to_upper_case=False)]))
    -        def foo(x): print(x)
    -
    -        for value in ['red', 'blue', 'Red', 'bLUe']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_is_enum_convert_false(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_is_enum_convert_false(self) -> None:
    -    @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual('RED', foo('RED'))
    -    self.assertEqual('BLUE', foo('BLUE'))
    -
    -    for value in ['fred', 1, 'GREEN']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -def test_validator_is_enum_convert_true(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_is_enum_convert_true(self) -> None:
    -    @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=True)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(MyEnum.RED, foo('RED'))
    -    self.assertEqual(MyEnum.BLUE, foo('BLUE'))
    -
    -    for value in ['fred', 1, 'GREEN']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -def test_validator_is_enum_int_enum_convert_true(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_is_enum_int_enum_convert_true(self) -> None:
    -    @validate(Parameter(name='x', validators=[IsEnum(MyIntEnum, convert=True)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(MyIntEnum.RED, foo('1'))
    -    self.assertEqual(MyIntEnum.BLUE, foo('2'))
    -    self.assertEqual(MyIntEnum.RED, foo(1))
    -    self.assertEqual(MyIntEnum.BLUE, foo(2))
    -
    -    for value in ['fred', 3, 'GREEN']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -def test_validator_is_enum_to_upper_case(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_is_enum_to_upper_case(self) -> None:
    -    @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual('RED', foo('red'))
    -    self.assertEqual('BLUE', foo('blue'))
    -    self.assertEqual('BLUE', foo('bLUe'))
    -
    -
    -
    -
    -def test_validator_is_enum_to_upper_case_disabled(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_is_enum_to_upper_case_disabled(self) -> None:
    -    @validate(Parameter(name='x', validators=[IsEnum(MyEnum, convert=False, to_upper_case=False)]))
    -    def foo(x): print(x)
    -
    -    for value in ['red', 'blue', 'Red', 'bLUe']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_is_uuid.html b/docs/pedantic/tests/validate/test_validator_is_uuid.html deleted file mode 100644 index 8db3daa..0000000 --- a/docs/pedantic/tests/validate/test_validator_is_uuid.html +++ /dev/null @@ -1,194 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_is_uuid API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_is_uuid

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorIsUUID -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorIsUUID(TestCase):
    -    def test_validator_is_uuid(self):
    -        @validate(Parameter(name='x', validators=[IsUuid()], required=False))
    -        def foo(x):
    -            return x
    -
    -        for id_ in [str(uuid1()), str(uuid3(uuid1(), 'b')), str(uuid4()), str(uuid5(uuid1(), 'b'))]:
    -            self.assertEqual(id_, foo(id_))
    -
    -        for no_id in ['invalid', 12]:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(no_id)
    -
    -    def test_validator_is_uuid_with_for_each_and_none_value(self):
    -        @validate(Parameter(name='x', validators=[ForEach(IsUuid())]))
    -        def foo(x):
    -            return x
    -
    -        uuid = str(uuid1())
    -        self.assertEqual([], foo([]))
    -        self.assertEqual([uuid], foo([uuid]))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo([None])
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_is_uuid(self) -
    -
    -
    - -Expand source code - -
    def test_validator_is_uuid(self):
    -    @validate(Parameter(name='x', validators=[IsUuid()], required=False))
    -    def foo(x):
    -        return x
    -
    -    for id_ in [str(uuid1()), str(uuid3(uuid1(), 'b')), str(uuid4()), str(uuid5(uuid1(), 'b'))]:
    -        self.assertEqual(id_, foo(id_))
    -
    -    for no_id in ['invalid', 12]:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(no_id)
    -
    -
    -
    -
    -def test_validator_is_uuid_with_for_each_and_none_value(self) -
    -
    -
    - -Expand source code - -
    def test_validator_is_uuid_with_for_each_and_none_value(self):
    -    @validate(Parameter(name='x', validators=[ForEach(IsUuid())]))
    -    def foo(x):
    -        return x
    -
    -    uuid = str(uuid1())
    -    self.assertEqual([], foo([]))
    -    self.assertEqual([uuid], foo([uuid]))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo([None])
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_match_pattern.html b/docs/pedantic/tests/validate/test_validator_match_pattern.html deleted file mode 100644 index 79f7174..0000000 --- a/docs/pedantic/tests/validate/test_validator_match_pattern.html +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_match_pattern API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_match_pattern

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorMatchPattern -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorMatchPattern(TestCase):
    -    def test_validator_match_pattern(self) -> None:
    -        pattern = r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$'
    -
    -        @validate(Parameter(name='x', validators=[MatchPattern(pattern)]))
    -        def foo(x):
    -            return x
    -
    -        for value in ['00:00', '02:45', '14:59', '23:59']:
    -            self.assertEqual(value, foo(value))
    -
    -        for value in ['00:70', '24:00', '30:00', 'invalid']:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo([3, 2, 5])
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_match_pattern(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_match_pattern(self) -> None:
    -    pattern = r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$'
    -
    -    @validate(Parameter(name='x', validators=[MatchPattern(pattern)]))
    -    def foo(x):
    -        return x
    -
    -    for value in ['00:00', '02:45', '14:59', '23:59']:
    -        self.assertEqual(value, foo(value))
    -
    -    for value in ['00:70', '24:00', '30:00', 'invalid']:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo([3, 2, 5])
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_max.html b/docs/pedantic/tests/validate/test_validator_max.html deleted file mode 100644 index 68e034b..0000000 --- a/docs/pedantic/tests/validate/test_validator_max.html +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_max API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_max

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorMax -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorMax(TestCase):
    -    def test_validator_max_length_include_boundary_true(self) -> None:
    -        @validate(Parameter(name='x', validators=[Max(3, include_boundary=True)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(3, foo(3))
    -        self.assertEqual(2, foo(2))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(4)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(3.001)
    -
    -    def test_validator_max_length_include_boundary_false(self) -> None:
    -        @validate(Parameter(name='x', validators=[Max(3, include_boundary=False)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(2.9999, foo(2.9999))
    -        self.assertEqual(2, foo(2))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(4)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(3)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_max_length_include_boundary_false(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_max_length_include_boundary_false(self) -> None:
    -    @validate(Parameter(name='x', validators=[Max(3, include_boundary=False)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(2.9999, foo(2.9999))
    -    self.assertEqual(2, foo(2))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(4)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(3)
    -
    -
    -
    -
    -def test_validator_max_length_include_boundary_true(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_max_length_include_boundary_true(self) -> None:
    -    @validate(Parameter(name='x', validators=[Max(3, include_boundary=True)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(3, foo(3))
    -    self.assertEqual(2, foo(2))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(4)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(3.001)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_max_length.html b/docs/pedantic/tests/validate/test_validator_max_length.html deleted file mode 100644 index 2ef27bd..0000000 --- a/docs/pedantic/tests/validate/test_validator_max_length.html +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_max_length API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_max_length

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorMaxLength -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorMaxLength(TestCase):
    -    def test_validator_max_length(self) -> None:
    -        @validate(Parameter(name='x', validators=[MaxLength(3)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual('hi', foo('hi'))
    -        self.assertEqual('hi!', foo('hi!'))
    -        self.assertEqual([1, 2, 3], foo([1, 2, 3]))
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo('hi!!')
    -
    -        assert ex.exception.message == 'hi!! is too long with length 4.'
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo([1, 2, 3, 4])
    -
    -        assert ex.exception.message == '[1, 2, 3, 4] is too long with length 4.'
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo(42)
    -
    -        assert ex.exception.message == '42 has no length.'
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_max_length(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_max_length(self) -> None:
    -    @validate(Parameter(name='x', validators=[MaxLength(3)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual('hi', foo('hi'))
    -    self.assertEqual('hi!', foo('hi!'))
    -    self.assertEqual([1, 2, 3], foo([1, 2, 3]))
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo('hi!!')
    -
    -    assert ex.exception.message == 'hi!! is too long with length 4.'
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo([1, 2, 3, 4])
    -
    -    assert ex.exception.message == '[1, 2, 3, 4] is too long with length 4.'
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo(42)
    -
    -    assert ex.exception.message == '42 has no length.'
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_min.html b/docs/pedantic/tests/validate/test_validator_min.html deleted file mode 100644 index 5fb2f9b..0000000 --- a/docs/pedantic/tests/validate/test_validator_min.html +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_min API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_min

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorMin -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorMin(TestCase):
    -    def test_validator_min_length_include_boundary_true(self) -> None:
    -        @validate(Parameter(name='x', validators=[Min(3, include_boundary=True)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(3, foo(3))
    -        self.assertEqual(4, foo(4))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(2)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(2.9999)
    -
    -    def test_validator_min_length_include_boundary_false(self) -> None:
    -        @validate(Parameter(name='x', validators=[Min(3, include_boundary=False)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual(3.0001, foo(3.0001))
    -        self.assertEqual(4, foo(4))
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(2)
    -
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(3)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_min_length_include_boundary_false(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_min_length_include_boundary_false(self) -> None:
    -    @validate(Parameter(name='x', validators=[Min(3, include_boundary=False)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(3.0001, foo(3.0001))
    -    self.assertEqual(4, foo(4))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(2)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(3)
    -
    -
    -
    -
    -def test_validator_min_length_include_boundary_true(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_min_length_include_boundary_true(self) -> None:
    -    @validate(Parameter(name='x', validators=[Min(3, include_boundary=True)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual(3, foo(3))
    -    self.assertEqual(4, foo(4))
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(2)
    -
    -    with self.assertRaises(expected_exception=ParameterException):
    -        foo(2.9999)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_min_length.html b/docs/pedantic/tests/validate/test_validator_min_length.html deleted file mode 100644 index 44e3eb3..0000000 --- a/docs/pedantic/tests/validate/test_validator_min_length.html +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_min_length API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_min_length

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorMinLength -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorMinLength(TestCase):
    -    def test_validator_min_length(self) -> None:
    -        @validate(Parameter(name='x', validators=[MinLength(3)]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual('hi!', foo('hi!'))
    -        self.assertEqual('hello', foo('hello'))
    -        self.assertEqual([1, 2, 3], foo([1, 2, 3]))
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo('hi')
    -
    -        assert ex.exception.message == 'hi is too short with length 2.'
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo([1, 2])
    -
    -        assert ex.exception.message == '[1, 2] is too short with length 2.'
    -
    -        with self.assertRaises(expected_exception=ParameterException) as ex:
    -            foo(42)
    -
    -        assert ex.exception.message == '42 has no length.'
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_min_length(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_min_length(self) -> None:
    -    @validate(Parameter(name='x', validators=[MinLength(3)]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual('hi!', foo('hi!'))
    -    self.assertEqual('hello', foo('hello'))
    -    self.assertEqual([1, 2, 3], foo([1, 2, 3]))
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo('hi')
    -
    -    assert ex.exception.message == 'hi is too short with length 2.'
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo([1, 2])
    -
    -    assert ex.exception.message == '[1, 2] is too short with length 2.'
    -
    -    with self.assertRaises(expected_exception=ParameterException) as ex:
    -        foo(42)
    -
    -    assert ex.exception.message == '42 has no length.'
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/pedantic/tests/validate/test_validator_not_empty.html b/docs/pedantic/tests/validate/test_validator_not_empty.html deleted file mode 100644 index 9b69012..0000000 --- a/docs/pedantic/tests/validate/test_validator_not_empty.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - -pedantic.tests.validate.test_validator_not_empty API documentation - - - - - - - - - - - -
    -
    -
    -

    Module pedantic.tests.validate.test_validator_not_empty

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class TestValidatorNotEmpty -(methodName='runTest') -
    -
    -
    - -Expand source code - -
    class TestValidatorNotEmpty(TestCase):
    -    def test_validator_not_empty(self) -> None:
    -        @validate(Parameter(name='x', validators=[NotEmpty()]))
    -        def foo(x):
    -            return x
    -
    -        self.assertEqual('hi', foo('hi'))
    -        self.assertEqual('hi', foo('   hi     '))
    -        self.assertEqual([1], foo([1]))
    -
    -        for value in ['', '   ', [], {}, set()]:
    -            with self.assertRaises(expected_exception=ParameterException):
    -                foo(value)
    -
    -

    A class whose instances are single test cases.

    -

    By default, the test code itself should be placed in a method named -'runTest'.

    -

    If the fixture may be used for many test cases, create as -many test methods as are needed. When instantiating such a TestCase -subclass, specify in the constructor arguments the name of the test method -that the instance is to execute.

    -

    Test authors should subclass TestCase for their own tests. Construction -and deconstruction of the test's environment ('fixture') can be -implemented by overriding the 'setUp' and 'tearDown' methods respectively.

    -

    If it is necessary to override the init method, the base class -init method must always be called. It is important that subclasses -should not change the signature of their init method, since instances -of the classes are instantiated automatically by parts of the framework -in order to be run.

    -

    When subclassing TestCase, you can set these attributes: -* failureException: determines which exception will be raised when -the instance's assertion methods fail; test methods raising this -exception will be deemed to have 'failed' rather than 'errored'. -* longMessage: determines whether long messages (including repr of -objects used in assert methods) will be printed on failure in addition -to any explicit message passed. -* maxDiff: sets the maximum length of a diff in failure messages -by assert methods using difflib. It is looked up as an instance -attribute so can be configured by individual tests if required.

    -

    Create an instance of the class that will use the named test -method when executed. Raises a ValueError if the instance does -not have a method with the specified name.

    -

    Ancestors

    -
      -
    • unittest.case.TestCase
    • -
    -

    Methods

    -
    -
    -def test_validator_not_empty(self) ‑> None -
    -
    -
    - -Expand source code - -
    def test_validator_not_empty(self) -> None:
    -    @validate(Parameter(name='x', validators=[NotEmpty()]))
    -    def foo(x):
    -        return x
    -
    -    self.assertEqual('hi', foo('hi'))
    -    self.assertEqual('hi', foo('   hi     '))
    -    self.assertEqual([1], foo([1]))
    -
    -    for value in ['', '   ', [], {}, set()]:
    -        with self.assertRaises(expected_exception=ParameterException):
    -            foo(value)
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/pedantic/__init__.py b/pedantic/__init__.py index d331986..f6deeb8 100644 --- a/pedantic/__init__.py +++ b/pedantic/__init__.py @@ -1,7 +1,7 @@ -from pedantic.decorators import overrides, rename_kwargs, timer, count_calls, trace, trace_if_returns, \ - does_same_as_function, deprecated, unimplemented, require_kwargs, pedantic, \ - pedantic_require_docstring, for_all_methods, trace_class, timer_class, pedantic_class, \ - pedantic_class_require_docstring, Rename, mock, frozen_dataclass, frozen_type_safe_dataclass, in_subprocess, \ +from pedantic.decorators import overrides, trace, trace_if_returns, \ + deprecated, require_kwargs, pedantic, \ + pedantic_require_docstring, for_all_methods, trace_class, pedantic_class, \ + pedantic_class_require_docstring, frozen_dataclass, frozen_type_safe_dataclass, in_subprocess, \ calculate_in_subprocess, retry from pedantic.mixins import GenericMixin, create_decorator, DecoratorType, WithDecoratedMethods diff --git a/pedantic/decorators/__init__.py b/pedantic/decorators/__init__.py index e7fdcda..6ef8c63 100644 --- a/pedantic/decorators/__init__.py +++ b/pedantic/decorators/__init__.py @@ -1,18 +1,11 @@ from .fn_deco_context_manager import safe_contextmanager, safe_async_contextmanager -from .fn_deco_count_calls import count_calls from .fn_deco_deprecated import deprecated -from .fn_deco_does_same_as_function import does_same_as_function from .fn_deco_in_subprocess import in_subprocess, calculate_in_subprocess -from .fn_deco_mock import mock from .fn_deco_overrides import overrides from .fn_deco_pedantic import pedantic, pedantic_require_docstring -from .fn_deco_rename_kwargs import rename_kwargs, Rename from .fn_deco_require_kwargs import require_kwargs from .fn_deco_retry import retry, retry_func -from .fn_deco_timer import timer from .fn_deco_trace import trace from .fn_deco_trace_if_returns import trace_if_returns -from .fn_deco_unimplemented import unimplemented -from .class_decorators import pedantic_class, pedantic_class_require_docstring, timer_class, trace_class, \ - for_all_methods +from .class_decorators import pedantic_class, pedantic_class_require_docstring, trace_class, for_all_methods from .cls_deco_frozen_dataclass import frozen_dataclass, frozen_type_safe_dataclass diff --git a/pedantic/decorators/class_decorators.py b/pedantic/decorators/class_decorators.py index dca6cd1..34495e4 100644 --- a/pedantic/decorators/class_decorators.py +++ b/pedantic/decorators/class_decorators.py @@ -4,7 +4,7 @@ from typing import Callable, Optional, Dict, Type from pedantic.constants import TYPE_VAR_ATTR_NAME, TYPE_VAR_METHOD_NAME, F, C, TYPE_VAR_SELF -from pedantic.decorators import timer, trace +from pedantic.decorators import trace from pedantic.decorators.fn_deco_pedantic import pedantic, pedantic_require_docstring from pedantic.env_var_logic import is_enabled from pedantic.exceptions import PedanticTypeCheckException @@ -68,11 +68,6 @@ def trace_class(cls: C) -> C: return for_all_methods(decorator=trace)(cls=cls) -def timer_class(cls: C) -> C: - """ Shortcut for @for_all_methods(timer) """ - return for_all_methods(decorator=timer)(cls=cls) - - def _get_wrapped(prop: Optional[F], decorator: F) -> Optional[F]: return decorator(prop) if prop is not None else None diff --git a/pedantic/decorators/fn_deco_count_calls.py b/pedantic/decorators/fn_deco_count_calls.py deleted file mode 100644 index 3fc1ebd..0000000 --- a/pedantic/decorators/fn_deco_count_calls.py +++ /dev/null @@ -1,32 +0,0 @@ -from datetime import datetime -from functools import wraps -from typing import Any - -from pedantic.constants import F, ReturnType - - -def count_calls(func: F) -> F: - """ - Prints how often the method is called during program execution. - - Example: - - >>> @count_calls - ... def often_used_method(): - ... return 42 - >>> often_used_method() - Count Calls: Call 1 of function 'often_used_method' at ... - >>> often_used_method() - Count Calls: Call 2 of function 'often_used_method' at ... - >>> often_used_method() - Count Calls: Call 3 of function 'often_used_method' at ... - """ - - @wraps(func) - def wrapper(*args: Any, **kwargs: Any) -> ReturnType: - wrapper.num_calls += 1 - print(f"Count Calls: Call {wrapper.num_calls} of function {func.__name__!r} at {datetime.now()}.") - return func(*args, **kwargs) - - wrapper.num_calls = 0 - return wrapper diff --git a/pedantic/decorators/fn_deco_does_same_as_function.py b/pedantic/decorators/fn_deco_does_same_as_function.py deleted file mode 100644 index 0ce47ea..0000000 --- a/pedantic/decorators/fn_deco_does_same_as_function.py +++ /dev/null @@ -1,54 +0,0 @@ -import inspect -from functools import wraps -from typing import Any - -from pedantic.constants import F, ReturnType - - -def does_same_as_function(other_func: F) -> F: - """ - Each time the decorated function is executed, the function other_func is also executed and the results - are compared. An AssertionError is raised if the results are not equal. - - Example: - - >>> def other_calculation(a, b, c): - ... return c + b + a - >>> @does_same_as_function(other_calculation) - ... def some_calculation(a, b, c): - ... return a + b + c - >>> some_calculation(1, 2, 3) - 6 - """ - - def decorator(decorated_func: F) -> F: - @wraps(decorated_func) - def wrapper(*args: Any, **kwargs: Any) -> ReturnType: - result = decorated_func(*args, **kwargs) - other = other_func(*args, **kwargs) - - if other != result: - raise AssertionError(f'Different outputs: Function "{decorated_func.__name__}" returns {result} and ' - f'function "{other_func.__name__}" returns {other} for parameters {args} {kwargs}') - return result - - @wraps(decorated_func) - async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType: - result = await decorated_func(*args, **kwargs) - - if inspect.iscoroutinefunction(other_func): - other = await other_func(*args, **kwargs) - else: - other = other_func(*args, **kwargs) - - if other != result: - raise AssertionError(f'Different outputs: Function "{decorated_func.__name__}" returns {result} and ' - f'function "{other_func.__name__}" returns {other} for parameters {args} {kwargs}') - return result - - if inspect.iscoroutinefunction(decorated_func): - return async_wrapper - else: - return wrapper - - return decorator diff --git a/pedantic/decorators/fn_deco_mock.py b/pedantic/decorators/fn_deco_mock.py deleted file mode 100644 index 7563918..0000000 --- a/pedantic/decorators/fn_deco_mock.py +++ /dev/null @@ -1,38 +0,0 @@ -import inspect -from functools import wraps -from typing import Any - -from pedantic.constants import ReturnType, F - - -def mock(return_value: ReturnType) -> F: - """ - Skip the execution of the function and simply return the given return value instead. - This can be useful you want to check quickly if the behavior of the function causes a specific problem. - Without this decorator you actually need to change the implementation of the function temporarily. - - Example: - - >>> @mock(return_value=42) - ... def my_function(a, b, c): - ... return a + b + c - >>> my_function(1, 2, 3) - 42 - >>> my_function(1000, 88, 204) - 42 - """ - - def decorator(func: F) -> F: - @wraps(func) - def wrapper(*args: Any, **kwargs: Any) -> ReturnType: - return return_value - - @wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType: - return return_value - - if inspect.iscoroutinefunction(func): - return async_wrapper - else: - return wrapper - return decorator diff --git a/pedantic/decorators/fn_deco_rename_kwargs.py b/pedantic/decorators/fn_deco_rename_kwargs.py deleted file mode 100644 index b529a22..0000000 --- a/pedantic/decorators/fn_deco_rename_kwargs.py +++ /dev/null @@ -1,47 +0,0 @@ -from functools import wraps -from typing import Callable - -from pedantic.constants import F, ReturnType - - -class Rename: - def __init__(self, from_: str, to: str) -> None: - self.from_ = from_ - self.to = to - - -def rename_kwargs(*params: Rename) -> Callable[[F], F]: - """ - Renames the keyword arguments based on the given "Rename" rules when the decorated function is called. - You can also use this to define aliases for keyword arguments. - - Example: - - >>> @rename_kwargs( - ... Rename(from_='firstname', to='a'), - ... Rename(from_='lastname', to='b'), - ... ) - ... def my_function(a, b): - ... return a + ' ' + b - >>> my_function(a='egon', b='olsen') # the normal way - 'egon olsen' - >>> my_function(firstname='egon', lastname='olsen') # using new defined keyword arguments - 'egon olsen' - """ - - param_dict = {p.from_: p.to for p in params} - - def decorator(func: F) -> F: - @wraps(func) - def wrapper(*args, **kwargs) -> ReturnType: - result_kwargs = {} - - for k, v in kwargs.items(): - if k in param_dict: - result_kwargs[param_dict[k]] = kwargs[k] - else: - result_kwargs[k] = kwargs[k] - - return func(*args, **result_kwargs) - return wrapper - return decorator diff --git a/pedantic/decorators/fn_deco_timer.py b/pedantic/decorators/fn_deco_timer.py deleted file mode 100644 index 843fc47..0000000 --- a/pedantic/decorators/fn_deco_timer.py +++ /dev/null @@ -1,44 +0,0 @@ -import inspect -from datetime import datetime -from functools import wraps -from typing import Any - -from pedantic.constants import F, ReturnType - - -def timer(func: F) -> F: - """ - Prints how long the execution of the decorated function takes. - - Example: - - >>> @timer - ... def long_taking_calculation(): - ... return 42 - >>> long_taking_calculation() - Timer: Finished function "long_taking_calculation" in 0:00:00... - 42 - """ - - @wraps(func) - def wrapper(*args: Any, **kwargs: Any) -> ReturnType: - start_time: datetime = datetime.now() - value = func(*args, **kwargs) - end_time = datetime.now() - run_time = end_time - start_time - print(f'Timer: Finished function "{func.__name__}" in {run_time}.') - return value - - @wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> ReturnType: - start_time: datetime = datetime.now() - value = await func(*args, **kwargs) - end_time = datetime.now() - run_time = end_time - start_time - print(f'Timer: Finished function "{func.__name__}" in {run_time}.') - return value - - if inspect.iscoroutinefunction(func): - return async_wrapper - else: - return wrapper diff --git a/pedantic/decorators/fn_deco_unimplemented.py b/pedantic/decorators/fn_deco_unimplemented.py deleted file mode 100644 index e84e513..0000000 --- a/pedantic/decorators/fn_deco_unimplemented.py +++ /dev/null @@ -1,26 +0,0 @@ -from functools import wraps -from typing import Any - -from pedantic.exceptions import NotImplementedException -from pedantic.constants import F, ReturnType - - -def unimplemented(func: F) -> F: - """ - For documentation purposes. Throw NotImplementedException if the function is called. - - Example: - - >>> @unimplemented - ... def my_function(a, b, c): - ... pass - >>> my_function(5, 4, 3) - Traceback (most recent call last): - ... - pedantic.exceptions.NotImplementedException: Function "my_function" is not implemented yet! - """ - - @wraps(func) - def wrapper(*args: Any, **kwargs: Any) -> ReturnType: - raise NotImplementedException(f'Function "{func.__qualname__}" is not implemented yet!') - return wrapper diff --git a/pyproject.toml b/pyproject.toml index 6a29fcb..f32855c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pedantic" -version = "2.4.0" +version = "3.0.0" description = "Some useful Python decorators for cleaner software development." readme = "README.md" requires-python = ">=3.11" diff --git a/tests/decorators/test_class_decorators.py b/tests/decorators/test_class_decorators.py index 08162bc..cb4f858 100644 --- a/tests/decorators/test_class_decorators.py +++ b/tests/decorators/test_class_decorators.py @@ -1,4 +1,4 @@ -from pedantic.decorators.class_decorators import trace_class, timer_class +from pedantic.decorators.class_decorators import trace_class def test_trace_class(): @@ -17,19 +17,3 @@ def generator() -> 'MyClass': m = MyClass.generator() m.double(b=42) - -def test_timer_class(): - @timer_class - class MyClass: - def __init__(self, s: str) -> None: - self.s = s - - def double(self, b: int) -> str: - return self.s + str(b) - - @staticmethod - def generator() -> 'MyClass': - return MyClass(s='generated') - - m = MyClass.generator() - m.double(b=42) diff --git a/tests/decorators/test_mock.py b/tests/decorators/test_mock.py deleted file mode 100644 index 07c7854..0000000 --- a/tests/decorators/test_mock.py +++ /dev/null @@ -1,10 +0,0 @@ -from pedantic import mock - - -def test_mock() -> None: - @mock(return_value=42) - def my_function(a, b, c): - return a + b + c - - assert my_function(1, 2, 3) == 42 - assert my_function(100, 200, 300) == 42 diff --git a/tests/decorators/test_rename_kwargs.py b/tests/decorators/test_rename_kwargs.py deleted file mode 100644 index 3f5e991..0000000 --- a/tests/decorators/test_rename_kwargs.py +++ /dev/null @@ -1,15 +0,0 @@ -from pedantic import rename_kwargs, Rename - - -def test_rename_kwargs(): - @rename_kwargs( - Rename(from_='x', to='a'), - Rename(from_='y', to='b'), - ) - def operation(a: int, b: int) -> int: - return a + b - - operation(4, 5) - operation(a=4, b=5) - operation(x=4, y=5) - operation(x=4, b=5) diff --git a/tests/decorators/test_small_method_decorators.py b/tests/decorators/test_small_method_decorators.py index fd81006..6f634c2 100644 --- a/tests/decorators/test_small_method_decorators.py +++ b/tests/decorators/test_small_method_decorators.py @@ -1,36 +1,9 @@ import asyncio -import warnings import pytest -from pedantic import timer, count_calls, trace, trace_if_returns, does_same_as_function, deprecated, \ - unimplemented, mock, require_kwargs -from pedantic.exceptions import NotImplementedException, PedanticCallWithArgsException - - -def test_unimplemented(): - @unimplemented - def dirt(i: int) -> str: - return str(i) - - with pytest.raises(expected_exception=NotImplementedException): - dirt(42) - - -def test_timer(): - @timer - def operation(i: int) -> str: - return str(i) - - operation(42) - - -def test_count_calls(): - @count_calls - def operation(i: int) -> str: - return str(i) - - operation(42) +from pedantic import trace, trace_if_returns, require_kwargs +from pedantic.exceptions import PedanticCallWithArgsException def test_trace(): @@ -50,42 +23,6 @@ def some_method(x, y): assert some_method(42, 58) == traced_method(42, 58) -def test_does_same_as_function(): - def some_method(x, y, z): - return x * (y + z) - - @does_same_as_function(some_method) - def other_method(x, y, z): - return x * y + x * z - - other_method(1, 2, 3) - other_method(4, 5, 6) - - -def test_does_same_as_function_wrong(): - def some_method(x, y, z): - return x * (y + z) - - @does_same_as_function(some_method) - def other_method(x, y, z): - return x * y + z - - other_method(0, 2, 0) - with pytest.raises(expected_exception=AssertionError): - other_method(4, 5, 6) - - -@pytest.mark.asyncio -async def test_count_calls_async(): - @count_calls - async def operation(i: int) -> str: - await asyncio.sleep(0) - return str(i) - - res = await operation(42) - assert res == '42' - - @pytest.mark.asyncio async def test_trace_async(): async def some_method(x, y): @@ -107,71 +44,6 @@ async def some_method(x, y): assert await some_method(42, 58), await traced_method(42, 58) -@pytest.mark.asyncio -async def test_timer_async(): - @timer - async def operation(i: int) -> str: - await asyncio.sleep(0.05) - return str(i) - - await operation(42) - - -@pytest.mark.asyncio -async def test_does_same_as_function_async(): - async def some_method(x, y, z): - await asyncio.sleep(0) - return x * (y + z) - - @does_same_as_function(some_method) - async def other_method(x, y, z): - await asyncio.sleep(0) - return x * y + x * z - - await other_method(1, 2, 3) - await other_method(4, 5, 6) - - -@pytest.mark.asyncio -async def test_does_same_as_function_async_and_sync(): - def some_method(x, y, z): - return x * (y + z) - - @does_same_as_function(some_method) - async def other_method(x, y, z): - await asyncio.sleep(0) - return x * y + x * z - - await other_method(1, 2, 3) - await other_method(4, 5, 6) - - -@pytest.mark.asyncio -async def test_does_same_as_function_wrong(): - async def some_method(x, y, z): - await asyncio.sleep(0) - return x * (y + z) - - @does_same_as_function(some_method) - async def other_method(x, y, z): - await asyncio.sleep(0) - return x * y + z - - await other_method(0, 2, 0) - - with pytest.raises(expected_exception=AssertionError): - await other_method(4, 5, 6) - - -@pytest.mark.asyncio -async def test_mock_async(): - @mock(return_value=42) - async def my_function(a, b, c): return a + b + c - - assert await my_function(1, 2, 3) == 42 - assert await my_function(100, 200, 300) == 42 - - @pytest.mark.asyncio async def test_require_kwargs(): @require_kwargs