Pytest简介

Pytest is a mature full-featured Python testing tool that helps you write better programs.
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries.

  通过官方网站介绍我们可以了解到,pytest是一个非常成熟的全功能的python测试框架,主要有

以下几个特点:

  • 简单灵活易上手
  • 支持参数化
  • 支持简单的单元测试和复杂的功能测试,还可以用来做自动化测试
  • 具有很多第三方插件,并且可以自定义扩展
  • 测试用例的skip和xfail处理
  • 可以很好的和Jenkins集成
  • 支持运行由nose, unittest编写的测试用例

Pytest安装

  1.直接使用pip命令安装

pip install -U pytest    # -U是如果已安装会自动升级最新版本

  2.验证安装结果

pytest --version    # 展示当前安装版本

C:\Users\edison>pytest --version
pytest 6.2.5

  3.在pytest测试框架中,要遵循以下约束:

  • 测试文件名要符合test_*.py或*_test.py格式(例如test_min.py)
  • 测试类要以Test开头,且不能带有init方法
  • 在单个测试类中,可以包含一个或多个test_开头的函数

Pytest测试执行

  pytest进行测试比较简单,我们来看一个实例:

import pytest    # 导入pytest包

def test_001():    # 函数以test_开头
print("test_01") def test_002():
print("test_02") if __name__ == '__main__':
pytest.main(["-v","test_1214.py"]) # 调用pytest的main函数执行测试

  这里我们定义了了两个测试函数,直接打印出结果,下面执行测试:

============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\Code
collecting ... collected 2 items test_1214.py::test_001 PASSED [ 50%]
test_1214.py::test_002 PASSED [100%] ============================== 2 passed in 0.11s ============================== Process finished with exit code 0

  输出结果中显示执行了多少条案例、对应的测试模块、通过条数以及执行耗时。

测试类主函数

pytest.main(["-v","test_1214.py"])

通过python代码执行 pytest.main()
1.直接执行pytest.main() 【自动查找当前目录下,以test_开头的文件或者以_test结尾的py文件】
2.设置pytest的执行参数 pytest.main(['--html=./report.html','test_login.py'])【执行test_login.py文件,并生成html格式的报告】

main()括号内可传入执行参数和插件参数,通过[]进行分割,[]内的多个参数通过‘逗号,’进行分割

运行目录及子包下的所有用例 pytest.main(['目录名'])

运行指定模块所有用例 pytest.main(['test_reg.py'])

运行指定模块指定类指定用例 pytest.main(['test_reg.py::TestClass::test_method']) 冒号分割 -m=xxx: 运行打标签的用例
-reruns=xxx:失败重新运行
-q: 安静模式, 不输出环境信息
-v: 丰富信息模式, 输出更详细的用例执行信息
-s: 显示程序中的print/logging输出
--resultlog=./log.txt 生成log
--junitxml=./log.xml 生成xml报告

断言方法

  pytest断言主要使用Python原生断言方法,主要有以下几种:

  • == 内容和类型必须同时满足相等
  • in 实际结果包含预期结果
  • is 断言前后两个值相等
import pytest    # 导入pytest包

def add(x,y):    # 定义以test_开头函数
return x + y def test_add():
assert add(1,2) == 3 # 断言成功 str1 = "Python,Java,Ruby"
def test_in():
assert "PHP" in str1 # 断言失败 if __name__ == '__main__':
pytest.main(["-v","test_pytest.py"]) # 调用main函数执行测试
============================= test session starts =============================
platform win32 -- Python 3.8.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- D:\Code\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\Code
collecting ... collected 2 items test_pytest.py::test_add PASSED [ 50%]
test_pytest.py::test_in FAILED [100%] ================================== FAILURES ===================================
___________________________________ test_in ___________________________________ def test_in():
> assert "PHP" in str1
E AssertionError: assert 'PHP' in 'Python,Java,Ruby' test_pytest.py:11: AssertionError
=========================== short test summary info ===========================
FAILED test_pytest.py::test_in - AssertionError: assert 'PHP' in 'Python,Java...
========================= 1 failed, 1 passed in 0.18s ========================= Process finished with exit code 0

  可以看到运行结果中明确指出了错误原因是“AssertionError”,因为PHP不在str1中。

常用命令详解

1.运行指定案例

if __name__ == '__main__':
pytest.main(["-v","-s","test_1214.py"])

2.运行当前文件夹包括子文件夹所有用例

if __name__ == '__main__':
pytest.main(["-v","-s","./"])

3.运行指定文件夹(code目录下所有用例)

if __name__ == '__main__':
pytest.main(["-v","-s","code/"])

4.运行模块中指定用例(运行模块中test_add用例)

if __name__ == '__main__':
pytest.main(["-v","-s","test_pytest.py::test_add"])

5.执行失败的最大次数

  使用表达式"--maxfail=num"来实现(注意:表达式中间不能存在空格),表示用例失败总数等于num 时停止运行。

6.错误信息在一行展示

  在实际项目中如果有很多用例执行失败,查看报错信息将会很麻烦。使用"--tb=line"命令,可以很好解决这个问题。

