手机版
你好,游客 登录 注册
背景:
阅读新闻

Python单元测试框架pytest

[日期:2017-11-06] 来源:Linux社区  作者:ranxf [字体:大 中 小]

pytest帮你写出更好的程序

1、An example of a simple test:(一个简单的例子),命名为test_pytest1.py

def funx(x):
    return x + 1


def test_answer():
    assert funx(2) == 5

运行:

  • 进入Python脚本路径:pytest test_pytest1.py

  root@localhost:/home/ranxf/Python3单元测试/demo# pytest test_pytest1.py
============================= test session starts ==============================
platform linux -- Python 3.5.2, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /home/ranxf/Python3单元测试/demo, inifile:
collected 1 item                                                               

test_pytest1.py F

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

    def test_answer():
>      assert funx(2) == 5
E      assert 3 == 5
E        +  where 3 = funx(2)

test_pytest1.py:8: AssertionError
=========================== 1 failed in 0.02 seconds ===========================

 

  • 进入python脚本路径:pytest -q test_pytest1.py(加一个参数-q),运行结果:

root@localhost:/home/ranxf/Python3单元测试/demo# pytest -q test_pytest1.py
F
=================================== FAILURES ===================================
_________________________________ test_answer __________________________________

    def test_answer():
>      assert funx(2) == 5
E      assert 3 == 5
E        +  where 3 = funx(2)

test_pytest1.py:8: AssertionError
1 failed in 0.02 seconds

两种运行结果有一点差异,就是少了一些版本信息。

3、一个测试类中创建多个测试用例:

# 一个测试类种创建多个测试用例


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

    def test_two(self):
        x = "hello"
        assert x == "hi"

4、pytest同样可以提供main()函数来执行测试用例:

目录结构:

"""
pytest中同样提供了main() 来函数来执行测试用例。

pytest/

├── test_pytest1.py

├── test_pytest2.py

└── test_main.py
"""

注:主函数中的文件名只能是test_main.py(如果改为test_pytest3这种格式,将不会遍历执行同路径的其他用例)

import pytest


def test_main():
    assert 5 != 5

if __name__ == "__main__":
    # pytest.main()  # 遍历相同目录下的所以test开头的用例
    # pytest.main("-q test_main.py")  # 指定测试文件
    pytest.main("/root/Documents/python3_1000/1000/python3_pytest")  # 指定测试目录

5、pytest生成Html格式的测试报告:

  python3 -m pytest test_main.py --html=report/test_main.html

官网:https://docs.pytest.org/en/latest/

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-11/148328.htm

linux
相关资讯       pytest  Python单元测试框架 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款