我对用Python进行单元测试还很陌生。我想在我的代码中测试一些函数。特别是我需要测试输出是否有特定的维度或者相同的维度。你知道吗
我的用于单元测试的Python脚本如下所示:
import unittest
from func import *
class myTests(unittest.TestCase):
def setUp(self):
# I am not really sure whats the purpose of this function
def test_main(self):
# check if outputs of the function "main" are not empty:
self.assertTrue(main, msg = 'The main() function provides no return values!')
# check if "run['l_modeloutputs']" and "run['l_modeloutputs']", within the main() function have the same size:
self.assertCountEqual(self, run['l_modeloutputs'], run['l_dataoutputs'], msg=None)
# --> Doesn't work so far!
# check if the dimensions of "props['k_iso']", within the main() function are (80,40,100):
def tearDown(self):
# I am also not sure of the purpose of this function
if _name__ == "__main__":
unittest.main()
下面是正在测试的代码:
def main(param_file):
# Load parameter file
run, model, sequences, hydraulics, flowtrans, elements, mg = hu.model_setup(param_file)
# some other code
...
if 'l_modeloutputs' in run:
if hydraulics['flag_gen'] is False:
print('No hydraulic parameters generated. No model outputs saved')
else:
save_models(realdir, realname, mg, run['l_modeloutputs'], flowtrans, props['k_iso'], props['ktensors'])
我需要从func.py
访问main
函数的参数run['l_modeloutputs']
和run['l_dataoutputs']
。如何将这些参数的维度传递给单元测试脚本?你知道吗
这听起来有点像两件事中的一件。要么你的代码目前没有以一种易于测试的方式进行布局,要么你正试图一次性测试或调用太多的代码。你知道吗
如果您的代码如下所示:
如果您试图测试从
file_name
得到的数据以及results
的大小,那么您可能需要考虑对其进行重构,以便可以测试更小的操作。也许:当然,如果您已经有了类似的设置,那么下面的内容也适用。这样您就可以进行更简单的测试,因为您可以轻松控制测试(
file_name
或file_contents
)的内容,然后可以测试结果(file_contents
或results
)以获得预期的结果。你知道吗使用
unittest
模块,您基本上可以为每个测试创建一个小函数:然后可以对不同的潜在输入集重复此操作,包括良好和边缘情况。你知道吗
它可能值得寻找一个更深入的教程,因为这显然只是一个非常快速的浏览。你知道吗
并且
setUp
和tearDown
只有在您编写的每个测试都有一些事情要做的情况下才需要(也就是说,您以特定的方式设置了一个对象,对于几个测试,这可以在setUp
中完成,并在每个测试函数之前运行它。你知道吗相关问题 更多 >
编程相关推荐