学习笔记-Pytest(一)简介

1. pytest简介

pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高。

2. 安装pytest

pip install -U pytest
#查看是否安装成功
pytest --version

3. 一个简单的例子

1.新建一个test_sample.py文件,(文件命名以test_*开头或者*_test结尾)

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

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

2.在terminal中输入pytest,运行结果:

D:\YOYO>pytest
============================= test session starts =============================
platform win32 -- Python 3.6.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 ===========================

4. 执行测试类

1.前面是写的一个test开头的测试函数,当用例用多个的时候,写函数就不太合适了。这时可以把多个测试用例,写到一个测试类里。

# 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参数,-q参数用来指定执行的文件,不指定就执行该文件夹下所有的用例

py.test -q test_class.py
D:\YOYO>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

5. 使用规则

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用assert
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容