I have these files:
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
test.py
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Post
class BlogTests(TestCase):
def setUpTestDate(cls):
# create a user
testuser1 = User.objects.create_user(
username='testuser1', password='abc123')
testuser1.save()
# create a blog post
test_post = Post.objects.create(
author=testuser1, title='Blog title', body='Body content...')
test_post.save()
def test_blog_content(self):
post = Post.objects.get(id=1)
expected_author = f'{post.author}'
expected_title = f'{post.title}'
expected_body = f'{post.body}'
self.assertEqual(expected_author, 'testuser1')
self.assertEqual(expected_title, 'Blog title')
self.assertEqual(expected_body, 'Body content...')
When I run python manage.py test
I get this error:
$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_blog_content (posts.tests.BlogTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/paulcarron/PycharmProjects/blogapi/posts/tests.py", line 20, in test_blog_content
post = Post.objects.get(id=1)
File "/Users/paulcarron/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/paulcarron/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
posts.models.Post.DoesNotExist: Post matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
Destroying test database for alias 'default'...
I've double checked and can't see any mistakes in my code. Is there something I've got wrong?
Aucun commentaire:
Enregistrer un commentaire