在django单元测试中使用用户模型的问题 [英] Problems using User model in django unit tests

查看:155
本文介绍了在django单元测试中使用用户模型的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下django测试用例给我错误:

I have the following django test case that is giving me errors:

class MyTesting(unittest.TestCase):
    def setUp(self):
        self.u1 = User.objects.create(username='user1')
        self.up1 = UserProfile.objects.create(user=self.u1)

    def testA(self):
        ...

    def testB(self):
        ...

当我运行测试时, testA 将成功传递,但在之前testB 开始,我收到以下错误:

When I run my tests, testA will pass sucessfully but before testB starts, I get the following error:

IntegrityError: column username is not unique

很明显,它正在尝试创建 self.u1 在每个测试用例之前,发现它已经存在于数据库中。在每个测试用例之后,如何正确地清理它,以便以后的情况正常运行?

It's clear that it is trying to create self.u1 before each test case and finding that it already exists in the Database. How do I get it to properly clean up after each test case so that subsequent cases run correctly?

推荐答案

setUp 和< a href =http://docs.python.org/dev/library/unittest.html#unittest.TestCase.tearDown =noreferrer> tearDown tearDown 方法删除创建的用户。

setUp and tearDown methods on Unittests are called before and after each test case. Define tearDown method which deletes the created user.

class MyTesting(unittest.TestCase):
    def setUp(self):
        self.u1 = User.objects.create(username='user1')
        self.up1 = UserProfile.objects.create(user=self.u1)

    def testA(self):
        ...

    def tearDown(self):
        self.up1.delete()
        self.u1.delete()

我也会建议创建用户个人资料,使用 post_save 信号,除非您真的要手动创建用户配置文件对于每个用户。

I would also advise to create user profiles using post_save signal unless you really want to create user profile manually for each user.

后续删除评论:

Django docs


当Django删除对象时,
模拟SQL
约束的行为DELETE CASCADE - 在
其他单词中,任何具有
指向
的对象的外键的对象将被删除
将与
一起删除。

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

在您的情况下,用户个人资料指向用户,因此您应该删除用户首先同时删除个人资料。

In your case, user profile is pointing to user so you should delete the user first to delete the profile at the same time.

这篇关于在django单元测试中使用用户模型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