Python单体测试

本文介绍如何使用Python的HtmlTestRunner工具进行单体测试,包括安装测试环境、测试工具,以及编写和运行测试程序的方法。通过实例演示了各种测试用例的编写,如字符串方法测试、错误和失败标记的测试等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

单体测试通过unitest进行。

1.安装单体测试环境

安装PIP

$ sudo python -m ensurepip --default-pip

升级PIP组件

$ python -m pip install --upgrade pip setuptools wheel

安装测试工具

https://pypi.org/project/html-testRunner/#files

安装HtmlTestRunner测试工具

$ sudo pip install https://files.pythonhosted.org/packages/cd/30/79c7891abe90cd8a5711531f5af246671b43015a5900b721a695bfa01a8e/html-testRunner-1.1.2.tar.gz

2. 编写测试程序

 

测试程序

    import HtmlTestRunner
    import unittest


    class TestStringMethods(unittest.TestCase):
        """ Example test for HtmlRunner. """

        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)

        def test_error(self):
            """ This test should be marked as error one. """
            raise ValueError

        def test_fail(self):
            """ This test should fail. """
            self.assertEqual(1, 2)

        @unittest.skip("This is a skipped test.")
        def test_skip(self):
            """ This test should be skipped. """
            pass

    if __name__ == '__main__':
        unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='example_dir'))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值