gpt4 book ai didi

python ,单元测试: is there a way to pass command line options to the app

转载 作者:IT老高 更新时间:2023-10-28 20:37:45 24 4
gpt4 key购买 nike

我有一个导入 unittest 并有一些 TestCases 的模块。我想接受一些命令行选项(例如下面的数据文件的名称),但是当我尝试传递选项时,我收到消息 option -i notrecognized。是否可以让 unittest + 为应用程序提供选项(注意:我正在使用 optparse 来处理选项)?谢谢。

$ python test_app_data.py -i data_1.txt

option -i not recognized

======================

跟进:这是建议解决方案的实现:

import cfg_master  #has the optparse option-handling code

...

if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)

del_lst.reverse()
for i in del_lst:
del sys.argv[i]

unittest.main()

最佳答案

基于 Alex 的回答,使用 argparse 实际上很容易做到:

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='My Input')
parser.add_argument('filename', default='some_file.txt')
parser.add_argument('unittest_args', nargs='*')

args = parser.parse_args()
# TODO: Go do something with args.input and args.filename

# Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
sys.argv[1:] = args.unittest_args
unittest.main()

我还没有测试你可以传递给 unittest 的所有标志以查看它们是否有效,但是传递测试名称确实有效,例如:

python test.py --input=foo data.txt MyTest

使用 foodata.txt 运行 MyTest。

关于 python ,单元测试: is there a way to pass command line options to the app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1029891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com