fixture details - as an argument, error and failed difference

Foreword

pytest fixture is a core function, but also highlights features, proficiency in use of fixture, pytest with them will be handy!

Introduction fixture

The object is to provide a fixture fixed baseline, the test can be reliably and repeatedly performed on the baseline. Providing different from traditional fixture unit test (setup / teardown) a significant improvement:

  • Independent name, and from which the test functions, modules, or the entire class project activated by declaration.
  • Achieve a modular fashion, each fixture can call each other.
  • fixture extended range from simple to complex functional test unit, and allows the assembly configuration options test fixture and parameterized, across function or function, class type, module or an entire test session module according sessio range.

fixture as an argument

Defined fixture with almost the definition of normal function, the only difference is to add a decorator @ pytest.fixture on the function (), fixture name do not start with test_, separate area with use cases. Use case is named test_ beginning.

fixture can have a return value, if not return default return None. Call return value use cases fixture, the fixture is directly a function name as a variable name, the following cases

# test_fixture1.py
import pytest

@pytest.fixture()
def user():
    print("获取用户名")
    a = "yoyo"
    return a

def test_1(user):
    assert user == "yoyo"

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

operation result

============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO\fixt, inifile:
plugins: rerunfailures-4.1, metadata-1.7.0, html-1.19.0, allure-adaptor-1.7.10
collected 1 item

test_fixture1.py 获取用户名
.

========================== 1 passed in 0.20 seconds ===========================

error and failed difference

Test results are generally three types: passed, failed, error. (Use cases except skip)

If the use case inside the assertion failure in test_, that failed

Test_fixture2.py # 
Import pytest 

@ pytest.fixture () 
DEF the User (): 
    Print ( " get the user name " ) 
    A = " yoyo " 
    return A 

DEF TEST_1 (the User): 
    the Assert the User == " yoyo111 "   # use cases failure is failed 

IF the __name__ == " __main__ " : 
    pytest.main ([ " -s " , " test_fixture2.py " ])

If the fixture inside the assertion fails, and that is error

test_fixture3.py
import pytest

@pytest.fixture()
def user():
    print("获取用户名")
    a = "yoyo"
    assert a == "yoyo123"  # fixture失败就是error
    return a

def test_1(user):
    assert user == "yoyo"

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

 

Guess you like

Origin www.cnblogs.com/guo2733/p/10948477.html