Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a Django CreateView?

I want to practice testing on Django, and I have a CreateView I want to test. The view allows me to create a new post and I want to check if it can find posts without a publication date, but first I'm testing posts with published date just to get used to 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<pk>\\d+)/$']

How do I get the pk for that newly created post?

Thank you!

like image 962
ManuAlvarado22 Avatar asked Nov 04 '17 14:11

ManuAlvarado22


1 Answers

You can get it directly from the database.

Note, you shouldn't call two views in your test. Each test should only call the code it is actually testing, so this should be two separate views: one to call the create view and assert that the entry is in the db, and one that creates an entry directly and then calls the detail view to check that it displays. 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")
like image 83
Daniel Roseman Avatar answered Oct 25 '22 06:10

Daniel Roseman