命令行args python的单元测试

2024-06-26 01:37:29 发布

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

我有一个shell脚本,目前需要3个参数。我通过一个shell脚本来运行它,这个shell脚本文件名是运行python脚本的目录,还有测试数据目录的名称。我希望能够编写一个单元测试来执行下面的命令,但前提是我要更改日期,这取决于可用的数据,它要么通过要么失败。你知道吗

main_config.sh
yamldir=$1

for yaml in $(ls ${yamldir}/*.yaml | grep -v "export_config.yaml"); do

    if [ "$yaml" != "export_config.yaml" ]; then

        echo "Running export for $yaml file...";
        python valid.py -p ${yamldir}/export_config.yaml -e $yaml -d ${endDate}
        wait

    fi

done

这是在命令行上执行的

./main_config.sh /Users/name/Desktop/yaml/ 2018-12-23

这将失败并在终端上输出,因为没有名为2012-12-23的目录:

./main_config.sh /yaml/ 2018-12-23
    Running export for apa.yaml file...
    apa.json does not exist

如果存在该目录,则会通过并在终端上输出:

Running export for apa.yaml file...
File Name: apa.json Exists 
File Size: 234 Bytes 
Writing to file

我的python脚本如下:

def main(get_config):
    cfg = get_config()[0]  # export_config.yaml
    data = get_config()[1]  # export_apa.yaml
    date = get_config()[2]  # data folder - YYYY-MM-DD

# Conditional Logic


def get_config():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--parameter-file", action="store", required=True)
    parser.add_argument("-e", "--export-data-file", action="store", required=True)
    parser.add_argument("-d", "--export-date", action="store", required=False)
    args = parser.parse_args()

    return [funcs.read_config(args.parameter_file), funcs.read_config(args.export_data_file), args.export_date]


if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)
    main(get_config)

Tags: 目录脚本configparseryamlfordataget
1条回答
网友
1楼 · 发布于 2024-06-26 01:37:29

在我看来,这不是一个典型的单元测试(测试函数或方法),而是一个集成测试(从外部测试子系统)。当然,您仍然可以使用典型的Python测试工具来解决这个问题,比如unittest。你知道吗

一个简单的解决方案是使用subprocess运行脚本,捕获输出,然后作为测试的一部分解析该输出:

import unittest

import os
import sys
if os.name == 'posix' and sys.version_info[0] < 3:
    import subprocess32 as subprocess
else:
    import subprocess

class TestScriptInvocation(unittest.TestCase):

    def setUp(self):
        """call the script and record its output"""
        result = subprocess.run(["./main_config.sh", "/Users/yasserkhan/Desktop/yaml/", "2018-12-23"], stdout=subprocess.PIPE)
        self.returncode = result.returncode
        self.output_lines = result.stdout.decode('utf-8').split('\n')

    def test_returncode(self):
        self.assertEqual(self.returncode, 0)

    def test_last_line_indicates_success(self):
        self.assertEqual(self.output_lines[-1], 'Writing to file')

if __name__ == '__main__':
    unittest.main()

请注意,此代码使用python3subprocess模块的后端口。另外,它尝试解码result.stdout的内容,因为在python3上,它将是bytes对象,而不是像python2上那样的str。我没有测试它,但这两件事应该使代码在2到3之间可移植。你知道吗

还要注意,使用像"/Users/yasserkhan/Desktop/yaml"这样的绝对路径很容易中断,因此您需要找到一个相对路径,或者使用环境变量将一个基本路径传递给您的测试。你知道吗

您可以添加额外的测试来解析其他行,并检查合理的输出,如预期范围内的文件大小。你知道吗

相关问题 更多 >