【自动化测试】Pytest的必会技巧 —— pytest setup和teardown

pytest setup和teardown

我们在使用selenium执行web自动化测试的时候,当我们需要执行多条测试用例时,执行一条用例就启动一次浏览器显然效率就太低了,我们需要一次启动浏览器,执行多条用例。pytest可以满足我们的需求吗?答案是pytest的setup和teardown完美匹配我们的需求,unittest有的它有,unittest没有的它也有!

作用范围

  • 模块级(setup_module/teardown_module)开始于模块始末,全局的
  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)
  • 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)
  • 方法级(setup_method/teardown_method)开始于方法始末(在类中
  • 类里面的(setup/teardown)运行在调用方法的前后

函数级

setup_function/teardown_function

每个用例开始和结束调用一次


# test_demo.py

# coding:utf-8
import pytest
# 函数式

def setup_function():
    print("setup_function:每个用例开始前都会执行")

def teardown_function():
    print("teardown_function:每个用例结束后都会执行")

def test_one():
    print("正在执行----test_one")
    x = "this"
    assert 'h' in x

def test_two():
    print("正在执行----test_two")
    x = "hello"
    assert hasattr(x, 'check')

def test_three():
    print("正在执行----test_three")
    a = "hello"
    b = "hello world"
    assert a in b

if __name__ == "__main__":
    pytest.main(["-s", "test_fixt.py"])

运行结果:

============================= test session starts =============================
collecting ... collected 3 items

test_demo.py::test_one setup_function:每个用例开始前都会执行
PASSED                                            [ 33%]正在执行----test_one
teardown_function:每个用例结束后都会执行

test_demo.py::test_two setup_function:每个用例开始前都会执行
FAILED                                            [ 66%]正在执行----test_two

test_demo.py:19 (test_two)
def test_two():
        print("正在执行----test_two")
        x = &

你可能感兴趣的:(自动化测试实战,pytest,测试用例,自动化测试,测试工程师,测试工具)