在 django 单元测试中使用用户模型的问题
我有以下 django 测试用例,它给了我错误:
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
启动之前,我收到以下错误:
IntegrityError: column username is not unique
很明显它试图在每个测试用例之前创建 self.u1 并发现它已经存在于数据库中。如何在每个测试用例之后正确清理它,以便后续用例正确运行?
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):
...
When I run my tests, testA
will pass sucessfully but before testB
starts, I get the following error:
IntegrityError: column username is not unique
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
setUp
和tearDown
调用 Unittest 上的方法每个测试用例之前和之后。定义tearDown
方法删除创建的用户。我还建议创建用户配置文件 使用
post_save
信号,除非您确实想为每个用户手动创建用户配置文件。删除评论的后续:
来自 Django 文档:
在您的情况下,用户配置文件指向用户,因此您应该先删除用户,同时删除配置文件。
setUp
andtearDown
methods on Unittests are called before and after each test case. DefinetearDown
method which deletes the created user.I would also advise to create user profiles using
post_save
signal unless you really want to create user profile manually for each user.Follow-up on delete comment:
From Django docs:
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 在每次测试运行后自动刷新测试数据库,那么您应该扩展 django.test.TestCase,而不是 django.utils.unittest.TestCase (因为您目前正在做)。
最好在每次测试后转储数据库,这样您就可以额外确保测试是一致的,但请注意,由于这种额外的开销,您的测试将运行得更慢。
请参阅“编写测试”Django 文档中的警告部分。
If you want django to automatically flush the test database after each test is run then you should extend
django.test.TestCase
, NOTdjango.utils.unittest.TestCase
(as you are doing currently).It's good practice to dump the database after each test so you can be extra-sure you're tests are consistent, but note that your tests will run slower with this additional overhead.
See the WARNING section in the "Writing Tests" Django Docs.
准确地说,
setUp
的存在就是为了在每个测试用例之前运行一次。相反的方法,即在每个测试用例之后运行一次的方法,名为
tearDown
:这是您删除self.u1
等的地方(大概是通过只需调用 self.u1.delete(),除非除了删除对象之外还有补充的专门清理要求)。Precisely,
setUp
exists for the very purpose of running once before each test case.The converse method, the one that runs once after each test case, is named
tearDown
: that's where you deleteself.u1
etc (presumably by just callingself.u1.delete()
, unless you have supplementary specialized clean-up requirements in addition to just deleting the object).