当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python unittest assertIs()用法及代码示例


Python中的assertIs()是一个单元测试库函数,用于单元测试以测试第一个和第二个输入值是否求值到同一对象。此函数将使用三个参数作为输入,并根据断言条件返回布尔值。如果两个输入的求值对象相同,则assertIs()将返回true,否则返回false。

用法: assertIs(firstValue, secondValue, message)

参数:assertIs()接受以下三个参数的说明:

  • firstValue按函数比较中使用的任何类型的变量
  • secondValue:按函数比较时使用的任何类型的变量
  • message:作为测试消息失败时显示的消息的字符串语句。

下面列出了两个不同的示例,它们说明了给定assert函数的正面和负面测试案例:

示例1:否定测试用例



Python3

# unit test case 
import unittest 
  
class DummyClass:
  x = 5
  
class TestMethods(unittest.TestCase):
    # test function to test object equality of two value 
    def test_negative(self):
        firstValue = DummyClass() 
        secondValue = DummyClass() 
        # error message in case if test case got failed 
        message = "First value & second value are not evaluated to same object !"
        # assertIs() to check that if first & second evaluated to same object 
        self.assertIs(firstValue, secondValue, message) 
  
if __name__ == '__main__':
    unittest.main()

输出:

F
======================================================================
FAIL:test_negative (__main__.TestMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "p1.py", line 15, in test_negative
    self.assertIs(firstValue, secondValue, message)
AssertionError:<__main__.DummyClass object at 0x7f1d20251b70> is 
not <__main__.DummyClass object at 0x7f1d20251ba8>:
 First value and second value are not evaluated to same object!

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)


示例2:正测试用例

Python3

# unit test case 
import unittest 
  
class DummyClass:
  x = 5
  
class TestMethods(unittest.TestCase):
    # test function to test object equality of two value 
    def test_positive(self):
        firstValue = DummyClass() 
        secondValue = firstValue 
        # error message in case if test case got failed 
        message = "First value and second value are not evaluated to same object !"
        # assertIs() to check that if first & second evaluated to same object 
        self.assertIs(firstValue, secondValue, message) 
  
if __name__ == '__main__':
    unittest.main()

输出:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


参考:https://docs.python.org/3/library/unittest.html




相关用法


注:本文由纯净天空筛选整理自Shivam.Pradhan大神的英文原创作品 Python unittest – assertIs() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。