Python标准测试框架unittest基础用法

import unittest
import sys
class TestStringMethod(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        print('test start')
        
    @classmethod
    def tearDownClass(self):
        print('test end')
        
    def setUp(self):
        print('single test start')
        
    def tearDown(self):
        print('single test end')
    
    @unittest.skipIf(condition = sys.platform == 'win32', reason = 'Do not support win32')
    def test_upper(self):
        print('upper')
        self.assertEqual('foo'.upper(), 'FOO')
        
    @unittest.skipIf(condition=sys.version_info < (3,8), reason='only support python 3.8 +')
    def test_isupper(self):
        print('isupper')
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper()) 
        
    def test_split(self):
        print('split')
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        #另一种重要的断言就是期待抛出指定类型的Error,
        #比如通过s.split(2)访问不存在的key时,断言会抛出TypeError:
        # 测试with里面的操作是不是成功地raise了我们想要的这个error(这里是TypeError)
        with self.assertRaises(TypeError):
            print('error type')
            s.split(2)

classmethod装饰器

setUpClass, setUpClass, setUp, setUp

unittest.skipIf装饰器

unittest.skipIf(condition = sys.platform == 'win32', reason = 'Do not support win32')

unittest库

unittest.TestCase类

测试文件的命名规范

测试模块,测试类,测试函数(方法)

测试代码的调用方式:

python -m test_string
只想调用某个测试方法怎么办

项目的目录结构,测试代码放哪里?

加__init__.py可以让文件变成module?

with self.assertRaises(TypeError)的含义:

测试with里面的操作(这里是s.split(2)语句)

是不是真的raise了我们想看到的这个error(这里是TypeError)

posted @ 2023-01-28 15:43  wjybq  阅读(13)  评论(0)    收藏  举报