pytest 参数化方法设置 [英] pytest parameterized method setup

查看:88
本文介绍了pytest 参数化方法设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个参数化的 pytest 测试方法,test_1.在为此测试方法运行所有参数化案例之前,我想调用另一个方法 tmp_db_uri,它创建一个临时数据库并生成数据库的 uri.我只想调用该生成器一次,以便我可以对所有测试用例使用相同的临时数据库.我想,如果我从夹具 (db_uri) 调用它,那就可以了,因为我认为每个测试都会创建一次夹具,但似乎每个案例都会调用夹具在这个测试中,每次都会创建一个新的临时数据库.

I have a parameterized pytest test method, test_1. Before all the parameterized cases are run for this test method, I'd like to call another method, tmp_db_uri, which creates a temporary database and yields the uri for the database. I only want to call that generator once, so that I can use the same temporary database for all the test cases. I thought that if I called it from a fixture (db_uri), that would do the trick, since I thought that fixtures are created once per test, but it seems that the fixture is getting called for each case in this test, and a new temporary database is being created each time.

这样做的正确方法是什么?有没有办法在运行所有案例之前运行此方法的设置,只使用一个 tmp_db_uri?我不希望临时数据库挂在整个测试模块中 - 只是在这个测试期间(清理由 tmp_db_uri 上的上下文管理器处理).

What is the correct way to do this? Is there a way to run a setup for this method before all the cases are run, to use just one tmp_db_uri? I don't want the temporary database hanging around for the entire test module - just for the duration of this one test (cleanup is handled by a context manager on tmp_db_uri).

我目前有类似的东西:

@pytest.fixture
def db_uri(tmp_db_uri):
    return tmp_db_uri

@pytest.mark.parameterize(("item1","item2"), ((1, "a"), (2, "b")))
def test_1(item1, item2, db_uri):
    print("do something")

推荐答案

你可以创建一个模块级的fixture,这样它只为整个测试模块创建一次,或者你可以创建一个全局变量并返回db,如果是的话已经创建或以其他方式创建.

You can create a module level fixture ,so that it's created only once for the entire test module or you can create a global variable and return the db if it is already created or create otherwise.

@pytest.fixture(scope="module")
def db_uri(tmp_db_uri):
    return tmp_db_uri

TMP_DB = None
@pytest.fixture
def db_uri(tmp_db_uri):
    global TMP_DB
    if not TMP_DB:
        # do your stuff to create tmp_db 
        TMP_DB = tmp_db_uri
    return TMP_DB

这篇关于pytest 参数化方法设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