當前位置: 首頁>>代碼示例>>Python>>正文


Python unittest.TestCase方法代碼示例

本文整理匯總了Python中unittest.TestCase方法的典型用法代碼示例。如果您正苦於以下問題:Python unittest.TestCase方法的具體用法?Python unittest.TestCase怎麽用?Python unittest.TestCase使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在unittest的用法示例。


在下文中一共展示了unittest.TestCase方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_factory

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_factory(test):
    """Creates testcase for test dict"""
    tree1 = Tree.from_text(test["t1"])
    tree2 = Tree.from_text(test["t2"])
    config = PerEditOperationConfig(.4, .4, .6)

    class TestPerEditOperationCorrectness(unittest.TestCase):
        """Correctness unit tests of distance computation for node labels with
        a single string value and per-edit-operation cost model."""

        def test_distance_unit_cost(self):
            apted = APTED(tree1, tree2, config)
            apmted = AllPossibleMappingsTED(tree1, tree2, config)
            self.assertAlmostEqual(
                apmted.compute_edit_distance(),  # correct result
                apted.compute_edit_distance()    # result
            )

    return type(
        "TestPerEditOperationCorrectness{}".format(test["testID"]),
        (TestPerEditOperationCorrectness,), {}
    ) 
開發者ID:JoaoFelipe,項目名稱:apted,代碼行數:24,代碼來源:test_per_edit_operation_correctness.py

示例2: test_setup_class_install_environment_install

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_setup_class_install_environment_install(self):
        from calmjs import cli
        from calmjs.npm import Driver

        utils.stub_mod_call(self, cli)
        utils.stub_base_which(self, 'npm')
        utils.stub_os_environ(self)
        os.environ.pop('CALMJS_TEST_ENV', '')

        cwd = os.getcwd()
        TestCase = type('TestCase', (unittest.TestCase,), {})
        utils.setup_class_install_environment(
            TestCase, Driver, ['dummy_package'])
        self.assertEqual(self.mock_tempfile.count, 1)
        self.assertNotEqual(TestCase._env_root, cwd)
        self.assertEqual(TestCase._env_root, TestCase._cls_tmpdir)
        self.assertTrue(exists(join(TestCase._env_root, 'package.json')))
        p, kw = self.call_args
        self.assertEqual(p, (['npm', 'install'],))
        self.assertEqual(kw['cwd'], TestCase._cls_tmpdir) 
開發者ID:calmjs,項目名稱:calmjs,代碼行數:22,代碼來源:test_testing.py

示例3: test_setup_class_install_environment_predefined_no_dir

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_setup_class_install_environment_predefined_no_dir(self):
        from calmjs.cli import PackageManagerDriver
        from calmjs import cli

        utils.stub_os_environ(self)
        utils.stub_mod_call(self, cli)
        cwd = mkdtemp(self)
        # we have the mock_tempfile context...
        self.assertEqual(self.mock_tempfile.count, 1)
        os.chdir(cwd)

        # a very common use case
        os.environ['CALMJS_TEST_ENV'] = '.'
        TestCase = type('TestCase', (unittest.TestCase,), {})
        # the directory not there.
        with self.assertRaises(unittest.SkipTest):
            utils.setup_class_install_environment(
                TestCase, PackageManagerDriver, [])
        # temporary directory should not be created as the skip will
        # also stop the teardown from running
        self.assertEqual(self.mock_tempfile.count, 1)
        # this is still set, but irrelevant.
        self.assertEqual(TestCase._env_root, cwd)
        # tmpdir not set.
        self.assertFalse(hasattr(TestCase, '_cls_tmpdir')) 
開發者ID:calmjs,項目名稱:calmjs,代碼行數:27,代碼來源:test_testing.py

示例4: validator

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def validator(prompt_context: PromptValidatorContext):
    tester = unittest.TestCase()
    tester.assertTrue(prompt_context.attempt_count > 0)

    activity = prompt_context.recognized.value

    if activity.type == ActivityTypes.event:
        if int(activity.value) == 2:
            prompt_context.recognized.value = MessageFactory.text(str(activity.value))
            return True
    else:
        await prompt_context.context.send_activity(
            "Please send an 'event'-type Activity with a value of 2."
        )

    return False 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:18,代碼來源:test_activity_prompt.py

示例5: _load_package_tests

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def _load_package_tests(name):
    """
    Load the test classes from another modularcrypto package

    :param name:
        A unicode string of the other package name

    :return:
        A list of unittest.TestCase classes of the tests for the package
    """

    package_dir = os.path.join('..', name)
    if not os.path.exists(package_dir):
        return []

    tests_module_info = imp.find_module('tests', [package_dir])
    tests_module = imp.load_module('%s.tests' % name, *tests_module_info)
    return tests_module.test_classes() 
開發者ID:wbond,項目名稱:oscrypto,代碼行數:20,代碼來源:coverage.py

