美文网首页我的收藏
Pytest+Allure搭建接口框架(四)

Pytest+Allure搭建接口框架(四)

作者: Aaron_fcff | 来源:发表于2019-05-08 21:40 被阅读52次

前言:之前上网查阅到pytest框架具有更加灵活的测试方法,于是查阅了资料研究了它。总结下几个我比较在意也比较喜欢的点:
1.细粒度地控制要测试的测试用例
2.具有很多第三方插件,并且可以自定义扩展
3.失败case的重复执行
4.可以很好地和jenkins结合
5.兼容python和unittest多个版本
话不多说,马上开始......

一、安装 & 说明

十分简单,只需执行一句命令即可==>

pip install pytest

这里需要说明一下pyetest的一些编写规则,需要按照它规定的编码风格才能使你的代码正确运行pytest进行测试
1.所有的python文件名都需要满足 test_*.py格式 或 *test.py格式
2.在python文件中,待测试类需以Test开头
3.在python文件中,待测试函数需包含test
开头,可以包含一个或多个test_开头的函数
4.断言直接使用assert xxxx即可

二、初尝

a)首先从简单的断言开始

import pytest


class TestCase:
    def test_one(self):
        assert 0 == 1


if __name__ == '__main__':
    pytest.main()

结果如下所示:

============================= test session starts =============================
platform win32 -- Python 3.7.2, pytest-4.4.0, py-1.8.0, pluggy-0.9.0
rootdir: C:\PycharmProjects\NewMYAPI
plugins: allure-pytest-2.6.2
collected 1 item

test_report.py F                                                         [100%]

================================== FAILURES ===================================
______________________________ TestCase.test_one ______________________________

self = <test_report.TestCase object at 0x000001896D067CC0>

    def test_one(self):
>       assert 0 == 1
E       assert 0 == 1

test_report.py:7: AssertionError
========================== 1 failed in 0.18 seconds ===========================

一目了然的结果,分别是你的运行环境、执行目录、附加、测试数、执行进度、结果详情包括断言结果。

b)setup/teardown函数
主要作用:运行于测试方法的始末,即:每运行一次测试函数就会运行一次setup & teardown

import pytest


class Test_ABC:
    def setup(self):
        print("------->setup")

    def teardown(self):
        print("------->teardown")

    def test_a(self):
        print("------->test_a")
        assert 1 == 1

    def test_b(self):
        print("------->test_b")
        assert 2 == 0

    def test_c(self):
        print("------->test_c")
        assert 3 != 1


if __name__ == '__main__':
    pytest.main("-s  test_case.py")

运行结果如下:

test_case.py ------->setup
------->test_a
.------->teardown
------->setup
------->test_b
F------->teardown
------->setup
------->test_c
.------->teardown

c)setup_class/teardown_class函数
主要作用:运行于测试类的始末,即:每运行一测试类就会运行一次setup_class & teardown_class

import pytest


class TestCase:

    def setup_class(self):
        print("=======>setup class")

    def teardown_class(self):
        print("=======>teardown class")

    def test_one(self):
        assert 0 == 1

    def test_twp(self):
        assert 1 == 1


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

运行结果如下:

test_report.py =======>setup class
F.=======>teardown class

下回,我将会学习更多有关pytest有用有趣的功能...

相关文章

网友评论

    本文标题:Pytest+Allure搭建接口框架(四)

    本文链接:https://www.haomeiwen.com/subject/qdrjnqtx.html