<p>从Python 3.2开始,<code>unittest.TestCase.assertItemsEqual</code>(<a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertItemsEqual" rel="noreferrer">doc</a>)已经被<code>unittest.TestCase.assertCountEqual</code>(<a href="https://docs.python.org/3.2/library/unittest.html#unittest.TestCase.assertCountEqual" rel="noreferrer">doc</a>)所取代,它正是您所寻找的,正如您可以从Python<a href="https://docs.python.org/3.2/library/unittest.html" rel="noreferrer">standard library documentation</a>中读取的那样。这个方法的名字有点误导人,但它确实符合你的要求。</p>
<blockquote>
<p>a and b have the same elements in the same number, regardless of their order</p>
</blockquote>
<p>这里有一个简单的例子,比较两个具有相同元素但顺序不同的列表。</p>
<ul>
<li>使用<code>assertCountEqual</code>测试将成功</li>
<li>使用<code>assertListEqual</code>由于两个列表的顺序不同,测试将失败</li>
</ul>
<p>这里有一个小的脚本示例。</p>
<pre><code>import unittest
class TestListElements(unittest.TestCase):
def setUp(self):
self.expected = ['foo', 'bar', 'baz']
self.result = ['baz', 'foo', 'bar']
def test_count_eq(self):
"""Will succeed"""
self.assertCountEqual(self.result, self.expected)
def test_list_eq(self):
"""Will fail"""
self.assertListEqual(self.result, self.expected)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p><strong>边注:</strong>请确保要比较的列表中的元素是可排序的。</p>