Django 断言失败:assertInHTML('hello', '<html>hello</html>')

Django assert failure: assertInHTML('hello', '<html>hello</html>')

在 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:\...\lib\site-packages\django\test\testcases.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:\...\Programs\Python\Python35-32\lib\unittest\case.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 docs 只是说 "The passed-in arguments must be valid 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。

这是一个 bug in Django:

assertInHTML(needle, haystack) has the following behaviour

assertInHTML('<p>a</p>', '<div><p>a</p><p>b</p></div>') passes: clearly correct

assertInHTML('<p>a</p><p>b</p>', '<p>a</p><p>b</p>') passes: possibly correct

assertInHTML('<p>a</p><p>b</p>', '<div><p>a</p><p>b</p></div>') fails with an assertion error.

当 needle 没有包装其他所有内容的唯一根元素时,就会出现问题。

proposed fix(它已经被搁置了一段时间!)是在您尝试这样做时引发异常 - 即,针必须有一个 HTML 标签,将所有内容包裹在里面它。