我需要为一些
python类创建一个单元测试.我有一个输入和预期结果的数据库,应由UUT为这些输入生成.
这是我想要做的伪代码:
- for i=1 to NUM_TEST_CASES:
- Load input for test case i
- execute UUT on the input and save output of run
- Load expected result for test case i
- Compare output of run with the expected result
我可以使用unittest软件包实现这一目标,还是有更好的测试包用于此目的?
解决方法
您描述测试的方式与单元测试一般是奇怪的匹配.单元测试通常不会从外部文件加载测试数据或休息结果.通常,它只是在单元测试中硬编码.
这并不是说你的计划不会奏效.这只是说这是非典型的.
你有两个选择.
>(我们做什么).编写一个小脚本,执行“为测试用例i加载输入”和“为测试用例i加载预期结果”.使用它来生成所需的unittest代码. (我们使用Jinja2模板从源文件中编写Python代码.)
你剩下的是“典型”形式的正确Unittest文件,其中包含测试用例和预期结果的静态数据.
>编写setUp方法来执行“为测试用例i加载输入”和“为测试用例i加载预期结果”.编写测试方法来练习UUT.
它可能看起来像这样.
- class OurTest( unittest.TestCase ):
- def setUp( self ):
- self.load_data()
- self.load_results()
- self.uut = ... UUT ...
- def runTest( self ):
- ... exercise UUT with source data ...
- ... check results,using self.assertXXX methods ...
想多次运行?这样做的一种方式.
- class Test1( OurTest ):
- source_file = 'this'
- result_file = 'that'
- class Test2( OutTest ):
- source_file= 'foo'
- result_file= 'bar'
这将允许unittest主程序找到并运行您的测试.