django - 命令行中的Django测试错误:匹配的查询不存在
问题描述
这是我的tests.py
文件:
from django.test import TestCase
from .models import *
from django.contrib.auth.models import User
class ArticleTestCase(TestCase):
@classmethod
def setup(self):
Article.objects.create(
article_title="title1",
article_content="content of article",
)
def test_article_title(self):
a1 = Article.objects.get(pk=1)
article_name = a1.article_title
self.assertEquals(article_name, 'title1')
但是,我总是收到这个错误:
Traceback (most recent call last):
File "F:\Django_Blog_Live\swagato_blog_site\blog_api\tests.py", line 16, in test_article_title
a1 = Article.objects.get(pk=1)
File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "F:\Django_Blog_Live\env\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
blog_api.models.Article.DoesNotExist: Article matching query does not exist.
并且错误描述指向这个语句:a1 = Article.objects.get(pk=1)
我究竟做错了什么?
解决方案
setup
不是该方法的正确名称。正确的名称是setUp
(注意大写U
)。它不是一个classmethod
.
还有另setUpClass
一种方法称为classmethod
.
两者之间的区别在于setUp
在每个测试方法之前运行,而setUpClass
对整个测试用例运行一次。
用法:
使用setUp
方法很简单:
class ArticleTestCase(TestCase):
def setUp(self):
# create objects
# ...
在 Django 中,如果你使用setUpClass
,你还需要super
调用父类:
class ArticleTestCase(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass() # call parent
# create objects
# ...
推荐阅读
- php - PHP 使用网络端口连接到 Redis 服务。RedisException:没有这样的文件或目录
- python - Pandas 数据框中的 SQL 查询等价物
- python - 如何避免类的属性错误?
- r - 如何将 (1) Yes 和 (2) No 更改为 0 和 1?
- macos - 将输出传送到另一个延迟命令时如何暂停主命令
- javascript - Typescript - 导入 Express 不起作用
- python - crontab 调用 shell 脚本出现导入错误
- acumatica - 如何更改销售订单页面中选项卡的顺序
- c++ - QML 中的 viewRoot 是什么?
- javascript - Javascript Ajax 上传文件到 Python 后端