我正在测试上下文变量是否包含字符串
def test_past_question(self):
past_question = create_question(question_text='past question',days=-30)
response = self.client.get(reverse('polls:detail',args=(past_question.id,)))
self.assertQuerysetEqual(response.context['question'],'<Question: past question>')
但是会引发以下错误:
(mysite)sugumar @ mysitedotcom:〜/ python / django / mysite $ python manage.py test polls为别名“ default”创建测试数据库... 系统检查未发现任何问题(0静音)。 .E ........ ================================================== ===================错误:test_past_question(polls.tests.QuestionDetailViewTests) -------------------------------------------------- --------------------追溯(最近一次通话):文件 “ /home/sugumar/python/django/mysite/polls/tests.py”,第73行,在 test_past_question self.assertQuerysetEqual(response.context ['question'],'')文件 “ /home/sugumar/.local/share/virtualenvs/mysite-VWHaFuat/lib/python3.5/site-packages/django/test/testcases.py”, 在assertQuerysetEqual中的第946行 items = map(transform,qs)TypeError:“问题”对象不可迭代
-------------------------------------------------- -----------------------在0.069秒内进行了10次测试
FAILED(错误= 1)正在破坏测试数据库的别名“默认” ...
在命令行中:
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client = Client()
>>> from django.urls import reverse
>>> response = client.get(reverse('polls:detail',args=(1,)))
>>> response.context
[{'True': True, 'False': False, 'None': None}, {'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0xb74425ec>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0xb69feecc>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0xb7440bfc>>, 'csrf_token': <SimpleLazyObject: 'FrAJ52rWG57SSbSE9y4V2tammjvQqjBUyl2tK6aEzj8ZfENSyFl7Fy05bnQh3XyQ'>, 'request': <WSGIRequest: GET '/polls/1/'>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'object': <Question: What's Up?>, 'question': <Question: What's Up?>, 'view': <polls.views.DetailView object at 0xb6a2fd4c>}]
>>> response.context['question']
<Question: What's Up?>
>>> exit
看到它显示的命令,所以我尝试了
self.assertQuerysetEqual(response.context['question'],'<Question: past question>')
答案 0 :(得分:1)
通常,如果变量名是单数('question'
是单数),则表示这很可能不是QuerySet
(或多或少是一个集合),但是一个Question
对象。
此外,对象(如Question
对象)与其文本表示形式(如'<Question ...>'
)之间存在差异。两者不相同。
因此,您应该使用past_question
检查是否相等,例如:
def test_past_question(self):
past_question = create_question(question_text='past question',days=-30)
response = self.client.get(reverse('polls:detail',args=(past_question.id,)))
self.assertEqual(response.context['question'], past_question)