python - Py.test fixture : Use function fixture in scope fixture

标签 python python-2.7 selenium pytest fixtures

我正面临 pytest 固定装置的一个小问题,感谢您的帮助。

我有一些功能装置,如下所述。为简单起见,我没有展示实现。

@pytest.fixture()
def get_driver():
    pass

@pytest.fixture()
def login(get_driver):
    pass

@pytest.fixture()
def settings(login):
    pass

问题是我还需要一个( session 级别 ) fixture ,它在运行我的第一个测试用例之前进行设置。 (实际开始测试)。即转到设置页面并创建一些设置。 (登录后)

现在的问题是我不能这样做使用 session 级 fixture ,因为我不能在 session 级使用函数级装置。 或者我可以吗?
@pytest.fixture(scope="session")
def setup(settings):
    settings.create_settings()
    pass

最佳答案

您将需要使用一种解决方法。该操作需要在 function 中完成带 autouse 的范围 fixture 设置为 True .

您需要在 session 中初始化一个变量基于 fixture ,这将检查 settings已经完成与否。如果没有完成,那么您将进行设置并将标志更改为 False
下面是一个工作示例

import pytest


@pytest.fixture(scope="session", autouse=True)
def settings_page():
    config = {"config_done": False}
    return config


@pytest.fixture()
def init(request):
    print("init called")
    return "init"


@pytest.fixture()
def driver():
    print("driver called")

    return "driver"


@pytest.fixture(autouse=True)
def init_settings(settings_page, driver):
    if not settings_page["config_done"]:
        print("Settings being done only the first time")
        settings_page["config_done"] = True


@pytest.fixture()
def login():
    print("login called")
    return "login"


@pytest.fixture()
def logged_in_driver(init, driver, login):
    print("logged in driver is ready")
    return (init, driver, login)


@pytest.fixture()
def non_logged_in_driver(init, driver):
    print("non logged in driver is ready")
    return (init, driver)


def test_1(logged_in_driver):
    print("test_1")


def test_2(non_logged_in_driver):
    print("test_2")

输出如下
test.py driver called
Settings being done only the first time
init called
login called
logged in driver is ready
.test_1
driver called
init called
non logged in driver is ready
.test_2

所以你可以看到设置只发生一次

关于python - Py.test fixture : Use function fixture in scope fixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817153/

相关文章:

python - conda 更新不起作用 - conda 列表下的软件包版本保持不变

python - 你如何安装没有依赖项的python包

mysql - 无法在 Python 中导入 MySQLdb 模块

python - 属性错误: 'Sheet' object has no attribute 'row_len'

selenium - Windows 10 上使用 IEDriverServer 和 IE 11 时出现 java.net.ConnectException : Failed to connect to localhost error with Selenium 3. 11.0

javascript - selenium:单击按钮后如何获取页面源代码

python - IntelliJ IDEA 对所有内容都说 "unresolved reference"(Python、虚拟环境)

python - 使用 Python/Pandas 索引日期作为假期列表中的条件

python - 如何在 flatMap 函数中实现迭代

c# - PhantomJSDriver 点击元素 WebDriverException 超时