擅长:python、mysql、java
<p>将<code>autocommit = transaction.set_autocommit(False)</code>放在<code>send</code>函数内感觉不对。禁用事务可能是出于测试目的而在这里完成的,但经验法则是将测试逻辑保持在代码之外。在</p>
<p>正如@Alasdair指出的,<a href="https://docs.djangoproject.com/en/1.9/topics/db/transactions/#django-s-default-transaction-behavior" rel="nofollow">django docs</a>声明“出于性能原因,Django的TestCase类也将每个测试封装在事务中。”</p>
<p>从您的问题中不清楚您是否在测试特定的数据库事务逻辑,如果是这样,那么@Alasdair使用<code>TransactionTestCase</code>的答案就是正确的方法。在</p>
<p>否则,从<code>send</code>函数内的<code>stuff</code>周围删除事务上下文开关应该会有所帮助。在</p>
<p>既然您提到<code>pytest</code>作为您的测试运行程序,我也建议您使用pytest。pytestdjango插件具有一些很好的特性,比如使用<a href="http://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-transaction-false-request-database-access" rel="nofollow">markers</a>,有选择地将一些测试设置为需要事务。在</p>
<pre><code>pytest.mark.django_db(transaction=False)
</code></pre>
<p>如果安装一个插件太多了,那么您可以使用自己的<code>transaction manage</code>fixture。像</p>
^{pr2}$
<p>您的<code>test_send</code>将需要<code>no_transaction</code>夹具。在</p>
<pre><code>def test_send(no_transaction):
send()
</code></pre>