如何在Django中测试关闭数据库连接的方法?

问题描述 投票:4回答:2

我有一个使用Django ORM的长期运行的Python进程。它看起来像这样:

import django
from django.db import connection

from my_app import models


def my_process():
    django.setup()
    while (True):
        do_stuff()
        connection.close()
        models.MyDjangoModel().save()

有时do_stuff需要很长时间,此时我遇到了一个错误,我的MySql连接超时,因为数据库服务器将连接作为空闲终止。添加connection.close()行强制django每次都获得一个新连接并修复该问题。 (见https://code.djangoproject.com/ticket/21597)。

但是,我正在使用django.test.TestCase测试此过程,并且调用connection.close导致这些测试失败,因为django的TestCase类在事务中包装测试,并且在该事务中关闭连接会导致事务中断并引发django.db.transaction.TransactionManagementError

我尝试解决此问题的一种尝试是设置CONN_MAX_AGE数据库参数并调用connection.close_if_unusable_or_obsolete,但事务还将连接的autocommit设置从设置的True的默认值更改为False,这反过来导致close_if_unusable_or_obsolete尝试关闭连接(https://github.com/django/django/blob/master/django/db/backends/base/base.py#L497)。

我想我也可以在测试中嘲笑connection.close,所以它什么都不做,但这看起来有点像hacky。

测试需要关闭数据库连接的django方法的最佳方法是什么?

django django-testing django-database
2个回答
7
投票

好吧,我不确定这是不是最好的答案,但由于这个问题到目前为止还没有回复,我将发布我最终用于后人的解决方案:

我创建了一个辅助函数,在关闭连接之前检查我们当前是否处于原子块中:

import django
from django.db import connection

from my_app import models


def close_connection():
    """Closes the connection if we are not in an atomic block.

    The connection should never be closed if we are in an atomic block, as
    happens when running tests as part of a django TestCase. Otherwise, closing
    the connection is important to avoid a connection time out after long actions.     
    Django does not automatically refresh a connection which has been closed 
    due to idleness (this normally happens in the request start/finish part 
    of a webapp's lifecycle, which this process does not have), so we must
    do it ourselves if the connection goes idle due to stuff taking a really 
    long time.
    """
    if not connection.in_atomic_block:
        connection.close()


def my_process():
    django.setup()
    while (True):
        do_stuff()
        close_connection()
        models.MyDjangoModel().save()

正如评论所述,close_connection阻止connection.close被测试,因此我们不再破坏测试交易。


0
投票

Django有一个TransactionTestCase类,它不会将测试代码包含在数据库事务中,这与TestCase不同。希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.