栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytest基础

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytest基础

关于pytest的学习
  • 模块安装安装
  • 模块基本使用
  • 几个重要函数
    • 装饰器
    • 生成报告文件

模块安装安装

由于我预先安装了anaconda,所以在anaconda中安装

当然也可以在pycharm中的Terminal中安装,命令:

pip install -U pytest
模块基本使用

例子:
建立py文件test_tt.py,代码如下

import pytest


class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x
    def aa(self):
        print(3)
    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")


if __name__ == '__main__':
    #    pytest.main()
    pytest.main("test_study.py")

结果:

由结果可知,pytest的定义规则:

1.测试类以Test开头,并且不能带有 init 方法
2.测试函数以test_开头

可以看出未按规则的函数没有被测试,且测试通过pass,不通过fail,且显示其所占的比例。
这里还有网上说的其他一条规则:
测试文件以test_开头(以_test结尾也可以)和运行会运行同文件架下的所有test开头文件,但是这点我并没有实现,不知是哪里出了问题。值得注意的是main函数括号里即使填错了文件名仍可以正常运行。
刚学,不懂为神魔。

几个重要函数

类级别和函数级别

import pytest
# -*-coding:utf-8-*-
import pytest


# module一个模块只会执行一次,最开头和最结尾调用
def setup_module():
    print('每个模块执行一次 开始')


def teardown_module():
    print('每个模块执行一次 结束')


# function 每个用例执行一次,不会对类中的用例生效
def setup_function():
    print("每个类外用例前执行")


def teardown_function():
    print("每个类外用例后执行")


def test_case2():
    print("2")


class TestDemo:
    def setup_class(self):
        print("当前类之前执行")

    def teardown_class(self):
        print("当前类之后执行")

    def setup(self):
        print("类里的每个方法调用  前")

    def teardown(self):
        print("类里的每个方法调用  后")

    def test_case3(self):
        print("我是测试用例")



if __name__ == '__main__':
    #    pytest.main()
    pytest.main("test_tt.py")

看结果·:

可以看出module在整个模块的开始和结尾执行一次。
function在类外的所有内容开始和结尾执行一次。
class在类内的所有内容开始和结尾执行一次。

装饰器
import pytest
# -*-coding:utf-8-*-
import pytest


# 跳过这个用例skip装饰器
@pytest.mark.skip(reason="暂时不执行")
def test_case5():
    print("test5")


def test_case6():
    return 4


# 可以在用例里面做判断,判断结果为真跳过这条用例
def test_case7():
    if 4 == test_case6():
        pytest.skip("跳过原因case6等于4")
    print("case7")


# 可以直接在外面做判断skipif
@pytest.mark.skipif(test_case6() == 4, reason="跳过因为是windows系统")
def test_case8():
    print("case8")

if __name__ == '__main__':
    #    pytest.main()
    pytest.main("test_tt.py")

结果:

可以看到跳过的方法有三种;装饰器、装饰器加判断和类内判断。第一种直接不执行,后两种条件成立不执行。

生成报告文件

首先生成报告需要专属的模块allure。安装方法两种:
1.anaconda安装这个真的很方便。
2.网上的方法我没试过,分享给大家:
0.安装java1.8

1、安装alluer+ allure-pytest

    1)下载allure 的zip包,下载后放到python文件夹lib下        

    2)进入allure 的bin目录下,复制路径,放到path环境变量

    3)安装alluer-pytest

            pip install allure-pytest

报告生成:
pytest --alluredir=tmp test_tt.py

具体生成网页报告还需要安装额外模块:
pip install pytest-html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011717.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号