2 Star 3 Fork 2

小马 / LearnPytest

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

【Python】pytest - 自动化测试工具, 帮你写出最好的程序

官网

https://pytest.org/

安装

$ pip install pytest
$ pip list
$ pip show pytest
$ pytest --version
$ pytest --help

第一个测试

写一个加法函数,然后编写该函数的测试方法。

test_func.py

def add(x, y):
    return x+y

def test1():
    assert 3 == add(1, 1)

def test2():
    assert 1 != add(1, 1)
$ pytest -vv test_func.py
or
$ pytest

计算测试时间

计算显示每个测试执行的时间。

$ pytest --durations=0 -vv test_func.py

测试例外的发生

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

不同参数传递测试

为同一个函数传递不同参数进行测试。

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

分组测试

将测试方法分为不同的测试组,测试时可以单独测试某个组的方法。

$ pytest --markers
$ nano pytest.ini
...
[pytest]
markers =
    g1: group1.
    g2: group2.
...
$ pytest --markers

test_func.py

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
$ pytest -vv
$ pytest -vv -m g1
$ pytest -vv -m g2

课程文件

https://gitee.com/komavideo/LearnPytest

小马视频频道

http://komavideo.com

空文件

简介

【Python】pytest - 自动化测试工具, 帮你写出最好的程序 展开 收起
Python
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Python
1
https://gitee.com/komavideo/LearnPytest.git
git@gitee.com:komavideo/LearnPytest.git
komavideo
LearnPytest
LearnPytest
master

搜索帮助