【问题标题】:Python unittest AssertionError: unicode string is not unicode stringPython unittest AssertionError: unicode string is not unicode string
【发布时间】:2016-03-12 20:12:12
【问题描述】:

我有一个 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() 版本应该通过,因为我正在比较两种字符串类型。

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

【问题讨论】:

  • 是否需要强制第二个参数为unicode?​​span>
  • @dursk 并非如此,问题仍然存在。我都试过了,结果都一样。
  • 你为什么用assertIs而不是assertEqual
  • 我认为 unicode 字符串不能保证为唯一性进行哈希处理,因此您可能应该使用 == 而不是 is 进行比较。基本上你有同一个 unicode 字符串的两个不同的副本,虽然它们是相等的,但它们指的是相同文本的不同副本。
  • 查看unittest doc 并搜索assertIs。基本上它检查a is b,实际上你想要assertEqual,它检查a == b

标签: python python-2.7 unit-testing selenium


【解决方案1】:

尝试将 assertIs 检查替换为:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 2015-06-19
      • 1970-01-01
      相关资源
      最近更新 更多