[pytest] pass parameters to fixture

Take the login scenario as an example.

When performing automated testing, the account is usually randomly selected from the configuration file to log in. When you need to specify a user to log in, you need to add a parameterized decorator. The implementation is as follows:

# conftest.py
@pytest.fixture(scope="session")
def user(request):
    try:
        username = request.param
    except AttributeError:
        username = "random user"
    return username

"""使用默认用户登录"""
def test_login(user):
    print(f"获取用户信息:{
      
      user}")

--> 获取用户信息:random user

"""使用指定用户登录"""
@pytest.mark.parametrize("user", ["lan"], indirect=True)
def test_login(user):
    print(f"获取用户信息:{
      
      user}")

--> 获取用户信息:lan

To be more complicated, there are usually several steps for login, so encapsulate the login encapsulation function as a fixture, pass in a username and password, and log in directly in the use case.

@pytest.fixture
def auto_login(user):
    print(f"Fixture 内进行登录操作: {
      
      user}")
    return user

"""未指定用户,选取随机用户"""
def test_fixture(auto_login, user):
    print(f"用例内登录的用户是: {
      
      auto_login}")

--> Fixture 内进行登录操作: random user
--> 用例内登录的用户是: random user

"""已指定用户"""
@pytest.mark.parametrize("user", ["lan"], indirect=True)
def test_fixture(auto_login, user):
    print(f"用例内登录的用户是: {
      
      auto_login}")

--> Fixture 内进行登录操作: lan
--> 用例内登录的用户是: lan

Guess you like

Origin blog.csdn.net/lan_yangbi/article/details/129086339