pytest-快速上手

简介

pytest是Python的单元测试框架,同自带的unittest框架类似,但pytest框架使用起来更简洁,效率更高。

特点

  • 入门简单易上手,文档支持较好。
  • 支持单元测试和功能测试。
  • 支持参数化。
  • 可以跳过指定用例,或对某些预期失败的case标记成失败。
  • 支持重复执行失败的case。
  • 支持运行由unittest编写的测试用例。
  • 有很多第三方插件,并且可自定义扩展。
  • 方便和支持集成工具进行集成。

安装

pip install pytest

简单使用

import pytest

def test_case():
    print('test case -01')
    assert 0

def some_case():   # 不会被pytest识别
    print('test case -01')
    assert 1
    
class TestCase_02:

    def test_case_01(self):
        print('test case -01')
        assert 1
    def test_case_02(self):
        print('test case -02')
        assert 1
    def aaa_case_01(self):
        print('test case -01')
        assert 0

if __name__ == '__main__':
    pytest.main(['2-简单上手.py'])
  1. pytest,可以识别将test开头的函数当做测试用例
  2. pytest.main(['demo.py']),main中的参数是列表,不建议用字符串的形式
  3. pytest也识别以Test开头的用例类,并且,类中的用例也必须是test
  4. 断言结果
    • .表示成功
    • F表示失败

setup/teardown

不同于unittest的setup和teardown只有类的形式。而pytest的setup和teardown有以下几种形式:

  • 函数级别
    • setup_function
    • teardown_function
  • 类级别(类似于unittest的setupclass/teardownclass)
    • setup_class
    • teardown_class
  • 类中方法级别的(类似于unittest的setup/teardown)
    • setup_method
    • teardown_method
  • 模块级别的setup和teardown,在脚本中所有的用例函数和用例类执行之前和执行之后
    • setup_module
    • teardown_module
import pytest


def setup_module():
    print('模块级别的 setup_module')

def teardown_module():
    print('模块级别的 teardown_module')


def setup_function():
    print('在用例函数执行之前')

def teardown_function():
    print('在用例函数执行之后')

def test_login():
    print('test case test_login')
    assert 1

class TestCaseReg:
    def setup_class(self):
        print('类级别的 setup')
    def teardown_class(self):
        print('类级别的 teardown')

    def setup_method(self):
        print('类中方法级别的 setup')

    def teardown_method(self):
        print('类中方法级别的 teardown')

    def test_case_01(self):
        print('test case -01')
        assert 1
    def test_case_02(self):
        print('test case -02')
        assert 1

if __name__ == '__main__':
    pytest.main(['-s', '3-setup和teardown.py'])

pytest的配置文件

pytest脚本的几种运行方式

  1. 右键运行(不推荐)
  2. 终端执行 python demo.py 推荐
  3. 终端执行pytest,需要搭配配置文件来运行

配置文件

  1. 配置文件名称固定pytest.ini

    1. addopts,运行时的相关参数

    2. testpaths,跟unittest的TestLoader性质一样,用来存放所有的用例脚本

    3. python_files,脚本文件必须是以指定字符开头

      1. 如果你想运行scripts目录下指定的文件,你可以这样写
      python_files = test_login.py
      

      python_classes,脚本中的类名以指定字符开头

    4. python_functions,脚本中的函数名以指定字符开头

[pytest]
addopts = -s -v
testpaths = ./scripts
python_files = test_*.py
python_classes = Test*
python_functions = test_*
  1. 该配置文件必须在项目的根目录,并且与用例目录同级别

你可能感兴趣的:(pytest-快速上手)