python - Django 测试失败,posts.models.Post.DoesNotExist:后匹配查询不存在
问题描述
我有这些文件:
模型.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
测试.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...')
当我运行时,python manage.py test
我收到此错误:
$ 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'...
我已经仔细检查过,在我的代码中看不到任何错误。我有什么不对吗?
解决方案
正如@Robin Zigmond 指出的那样,我有一个错字。setUpTestDate
应该是setUpTestData
。
推荐阅读
- c# - 使用 xunit 在 .NET Core 集成测试中获取数据库连接字符串
- javascript - Amazon chrome 扩展事件未触发
- c - 是否可以在C中提取char指针数组的大小
- windows - 让 dll 从其调用 .exe 导入符号
- android - 如何在 Retrofit 2 中解析下面的 json?
- python - 使用python查找由空格分隔的字符串中存在的数字的总和
- dart - 有没有办法找到对象的范围?
- javascript - document.getElementsByClassName 给我未定义的值
- ios - Xcode 10 GM 中的未知类和 NSUnknownKeyException
- ios - Safari 是否控制在 iOS 上的非 Safari 浏览器中读取 cookie 的方式?