Django什么时候使用拆机方法

时间:2012-02-27 01:34:53

标签: django

根据文件:

  

另一方面,TestCase不会截断表并重新加载   测试开始时的初始数据。相反,它包含了测试   在数据库事务结束时回滚的数据库事务中的代码   测试。它还可以防止被测代码发出任何提交或   对数据库进行回滚操作,确保回滚到   测试结束将数据库恢复到其初始状态。在   为了保证所有TestCase代码都以干净的方式启动   数据库,Django测试运行器首先运行所有TestCase测试   任何其他可能在没有的情况下改变数据库的测试(例如doctests)   将其恢复到原始状态。

所以,如果我有一个看起来像这样的测试:

class GeneralUserCreateTest(TestCase):

    def setUp(self):
        create_roletypes()
        create_permissiontypes()
        self.client = Client()
        self.event = create_event()

    def test_create(self):
        create_url = reverse('event_user_signup', args=[self.event.slug])

        post_data = {
            'signup-account-email': 'foo@bar.com',
            'signup-account-password': 'foobar',
            'signup-account-password2': 'foobar',
            'signup-account-first_name': 'Foo',
            'signup-account-last_name': 'Bar',
        }
        response = self.client.post(create_url, data=post_data)
        self.assertEqual(response.status_code, 302)

        # check creation of user object
        self.assertEqual(User.objects.filter(email=post_data['signup-account-email']).count(), 1)
        user = User.objects.get(username=post_data['signup-account-email'])

        # user and profile objects created
        self.assertEqual(User.objects.all().count(), 1)
        self.assertEqual(Profile.objects.all().count(), 1)

        # get the first user and profile object to test against submitted field
        user = User.objects.all()[0]
        profile = Profile.objects.all()[0]
        role = Role.objects.filter(event=self.event, profiles=profile)[0]
        self.assertEqual(role.roletype.name, 'General')
        self.assertEqual(user.username, post_data['signup-account-email'])
        self.assertEqual(user.email, post_data['signup-account-email'])
        self.assertEqual(profile.first_name, post_data['signup-account-first_name'])
        self.assertEqual(profile.last_name, post_data['signup-account-last_name'])

是否仍然需要运行teardown方法或TestCase课程是否需要处理?如果是这样的话,应该在teardown类的可用性的情况下何时使用TestCase方法?

3 个答案:

答案 0 :(得分:26)

出于数据库的目的,tearDown毫无意义,因为每个测试都在事务中运行。但是,并非测试中的所有内容都涉及数据库。您可以测试文件创建/读取,分离进程,打开网络连接等。这些类型的事情通常要求您在完成后“关闭”它们。这就是tearDown的用途,即清除setUp方法中与数据库无关的内容。 (但是,如果您实际上直接连接到数据库,即实际的Django测试必须确保所有DBAPI工作正常,您也需要在那里进行清理。)

答案 1 :(得分:10)

我正在处理一个处理一些文件上传的项目,我需要删除测试创建的文件,tearDown方法在这种情况下非常有用。

import shutil

#....
#....

    def tearDown(self):
        shutil.rmtree(settings.UPLOAD_ROOT)

答案 2 :(得分:5)

如果您使用的是MongoDB或Redis等备用数据库,并且需要加载一组初始数据(“集合”),则还需要覆盖tearDown方法。

请参阅http://www.belchak.com/2011/02/07/unit-testing-django-with-a-nosql-backend/

通常,django.test.TestCase在每个开头都会执行完整的数据库刷新 新的考验。这意味着我们不需要像Chris Pratt上面提到的那样在我们的tearDown中手动删除对象。下一个测试setUp将确保数据库是干净的。

但是,如果我们使用doctests和unittest.TestCase,则在再次运行测试之前不会有数据库刷新。在测试开始时,数据库将处于前一个状态 测试左。这意味着前一次运行留下的任何杂散数据都会导致冲突。因此,如果我们使用doctests或unittest.TestCase进行django测试,清理可能是一种很好的做法。

最后,在更复杂的场景中,故意坚持测试数据库来查找特定的单元测试错误也是有意义的。