【问题标题】:pytest: how to get return value from a fixture and pytest.mark.parametrize in the same functionpytest:如何在同一个函数中从夹具和 pytest.mark.parametrize 获取返回值
【发布时间】:2020-06-08 06:39:19
【问题描述】:

我正在努力完成以下工作:

  • pytest 夹具返回数据库句柄

  • pytest.mark.parametrize 传递将运行测试的参数

我浏览了 pytest 文档、多个论坛。我没有得到任何答复。有人可以提出解决问题的方法吗?还是另一种方法?

编辑 1: 我希望数据库连接在设置功能中只发生一次。此数据库连接用于所有测试功能。测试函数将针对参数化值中的参数运行。如何从夹具返回 db_conn 值?

import pytest

@pytest.fixture(scope="module")
def conn():
    db_conn = get_db_conn()
    yield db_conn
    db_conn.close()


@pytest.mark.parametrize("arg",[1,2,3])
def test_1(arg):
    db_conn.insert(arg)
    process(arg)

@pytest.mark.parametrize("arg",["a","b","c"])
def test_2(arg):
    db_conn.insert(arg)
    process(arg)

【问题讨论】:

  • def test_1(arg) -> def test_1(conn, arg)pytest 将为测试签名中未明确参数化的每个参数寻找一个夹具。 (有一些边缘情况,如关键字 args 或 mock.patch 返回,但它们与您的情况无关)。

标签: pytest fixtures


【解决方案1】:

是否尝试将 conn 固定装置作为测试参数传递?

import pytest

@pytest.fixture(scope="module")
def conn():
    db_conn = get_db_conn()
    yield db_conn
    db_conn.close()


@pytest.mark.parametrize("arg",[1,2,3])
def test_1(arg, conn):
    conn.insert(arg)
    process(arg)

@pytest.mark.parametrize("arg",["a","b","c"])
def test_2(arg, conn):
    conn.insert(arg)
    process(arg)

这个简单的模拟 (test_fixture_params.py) 应该演示用法:

import pytest


@pytest.fixture(scope="module")
def conn():
    print('Opening db connection')
    yield 'MY DB CONNECTION'
    print('Closing db connection')


@pytest.mark.parametrize("arg",[1,2,3])
def test_1(arg, conn):
    print(conn, arg)


@pytest.mark.parametrize("arg",["a","b","c"])
def test_2(arg, conn):
    print(conn, arg)

对于pytest -s test_fixture_params.py,输出应为:

$ pytest -s test_fixture_params.py 
===================================================== test session starts =====================================================
platform linux -- Python 3.8.1, pytest-5.4.3, py-1.8.1, pluggy-0.13.1
collected 6 items                                                                                                             

test_fixture_params.py Opening db connection
MY DB CONNECTION 1
.MY DB CONNECTION 2
.MY DB CONNECTION 3
.MY DB CONNECTION a
.MY DB CONNECTION b
.MY DB CONNECTION c
.Closing db connection


====================================================== 6 passed in 0.03s ======================================================

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多