我刚开始使用django测试,所以我仍然试图绕过它。
我有两个型号。让我们说Topic
和SubTopic
class Topic(models.Model):
name = models.CharField(max_length=1, unique=True)
class SubTopic(models.Model):
topic = ForeignKey(Topic)
name = models.CharField(max_length=1)
我想设置一个测试用例来检查是否:
topic: 1
subtopic:a (pk=1)
subtopic:b (pk=2)
subtopic:c (pk=3)
topic: 2
subtopic:a (pk=4)
subtopic:b (pk=5)
subtopic:c (pk=6)
但不可能:
topic: 1
subtopic:a (pk=1)
subtopic:a (pk=2)
subtopic:c (pk=3)
我猜怎么做:
def test_subtopics_cant_have_same_name(self):
topic_1 = Topic.objects.create(name='1')
suptopic_name = 'a'
subtopic_1 = SubTopic.objects.create(name=subtopic_name)
subtopic_2 = SubTopic.objects.create(name=subtopic_name)
subtopics = [ topic.name for topic in topic.subtopic_set.all()]
self.assertEqual(subtopics.count(subtopic_name),1)
这是正确的方法吗?
奖金问题
我对解决这个问题的逻辑的猜测是这样的:
class SubTopic(models.Model):
topic = ForeignKey(Topic)
name = models.CharField(max_length=1)
def save(*args, **kwargs):
subtopics = [ topic.name for topic in topic.subtopic_set.all()]
if name in subtopics:
raise IntegrityError('subtopic not unique for this topic')
else:
super(SubTopic, self).save(*args, **kwargs)
但我不确定是否有更好的方法..?因为检查现在测试失败了。 (保存subtopic_2时失败)
答案 0 :(得分:8)
您可以使用assertRaises
并抓住IntegrityError
:
class MyTestCase(TestCase):
def test_regular(self):
topic_1 = Topic.objects.create(name='1')
topic_2 = Topic.objects.create(name='2')
for subtopic_name in ['a', 'b', 'c']:
SubTopic.objects.create(name=subtopic_name, topic=topic_1)
SubTopic.objects.create(name=subtopic_name, topic=topic_2)
subtopics_1 = [topic.name for topic in topic_1.subtopic_set.all()]
subtopics_2 = [topic.name for topic in topic_2.subtopic_set.all()]
self.assertEqual(subtopics_1, subtopics_2, ['a', 'b', 'c'])
def test_uniqueness(self):
topic_1 = Topic.objects.create(name='1')
SubTopic.objects.create(name='a', topic=topic_1)
with self.assertRaises(IntegrityError):
SubTopic.objects.create(name='a', topic=topic_1)
test_uniqueness
测试将失败,直到您设置unique_together
:
class SubTopic(models.Model):
topic = ForeignKey(Topic)
name = models.CharField(max_length=1)
class Meta:
unique_together = ('topic', 'name')