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

Rex*_*exE 6 python django assert

在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)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么第一个断言通过,但第二个断言不通过:

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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 3.5.1和Django 1.8.8.

sol*_*oke 5

这是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标记,包装里面的一切它。