1
我对Django相当陌生,并且已经完成了一些测试驱动开发。我尝试遵守TDD的原则,但是有一些我不知道如何进行的背景(如下面的模型)。我有一个与我在这里展示的非常相似的模型。基本上,这个想法是构建一本书。有时候这本书由章节组成,其他时候这本书包含章节和其他书籍。所以,我的问题真的是试图进行测试,直到我得到一个类似于下面的具有相同功能的模型。我已经在我的python shell中测试了这个模型,并且输出了我期望的结果,但是我希望更强大一些。 我也希望能够在我的项目的核心中使用这个模型,并且需要能够在我继续建立顶层时对其进行测试。测试这种模型的一些很好的示例单元测试是什么?或者在何处寻找可以与ContentType和其他抽象模型一起使用的测试的建议?谢谢!在Django中进行内容类型模型的单元测试
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
class Element(models.Model):
title = models.TextField()
class Meta:
abstract = True
class Chapter(Element):
body = models.TextField()
def __unicode__(self):
return self.body
class Book(Element):
description = models.TextField()
def __unicode__(self):
return self.description
class BookElement(models.Model):
protocol_id = models.PositiveIntegerField()
element_content_type = models.ForeignKey(ContentType)
element_id = models.PositiveIntegerField()
element = generic.GenericForeignKey('element_content_type', 'element_id')
# Sort order, heavy things sink.
element_weight = models.PositiveIntegerField()
def __unicode__(self):
return u'%s %s' % (self.protocol_id, self.element , self.element_weight)
更新 下面是测试我制定了进入元素融入到数据库和检索它们。它的工作原理,但似乎漫长的测试不止一件事。如果有更好的方法,我愿意接受建议。
class BookAndChapterModelTest(TestCase):
def test_saving_and_retrieving_book_elements(self):
# input data objects and save
book = Book()
book.title = "First book"
book.description = "Testing, round one"
book.save()
first_chapter = Chapter()
first_chapter.title = 'step 1'
first_chapter.body ='This is step 1'
first_chapter.save()
second_chapter = Chapter()
second_chapter.title = 'step 2'
second_chapter.body = 'This is step 2'
second_chapter.save()
# link content types to chapter or book model
chapter_ct = ContentType.objects.get_for_model(first_chapter)
book_ct = ContentType.objects.get_for_model(book)
# Assemble BookElement order by weight of chapter or book
BookElement.objects.create(
book_id=book.pk,
element_content_type=chapter_ct,
element_id=first_chapter.pk,
element_weight='1')
BookElement.objects.create(
book_id=book.pk,
element_content_type=chapter_ct,
element_id=second_chapter.pk,
element_weight='2')
BookElement.objects.create(
book_id=book.pk,
element_content_type=book_ct,
element_id=book.pk,
element_weight='3')
# Test number of elements
saved_book_element = BookElement.objects.all()
self.assertEqual(saved_book_element.count(), 3)
# Test elements are in the proper position based on weighting
first_book_element = saved_book_element[0]
self.assertEqual(str(first_book_element), 'This is step 1')
third_book_element = saved_book_element[2]
self.assertEqual(str(third_book_element), "Testing, round one")
我从来没有使用工厂男孩。你能详细阐述一下如何整合它? – user3597703 2014-10-02 19:22:37