接口调用

  本地写一个查询用户信息的接口,通过pytest来调用,并进行接口断言。

 1 # -*- coding: utf-8 -*-
2 import pytest
3 import requests
4
5 def test_agent():
6 r = requests.post(
7 url="http://127.0.0.1:9000/get_user",
8 data={
9 "name": "吴磊",
10 "sex": 1
11 },
12 headers={"Content-Type": "application/json"}
13 )
14 print(r.text)
15 assert r.json()['data']['retCode'] == "00" and r.json()['data']['retMsg'] == "调用成功"
16
17 if __name__ == "__main__":
18 pytest.main(["-v","test_api.py"])

Python测试框架pytest入门基础的更多相关文章

  1. Python测试框架pytest命令行参数用法

    在Shell执行pytest -h可以看到pytest的命令行参数有这10大类,共132个 序号 类别 中文名 包含命令行参数数量 1 positional arguments 形参 1 2 gene ...

  2. python测试框架-pytest

    一.pytest 介绍.运行.参数化和数据驱动.Fixture pytest安装与介绍 官网 : pip install -U pytest 查看版本号:pytest --version 为何选择py ...

  3. 小白学 Python 爬虫(35):爬虫框架 Scrapy 入门基础(三) Selector 选择器

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  4. 全功能Python测试框架:pytest

    python通用测试框架大多数人用的是unittest+HTMLTestRunner,这段时间看到了pytest文档,发现这个框架和丰富的plugins很好用,所以来学习下pytest.   imag ...

  5. 可能是 Python 中最火的第三方开源测试框架 pytest

    作者:HelloGitHub-Prodesire HelloGitHub 的<讲解开源项目>系列,项目地址:https://github.com/HelloGitHub-Team/Arti ...

  6. 小白学 Python 爬虫(34):爬虫框架 Scrapy 入门基础(二)

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  7. 小白学 Python 爬虫(36):爬虫框架 Scrapy 入门基础(四) Downloader Middleware

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  8. 小白学 Python 爬虫(37):爬虫框架 Scrapy 入门基础(五) Spider Middleware

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  9. 小白学 Python 爬虫(38):爬虫框架 Scrapy 入门基础(六) Item Pipeline

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

随机推荐

  1. 【Python】300行代码搞定HTML模板渲染

    一.前言 模板语言由HTML代码和逻辑控制代码组成,此处@PHP.通过模板语言可以快速的生成预想的HTML页面.应该算是后端渲染不可缺少的组成部分. 二.功能介绍 通过使用学习tornado.bott ...

  2. [ARC117E]Zero-Sum Ranges 2

    令$sum_{i}=\sum_{j=1}^{i}a_{j}$,即要求其满足: 1.$sum_{0}=sum_{2n}=0$且$\forall 1\le i\le 2n,|sum_{i}-sum_{i- ...

  3. [atARC086F]Shift and Decrement

    将$A$操作看作直接除以2(保留小数),最终再将$a_{i}$取整 记$k$表示$A$操作的次数,$p_{i}$表示第$i$次$A$和第$i+1$次$A$之间$B$操作的次数(特别的,$p_{0}$为 ...

  4. HDC技术分论坛:HarmonyOS新一代UI框架的全面解读

    作者:yuzhiqiang,UI编程框架首席技术专家 在Harmony 3.0.0开发者预览版中,包含了新一代的声明式UI框架ArkUI 3.0.多语言跨平台编译器ArkCompiler 3.0.跨端 ...

  5. Python+selenium之弹窗

  6. 贪心/构造/DP 杂题选做

    本博客将会收录一些贪心/构造的我认为较有价值的题目,这样可以有效的避免日后碰到 P7115 或者 P7915 这样的题就束手无策进而垫底的情况/dk 某些题目虽然跟贪心关系不大,但是在 CF 上有个 ...

  7. SPOJ 1557 GSS2 - Can you answer these queries II (线段树+维护历史最值)

    都说这题是 GSS 系列中最难的,今天做了一下,名副其实 首先你可以想到各种各样的在线乱搞想法,线段树,主席树,平衡树,等等,但发现都不太可行. 注意到题目也没有说强制在线,因此可以想到离线地去解决这 ...

  8. 【GWAS】如何计算显著关联位点的表型解释率PVE(phenotypic variation explained)?

    我已经通过Gemma得到了关联分析的结果,如下. prefix.log.txt 中包含了一个总的PVE,这不是我们想要的. 那么,如何计算这些位点的表型解释率? 据了解,有些关联分析软件是可以同时得到 ...

  9. python-django-数据查询条件

    查询用户的状态是2或者是4的情况 空值和空字符串是不一样的东西!!! 需要注意的是: 项目setting.py里面的时区采用的是美国的时区,我们不要使用这个时区 使用这个时区的,我们输入的日期会进行转 ...

  10. Golang gRPC调试工具

    目录 Golang gRPC调试工具 1. 命令行工具 grpcurl 1.1 安装 1.2 验证 1.3 注册反射 1.4 使用示例 2. web调试工具grpcui 2.1 安装 2.2 验证 2 ...