从函数访问变量和列表

2024-07-01 08:29:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我对用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']。如何将这些参数的维度传递给单元测试脚本?你知道吗


Tags: oftherunselfifmaindefcheck
1条回答
网友
1楼 · 发布于 2024-07-01 08:29:41

这听起来有点像两件事中的一件。要么你的代码目前没有以一种易于测试的方式进行布局,要么你正试图一次性测试或调用太多的代码。你知道吗

如果您的代码如下所示:

main(file_name):
    with open(file_name) as file:
        ... do work ...
        results = outcome_of_work

如果您试图测试从file_name得到的数据以及results的大小,那么您可能需要考虑对其进行重构,以便可以测试更小的操作。也许:

main(file_name):
    # `get_file_contents` appears to be `hu.model_setup`
    # `file_contents` would be `run`
    file_contents = get_file_contents(file_name)
    results = do_work_on_file_contents(file_contents)

当然,如果您已经有了类似的设置,那么下面的内容也适用。这样您就可以进行更简单的测试,因为您可以轻松控制测试(file_namefile_contents)的内容,然后可以测试结果(file_contentsresults)以获得预期的结果。你知道吗

使用unittest模块,您基本上可以为每个测试创建一个小函数:

class Test(TestCase):

    def test_get_file_contents(self):
        # ... set up example `file-like object` ...
        run = hu.model_setup(file_name)
        self.assertCountEqual(
                run['l_modeloutputs'], run['l_dataoutputs'])

    ... repeat for other possible files ...

    def test_do_work_on_file_contents(self):
        example_input = ... setup input ...
        example_output = do_work_on_file_contents(example_input)
        assert example_output == as_expected

然后可以对不同的潜在输入集重复此操作,包括良好和边缘情况。你知道吗

它可能值得寻找一个更深入的教程,因为这显然只是一个非常快速的浏览。你知道吗

并且setUptearDown只有在您编写的每个测试都有一些事情要做的情况下才需要(也就是说,您以特定的方式设置了一个对象,对于几个测试,这可以在setUp中完成,并在每个测试函数之前运行它。你知道吗

相关问题 更多 >

    热门问题