Python unittest.case() Examples

The following are 30 code examples for showing how to use unittest.case(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module unittest , or try the search function .

Example 1
Project: edgedb   Author: edgedb   File: runner.py    License: Apache License 2.0 6 votes vote down vote up
def addExpectedFailure(self, test, err):
        method = getattr(test, test._testMethodName)
        try:
            reason = method.__et_xfail_reason__
            not_impl = getattr(method, '__et_xfail_not_implemented__', False)
        except AttributeError:
            # Maybe the whole test case class is decorated?
            reason = getattr(test, '__et_xfail_reason__', None)
            not_impl = getattr(test, '__et_xfail_not_implemented__', False)

        marker = Markers.not_implemented if not_impl else Markers.xfailed
        if not_impl:
            self.notImplemented.append(
                (test, self._exc_info_to_string(err, test)))
        else:
            super().addExpectedFailure(test, err)

        self.report_progress(test, marker, reason) 
Example 2
Project: recruit   Author: Frank-qlu   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 3
Project: lambda-packs   Author: ryfeus   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 4
Project: ironpython2   Author: IronLanguages   File: test_py3kwarn.py    License: Apache License 2.0 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 5
Project: edgedb   Author: edgedb   File: runner.py    License: Apache License 2.0 5 votes vote down vote up
def teardown_suite() -> None:
    # The TestSuite methods are mutating the *result* object,
    # and the suite itself does not hold any state whatsoever,
    # and, in our case specifically, it doesn't even hold
    # references to tests being run, so we can think of
    # its methods as static.
    suite = StreamingTestSuite()
    suite._tearDownPreviousClass(None, result)
    suite._handleModuleTearDown(result) 
Example 6
Project: edgedb   Author: edgedb   File: runner.py    License: Apache License 2.0 5 votes vote down vote up
def format_test(self, test):
        if isinstance(test, unittest.case._SubTest):
            if test.params:
                params = ', '.join(
                    f'{k}={v!r}' for k, v in test.params.items())
            else:
                params = '<subtest>'
            return f'{test.test_case} {{{params}}}'
        else:
            if hasattr(test, 'fail_notes') and test.fail_notes:
                fail_notes = ', '.join(
                    f'{k}={v!r}' for k, v in test.fail_notes.items())
                return f'{test} {{{fail_notes}}}'
            else:
                return str(test) 
Example 7
Project: BinderFilter   Author: dxwu   File: test_py3kwarn.py    License: MIT License 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 8
Project: oss-ftp   Author: aliyun   File: test_py3kwarn.py    License: MIT License 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 9
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 10
Project: GraphicDesignPatternByPython   Author: Relph1119   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 11
Project: PocoUnit   Author: AirtestProject   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def _addSkip(self, result, test_case, reason):
        # copy from python3.5.3 unittest.case
        addSkip = getattr(result, 'addSkip', None)
        if addSkip is not None:
            addSkip(test_case, reason)
        else:
            warnings.warn("TestResult has no addSkip method, skips not reported",
                          RuntimeWarning, 2)
            result.addSuccess(test_case) 
Example 12
Project: PocoUnit   Author: AirtestProject   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def _feedErrorsToResult(self, result, errors):
        # copy from python3.5.3 unittest.case
        for test, exc_info in errors:
            if exc_info is not None:
                if issubclass(exc_info[0], self.failureException):
                    result.addFailure(test, exc_info)
                else:
                    result.addError(test, exc_info) 
Example 13
Project: PocoUnit   Author: AirtestProject   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def _addExpectedFailure(self, result, exc_info):
        # copy from python3.5.3 unittest.case
        try:
            addExpectedFailure = result.addExpectedFailure
        except AttributeError:
            warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
                          RuntimeWarning)
            result.addSuccess(self)
        else:
            addExpectedFailure(self, exc_info) 
