Skip to main content
 首页 » 编程设计

python之pytest-django 将固定装置添加到 live_server 固定装置

2024年12月31日20dflying

我需要向 pytest-django 提供的 live_server fixture 添加 fixture,特别是覆盖 django_db_setup。

话虽这么说,但我知道对未清除干净的数据库运行测试并不理想,但这正是我正在使用的。

在我们的普通测试套件中,我们使用覆盖 django_db_setup 来在我们的 conftest.py 文件中执行任何操作,如下所示

@pytest.fixture(scope="session") 
def django_db_setup(): 
    pass 

看来,当我使用 pytest-django 提供的 live_server fixture 时,它不会接受这一点,因为它会在测试结束时尝试刷新数据库。如何规避这一点?我找到了如下所示的结束,但如果有更好的解决方案,我想避免它。

@pytest.fixture(scope='session') 
def my_live_server(request): 
    request.getfixturevalue('django_db_setup') 
    return live_server(request) 

请您参考如下方法:

It appears that when I use the live_server fixture provided by pytest-django it does not honor this as it attempts to flush the db at the end of the tests.

你完全正确;在测试中使用 live-server fixture 将静默触发事务行为(就像您将 transactional_db fixture 传递给测试一样)。 AFAIK 这不能通过配置关闭(如果证明是错误的,我会很高兴);必须弄乱 pytest-django 的内部结构。在您的 conftest.py 中:

# conftest.py 
 
import pytest 
 
@pytest.fixture(scope="session") 
def django_db_setup(): 
    pass 
 
@pytest.fixture(autouse=True, scope='function') 
def _live_server_helper(request): 
    if 'live_server' not in request.funcargnames: 
        return 
 
    request.getfixturevalue('django_db_setup') 
 
    live_server = request.getfixturevalue('live_server') 
    live_server._live_server_modified_settings.enable() 
    request.addfinalizer(live_server._live_server_modified_settings.disable) 

当然,这不是一个很好的解决方案,但它可以解决问题。您至少可以通过引入自定义标记来“减轻可能的损害”,以便修补的助手仅应用于标记的测试:

@pytest.fixture(autouse=True, scope='function') 
def _live_server_helper(request): 
    markers = [marker.name for marker in request.node.iter_markers()] 
    if 'live_server_no_flush' not in markers: 
        request.getfixturevalue('_live_server_helper') 
        return 
 
    # rest of code same as above 
    if 'live_server' not in request.funcargnames: 
        return 
 
    request.getfixturevalue('django_db_setup') 
 
    live_server = request.getfixturevalue('live_server') 
    live_server._live_server_modified_settings.enable() 
    request.addfinalizer(live_server._live_server_modified_settings.disable) 

现在新行为仅适用于标记为 live_server_no_flush 的测试:

@pytest.mark.live_server_no_flush 
def test_spam(live_server): 
    ...