Python的单元测试,通过输入测试
Python's unittest, pass test by input
我正在测试绘制地图的代码,测试它的唯一方法几乎就是亲眼看到结果,所以我想插入一个输入 (Y/n)测试功能,如果是Y则认为测试通过。
from unittest import TestCase
from .app import main
from .test_cases import test1
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
if 'y' in worked:
# code to tell python the test passed.
else:
# code to tell python the test failed.
您要找的是AssertIn()
。参见:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn
因此您的代码将如下所示:
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
self.assertIn('y', worked)
您可能应该使用 assertEqual()
,因为您正在检查是否相等,所以它应该是 self.assertEqual('y', worked.lower())
。参见:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual
对于单元测试,最重要的是整体测试退出代码。如果您希望您的测试仅在输入 "n" 时失败,只需让测试失败:
from unittest import TestCase
from .app import main
from .test_cases import test1
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
if worked == 'n':
raise Exception('Test has failed!')
我正在测试绘制地图的代码,测试它的唯一方法几乎就是亲眼看到结果,所以我想插入一个输入 (Y/n)测试功能,如果是Y则认为测试通过。
from unittest import TestCase
from .app import main
from .test_cases import test1
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
if 'y' in worked:
# code to tell python the test passed.
else:
# code to tell python the test failed.
您要找的是AssertIn()
。参见:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIn
因此您的代码将如下所示:
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
self.assertIn('y', worked)
您可能应该使用 assertEqual()
,因为您正在检查是否相等,所以它应该是 self.assertEqual('y', worked.lower())
。参见:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual
对于单元测试,最重要的是整体测试退出代码。如果您希望您的测试仅在输入 "n" 时失败,只需让测试失败:
from unittest import TestCase
from .app import main
from .test_cases import test1
class Test(TestCase):
def test_main(self):
main(gdt1=test1[0],
gdt2=test1[1],
uav=test1[2])
# This function plot the map, again, it doesn't matter what's the output for this question.
worked = input('Enter y/n')
if worked == 'n':
raise Exception('Test has failed!')