相关疑难解决方法(0)

你如何编写python模块的argparse部分的测试?

我有一个使用argparse库的Python模块.如何为代码库的该部分编写测试?

python unit-testing argparse

137
推荐指数
7
解决办法
4万
查看次数

Argparse单元测试:取消帮助消息

我正在为argparse实现编写测试用例.我打算测试'-h'功能.以下代码执行此操作.但它也输出脚本的用法.有没有办法压制那个?

self.assertRaises(SystemExit, arg_parse_obj.parse_known_args, ['-h'])
Run Code Online (Sandbox Code Playgroud)

另外,我们可以检查抛出的异常号码吗?例如'-h'抛出SystemExit:0,而无效或不足的args抛出SystemExit:2.有没有办法检查数字代码?

python unit-testing argparse

4
推荐指数
1
解决办法
1835
查看次数

使用unittest测试argparse-退出错误

要去关格雷格·哈斯在这个问题的答案,我试图让一个单元测试来检查当我通过它的一些ARGS不存在在该argparse是给相应的错误choices。但是,unittest使用以下try/except语句会产生误报。

另外,当我仅使用一条with assertRaises语句进行测试时,会argparse强制系统退出,并且程序不再执行任何其他测试。

我希望能够对此进行测试,但是鉴于argparse错误退出,也许这是多余的?

#!/usr/bin/env python3

import argparse
import unittest

class sweep_test_case(unittest.TestCase):
    """Tests that the merParse class works correctly"""

    def setUp(self):
        self.parser=argparse.ArgumentParser()
        self.parser.add_argument(
            "-c", "--color",
            type=str,
            choices=["yellow", "blue"],
            required=True)

    def test_required_unknown_TE(self):
        """Try to perform sweep on something that isn't an option.
        Should return an attribute error if it fails.
        This test incorrectly shows that the test passed, even though that must
        not be true."""
        args = …
Run Code Online (Sandbox Code Playgroud)

python unit-testing argparse python-3.x python-unittest

4
推荐指数
2
解决办法
2956
查看次数

python unittest for 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()
Run Code Online (Sandbox Code Playgroud)

A sample myapp.py would be:

my_options = [
    {
        "option": …
Run Code Online (Sandbox Code Playgroud)

python unit-testing python-2.7 argparse

2
推荐指数
1
解决办法
4128
查看次数