在Django shell中:
from django.test import SimpleTestCase
c = SimpleTestCase()
haystack = '<html><b>contribution</b></html>'
c.assertInHTML('<b>contribution</b>', haystack)
c.assertInHTML('contribution', haystack)
我不明白为什么第一个断言通过了,但第二个断言没有通过:
AssertionError Traceback (most recent call last)
<ipython-input-15-20da22474686> in <module>()
5
6 c.assertInHTML('<b>contribution</b>', haystack)
----> 7 c.assertInHTML('contribution', haystack)
c:...libsite-packagesdjangotesttestcases.py in assertInHTML(self, needle, haystack, count, msg_prefix)
680 else:
681 self.assertTrue(real_count != 0,
--> 682 msg_prefix + "Couldn't find '%s' in response" % needle)
683
684 def assertJSONEqual(self, raw, expected_data, msg=None):
C:...ProgramsPythonPython35-32libunittestcase.py in assertTrue(self, expr, msg)
675 if not expr:
676 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
--> 677 raise self.failureException(msg)
678
679 def _formatMessage(self, msg, standardMsg):
AssertionError: False is not true : Couldn't find 'contribution' in response
Django文档只是说"传入的参数必须是有效的HTML。"我不认为这是问题所在,因为第一行对assert_and_parse_html
的调用不会引发:
def assertInHTML(self, needle, haystack, count=None, msg_prefix=''):
needle = assert_and_parse_html(self, needle, None,
'First argument is not valid HTML:')
haystack = assert_and_parse_html(self, haystack, None,
'Second argument is not valid HTML:')
real_count = haystack.count(needle)
if count is not None:
self.assertEqual(real_count, count,
msg_prefix + "Found %d instances of '%s' in response"
" (expected %d)" % (real_count, needle, count))
else:
self.assertTrue(real_count != 0,
msg_prefix + "Couldn't find '%s' in response" % needle)
我使用的是Python 3.5.1和Django 1.8.8。
这是Django中的一个错误:
assertInHTML(needle, haystack)
具有以下行为
assertInHTML('<p>a</p>', '<div><p>a</p><p>b</p></div>')
通过:明确纠正
assertInHTML('<p>a</p><p>b</p>', '<p>a</p><p>b</p>')
通过:可能纠正
assertInHTML('<p>a</p><p>b</p>', '<div><p>a</p><p>b</p></div>')
因断言错误而失败。
当针头没有包裹其他所有东西的唯一根部元素时,就会出现问题。
建议的解决方案(已经搁置了一段时间!(是,如果你试图这样做,就会引发一个异常,即指针必须有一个HTML标记,它将所有内容都包裹在里面。