【发布时间】:2022-11-29 06:02:55
【问题描述】:
我知道这是一个老问题,成千上万的人回答了类似的问题,但我还是不明白...... 我应该如何为整个测试会话以及每个测试类使用设置/拆卸?
例如,我有以下测试文件结构:
- common_setup.py
- test_suite_1.py
- test_suite_2.py
这些文件是这样的:
# common_setup.py
import logging
import pytest
@pytest.fixture(scope="session")
def set_session_data():
# Setup
logging.info("In session setup")
# Teardown
yield
logging.info("In session teardown")
# test_suite_1.py
import logging
import pytest
import common_setup
@pytest.fixture(scope="class")
def set_data():
# Setup
logging.info("In test suite 1 setup")
# Teardown
yield
logging.info("In test suite 1 teardown")
@pytest.mark.usefixtures("set_data")
class TestClass:
def test_case_1():
logging.info("In test suite 1, test case 1")
def test_case_2():
logging.info("In test suite 1, test case 2")
# test_suite_2.py
import logging
import pytest
import common_setup
@pytest.fixtures(scope="class")
def set_data():
# Setup
logging.info("In test suite 2 setup")
# Teardown
yield
logging.info("In test suite 2 teardown")
@pytest.mark.usefixture("set_data")
class TestClass:
def test_case_1():
logging.info("In test suite 2, test case 1")
def test_case_2():
logging.info("In test suite 2, test case 2")
我希望会话设置/拆卸(“common_setup.py”)中的内容应该在每个会话中执行,并且每个测试套件也有它自己的特定设置/拆卸。
到目前为止,我有下面的日志,这意味着未调用会话范围的方法。我知道我没有使用它,但我不能简单地将它添加到 @pytest.mark.usefixture("set_data", "set_session_data") 之类的 usefixtures
2022-11-28 15:16:25 INFO In test suite 1 setup
2022-11-28 15:16:25 INFO In test suite 1, test case 1
2022-11-28 15:16:25 INFO In test suite 1, test case 2
2022-11-28 15:16:25 INFO In test suite 1 teardown
2022-11-28 15:16:25 INFO In test suite 2 setup
2022-11-28 15:16:25 INFO In test suite 2, test case 1
2022-11-28 15:16:25 INFO In test suite 2, test case 2
2022-11-28 15:16:25 INFO In test suite 2 teardown
任何讨论都适用。 谢谢!
尝试了不同的选项,上面的代码已经是我能走的最远的了……
预期的执行应该是:
- 会话设置(目前缺失)
- 套件 1 设置
- 套件1案例1
- 套件 1 案例 2
- 套件 1 拆解
- 套件 2 设置
- 套件 2 案例 1
- 套件 2 案例 2
- 套件 2 拆解
- 会话拆解(目前缺失)
【问题讨论】:
-
只需将
autouse=True添加到您的会话范围的夹具中。 -
这将我带到link,从字面上为我回答了所有问题。谢谢!