📜  Python unittest – assertIn()函数

📅  最后修改于: 2022-05-13 01:55:05.465000             🧑  作者: Mango

Python unittest – assertIn()函数

Python中的 assertIn() 是一个 unittest 库函数,用于在单元测试中检查字符串是否包含在 other 中。该函数将三个字符串参数作为输入,并根据断言条件返回一个布尔值。如果密钥包含在容器字符串中,它将返回 true,否则返回 false。

下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:

示例 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 = "gfg"
        container = "geeksforgeeks"
        # error message in case if test case got failed
        message = "key is not in container."
        # assertIn() to check if key is in container
        self.assertIn(key, container, message)
  
if __name__ == '__main__':
    unittest.main()


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


输出:

F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/e920f2cd9195a3fd72bd531f7f101754.py", line 12, in test_negative
    self.assertIn(key, container, message)
AssertionError: 'gfg' not found in 'geeksforgeeks' : key is not in container.

----------------------------------------------------------------------
Ran 1 test in 0.001s

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 = "geeks"
        container = "geeksforgeeks"
        # error message in case if test case got failed
        message = "key is not in container."
        # assertIn() to check if key is in container
        self.assertIn(key, container, message)
  
  
if __name__ == '__main__':
    unittest.main()

输出:

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

OK

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