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


Python unittest assertNotIn()用法及代碼示例


assertNotInPython中的()是單元測試庫函數,用於單元測試中以檢查其他字符串是否不包含字符串。此函數將使用三個字符串參數作為輸入,並根據斷言條件返回一個布爾值。如果 key 不包含在容器字符串中,它將返回true,否則返回false。

用法: assertNotIn(key, container, message)

參數assertNotIn()接受以下說明的三個參數:

  • key:在給定容器中檢查其存在性的字符串
  • container:在其中搜索關鍵字符串的字符串
  • message:作為測試消息失敗時顯示的消息的字符串語句。

下麵列出了兩個不同的示例,它們說明了給定assert函數的正麵和負麵測試案例:

示例1:否定測試用例



Python3

# test suite 
import unittest 
  
class TestStringMethods(unittest.TestCase):
    # test function to test whether key is present in container 
    def test_negative(self):
        key = "geeks"
        container = "geeksforgeeks"
        # error message in case if test case got failed 
        message = "key is present in container."
        # assertNotIn() to check if key is in container 
        self.assertNotIn(key, container, message) 
  
if __name__ == '__main__':
    unittest.main()

輸出:

F
======================================================================
FAIL:test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/e99e85838dde0c8ef29ab17fef478979.py", line 12, in test_negative
    self.assertNotIn(key, container, message)
AssertionError:'geeks' unexpectedly found in 'geeksforgeeks':key is present in container.

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

FAILED (failures=1)

示例2:正測試用例

Python3

# test suite 
import unittest 
  
  
class TestStringMethods(unittest.TestCase):
    # test function to test whether key is present in container 
    def test_positive(self):
        key = "gfgs"
        container = "geeksforgeeks"
        # error message in case if test case got failed 
        message = "key is present in container."
        # assertNotIn() to check if key is in container 
        self.assertNotIn(key, container, 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 – assertNotIn() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。