本文整理汇总了Python中unittest2.TestCase方法的典型用法代码示例。如果您正苦于以下问题:Python unittest2.TestCase方法的具体用法?Python unittest2.TestCase怎么用?Python unittest2.TestCase使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest2
的用法示例。
在下文中一共展示了unittest2.TestCase方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testPackageInitializationImport
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def testPackageInitializationImport(self):
"""Test that we can import nested messages from their __init__.py.
Such setup is not trivial since at the time of processing of __init__.py one
can't refer to its submodules by name in code, so expressions like
google.protobuf.internal.import_test_package.inner_pb2
don't work. They do work in imports, so we have assign an alias at import
and then use that alias in generated code.
"""
# We import here since it's the import that used to fail, and we want
# the failure to have the right context.
# pylint: disable=g-import-not-at-top
from google.protobuf.internal import import_test_package
# pylint: enable=g-import-not-at-top
msg = import_test_package.myproto.Outer()
# Just check the default value.
self.assertEqual(57, msg.inner.value)
# Since we had so many tests for protocol buffer equality, we broke these out
# into separate TestCase classes.
示例2: test_unexpected_success_test
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_unexpected_success_test(self):
class Succeeds(unittest.TestCase):
def test_me(self):
pass
try:
test_me = unittest.expectedFailure(test_me)
except AttributeError:
pass # Older python - just let the test pass
self.result.startTestRun()
Succeeds("test_me").run(self.result)
self.result.stopTestRun()
output = self.get_output()
expected = """<testsuite errors="0" failures="1" name="" tests="1" time="0.000">
<testcase classname="junitxml.tests.test_junitxml.Succeeds" name="test_me" time="0.000">
<failure type="unittest.case._UnexpectedSuccess"/>
</testcase>
</testsuite>
"""
expected_old = """<testsuite errors="0" failures="0" name="" tests="1" time="0.000">
<testcase classname="junitxml.tests.test_junitxml.Succeeds" name="test_me" time="0.000"/>
</testsuite>
"""
if output != expected_old:
self.assertEqual(expected, output)
示例3: test_skip_reason
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_skip_reason(self):
"""Check the skip element content is escaped"""
class SkipWithLt(unittest.TestCase):
def runTest(self):
self.fail("version < 2.7")
try:
runTest = unittest.skip("2.7 <= version")(runTest)
except AttributeError:
self.has_skip = False
else:
self.has_skip = True
doc = self._run_and_parse_test(SkipWithLt())
if self.has_skip:
self.assertEqual('2.7 <= version',
doc.getElementsByTagName("skip")[0].firstChild.nodeValue)
else:
self.assertTrue(
doc.getElementsByTagName("failure")[0].firstChild.nodeValue
.endswith("AssertionError: version < 2.7\n"))
示例4: test_error_with_invalid_cdata
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_error_with_invalid_cdata(self):
"""Check unicode outside the valid cdata range is stripped"""
if len("\uffff") == 1:
# Basic str type supports unicode
exception = ValueError("\ufffe\uffffEOF")
else:
class UTF8_Error(Exception):
def __unicode__(self):
return str(self).decode("UTF-8")
exception = UTF8_Error("\xef\xbf\xbe\xef\xbf\xbfEOF")
class ErrorWithBadUnicode(unittest.TestCase):
def runTest(self):
raise exception
doc = self._run_and_parse_test(ErrorWithBadUnicode())
self.assertTrue(
doc.getElementsByTagName("error")[0].firstChild.nodeValue
.endswith("Error: EOF\n"))
示例5: testRunnerRegistersResult
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def testRunnerRegistersResult(self):
class Test(unittest2.TestCase):
def testFoo(self):
pass
originalRegisterResult = unittest2.runner.registerResult
def cleanup():
unittest2.runner.registerResult = originalRegisterResult
self.addCleanup(cleanup)
result = unittest2.TestResult()
runner = unittest2.TextTestRunner(stream=StringIO())
# Use our result object
runner._makeResult = lambda: result
self.wasRegistered = 0
def fakeRegisterResult(thisResult):
self.wasRegistered += 1
self.assertEqual(thisResult, result)
unittest2.runner.registerResult = fakeRegisterResult
runner.run(unittest2.TestSuite())
self.assertEqual(self.wasRegistered, 1)
示例6: test_old_testresult
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_old_testresult(self):
class Test(unittest2.TestCase):
def testSkip(self):
self.skipTest('foobar')
def testExpectedFail(self):
raise TypeError
testExpectedFail = unittest2.expectedFailure(testExpectedFail)
def testUnexpectedSuccess(self):
pass
testUnexpectedSuccess = unittest2.expectedFailure(testUnexpectedSuccess)
for test_name, should_pass in (('testSkip', True),
('testExpectedFail', True),
('testUnexpectedSuccess', False)):
test = Test(test_name)
self.assertOldResultWarning(test, int(not should_pass))
示例7: testTestCaseDebugExecutesCleanups
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def testTestCaseDebugExecutesCleanups(self):
ordering = []
class TestableTest(unittest2.TestCase):
def setUp(self):
ordering.append('setUp')
self.addCleanup(cleanup1)
def testNothing(self):
ordering.append('test')
def tearDown(self):
ordering.append('tearDown')
test = TestableTest('testNothing')
def cleanup1():
ordering.append('cleanup1')
test.addCleanup(cleanup2)
def cleanup2():
ordering.append('cleanup2')
test.debug()
self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2'])
示例8: test_run_call_order__error_in_tearDown_default_result
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_run_call_order__error_in_tearDown_default_result(self):
class Foo(Test.LoggingTestCase):
def defaultTestResult(self):
return LoggingResult(self.events)
def tearDown(self):
super(Foo, self).tearDown()
raise RuntimeError('raised by Foo.tearDown')
events = []
Foo(events).run()
expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
'addError', 'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "TestCase.run() still works when the defaultTestResult is a TestResult
# that does not support startTestRun and stopTestRun.
示例9: test_failureException__subclassing__implicit_raise
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_failureException__subclassing__implicit_raise(self):
events = []
result = LoggingResult(events)
class Foo(unittest2.TestCase):
def test(self):
self.fail("foo")
failureException = RuntimeError
self.assertTrue(Foo('test').failureException is RuntimeError)
Foo('test').run(result)
expected = ['startTest', 'addFailure', 'stopTest']
self.assertEqual(events, expected)
# "The default implementation does nothing."
示例10: test_run__uses_defaultTestResult
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_run__uses_defaultTestResult(self):
events = []
class Foo(unittest2.TestCase):
def test(self):
events.append('test')
def defaultTestResult(self):
return LoggingResult(events)
# Make run() find a result object on its own
Foo('test').run()
expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
示例11: testAssertDictContainsSubset
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def testAssertDictContainsSubset(self):
self.assertDictContainsSubset({}, {})
self.assertDictContainsSubset({}, {'a': 1})
self.assertDictContainsSubset({'a': 1}, {'a': 1})
self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
self.assertRaises(unittest2.TestCase.failureException,
self.assertDictContainsSubset, {'a': 2}, {'a': 1},
'.*Mismatched values:.*')
self.assertRaises(unittest2.TestCase.failureException,
self.assertDictContainsSubset, {'c': 1}, {'a': 1},
'.*Missing:.*')
self.assertRaises(unittest2.TestCase.failureException,
self.assertDictContainsSubset, {'a': 1, 'c': 1},
{'a': 1}, '.*Missing:.*')
self.assertRaises(unittest2.TestCase.failureException,
self.assertDictContainsSubset, {'a': 1, 'c': 1},
{'a': 1}, '.*Missing:.*Mismatched values:.*')
self.assertRaises(self.failureException,
self.assertDictContainsSubset, {1: "one"}, {})
示例12: run_unittest
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def run_unittest(*classes):
"""Run tests from unittest.TestCase-derived classes."""
valid_types = (unittest.TestSuite, unittest.TestCase)
suite = unittest.TestSuite()
for cls in classes:
if isinstance(cls, str):
if cls in sys.modules:
suite.addTest(unittest.findTestCases(sys.modules[cls]))
else:
raise ValueError("str arguments must be keys in sys.modules")
elif isinstance(cls, valid_types):
suite.addTest(cls)
else:
suite.addTest(unittest.makeSuite(cls))
def case_pred(test):
if match_tests is None:
return True
for name in test.id().split("."):
if fnmatch.fnmatchcase(name, match_tests):
return True
return False
_filter_suite(suite, case_pred)
_run_suite(suite)
# We don't have sysconfig on Py2.6:
# #=======================================================================
# # Check for the presence of docstrings.
#
# HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or
# sys.platform == 'win32' or
# sysconfig.get_config_var('WITH_DOC_STRINGS'))
#
# requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
# "test requires docstrings")
#
#
# #=======================================================================
# doctest driver.
示例13: __call__
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def __call__(self, *args, **kwargs):
raise RuntimeError('You appear to be running a parameterized test case '
'without having inherited from parameterized.'
'TestCase. This is bad because none of '
'your test cases are actually being run.')
示例14: CoopTestCase
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def CoopTestCase(other_base_class):
"""Returns a new base class with a cooperative metaclass base.
This enables the TestCase to be used in combination
with other base classes that have custom metaclasses, such as
mox.MoxTestBase.
Only works with metaclasses that do not override type.__new__.
Example:
import google3
import mox
from google3.testing.pybase import parameterized
class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
...
Args:
other_base_class: (class) A test case base class.
Returns:
A new class object.
"""
metaclass = type(
'CoopMetaclass',
(other_base_class.__metaclass__,
TestGeneratorMetaclass), {})
return metaclass(
'CoopTestCase',
(other_base_class, TestCase), {})
示例15: test_dir_from_spec
# 需要导入模块: import unittest2 [as 别名]
# 或者: from unittest2 import TestCase [as 别名]
def test_dir_from_spec(self):
mock = Mock(spec=unittest.TestCase)
testcase_attrs = set(dir(unittest.TestCase))
attrs = set(dir(mock))
# all attributes from the spec are included
self.assertEqual(set(), testcase_attrs - attrs)
# shadow a sys attribute
mock.version = 3
self.assertEqual(dir(mock).count('version'), 1)