Django 功能测试:selenium.quit() 不重置数据库?

Django functional test: selenium.quit() doesn't reset database?

class FunctionalTest(LiveServerTestCase):

    def setUp(self):
        print("setUp")
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(3)

    def tearDown(self):
        print("tearDown")
        self.browser.quit()


class MyTest(FunctionalTest):

    def test1(self):
        cart = Cart.objects.create()
        print(cart.id)

    def test2(self):
        cart = Cart.objects.create()
        print(cart.id)

    def test3(self):
        cart = Cart.objects.create()
        print(cart.id)

当我运行考试的时候,

setUp
1
tearDown
.setUp
2
tearDown
.setUp
3
tearDown
.
----------------------------------------------------------------------
Ran 3 tests in 7.024s

我不明白为什么每个测试函数的结果都会影响其他测试函数(cartid

我的预期:

setUp
1
tearDown
.setUp
1
tearDown
.setUp
1
tearDown
.
----------------------------------------------------------------------
Ran 3 tests in 7.024s

这不是这里发生的事情。你们的测试不会互相妨碍。

LiveServerTestcase 是 TransactionTestcase

的子类

A TransactionTestCase resets the database after the test runs by truncating all tables. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

截断表不会重置自动更新计数器。默认情况下,所有 Django 模型都有一个自动递增的主键。

当您执行以下操作时,您只是打印出最近创建的模型的主键,并且该主键一直在增加。

 print(cart.id)

相反,你应该做的是

 self.assertEqual(1,Cart.objects.count())