【发布时间】:2016-10-08 10:14:28
【问题描述】:
我在一个模块中有一个函数,它创建了一个argparse:
def get_options(prog_version='1.0', prog_usage='', misc_opts=None):
options = [] if misc_opts is None else misc_opts
parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser()
parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(prog_version))
parser.add_argument('-c', '--config', dest='config', required=True, help='the path to the configuration file')
for option in options:
if 'option' in option and 'destination' in option:
parser.add_argument(option['option'],
dest=option.get('destination', ''),
default=option.get('default', ''),
help=option.get('description', ''),
action=option.get('action', 'store'))
return parser.parse_args()
myapp.py 的示例将是:
my_options = [
{
"option": "-s",
"destination": "remote_host",
"default": "127.0.0.1",
"description": "The remote server name or IP address",
"action": "store"
},
]
# Get Command Line Options
options = get_options(misc_opts=my_options)
print options.config
print options.remote_host
这将被称为:
$> python myapp.py -c config.yaml
$> config.yaml
127.0.0.1
现在,我正在尝试为此函数创建一个单元测试,但我的问题是我无法通过测试代码传递命令行参数。
# mytest.py
import unittest
from mymodule import get_options
class argParseTestCase(unittest.TestCase):
def test_parser(self):
options = get_options()
# ...pass the command line arguments...
self.assertEquals('config.yaml', options.config) # ofcourse this fails because I don't know how I will pass the command line arguments
我的问题是我需要将命令行参数传递给get_options(),但我不知道如何正确执行。
预期的正确调用:python mytest.py(-c config.yaml 应该以某种方式在测试代码中传递。)
什么是“工作”/现在不工作:
-
python mytest.py -c config.yaml也不起作用。返回AttributeError: 'module' object has no attribute 'config',因为它希望我改为调用argParseTestCase。换句话说,python mytest.py -c argParseTestCase“有效”,但当然是回报AssertionError: 'config.yaml' != 'argParseTestCase' -
python mytest.py -v在详细模式下运行单元测试也会失败。它返回:test_parser (main.argParseTestCase) ... mytest.py 1.0 错误 错误:test_parser (main.argParseTestCase)
回溯(最近一次通话最后): 文件“tests/unit_tests/mytest.py”,第 376 行,在 test_parser options = get_options() 文件“/root/test/lib/python2.7/site-packages/mymodule.py”,第 61 行,在 get_options 返回 parser.parse_args()
文件“/usr/local/lib/python2.7/argparse.py”,第 1701 行,在 parse_args args 中,argv = self.parse_known_args(args, namespace)
文件“/usr/local/lib/python2.7/argparse.py”,第 1733 行,在 parse_known_args 命名空间中,args = self._parse_known_args(args, namespace)
文件“/usr/local/lib/python2.7/argparse.py”,第 1939 行,在 _parse_known_args start_index = consume_optional(start_index)
文件“/usr/local/lib/python2.7/argparse.py”,第 1879 行,在 consume_optional take_action(action, args, option_string)
文件“/usr/local/lib/python2.7/argparse.py”,第 1807 行,在 take_action 操作中(self、namespace、argument_values、option_string)
调用中的文件“/usr/local/lib/python2.7/argparse.py”第 1022 行 parser.exit(message=formatter.format_help())
文件“/usr/local/lib/python2.7/argparse.py”,第 2362 行,退出 _sys.exit(status) 系统退出:0
【问题讨论】:
标签: python python-2.7 unit-testing argparse