gpt4 book ai didi

python - Django 转换为 CBV + 测试

转载 作者:行者123 更新时间:2023-11-28 21:16:00 25 4
gpt4 key购买 nike

我正在尝试测试我的应用。我查看了文档,并设法对我的 URL 和除一个 View 之外的所有 View 进行了测试。

我在将它转换为类 View 时遇到问题,我不确定我应该在这里进行哪种测试?文档解释了它是如何工作的,但我现在不知道从这里去哪里..

有人介意帮帮我吗?

这是我正在尝试转换和测试的 View :

def add_comment_to_article(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk}))
else:
form = CommentForm()
return render(request, 'news/add_comment_to_article.html', {'form': form})


我的网址:

app_name = "news"
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:article_id>/', views.article_view, name='article'),
path('articles/', views.ArticlesView.as_view(), name='articles'),
path('search/', include('haystack.urls',)),
path('<int:pk>/comment/', views.CommentCreateView.as_view(), name='add_comment_to_article'),
#path('articles/<int:category_id>', views.CategoryView.as_view(), name="category")
]

我的表单:

class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)

View 负责向我的文章帖子添加评论。谢谢!!

最佳答案

假设您的 CommentForm 中没有 post 字段,我可能会这样做:

# views.py
from django.views.generic import CreateView

from .models import Comment


class CommentCreateView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'my_template.html'

def form_valid(self, *args, **kwargs):
article = get_object_or_404(Article, pk=kwargs.get('pk'))
comment = form.save(commit=False)
comment.post = article
comment.save()
return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk}))

# tests.py

from django.tests import TestCase


class CreateCommentViewTestCase(TestCase):

def setUp(self):
# maybe look into factory boy if you haven't already
self.article = Article.objects.create()

def test_get(self):
response = self.client.get(reverse('news:add_comment_to_article', kwargs={'article_id': self.article.pk}))
self.assertEqual(response.status_code, 200)

def test_post(self):
# populate with form data
post_data = {'form_field': 'value'}
original_comment_count = self.article.comment_set.all().count()
response = self.client.post(reverse('news:add_comment_to_article', kwargs={'article_id': self.article.pk}))
new_comment_count = self.article.comment_set.all().count()
self.assertNotEqual(original_comment_count, new_comment_count)
self.assertEqual(response.status_code, 302)

django-webtest 对于测试 CBV 也非常有用。

关于python - Django 转换为 CBV + 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154023/

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