tho*_*mad 7 python django unit-testing django-testing pytest
我有许多Django测试,通常使用py.test运行它们.我最近在一个新文件中添加了一个新的测试用例test_selenium.py.这个测试用例使用了LiveServerTestCase和StaticLiveServerTestCase类(这是我的第一个,通常我只是使用TestCase).
在这个新文件中添加这一批新测试导致后续测试在py.test中失败(在它们全部通过之前).LiveServerTestCase在py.test 之后,数据库似乎没有被"重置" .我可以告诉我,因为我的模型的pk值增加了.
当我使用Django测试运行器运行这些测试时,它们都会通过,并在后续测试pk中重置 ; 在py.test测试运行器中pk,在LiveServerTestCase运行后的后续测试中会增加.因此,如果我在我的测试中硬编码创建一个对象并根据pk我期望它失败来检索它,因为Django和py.test之间的数据库是不同的.
任何想法为什么会这样,以及如何解决它?
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class UpdateCountSelenium(StaticLiveServerTestCase):
def setUp(self):
self.selenium = webdriver.Firefox()
self.delay = 3
def tearDown(self):
self.selenium.quit()
def test_ajax_hit(self):
self.selenium.get("%s%s" % (self.live_server_url, '/1/'))
# waits for javascript to load and tests the ajax view
wait = WebDriverWait(self.selenium, 3)
response = wait.until(EC.text_to_be_present_in_element((By.ID, 'counted-value'), 'true'))
self.assertTrue(response)
Run Code Online (Sandbox Code Playgroud)
A LiveServerTestCase和它的子类StaticLiveServerTestCase都继承自TransactionTestCase它,而TestCase在测试用例上重置数据库的方式与TestCase不同tearDown。以下是上述文档中的报价:
Django的TestCase类(如下所述)利用数据库事务处理工具来加快在每次测试开始时将数据库重置为已知状态的过程。但是,这样做的结果是,某些数据库行为无法在Django TestCase类中进行测试。例如,您不能测试使用事务select_for_update()时所需的代码块是否在事务中正在执行。在这种情况下,应使用TransactionTestCase。
TransactionTestCase和TestCase相同,除了将数据库重置为已知状态的方式以及测试代码测试提交和回滚的效果的能力之外:
一个TransactionTestCase测试通过截取所有表运行后重置数据库。一个TransactionTestCase可以调用commit和回滚并观察数据库这些调用的影响。
一个TestCase的,而另一方面,不测试后截断表。相反,它将测试代码包含在数据库事务中,该事务在测试结束时会回滚。这样可以保证测试结束时的回滚将数据库还原到其初始状态。
如您所述,您会看到保留了PK计数器。这是因为截断表意味着删除所有行,但这通常并不意味着PK计数器被重置。
我认为您对此很在意,因为您通过指定PK使用断言对象(例如assert YourModel.objects.filter(pk=1).exists()。
相反,我建议您在测试中声明X对象的存在(例如assert YourModel.objects.count() == 1,甚至声明您希望存在的特定对象),然后像往常一样在测试中使用这些对象。
| 归档时间: |
|
| 查看次数: |
1612 次 |
| 最近记录: |