# LearnPytest **Repository Path**: komavideo/LearnPytest ## Basic Information - **Project Name**: LearnPytest - **Description**: 【Python】pytest - 自动化测试工具, 帮你写出最好的程序 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 3 - **Forks**: 2 - **Created**: 2019-05-17 - **Last Updated**: 2022-10-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 【Python】pytest - 自动化测试工具, 帮你写出最好的程序 ================================================== ## 官网 https://pytest.org/ ## 安装 ```bash $ pip install pytest $ pip list $ pip show pytest $ pytest --version $ pytest --help ``` ## 第一个测试 写一个加法函数,然后编写该函数的测试方法。 ### test_func.py ```python def add(x, y): return x+y def test1(): assert 3 == add(1, 1) def test2(): assert 1 != add(1, 1) ``` ```bash $ pytest -vv test_func.py or $ pytest ``` ## 计算测试时间 计算显示每个测试执行的时间。 ```bash $ pytest --durations=0 -vv test_func.py ``` ## 测试例外的发生 ```python import pytest def func(x): if x == 0: raise ValueError("value error!") else: pass # func(1) # try: # func(0) # except ValueError as identifier: # print("error") def test_mytest1(): with pytest.raises(ValueError): func(0) def test_mytest2(): assert func(1) == None ``` ## 不同参数传递测试 为同一个函数传递不同参数进行测试。 ```python def add(x, y): return x+y import pytest @pytest.mark.parametrize( "x,y,expected", [ (1, 1, 2), (2, 2, 4), (10, 10, 20), ] ) def test_add(x, y, expected): assert add(x, y) == expected ``` ## 分组测试 将测试方法分为不同的测试组,测试时可以单独测试某个组的方法。 ```bash $ pytest --markers $ nano pytest.ini ... [pytest] markers = g1: group1. g2: group2. ... $ pytest --markers ``` ### test_func.py ```python import pytest @pytest.mark.g1 def test_func1(): pass @pytest.mark.g2 def test_func2(): pass @pytest.mark.g1 def test_func3(): pass @pytest.mark.g2 def test_func4(): pass @pytest.mark.g1 def test_func5(): pass ``` ```bash $ pytest -vv $ pytest -vv -m g1 $ pytest -vv -m g2 ``` ## 课程文件 https://gitee.com/komavideo/LearnPytest ## 小马视频频道 http://komavideo.com