免责声明:我是Django的新手并且正在测试
我在Django管理员中有一些模型,但我正在覆盖特定模型的save_model()函数。我无法测试Model.create(),因为未调用admin save_model()覆盖。测试此功能的正确方法是什么?任何示例代码都非常赞赏:)这是我的:
models.py
class Page(models.Model):
title = models.CharField(max_length=100)
content = models.CharField(max_length=50000)
path = models.CharField(max_length=300, unique=True,
help_text='Leave this blank to automatically generate a path.',
blank=True
)
pub_date = models.DateTimeField('publication date', default=timezone.now)
def __str__(self):
return self.title
admin.py
class NavigationInline(admin.StackedInline):
model = Navigation
class PageForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 120,
'rows': 20})
)
class Meta:
fields = ('title', 'pub_date')
model = Page
class PageAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['title', 'content', 'path']}),
('Scheduling', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
form = PageForm
inlines = [NavigationInline]
def save_model(self, request, obj, form, change):
obj.save()
# All kinds of craziness to be tested!
答案 0 :(得分:2)
最后我使用了django客户端。我最初没有这样做,因为我遇到了'管理形式数据丢失或被篡改'错误的问题,我最终检查发布到表单的数据,意识到我没有发布所需的'TOTAL -FORMS的价值观。一旦我添加了这些,客户端测试工作正常:
class ModelAdminTests(TestCase):
def create_page(self, title, content, parent_page_id=''):
self.client = Client()
self.client.login(username='admin', password='Password123')
self.client.post(
'/admin/pages/page/add/',
{
'title': title,
'content': content,
'pub_date_0': '2017-01-01',
'pub_date_1': '12:00:00',
'navigation-0-title': 'Home',
'navigation-0-weight': 0,
'navigation-0-parent': parent_page_id,
'navigation-TOTAL_FORMS': '1',
'navigation-INITIAL_FORMS': '0',
'navigation-MAX_NUM_FORMS': '1',
},
follow=True,
)
self.client.logout()
def setUp(self):
User.objects.create_superuser('admin', 'admin@example.com', 'Password123')
def test_route_created_with_page(self):
"""
When a page is created, a route should always be created also.
"""
page_title = 'Test'
page_content = 'This is the test page.'
self.create_page(
title=page_title,
content=page_content,
)
route = Route.objects.filter(pk=1).exists()
self.assertTrue(route)