argparse的python单元测试 [英] python unittest for argparse

查看:26
本文介绍了argparse的python单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个创建 argparse 的模块中有一个函数:

I have a function inside a module that creates an 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

现在,我正在尝试为此函数创建单元测试,但我的问题是我无法通过测试代码传递命令行参数.

Now, I am trying to create a unit test for this function but my problem is that I can't pass command line parameters via test code.

# 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() 但我不知道如何正确执行.

My problem is that I need to pass the command line arguments to get_options() but I don't know how to do it properly.

预期的正确调用:python mytest.py(-c config.yaml 应该以某种方式在测试代码中传递.)

Expected proper call: python mytest.py (-c config.yaml should be passed inside the test code somehow.)

什么是工作"/现在不工作:

What is "working"/not working right now:

  1. python mytest.py -c config.yaml 也不起作用.返回 AttributeError: 'module' object has no attribute 'config' 因为它希望我调用 argParseTestCase 代替.换句话说, python mytest.py -c argParseTestCase 有效"但当然会返回 AssertionError: 'config.yaml' !='argParseTestCase'
  2. python mytest.py -v 在详细模式下运行单元测试也失败.它返回:

  1. python mytest.py -c config.yaml is also not working. Returns AttributeError: 'module' object has no attribute 'config' since it expects me to call argParseTestCase instead. In other words, python mytest.py -c argParseTestCase "works" but would ofcourse be an return AssertionError: 'config.yaml' != 'argParseTestCase'
  2. python mytest.py -v to run the unit test in verbose mode also fails. It returns:

test_parser (ma​​in.argParseTestCase) ... mytest.py 1.0 错误错误:test_parser (ma​​in.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 = consumer_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 行,在 call parser.exit(message=formatter.format_help())
文件/usr/local/lib/python2.7/argparse.py",第 2362 行,在 exit _sys.exit(status) 中系统退出:0

test_parser (main.argParseTestCase) ... mytest.py 1.0 ERROR ERROR: test_parser (main.argParseTestCase)
Traceback (most recent call last): File "tests/unit_tests/mytest.py", line 376, in test_parser options = get_options() File "/root/test/lib/python2.7/site-packages/mymodule.py", line 61, in get_options return parser.parse_args()
File "/usr/local/lib/python2.7/argparse.py", line 1701, in parse_args args, argv = self.parse_known_args(args, namespace)
File "/usr/local/lib/python2.7/argparse.py", line 1733, in parse_known_args namespace, args = self._parse_known_args(args, namespace)
File "/usr/local/lib/python2.7/argparse.py", line 1939, in _parse_known_args start_index = consume_optional(start_index)
File "/usr/local/lib/python2.7/argparse.py", line 1879, in consume_optional take_action(action, args, option_string)
File "/usr/local/lib/python2.7/argparse.py", line 1807, in take_action action(self, namespace, argument_values, option_string)
File "/usr/local/lib/python2.7/argparse.py", line 1022, in call parser.exit(message=formatter.format_help())
File "/usr/local/lib/python2.7/argparse.py", line 2362, in exit _sys.exit(status) SystemExit: 0

推荐答案

我更喜欢显式传递参数,而不是依赖全局可用的属性,例如 sys.argv(其中 parser.parse_args() 在内部执行).因此,我通常通过自己传递参数列表来使用 argparse(到 main() 和随后的 get_options() 以及您需要它们的任何地方):

I prefer explicitly passing arguments instead of relying on globally available attributes such as sys.argv (which parser.parse_args() does internally). Thus I usually use argparse by passing the list of arguments myself (to main() and subsequently get_options() and wherever you need them):

def get_options(args, prog_version='1.0', prog_usage='', misc_opts=None):
    # ...
    return parser.parse_args(args)

然后传入参数

def main(args):
    get_options(args)

if __name__ == "__main__":
    main(sys.argv[1:])

这样我就可以替换和测试我喜欢的任何参数列表

that way I can replace and test any list of arguments I like

options = get_options(['-c','config.yaml'])
self.assertEquals('config.yaml', options.config) 

这篇关于argparse的python单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