Python unittest – assertNotIn()函数
Python中的assertNotIn () 是一个 unittest 库函数,用于在单元测试中检查一个字符串是否不包含在 other 中。该函数将三个字符串参数作为输入,并根据断言条件返回一个布尔值。如果密钥不包含在容器字符串中,它将返回 true,否则返回 false。
Syntax: assertNotIn(key, container, message)
Parameters: assertNotIn() accept three parameters which are listed below with explanation:
- key: a string whose presence is checked in the given container
- container: a string in which key string is searched
- message: a string sentence as a message which got displayed when the test case got failed.
下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:
示例 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()
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()
输出:
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