【发布时间】: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