【问题标题】:How to test a Django on_commit hook without clearing the database?如何在不清除数据库的情况下测试 Django on_commit 钩子?
【发布时间】:2017-03-03 17:38:03
【问题描述】:

on_commit 函数已添加到 Django 1.9,以便能够在当前事务提交后触发操作(例如 Celery 任务)。

他们稍后提到in the docs 应该使用TransactionTestCase 来测试依赖该功能的功能。但是,与TestCase(使用事务并将它们回滚)不同,TransactionTestCase 在每次测试后都会清空整个数据库。

不幸的是,我的数据迁移会在数据库中预加载一些有用的数据,这意味着在第一次测试清除数据库后后续测试将不再工作。

我最终通过嘲笑 on_commit 采取了一个肮脏的伎俩:

with mock.patch.object(django.db.transaction, 'on_commit', lambda t: t()):
    test_something()

有没有更好的办法?

【问题讨论】:

  • 其实你的解决方法还不错。而且我不想使用TransactionTestCase,因为它对我的用例来说很慢(大setUps 和很多固定装置。)
  • 我真的很喜欢这种解决方法——在某些情况下由于某种原因我还没有探索过,但它绝对比我的要好(一个 exec_on_commit() 函数,它执行任何应该执行的操作提交时)。

标签: python django testing transactions


【解决方案1】:

继续使用 TestCase 和假提交,强制执行 run_and_clear_commit_hooks 中的延迟操作。 查看这篇文章:

https://medium.com/gitux/speed-up-django-transaction-hooks-tests-6de4a558ef96

【讨论】:

  • 这是一个有趣的 hack,因此得到了支持,但我会警惕使用内部 Django 方法,以免在升级时遇到问题......
  • 这似乎不适用于 Django 2.2.1:File "venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 438, in validate_no_broken_transaction"An error occurred in the current transaction. You can't "django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
【解决方案2】:

从 3.2 版开始,Django 有一个内置的方法来测试 on_comit 钩子。 示例:

from django.core import mail
from django.test import TestCase


class ContactTests(TestCase):
    def test_post(self):
        with self.captureOnCommitCallbacks(execute=True) as callbacks:
            response = self.client.post(
                '/contact/',
                {'message': 'I like your site'},
            )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(callbacks), 1)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'Contact Form')
        self.assertEqual(mail.outbox[0].body, 'I like your site')

这里是官方文档:https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.TestCase.captureOnCommitCallbacks

【讨论】:

  • 很好,谢谢!我将更改已接受的答案,因为这比原来的答案要新得多;)
【解决方案3】:

我想到了两种可能性:

  1. 正如this 部分所说的post_migrate 在刷新后发出,因此您可以执行预加载一些有用的数据
  2. 您可以继承TransactionTestCase 并实现您的_fixture_teardown(您可以看到在方法的最后调用了flush)。

如果您的迁移成本不是太高,我可能会坚持使用第一个,如果迁移成本太高,我可能会坚持使用第二个。

【讨论】:

  • 使用post_migrate 信号是个好主意。我会看看我是否可以将我们的数据迁移转换为这个,因为它听起来整体上更干净!
【解决方案4】:

亚当约翰逊写了这个,我认为这里引用的代码可以解决问题:

https://adamj.eu/tech/2020/05/20/the-fast-way-to-test-django-transaction-on-commit-callbacks/

@contextmanager
    def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False):
        """Context manager to capture transaction.on_commit() callbacks."""
        callbacks = []
        start_count = len(connections[using].run_on_commit)
        try:
            yield callbacks
        finally:
            run_on_commit = connections[using].run_on_commit[start_count:]
            callbacks[:] = [func for sids, func in run_on_commit]
            if execute:
                for callback in callbacks:
                    callback()

用法:

class ContactTests(TestCase):
            def test_post(self):
                with self.captureOnCommitCallbacks(execute=True) as callbacks:
                    response = self.client.post(
                        '/contact/',
                        {'message': 'I like your site'},
                    )

                self.assertEqual(response.status_code, 200)
                self.assertEqual(len(callbacks), 1)

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2015-07-08
    相关资源
    最近更新 更多