assertEquals 和 assertEqual 在 Python 中的区别

251 投票
6 回答
88170 浏览
提问于 2025-04-15 11:56

在Python的 unittest.TestCase 里,assertEqualsassertEqual 这两个函数有什么区别吗?

如果没有区别,那为什么会有两个函数呢?只是为了方便吗?

6 个回答

35

不仅仅是针对Python 3.x,实际上在Python 2.7中,assertEquals这个功能也已经被淘汰了:

Method Name            | Deprecated alias(es)
_________________________________________________________
assertEqual()          | failUnlessEqual, assertEquals

详细信息可以查看这里

67

3.3 更新:来自 26.3.7.1.1. 不推荐使用的别名

由于历史原因,一些 TestCase 方法曾经有一个或多个别名,但现在这些别名已经不推荐使用了。下面的表格列出了正确的名称和它们不推荐使用的别名:

Method Name   | Deprecated alias | Deprecated alias
--------------+------------------+-----------------
assertEqual() | failUnlessEqual  | assertEquals
...
287

其实,在Python 2.6中,assertEqualassertEquals都是指向failUnlessEqual的方便别名。源代码是这么声明的:

# Synonyms for assertion methods
assertEqual = assertEquals = failUnlessEqual

Python 3中,正如你所说,failUnlessEqual已经被明确标记为不推荐使用。assertEquals也有这样的注释 :-)

# Synonyms for assertion methods
# The plurals are undocumented.  Keep them that way to discourage use.
# Do not add more.  Do not remove.
# Going through a deprecation cycle on these would annoy many people.

所以,总的来说,对于Python 2.x,你可以随便用你喜欢的,但在Python 3中,建议使用assertEqual

撰写回答