学习-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:\porject>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 ===========================
View Code

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:\porject>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
View Code

5. 使用规则

  • 测试文件以test_开头(以_test结尾也可以)
  • 测试类以Test开头,并且不能带有 init 方法
  • 测试函数以test_开头
  • 断言使用assert
posted @ 2019-07-12 16:09  小L小  阅读(352)  评论(0)    收藏  举报