本文整理汇总了Python中unittest.case方法的典型用法代码示例。如果您正苦于以下问题:Python unittest.case方法的具体用法?Python unittest.case怎么用?Python unittest.case使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest
的用法示例。
在下文中一共展示了unittest.case方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: addExpectedFailure
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例2: assert_raises
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例3: test_reduce_move
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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))
示例4: teardown_suite
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例5: format_test
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例6: _addSkip
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例7: _feedErrorsToResult
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例8: _addExpectedFailure
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例9: _addUnexpectedSuccess
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例10: record_exceptions
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例11: ignore_loop
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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)
示例12: subTest
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
def subTest(self, *args, **kwargs):
try:
self._subtest = unittest.case._SubTest(self, object(), {})
yield
finally:
self._subtest = None
示例13: _create
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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
示例14: getTestCaseNames
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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
示例15: decorate_methods
# 需要导入模块: import unittest [as 别名]
# 或者: from unittest import case [as 别名]
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