Pytest单元测试框架-Pytest环境安装

Pytest单元测试框架-Pytest环境安装

 

unittest是python自带的单元测试框架,它封装好了一些校验返回的结果方法和一些用例执行前的初始化操做,使得单元测试易于开展,由于它的易用性,不少同窗也拿它来作功能测试和接口测试,只需简单开发一些功能(报告,初始化webdriver,或者http请求方法)即可实现。html

但自动化测试中咱们经常须要根据不一样需求挑选部分测试用例运行,而且咱们但愿用例克服环境不稳定的局限,即运行失败后自动从新运行一次,若是成功就认为是环境问题致使第一次失败,还有咱们常常但愿测试用例能够并发执行等等,这些unittest都作不到或者须要大量二次开发才能作到,那么有没有更增强大的框架能够替代unittests呢?python

pytest是python里的一个强大框架,它能够用来作单元测试,你也能够用来作功能,接口自动化测试。并且它比unittest支持的功能更多更全面。可是pytest在Getstarted里给出的实例却很简单,不少同窗错觉得它只是跟unittest同样是个单元测试框架罢了,若是你查询中文互联网,你也只能找到寥寥数篇大体同样的用法,能够说pytest的精髓使用,没有被你们挖掘出来,如此强大的框架不该该被埋没,今天我就带领你们深刻pytest使用,共同领略pytest的强大。web

1.安装pytest单元测试框架session

2.检查Pytest安装版本 使用的命令是:pip show pytest并发

也可使用 pytest -version 来查看框架

先来看一下第一个例子.新建一个python文件,collect.py 代码以下:函数

def func(x):
    return x+1
def test_answer():
    assert func(3) == 5
test_answer()

运行结果以下:post

Traceback (most recent call last):
  File "E:/untitled1/collect.py", line 90, in <module>
    test_answer()
  File "E:/untitled1/collect.py", line 89, in test_answer
    assert func(3) == 5
AssertionError

固然,也能够进入到collect.py所在文件中,使用pytest命令来执行:单元测试

复制代码
E:\untitled1>pytest collect.py
============================= test session starts =============================
platform win32 -- Python 3.5.1, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: E:\untitled1
collected 0 items / 1 errors

=================================== ERRORS ====================================
_________________________ ERROR collecting collect.py _________________________
collect.py:90: in <module>
    test_answer()
collect.py:89: in test_answer
    assert func(3) == 5
E   assert 4 == 5
E    +  where 4 = func(3)
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.13 seconds ===========================

E:\untitled1>
复制代码

须要说明的是:pytest运行规则是自动查找python文件中以 test 开头的函数并执行。继续定义一个类。把多个函数封装到类中。以下:测试

复制代码
class TestClass():
    def test_one(self):
        x = 'hello'
        assert 'h' in x

    def test_two(self):
        x = 'hello'
        assert hasattr(x, 'check')
复制代码

使用cmd命令来运行testclass测试类,继续执行collect.py文件:

复制代码
E:\untitled1>pytest -q  collect.py
.F                                                                       [100%]
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________

self = <collect.TestClass object at 0x0000000003679DD8>

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

collect.py:102: AssertionError
1 failed, 1 passed in 0.07 seconds
复制代码

(-q表示的是显示简单的测试结果)由测试结果可知,第一个用例是经过的,第二个是失败啊的。测试结果能够很清楚的查看报错缘由!

Pytest运行规则:

1. 测试文件必须以test开头或者_test结尾。
2. 测试类必须是以test开头,且不能有init初始化方法
3. 测试函数必须是以test开头
4. 测试断言必须是assert方法 

做者:丨Fighter.Lu丨 点滴记录,开源共享。帮助更多有须要的人解决问题!博主博客地址:http://www.cnblogs.com/fighter007/
相关文章
相关标签/搜索