Python unittest – assertIsNot()函数
Python中的 assertIsNot() 是一个 unittest 库函数,用于在单元测试中测试第一个和第二个输入值是否不评估为同一个对象。该函数将三个参数作为输入,并根据断言条件返回一个布尔值。如果两个输入的计算结果不是同一个对象,则 assertIsNot() 将返回 true,否则返回 false。
Syntax: assertIsNot(firstValue, secondValue, message)
Parameters: assertIsNot() accept three parameters which are listed below with explanation:
- firstValue variable of any type which is used in the comparison by function
- secondValue: variable of any type which is used in the comparison by function
- message: a string sentence as a message which got displayed when the test case got failed.
下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:
示例 1:否定测试用例
Python3
# unit test case
import unittest
class DummyClass:
x = 5
class TestMethods(unittest.TestCase):
# test function
def test_negative(self):
firstValue = DummyClass()
secondValue = firstValue
# error message in case if test case got failed
message = "First value & second value evaluates to same object !"
# assertIs() to check that if first & second don't evaluated to same object
self.assertIsNot(firstValue, secondValue, message)
if __name__ == '__main__':
unittest.main()
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 = DummyClass()
# error message in case if test case got failed
message = "First value and second value evaluated to same object !"
# assertIs() to check that if first & second don't evaluates to same object
self.assertIsNot(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.assertIsNot(firstValue, secondValue, message)
AssertionError: unexpectedly identical: <__main__.DummyClass object at 0x7f75c2e33b70>
: First value & second value evaluates 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 = DummyClass()
# error message in case if test case got failed
message = "First value and second value evaluated to same object !"
# assertIs() to check that if first & second don't evaluates to same object
self.assertIsNot(firstValue, secondValue, message)
if __name__ == '__main__':
unittest.main()
输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
参考:https://docs。 Python.org/3/library/unittest.html