python 单元测试

2019-12-18  本文已影响0人  黑曼巴yk

简介

unittest单元测试工具收到JUnit启发,和其他主流测试框架风格一致
https://docs.python.org/zh-cn/3/library/unittest.html

用例发现和执行

unittest 支持用例自动发现

unittest 支持执行指定用例

用例编写

import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()

测试 Fixtures

fixtures简答来说就是测试前置(setUp)和清理(tearDown)方法
测试前置方法(setUp)用来做一些准备工作,比如建立数据库连接。他在测试仪用例执行前被测试框架自动调用

测试清理方法(tearDown)用来做一些清理工作,比如断开数据库连接,他会在用例执行完成后被测试框架自动调用

生效级别:测试方法

class MyTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

生效级别:测试类

class MyTestCase(unittest.TestCase):
    def setUpClass(self):
        pass

    def tearDownClass(self):
        pass

生效级别:测试模块

def setUpModule():
    pass

def tearDownModule():
    pass

跳过测试和预计失败

class MyTestCase(unittest.TestCase):

    @unittest.skip("直接跳过")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "满足条件跳过")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "满足条件不跳过")
    def test_windows_support(self):
        # windows specific testing code
        pass

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("跳过")
        # test code that depends on the external resource
        pass

    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "这个目前是失败的")

上一篇 下一篇

猜你喜欢

热点阅读