什么是Python中的assertEquals?

2024-04-23 23:51:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在django中有以下test.py文件。你能解释一下这个密码吗?

from contacts.models import Contact
...
class ContactTests(TestCase):
    """Contact model tests."""

    def test_str(self):

        contact = Contact(first_name='John', last_name='Smith')

        self.assertEquals(
            str(contact),
            'John Smith',
        )

Tags: 文件djangonamefrompytestself密码
3条回答
from contacts.models import Contact  # import model Contact
...
class ContactTests(TestCase):  # start a test case
    """Contact model tests."""

    def test_str(self):  # start one test

        contact = Contact(first_name='John', last_name='Smith')  # create a Contact object with 2 params like that

        self.assertEquals(  # check if str(contact) == 'John Smith'
            str(contact),  
            'John Smith',
        )

基本上,它会检查str(contact)=‘John Smith’,如果不是,那么assert equal失败,测试失败,它会通知您该行的错误。

换句话说,assertEquals是一个函数,用于检查两个变量是否相等,以便进行自动测试:

def assertEquals(var1, var2):
    if var1 == var2:
        return True
    else:
        return False

希望有帮助。

assertEqualsTestCase.assertEqual(即a method on the ^{} class)的(不推荐使用)别名。

它形成一个测试断言;其中str(contact)必须等于'John Smith',测试才能通过。

带有s的表单已被标记为已弃用since 2010,但它们实际上尚未被删除,此时没有删除它们的具体承诺。如果在启用了不推荐警告(如recommended in PEP 565)的情况下运行测试,您将看到一个警告:

test.py:42: DeprecationWarning: Please use assertEqual instead.
  self.assertEquals(

由于Python 3.2,不推荐使用^{},您应该使用^{}(不使用s)。

或者^{}

相关问题 更多 >