Python unittest2.TestCase() Examples
The following are 30
code examples of unittest2.TestCase().
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 also want to check out all available functions/classes of the module
unittest2
, or try the search function
.
Example #1
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 7 votes |
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)
Example #2
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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"))
Example #3
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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"}, {})
Example #4
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: reflection_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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.
Example #6
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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"))
Example #7
Source File: test_unittest2_with.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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))
Example #8
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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'])
Example #9
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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."
Example #10
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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.
Example #11
Source File: test_runner.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 6 votes |
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)
Example #12
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_setUp(self): class Foo(unittest2.TestCase): def runTest(self): pass # ... and nothing should happen Foo().setUp() # "The default implementation does nothing."
Example #13
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_error_with_surrogates(self): """Check unicode surrogates are handled properly, paired or otherwise This is a pain due to suboptimal unicode support in Python and the various changes in Python 3. On UCS-2 builds there is no easy way of getting rid of unpaired surrogates while leaving valid pairs alone, so this test doesn't require astral characters are kept there. """ if len("\uffff") == 1: exception = ValueError("paired: \U000201a2" " unpaired: "+chr(0xD800)+"-"+chr(0xDFFF)) astral_char = "\U000201a2" else: class UTF8_Error(Exception): def __unicode__(self): return str(self).decode("UTF-8") exception = UTF8_Error("paired: \xf0\xa0\x86\xa2" " unpaired: \xed\xa0\x80-\xed\xbf\xbf") astral_char = "\U000201a2".decode("unicode-escape") class ErrorWithSurrogates(unittest.TestCase): def runTest(self): raise exception doc = self._run_and_parse_test(ErrorWithSurrogates()) traceback = doc.getElementsByTagName("error")[0].firstChild.nodeValue if sys.maxunicode == 0xFFFF: pass # would be nice to handle astral characters properly even so else: self.assertTrue(astral_char in traceback) self.assertTrue(traceback.endswith(" unpaired: -\n"))
Example #14
Source File: test_runner.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def testBufferAndFailfast(self): class Test(unittest2.TestCase): def testFoo(self): pass result = unittest2.TestResult() runner = unittest2.TextTestRunner(stream=StringIO(), failfast=True, buffer=True) # Use our result object runner._makeResult = lambda: result runner.run(Test('testFoo')) self.assertTrue(result.failfast) self.assertTrue(result.buffer)
Example #15
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_failure_with_amp(self): """Check the failure element content is escaped""" class FailWithAmp(unittest.TestCase): def runTest(self): self.fail("& should be escaped as &") doc = self._run_and_parse_test(FailWithAmp()) self.assertTrue( doc.getElementsByTagName("failure")[0].firstChild.nodeValue .endswith("AssertionError: & should be escaped as &\n"))
Example #16
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_defaultTestResult(self): class Foo(unittest2.TestCase): def runTest(self): pass result = Foo().defaultTestResult() self.assertEqual(type(result), unittest2.TestResult) # "When a setUp() method is defined, the test runner will run that method # prior to each test. Likewise, if a tearDown() method is defined, the # test runner will invoke that method after each test. In the example, # setUp() was used to create a fresh sequence for each test." # # Make sure the proper call order is maintained, even if setUp() raises # an exception.
Example #17
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_run_call_order_default_result(self): class Foo(unittest2.TestCase): def defaultTestResult(self): return OldTestResult() def test(self): pass Foo('test').run() # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework. The initial value of this # attribute is AssertionError"
Example #18
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_failureException__default(self): class Foo(unittest2.TestCase): def test(self): pass self.assertTrue(Foo('test').failureException is AssertionError) # "This class attribute gives the exception raised by the test() method. # If a test framework needs to use a specialized exception, possibly to # carry additional information, it must subclass this exception in # order to ``play fair'' with the framework." # # Make sure TestCase.run() respects the designated failureException
Example #19
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_id(self): class Foo(unittest2.TestCase): def runTest(self): pass self.assertIsInstance(Foo().id(), basestring) # "If result is omitted or None, a temporary result object is created # and used, but is not made available to the caller. As TestCase owns the # temporary result startTestRun and stopTestRun are called.
Example #20
Source File: test_case.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def testAssertMultiLineEqual(self): sample_text = """\ http://www.python.org/doc/2.3/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] """ revised_sample_text = """\ http://www.python.org/doc/2.4.1/lib/module-unittest.html test case A test case is the smallest unit of testing. [...] You may provide your own implementation that does not subclass from TestCase, of course. """ sample_text_error = """\ - http://www.python.org/doc/2.3/lib/module-unittest.html ? ^ + http://www.python.org/doc/2.4.1/lib/module-unittest.html ? ^^^ test case - A test case is the smallest unit of testing. [...] + A test case is the smallest unit of testing. [...] You may provide your ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. """ self.maxDiff = None for type_changer in (lambda x: x, lambda x: x.decode('utf8')): try: self.assertMultiLineEqual(type_changer(sample_text), type_changer(revised_sample_text)) except self.failureException, e: # need to remove the first line of the error message error = str(e).encode('utf8').split('\n', 1)[1] # assertMultiLineEqual is hooked up as the default for # unicode strings - so we can't use it for this check self.assertTrue(sample_text_error == error)
Example #21
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_quotes_in_test_case_id(self): """Check that quotes in an attribute are escaped""" class QuoteId(unittest.TestCase): def id(self): return unittest.TestCase.id(self) + '("quotes")' def runTest(self): pass doc = self._run_and_parse_test(QuoteId()) self.assertEqual('runTest("quotes")', doc.getElementsByTagName("testcase")[0].getAttribute("name"))
Example #22
Source File: support.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
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.
Example #23
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_expected_failure_test(self): expected_failure_support = [True] class ExpectedFail(unittest.TestCase): def test_me(self): self.fail("fail") try: test_me = unittest.expectedFailure(test_me) except AttributeError: # Older python - just let the test fail expected_failure_support[0] = False self.result.startTestRun() ExpectedFail("test_me").run(self.result) self.result.stopTestRun() output = self.get_output() expected = """<testsuite errors="0" failures="0" name="" tests="1" time="0.000"> <testcase classname="junitxml.tests.test_junitxml.ExpectedFail" name="test_me" time="0.000"/> </testsuite> """ expected_old = """<testsuite errors="0" failures="1" name="" tests="1" time="0.000"> <testcase classname="junitxml.tests.test_junitxml.ExpectedFail" name="test_me" time="0.000"> <failure type="AssertionError">failure</failure> </testcase> </testsuite> """ if expected_failure_support[0]: self.assertEqual(expected, output) else: self.assertEqual(expected_old, output)
Example #24
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_successful_test(self): class Passes(unittest.TestCase): def test_me(self): pass self.result.startTestRun() Passes("test_me").run(self.result) self.result.stopTestRun() self.assertEqual("""<testsuite errors="0" failures="0" name="" tests="1" time="0.000"> <testcase classname="junitxml.tests.test_junitxml.Passes" name="test_me" time="0.000"/> </testsuite> """, self.get_output())
Example #25
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_failing_test(self): class Fails(unittest.TestCase): def test_me(self): self.fail() self.result.startTestRun() Fails("test_me").run(self.result) self.result.stopTestRun() self.assertEqual("""<testsuite errors="0" failures="1" name="" tests="1" time="0.000"> <testcase classname="junitxml.tests.test_junitxml.Fails" name="test_me" time="0.000"> <failure type="AssertionError">failure</failure> </testcase> </testsuite> """, self.get_output())
Example #26
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_erroring_test(self): class Errors(unittest.TestCase): def test_me(self): 1/0 self.result.startTestRun() Errors("test_me").run(self.result) self.result.stopTestRun() self.assertEqual("""<testsuite errors="1" failures="0" name="" tests="1" time="0.000"> <testcase classname="junitxml.tests.test_junitxml.Errors" name="test_me" time="0.000"> <error type="ZeroDivisionError">error</error> </testcase> </testsuite> """, self.get_output())
Example #27
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_test_id_with_parameter(self): class Passes(unittest.TestCase): def id(self): return unittest.TestCase.id(self) + '(version_1.6)' def test_me(self): pass self.result.startTestRun() Passes("test_me").run(self.result) self.result.stopTestRun() output = self.get_output() self.assertTrue('Passes" name="test_me(version_1.6)"' in output)
Example #28
Source File: test_junitxml.py From ConTroll_Remote_Access_Trojan with Apache License 2.0 | 5 votes |
def test_test_count(self): class Passes(unittest.TestCase): def test_me(self): pass self.result.startTestRun() Passes("test_me").run(self.result) Passes("test_me").run(self.result) self.result.stopTestRun() # When tests are run, the number of tests is counted. output = self.get_output() self.assertTrue('tests="2"' in output)
Example #29
Source File: assert_equal.py From mitogen with BSD 3-Clause "New" or "Revised" License | 5 votes |
def text_diff(a, b): tc = TestCase() tc.maxDiff = None try: tc.assertEqual(a, b) return None except AssertionError as e: return str(e)
Example #30
Source File: testlib.py From mitogen with BSD 3-Clause "New" or "Revised" License | 5 votes |
def tearDown(self): self._teardown_check_zombies() self._teardown_check_threads() self._teardown_check_fds() super(TestCase, self).tearDown()