Python 单元测试 - pytest

2019-02-15  本文已影响0人  tafanfly

pytest是python的一种单元测试框架,需要手动安装。与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高, 用法更丰富。

安装及查看版本

pip install pytest

$ pytest --version
This is pytest version 3.5.1, imported from /home/tafan/.local/lib/python2.7/site-packages/pytest.pyc

pytest --help

pytest 用法

已知被测对象demo.py

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

def add(a, b):
    return a+b

def minus(a, b):
    return a-b

1. 测试函数案例 test_demo_module.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from demo import add, minus

def setup_module(self):
    print "this setup method only called once.\n"

def teardown_module(self):
    print "this teardown method only called once too.\n"

def setup_function(self):
    print "do something before test : prepare environment.\n"

def teardown_function(self):
    print "do something after test : clean up.\n"

def test_add():
    assert add(1, 2) == 3

def test_minus():
    assert minus(3, 2) == 1

2. 测试类案例 test_demo_class.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

from demo import add, minus


class TestDemo(object):
    def setup_class(self):
        print "this setup method only called once.\n"

    def teardown_class(self):
        print "this teardown method only called once too.\n"

    def setup(self):
        print "do something before test : prepare environment.\n"

    def teardown(self):
        print "do something after test : clean up.\n"

    def test_add(self):
        assert add(1, 2) == 3

    def test_minus(self):
        assert minus(3, 2) == 1

3. pytest执行命令:

4. 生成html报告

Python 单元测试 - report


5. 常用参数

-s : 打印测试案例中print信息
-q : 只显示结果[. F E S], 不展示过程
-x : 遇到失败案例,停止测试
--maxfail=num: 失败num个案例后,停止测试

上一篇 下一篇

猜你喜欢

热点阅读