gpt4 book ai didi

python - 如何为 Django 管理页面的功能编写测试?

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:05 25 4
gpt4 key购买 nike

免责声明:我是 Django 和测试的新手

我在 Django 管理中有一些模型,但我覆盖了特定模型的 save_model() 函数。我无法测试 Model.create() 因为管理 save_model() 覆盖没有被调用。测试此功能的正确方法是什么?任何示例代码将不胜感激 :) 这是我的代码:

模型.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

管理员.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!

最佳答案

最后我用的是django客户端。我最初没有这样做是因为我遇到了“管理表单数据丢失或被篡改”的错误,最后我检查了发布到表单的数据,意识到我没有发布所需的“总计” -FORMS 的值(value)观。添加这些后,客户端测试工作正常:

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)

关于python - 如何为 Django 管理页面的功能编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com