zoukankan      html  css  js  c++  java
  • Pytest单元测试框架之简单操作示例

    前言:

      Pytest是第三方单元格测试框架,更加简单,灵活,而且提供了更多丰富的扩展;

    Pytest与UnitTest框架的区别

    UnitTest测试用例执行顺序是依照ascii码执行,而Pytest是根据测试用例顺序执行;

     1、Pytest官方网站: https://docs.pytest.org/en/latest/

     2、Pytest支持 pip 安装,pip3 install pytest,安装成功后直接导入包使用,如: import pytest 

     3、在Pytest中,它会寻找以test开头或test结尾的测试模块(test**.py、**test.py),然后在模块中执行以test开头的测试方法代码,依据这个进行编写测试用例

     4、断言:在UnitTest单元测试框架中提供了丰富的断言方法,如assertEqual() 、assertIn()、assertTrue()、assertIs()等;

                     在Pytest单元测试框架并没有提供专门的断言方法,而是直接使用Python的assert进行断言

    # 导入包
    import pytest

    #功能:用于计算a与b相加的和
    def add(a,b):
    return a + b

    #功能:用于判断素数
    def is_prime(n):
    if n < 1:
    return False
    for i in range(2,n):
    if n % i == 0:
    return False
    return True

    #测试相等
    def test_add_1():
    assert add(3,4) == 7

    #测试不相等
    def test_add_2():
    assert add(17,22) != 50

    #测试大于或者等于
    def test_add_3():
    assert add(17,22) <= 50

    #测试小于或者等于
    def test_add_4():
    assert add(17,22) >= 38

    #测试包含
    def test_in():
    a = 'Hello'
    b = 'He'
    assert b in a

    #测试不包含
    def test_not_in():
    a = 'Hello'
    b = 'hi'
    assert b not in a

    #判断是否为True
    def test_true_1():
    assert is_prime(13)

    #判断是否为True
    def test_true_2():
    assert is_prime(7) is True

    #判断是否不为True
    def test_true_3():
    assert is_prime(4) is False

    #判断是否不为True
    def test_true_4():
    assert is_prime(6) is not True

    #判断是否为False
    def test_false_1():
    assert is_prime(8) is False

    if __name__ == '__main__':
    # main()方法默认执行当前模块中所有以”test开头或test结尾“的函数
    pytest.main()

    # 若执行终端窗口中使用pytest执行看到执行用例的进度条的话,则需安装 pip3 install pytest-sugar

    见执行后输出结果:

     其实在一个模块中,不仅包含了函数,还有类,下面来写一段代码实例

    # 导入包
    import pytest

    #功能:用于计算a与b相加的和
    def add(a,b):
    return a + b

    #测试相等
    def test_add_1():
    assert add(3,4) == 7

    #测试不相等
    def test_add_2():
    assert add(17,22) != 50

    class TestAdd(object):
    # 测试大于或者等于
    def test_add_3(self):
    assert add(17, 22) <= 50

    # 测试小于或者等于
    def test_add_4(self):
    assert add(17, 22) >= 38
    if __name__ == '__main__':
      
    pytest.main(['-s','-v','test_assert.py'])

    见执行后输出结果:

     总结:

    1、要执行的测试模块必须以test开头

    2、要执行的测试函数必须以test开头或test结尾

    3、若类要被Pytest执行,那么该类名称首字母必须是:Test,否则不会被执行

  • 相关阅读:
    javascript获得元素的尺寸和位置二 : clientWidth/Height、scrollWidth/Height、scrollTop/Left
    CSS中的Position属性
    JavaScript沙箱SandBox设计模式
    JavaScript中为事件句柄绑定监听函数
    MatrixTransform矩阵变换
    getBoundingClientRect计算页面元素的offsetLeft、offsetTop
    PHP Warning: date() [function.date]: It is not safe to rely on the system's timezone
    CollectGarbage函数JS清理垃圾,内存释放
    (转)python路径操作新标准:pathlib 模块
    (转)sql函数总结(更新中... ...)
  • 原文地址:https://www.cnblogs.com/Teachertao/p/14673403.html
Copyright © 2011-2022 走看看