网络编程
位置:首页>> 网络编程>> Python编程>> python单元测试框架pytest介绍

python单元测试框架pytest介绍

作者:小旭2021  发布时间:2021-06-11 15:28:55 

标签:python,单元,测试,框架,pytest

pytest是python语言中一款强大的单元测试框架,用来管理和组织测试用例,可应用在单元测试、自动化测试工作中。

unittest也是python语言中一款单元测试框架,但是功能有限,没有pytest灵活。

就像:苹果电脑mac air和mac pro一样。都是具备同样的功能,但是好用,和更好用。

本文包含以下几个内容点:

  • 1)pytest的简单示例

  • 2)pytest的安装

  • 3)pytest的特征、与unittest的区别。

  • 4) pytest如何自动识别用例。

  • 5)pytest框架中,用例的运行顺序。

1)pytest写用例很简单

下面是一个简单的例子:

import random

def test_demo():
assert 7 == random.randint(0,10)

运行结果如下:

============================= test session starts =============================
platform win32 -- Python 3.7.2, pytest-4.6.3, py-1.8.0, pluggy-0.12.0
rootdir: D:\Pychram-Workspace\STUDY_PYTEST
plugins: allure-pytest-2.6.5, html-1.21.1, metadata-1.8.0, rerunfailures-7.0collected 1 item

simple.py F
simple.py:10 (test_demo)
7 != 6

Expected :6
Actual   :7

========================== 1 failed in 0.14 seconds ===========================

2)pytest的安装

安装命令:

pip install pytest

3)pytest的特征、与unittest的区别。

pytest的特征如下:

  • 3.1 自动识别测试用例。(unittest当中,需要引入TestSuite,主动加载测试用例。)

  • 3.2 简单的断言表达:assert表达式即可。(unittest当中,self.assert*)

  • 3.3 有测试会话、测试模块、测试类、测试函数级别的fixture。(unittest当中是测试类、测试函数级别的fixture)

  • 3.4有非常丰富的插件,目前在600+,比如allure插件。(unittest无)

  • 3.5测试用例不需要封装在测试类当中。(unittest中需要自定义类并继承TestCase)

那么pytest是如何自动识别测试用例的呢?我们在编写pytest用例的时候,需要遵守哪些规则呢?

4) pytest如何自动识别用例

识别规则如下:

1、搜索根目录:默认从当前目录中搜集测试用例,即在哪个目录下运行pytest命令,则从哪个目录当中搜索;

2、搜索规则:

1)搜索文件:符合命名规则 test_*.py 或者 *_test.py 的文件

2)在满足1)的文件中识别用例的规则:

  • 2.1)以test_开头的函数名;

  • 2.2)以Test开头的测试类(没有__init__函数)当中,以test_开头的函数

示例:在D:\pycharm_workspace目录下,创建一个python工程,名为study_pytest。在工程下,创建一个python包,包名为TestCases。

在包当中,创建一个测试用例文件:test_sample_1.py。文件内容如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# 定义py文件下的测试用例
def test_sample():
    print("我是测试用例!")

class TestSample:

def test_ss(self):
        print("我也是测试用例!")

def hello_pytest(self):
        print("hi,pytest,我不是用例哦!!")

按照上面定义的搜索规则,需要跳转到工程目录,然后再执行命令:pytest -v 。 执行结果如下:

python单元测试框架pytest介绍

让我们愉快的加进来第2个测试文件:test_sample_2.py,内容如下:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

def add(a,*args):
   sum = a
   for item in args:
       sum += item
   return sum

def test_add_two_number():
   assert 33 == add(11,22)
   assert 55.55 == add(22.22,33.33)

def test_add_three_number():
   assert 101 == add(10,90,1)

再次运行命令:pytest -v 得到如下结果:

python单元测试框架pytest介绍

通过多个用例文件的执行,可以看出用例的执行顺序。

5) pytest中用例的执行顺序

原则:先搜索到的py文件中的用例,先执行。在同一py文件当中,按照代码顺序,先搜索到的用例先执行。

来源:https://www.cnblogs.com/chenyablog/p/15162324.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com