如何在 conftest.py 中设置会话详细信息以获取 yield 以及 pytest 中的 fixture?
How can I set session details in conftest.py for yield along with fixture in pytest?
我的目标是在 conftest.py 文件 中创建一个预测试和 post 测试,这将 运行 在我的测试中的每个测试用例之后套房。即我试图 运行 在所有测试和方法 (logout() ) 经过所有测试。
我试过使用下面的代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我观察到,虽然我的预测试 (login_page() & login()) 完美 运行ning,但在所有测试用例之前,post-测试 ( logout()) 没有按预期工作,在我选择的所有测试用例执行后 运行仅 。
为了尝试不同的方法,我也尝试在 conftest.py 中使用以下代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
@pytest.yield_fixture(scope="session", autouse=True)
def posttest():
logout()
上述方法只是抛出一些错误,并没有启动测试。
我还在 conftest.py 文件
中尝试了以下代码片段
@pytest.yield_fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我认为你真的很接近,你的问题来自于使用 "session"
范围,这是更高的可能范围(更多信息参见 Pytest fixture scope)。
使用 "session"
意味着您的夹具对所有测试执行一次 运行。如果你在那个 fixture 中 yield
-ing,yield
之前的内容将在所有测试之前执行(而不是在每个测试之前!),而之后的内容将 运行 毕竟测试有 运行.
将此切换为 "function"
将使夹具 运行 before/after 改为每次测试,这就是您想要的:
@pytest.fixture(scope="function", autouse=True)
def login_context(): # Renamed for clarity
login_page()
login()
yield driver # Not sure what this is?
logout()
注意这里的重命名:pretest
是误导,因为部分 fixture 将在测试后实际执行。
我的目标是在 conftest.py 文件 中创建一个预测试和 post 测试,这将 运行 在我的测试中的每个测试用例之后套房。即我试图 运行 在所有测试和方法 (logout() ) 经过所有测试。
我试过使用下面的代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我观察到,虽然我的预测试 (login_page() & login()) 完美 运行ning,但在所有测试用例之前,post-测试 ( logout()) 没有按预期工作,在我选择的所有测试用例执行后 运行仅 。
为了尝试不同的方法,我也尝试在 conftest.py 中使用以下代码片段
@pytest.fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
@pytest.yield_fixture(scope="session", autouse=True)
def posttest():
logout()
上述方法只是抛出一些错误,并没有启动测试。
我还在 conftest.py 文件
中尝试了以下代码片段@pytest.yield_fixture(scope="session", autouse=True)
def pretest():
login_page()
login()
yield driver
logout()
我认为你真的很接近,你的问题来自于使用 "session"
范围,这是更高的可能范围(更多信息参见 Pytest fixture scope)。
使用 "session"
意味着您的夹具对所有测试执行一次 运行。如果你在那个 fixture 中 yield
-ing,yield
之前的内容将在所有测试之前执行(而不是在每个测试之前!),而之后的内容将 运行 毕竟测试有 运行.
将此切换为 "function"
将使夹具 运行 before/after 改为每次测试,这就是您想要的:
@pytest.fixture(scope="function", autouse=True)
def login_context(): # Renamed for clarity
login_page()
login()
yield driver # Not sure what this is?
logout()
注意这里的重命名:pretest
是误导,因为部分 fixture 将在测试后实际执行。