Python单元测试断言错误:unicode字符串不是unicode字符串



我有一个web服务器,它返回包含以下内容的HTML:

<div class="well">
    <blockquote>
        <h2>Blueberry Pancakes Are Bomb</h2>
    </blockquote>
</div>

我写了一个这样的人工功能测试:

def test_page_has_blueberry_in_blockquote(self):
    # User goes to inspire_my_palate page
    self.browser.get('http://localhost:8000/inspire_my_palate')
    # He sees a blockquote with a header containing 'Blueberry ...'
    food_text = self.browser.find_element_by_xpath('//div[@class="well"]/blockquote/h2').text
    self.assertIs(food_text, u'Blueberry Pancakes Are Bomb')

当我运行测试时,我得到了这个错误:

(foodie_env)fatman:foodie$ python functional_tests.py
.F
======================================================================
FAIL: test_page_has_blueberry_in_blockquote (__main__.NewVisitorNavbar)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "functional_tests.py", line 179, in test_page_has_blueberry_in_blockquote
    self.assertIs(food_text, u'Blueberry Pancakes Are Bomb')
AssertionError: u'Blueberry Pancakes Are Bomb' is not u'Blueberry Pancakes Are Bomb'
----------------------------------------------------------------------
Ran 2 tests in 6.656s
FAILED (failures=1)

我也试过:

self.assertIs(food_text, 'Blueberry Pancakes Are Bomb')

是否将字符串转换为unicode似乎不会改变任何内容。我仍然会得到相同的断言错误。

更新:如果我将断言测试更改为:,我将通过测试

self.assertEquals(food_text, u'Blueberry Pancakes Are Bomb')

然而,我仍然想知道assertIs()测试失败的原因。我猜这是由于字符串在内存中的表示方式。直观地说,assertIs()版本应该通过,因为我正在比较两种字符串类型。

断言错误不是很直观,而且令人困惑。是什么导致了这个奇怪的断言错误?

尝试将assertIs检查替换为:

self.assertEqual(food_text, u'Blueberry Pancakes Are Bomb')

为了进一步扩展@TomKarzes的答案,assertIs()正在评估两个对象。在以下代码中,这两个字符串表示为内存中的两个不同对象:

self.assertEqual(food_text, u'Blueberry Pancakes Are Bomb')

因此,这个断言将失败,因为这两个对象的求值结果不相同。

另一方面,assertEquals()正在比较两个字符串的相似性,因此该断言通过。

最新更新