1024programmer Java How to test DjangoCreateView?

How to test DjangoCreateView?

I want to practice testing on Django and have a CreateView to test. The view allows me to create a new post and I want to check if it can find posts without a publish date, but first I want to test posts with a publish date to get used to the syntax. This is what I have:

import datetime
 from django.test import TestCase
 from django.utils import timezone
 from django.urls import reverse
 from .models import Post, Comment

 # Create your tests here.
 class PostListViewTest(TestCase):

     def test_published_post(self):
         post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date'  :timezone.now()})
         respOnse= self.client.get(reverse('blog:post_detail'))
         self.assertContains(response, "really important")
 

But I get this:

django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no
 arguments not found. 1 pattern(s) tried: ['post/(?P\\d+)/$']
 

How to get the pk of this newly created post?

Thank you!

1> Daniel Rosem..:


You can get it directly from the database.

Please note that you should not call both views in your test. Each test should only call the code it actually tests, so this should be two separate views: one that calls to create the view and asserts that the entry is in the database, and one that directly creates an entry and then calls the details view to check if it show. So:

def test_published_post(self):
     self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone  .now()})
     self.assertEqual(Post.objects.last().title, "Super Important Test")

 def test_display_post(self):
     post = Post.objects.create(...whatever...)
     respOnse= self.client.get(reverse('blog:post_detail', pk=post.pk))
     self.assertContains(response, "really important")
 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/771090

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索