命令行args-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)

对我来说,这似乎不是一个典型的单元测试(测试函数或方法(,而是一个集成测试(从外部测试子系统(。当然,您仍然可以使用典型的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()

请注意,此代码使用Python 3subprocess模块的后台端口。此外,它试图解码result.stdout的内容,因为在Python 3上,它将是bytes对象,而不是像在Python 2上那样是str。我没有测试它,但这两件事应该使代码在2和3之间可移植。

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

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

最新更新