如何使用 Python 中的 Unittest 断言整数在范围内?
How to assert an integer is within range by using Unittest in Python?
我有一个文件来验证标签
#configmanager.py
class FunctionNode(object):
def __validate_func_label(self, func_label):
pattern = re.compile('^fn[1-9][0-9]{0,1}$')
if not pattern.match(func_label):
raise Exception(
f"Invalid value {func_label} for function label in function config.")
而且我必须使用单元测试为其编写测试用例。测试用例将检查用户输入的 fn
是否在 1 到 99 之间,它将通过。否则,如果 fn
超出范围,例如 fn0
或 fn100
,那么它将失败。我写了一个 TestClass
#test__validate_func_label.py
import unittest
from configmanager import FunctionNode
class TestValidateFuncLabel(unittest.TestCase):
def setUp(self):
pass
def test_fn_within_range(self):
for i in range(1,99):
self.assertEqual(fn(i),output[i])
if __name__ == "__main__":
unittest.main()
但我觉得我走的路不对。
有什么方法可以断言 fn
在 1 到 99 的范围内?
感谢任何帮助。
self.assertTrue( 0<=y<=99)
其中 y
是您正在检查的 fn
的值。
但是,我不明白你的问题与你的代码有什么关系。在您的代码中,您断言 fn(i)
具有特定值(取自名为 output
的列表,该列表未在其他地方定义),其中 i
取 1 到 98 之间的每个值。
但是在您的问题中,您询问了关于断言一个值介于这些数字之间的问题。
另一个解决方案是:
https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn
self.assertIn(fn, range(1, 100))
我有一个文件来验证标签
#configmanager.py
class FunctionNode(object):
def __validate_func_label(self, func_label):
pattern = re.compile('^fn[1-9][0-9]{0,1}$')
if not pattern.match(func_label):
raise Exception(
f"Invalid value {func_label} for function label in function config.")
而且我必须使用单元测试为其编写测试用例。测试用例将检查用户输入的 fn
是否在 1 到 99 之间,它将通过。否则,如果 fn
超出范围,例如 fn0
或 fn100
,那么它将失败。我写了一个 TestClass
#test__validate_func_label.py
import unittest
from configmanager import FunctionNode
class TestValidateFuncLabel(unittest.TestCase):
def setUp(self):
pass
def test_fn_within_range(self):
for i in range(1,99):
self.assertEqual(fn(i),output[i])
if __name__ == "__main__":
unittest.main()
但我觉得我走的路不对。
有什么方法可以断言 fn
在 1 到 99 的范围内?
感谢任何帮助。
self.assertTrue( 0<=y<=99)
其中 y
是您正在检查的 fn
的值。
但是,我不明白你的问题与你的代码有什么关系。在您的代码中,您断言 fn(i)
具有特定值(取自名为 output
的列表,该列表未在其他地方定义),其中 i
取 1 到 98 之间的每个值。
但是在您的问题中,您询问了关于断言一个值介于这些数字之间的问题。
另一个解决方案是:
https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn
self.assertIn(fn, range(1, 100))