Example 14
Project: PocoUnit   Author: AirtestProject   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def _addUnexpectedSuccess(self, result):
        # copy from python3.5.3 unittest.case
        try:
            addUnexpectedSuccess = result.addUnexpectedSuccess
        except AttributeError:
            warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
                          RuntimeWarning)
            # We need to pass an actual exception and traceback to addFailure,
            # otherwise the legacy result can choke.
            try:
                raise _UnexpectedSuccess
            except _UnexpectedSuccess:
                result.addFailure(self, sys.exc_info())
        else:
            addUnexpectedSuccess(self) 
Example 15
Project: PocoUnit   Author: AirtestProject   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def record_exceptions(self, errors):
        assertionRecorder = self.get_result_emitter('assertionRecorder')
        for case, exc_info in errors:
            if not exc_info or exc_info in self._exceptions:
                continue
            self._exceptions.add(exc_info)
            if type(exc_info) is tuple:
                exc_type, e, tb = exc_info
                assertionRecorder.traceback(exc_type, e, tb) 
Example 16
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 17
Project: pySINDy   Author: luckystarufo   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 18
Project: asynctest   Author: Martiusweb   File: case.py    License: Apache License 2.0 5 votes vote down vote up
def ignore_loop(func=None):
    """
    Ignore the error case where the loop did not run during the test.
    """
    warnings.warn("ignore_loop() is deprecated in favor of "
                  "fail_on(unused_loop=False)", DeprecationWarning)
    checker = asynctest._fail_on._fail_on({"unused_loop": False})
    return checker if func is None else checker(func) 
Example 19
Project: gcblue   Author: gcblue   File: test_py3kwarn.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 20
Project: tappy   Author: python-tap   File: test_result.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def subTest(self, *args, **kwargs):
        try:
            self._subtest = unittest.case._SubTest(self, object(), {})
            yield
        finally:
            self._subtest = None 
Example 21
Project: abseil-py   Author: abseil   File: absltest.py    License: Apache License 2.0 5 votes vote down vote up
def _create(cls, base_path, file_path, content, mode, encoding, errors):
    # type: (Text, Optional[Text], AnyStr, Text, Text, Text) -> Tuple[_TempFile, Text]
    # pylint: enable=line-too-long
    """Module-private: create a tempfile instance."""
    if file_path:
      cleanup_path = os.path.join(base_path, _get_first_part(file_path))
      path = os.path.join(base_path, file_path)
      _makedirs_exist_ok(os.path.dirname(path))
      # The file may already exist, in which case, ensure it's writable so that
      # it can be truncated.
      if os.path.exists(path) and not os.access(path, os.W_OK):
        stat_info = os.stat(path)
        os.chmod(path, stat_info.st_mode | stat.S_IWUSR)
    else:
      _makedirs_exist_ok(base_path)
      fd, path = tempfile.mkstemp(dir=str(base_path))
      os.close(fd)
      cleanup_path = path

    tf = cls(path)

    if content:
      if isinstance(content, six.text_type):
        tf.write_text(content, mode=mode, encoding=encoding, errors=errors)
      else:
        tf.write_bytes(content, mode)

    else:
      tf.write_bytes(b'')

    return tf, cleanup_path 
Example 22
Project: abseil-py   Author: abseil   File: absltest.py    License: Apache License 2.0 5 votes vote down vote up
def getTestCaseNames(self, testCaseClass):  # pylint:disable=invalid-name
    """Validates and returns a (possibly randomized) list of test case names."""
    for name in dir(testCaseClass):
      if _is_suspicious_attribute(testCaseClass, name):
        raise TypeError(TestLoader._ERROR_MSG % name)
    names = super(TestLoader, self).getTestCaseNames(testCaseClass)
    if self._seed is not None:
      logging.info('Randomizing test order with seed: %d', self._seed)
      logging.info('To reproduce this order, re-run with '
                   '--test_randomize_ordering_seed=%d', self._seed)
      self._random.shuffle(names)
    return names 