示例6: testCleanUp

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def testCleanUp(self):
        class TestableTest(unittest.TestCase):
            def testNothing(self):
                pass

        test = TestableTest('testNothing')
        self.assertEqual(test._cleanups, [])

        cleanups = []

        def cleanup1(*args, **kwargs):
            cleanups.append((1, args, kwargs))

        def cleanup2(*args, **kwargs):
            cleanups.append((2, args, kwargs))

        test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
        test.addCleanup(cleanup2)

        self.assertEqual(test._cleanups,
                         [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
                          (cleanup2, (), {})])

        self.assertTrue(test.doCleanups())
        self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))]) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:27,代碼來源:test_runner.py

示例7: testTestCaseDebugExecutesCleanups

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def testTestCaseDebugExecutesCleanups(self):
        ordering = []

        class TestableTest(unittest.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']) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:26,代碼來源:test_runner.py

示例8: test_init__no_test_name

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_init__no_test_name(self):
        class Test(unittest.TestCase):
            def runTest(self): raise MyException()
            def test(self): pass

        self.assertEqual(Test().id()[-13:], '.Test.runTest')

        # test that TestCase can be instantiated with no args
        # primarily for use at the interactive interpreter
        test = unittest.TestCase()
        test.assertEqual(3, 3)
        with test.assertRaises(test.failureException):
            test.assertEqual(3, 2)

        with self.assertRaises(AttributeError):
            test.run()

    # "class TestCase([methodName])"
    # ...
    # "Each instance of TestCase will run a single test method: the
    # method named methodName." 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:23,代碼來源:test_case.py

示例9: test_failureException__subclassing__explicit_raise

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_failureException__subclassing__explicit_raise(self):
        events = []
        result = LoggingResult(events)

        class Foo(unittest.TestCase):
            def test(self):
                raise RuntimeError()

            failureException = RuntimeError

        self.assertTrue(Foo('test').failureException is RuntimeError)


        Foo('test').run(result)
        expected = ['startTest', 'addFailure', 'stopTest']
        self.assertEqual(events, expected)

    # "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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:25,代碼來源:test_case.py

示例10: test_failureException__subclassing__implicit_raise

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_failureException__subclassing__implicit_raise(self):
        events = []
        result = LoggingResult(events)

        class Foo(unittest.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." 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:20,代碼來源:test_case.py

示例11: test_run__uses_defaultTestResult

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_run__uses_defaultTestResult(self):
        events = []
        defaultResult = LoggingResult(events)

        class Foo(unittest.TestCase):
            def test(self):
                events.append('test')

            def defaultTestResult(self):
                return defaultResult

        # Make run() find a result object on its own
        result = Foo('test').run()

        self.assertIs(result, defaultResult)
        expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
            'stopTest', 'stopTestRun']
        self.assertEqual(events, expected)


    # "The result object is returned to run's caller" 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:23,代碼來源:test_case.py

示例12: testPickle

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def testPickle(self):
        # Issue 10326

        # Can't use TestCase classes defined in Test class as
        # pickle does not work with inner classes
        test = unittest.TestCase('run')
        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):

            # blew up prior to fix
            pickled_test = pickle.dumps(test, protocol=protocol)
            unpickled_test = pickle.loads(pickled_test)
            self.assertEqual(test, unpickled_test)

            # exercise the TestCase instance in a way that will invoke
            # the type equality lookup mechanism
            unpickled_test.assertEqual(set(), set()) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:18,代碼來源:test_case.py

示例13: setUp

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def setUp(self):
        class TestableTestFalse(unittest.TestCase):
            longMessage = False
            failureException = self.failureException

            def testTest(self):
                pass

        class TestableTestTrue(unittest.TestCase):
            longMessage = True
            failureException = self.failureException

            def testTest(self):
                pass

        self.testableTrue = TestableTestTrue('testTest')
        self.testableFalse = TestableTestFalse('testTest') 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:19,代碼來源:test_assertions.py

示例14: test_loadTestsFromTestCase__no_matches

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_loadTestsFromTestCase__no_matches(self):
        class Foo(unittest.TestCase):
            def foo_bar(self): pass

        empty_suite = unittest.TestSuite()

        loader = unittest.TestLoader()
        self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)

    # "Return a suite of all tests cases contained in the TestCase-derived
    # class testCaseClass"
    #
    # What happens if loadTestsFromTestCase() is given an object
    # that isn't a subclass of TestCase? Specifically, what happens
    # if testCaseClass is a subclass of TestSuite?
    #
    # This is checked for specifically in the code, so we better add a
    # test for it. 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:20,代碼來源:test_loader.py

示例15: test_loadTestsFromTestCase__TestSuite_subclass

# 需要導入模塊: import unittest [as 別名]
# 或者: from unittest import TestCase [as 別名]
def test_loadTestsFromTestCase__TestSuite_subclass(self):
        class NotATestCase(unittest.TestSuite):
            pass

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromTestCase(NotATestCase)
        except TypeError:
            pass
        else:
            self.fail('Should raise TypeError')

    # "Return a suite of all tests cases contained in the TestCase-derived
    # class testCaseClass"
    #
    # Make sure loadTestsFromTestCase() picks up the default test method
    # name (as specified by TestCase), even though the method name does
    # not match the default TestLoader.testMethodPrefix string 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:20,代碼來源:test_loader.py


注:本文中的unittest.TestCase方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。