可以将@pytest.fixture用于测试用例吗?

0 投票
2 回答
58 浏览
提问于 2025-04-14 18:15

假设我有两个测试用例,第一个是 test_log_in,第二个是 test_log_out。我想在每个测试用例的前后都使用这两个用例。我知道我们可以在 conftest.py 文件里使用 pytest.fixture,但在这种情况下,test_log_in 和 test_log_out 是测试用例,我不想把它们放到 conftest.py 里。有没有什么办法可以实现这个想法呢?非常感谢你的帮助!

#here is my conftest.py
@pytest.fixture(scope="function")
def appium_driver(request):
   pass

@pytest.fixture
def log_on_failure(request, appium_driver):
   pass

#here is my test.py and I want to run test_login before every single test case and test_logout after every single test case
class Test_Login(base_test):

    def test_login(self, username, password):
        #test_login

    def test_logout():
        #test_logout

我看过 pytest 的文档,但没有找到相关的信息。

2 个回答

-1

是的,可以把 @pytest.fixture 当作一个测试用例来使用。

1

这可能就是你需要的,因为我看不出有什么理由把一个固定装置当作测试来用。

import pytest

@pytest.fixture
def log_in_out(username, password):
    print(f"log in {username}/{password}")
    assert 1 == 1
    yield
    print("log out")
    assert 1 == 1

class BaseTest:
    pass

#here is my test.py and I want to run test_login before every single test case and test_logout after every single test case
class Test_Login(BaseTest):

    @pytest.mark.parametrize("username, password", [("user1", "pass1")])
    def test_something(self, username, password, log_in_out):
        print("test_something")
        assert 1 == 1

撰写回答