Example 23
Project: CTFCrackTools-V2   Author: Acmesec   File: test_py3kwarn.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 24
Project: coffeegrindsize   Author: jgagneastro   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 25
Project: Carnets   Author: holzschu   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 26
Project: Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda   Author: PacktPublishing   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 27
Project: CTFCrackTools   Author: Acmesec   File: test_py3kwarn.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_reduce_move(self):
        from operator import add
        # reduce tests may have already triggered this warning
        reset_module_registry(unittest.case)
        with warnings.catch_warnings():
            warnings.filterwarnings("error", "reduce")
            self.assertRaises(DeprecationWarning, reduce, add, range(10)) 
Example 28
Project: twitter-stock-recommendation   Author: alvarobartt   File: utils.py    License: MIT License 5 votes vote down vote up
def assert_raises(*args, **kwargs):
    """
    assert_raises(exception_class, callable, *args, **kwargs)
    assert_raises(exception_class)

    Fail unless an exception of class exception_class is thrown
    by callable when invoked with arguments args and keyword
    arguments kwargs. If a different type of exception is
    thrown, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    Alternatively, `assert_raises` can be used as a context manager:

    >>> from numpy.testing import assert_raises
    >>> with assert_raises(ZeroDivisionError):
    ...     1 / 0

    is equivalent to

    >>> def div(x, y):
    ...     return x / y
    >>> assert_raises(ZeroDivisionError, div, 1, 0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    return _d.assertRaises(*args,**kwargs) 
Example 29
Project: recruit   Author: Frank-qlu   File: utils.py    License: Apache License 2.0 4 votes vote down vote up
def decorate_methods(cls, decorator, testmatch=None):
    """
    Apply a decorator to all methods in a class matching a regular expression.

    The given decorator is applied to all public methods of `cls` that are
    matched by the regular expression `testmatch`
    (``testmatch.search(methodname)``). Methods that are private, i.e. start
    with an underscore, are ignored.

    Parameters
    ----------
    cls : class
        Class whose methods to decorate.
    decorator : function
        Decorator to apply to methods
    testmatch : compiled regexp or str, optional
        The regular expression. Default value is None, in which case the
        nose default (``re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)``)
        is used.
        If `testmatch` is a string, it is compiled to a regular expression
        first.

    """
    if testmatch is None:
        testmatch = re.compile(r'(?:^|[\\b_\\.%s-])[Tt]est' % os.sep)
    else:
        testmatch = re.compile(testmatch)
    cls_attr = cls.__dict__

    # delayed import to reduce startup time
    from inspect import isfunction

    methods = [_m for _m in cls_attr.values() if isfunction(_m)]
    for function in methods:
        try:
            if hasattr(function, 'compat_func_name'):
                funcname = function.compat_func_name
            else:
                funcname = function.__name__
        except AttributeError:
            # not a function
            continue
        if testmatch.search(funcname) and not funcname.startswith('_'):
            setattr(cls, funcname, decorator(function))
    return 
Example 30
Project: recruit   Author: Frank-qlu   File: utils.py    License: Apache License 2.0 4 votes vote down vote up
def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
                    err_msg='', verbose=True):
    """
    Raises an AssertionError if two objects are not equal up to desired
    tolerance.

    The test is equivalent to ``allclose(actual, desired, rtol, atol)``.
    It compares the difference between `actual` and `desired` to
    ``atol + rtol * abs(desired)``.

    .. versionadded:: 1.5.0

    Parameters
    ----------
    actual : array_like
        Array obtained.
    desired : array_like
        Array desired.
    rtol : float, optional
        Relative tolerance.
    atol : float, optional
        Absolute tolerance.
    equal_nan : bool, optional.
        If True, NaNs will compare equal.
    err_msg : str, optional
        The error message to be printed in case of failure.
    verbose : bool, optional
        If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
        If actual and desired are not equal up to specified precision.

    See Also
    --------
    assert_array_almost_equal_nulp, assert_array_max_ulp

    Examples
    --------
    >>> x = [1e-5, 1e-3, 1e-1]
    >>> y = np.arccos(np.cos(x))
    >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np

    def compare(x, y):
        return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol,
                                       equal_nan=equal_nan)

    actual, desired = np.asanyarray(actual), np.asanyarray(desired)
    header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
    assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
                         verbose=verbose, header=header, equal_nan=equal_nan)