當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。