天天看点

软件测试系列:pytest框架环境准备与入门

作者:Ray软件测试

pytest简介

pytest是python的单元测试框架,与python自带的unittest测试框架类似,比unittest框架使用更简洁,效率更高。具有如下特点:

  • 容易上手,入门简单,文档丰富,文档中有很多实例可以参考
  • 能够支持简单的单元测试和复杂的功能测试
  • 支持参数化
  • 执行测试过程中可以将某些测试跳过(skip),或对某些预期失败的case标记成失败
  • 支持重复执行(rerun)失败的case
  • 支持运行由nose, unittest编写的测试case
  • 可生成html报告
  • 方便的和持续集成工具jenkins集成
  • 可支持执行部分用例
  • 具有很多第三方插件,支持自定义扩展

安装pytest

1、安装方法

pip install -U pytest           

2、查看安装版本

pip show pytest
或者
pytest —version           

测试函数快速入门

1、新建一个test_sample.py文件,写以下代码

# content of test_sample.py
def func(x):
    return x +1

def test_answer():
    assert func(3)==5           

2、打开test_sample.py所在的文件夹,cmd窗口输入:pytest(或者输入py.test也可以),运行结果如下:

D:\RAY>pytest
============================= test session starts =============================
platform win32 -- Python 3.11.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO, inifile:
collected 1 item

test_sample.py F                                                         [100%]

================================== FAILURES ===================================
_________________________________ test_answer _________________________________

    def test_answer():
>       assert func(3)==5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:6: AssertionError
========================== 1 failed in 0.19 seconds ===========================           

3、pytest运行规则:查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行。

测试类快速入门

1、当用例有多个的时候,写函数不太合适。可以把多个测试用例,写到一个测试类里。

# test_class.py

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')           

2、打开cmd,cd到test_class.py的文件目录,如果只想运行这个文件,加上-q参数(用来指定执行的文件,不指定就执行该文件夹下所有的用例)

D:\RAY>py.test -q test_class.py
.F                                                                       [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________

self = <test_class.TestClass object at 0x00000000039F1828>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

test_class.py:11: AssertionError
1 failed, 1 passed in 0.04 seconds           
软件测试系列:pytest框架环境准备与入门