文章目录

  • 1. pytest介绍
  • 2. pytest安装
  • 2.1基本介绍
  • 2.2 安装
  • 3. 快速入门
  • 3.1 创建一个pytest测试
  • 3.2 一个类中有多个测试函数
  • 3.3 pytest基本规则


1. pytest介绍

pytest算是当前基于python语言实现测试较为流行且成熟的测试框架之一。为什么pytest会受到大家的认可呢?它具有以下特点:

  1. 简单灵活,容易上手,文档丰富;
  2. 支持参数化,可以细粒度地控制要测试的测试用例;
  3. 能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+requests);
  4. pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)等;
  5. 测试用例的skip和xfail处理;
  6. 可以很好的和CI工具结合,例如jenkins

2. pytest安装

2.1基本介绍

官网:https://docs.pytest.org/en/latest/Pythons: Python 3.5, 3.6, 3.7, PyPy3
Platforms: Linux and Windows
PyPI package name: pytest

2.2 安装

1.命令行中输入以下命令:

pip install -U pytest

2.安装完成后检查版本:

pytest --version

3.pytest 帮助

pytest -h

python pytest allure安装教程 pytest下载_自动化测试

3. 快速入门

3.1 创建一个pytest测试

对fun函数进行测试

python pytest allure安装教程 pytest下载_python_02


执行pytest, 运行func(3)的结果不等于5,因此结果为failed.

python pytest allure安装教程 pytest下载_软件测试_03


pytest运行当前目录及其子目录中所有以test开头或test结尾的.py文件,如:test_.py 或_test.py,找到文件后,在文件中找到以test开头的函数并执行。

3.2 一个类中有多个测试函数

上面的例子中,只有一个测试函数。当有多个测试函数或测试用例时,可放在一个类中,pytest可以很容易的创建一个测试类包含一个或多个测试函数。

# content of test_sample.py
class TestClass:
    def test_one(self):
        x = "hello"
        assert "o" in x

    def test_two(self):
        x = "this"
        assert hasattr(x,"check”)

pytes会找到两个带有测试前缀的函数。注意在类名的前面要加上Test,否则将跳过该类。

执行结果如下,可以清晰的看到一个用例执行成功,一个用例失败。

python pytest allure安装教程 pytest下载_python_04

3.3 pytest基本规则

测试文件:以test_开头或以_test结尾。
测试类:以Test开头,不能带有 init 方法。
测试函数:以test_开头。