pytest argparse 测试用例不起作用

Posted

技术标签:

【中文标题】pytest argparse 测试用例不起作用【英文标题】:pytest argparse test case does not work 【发布时间】:2017-12-25 04:26:18 【问题描述】:

我正在使用 Python 3.4.6。

这里是工厂:

def create_parser():
    """ Create argument parser """

    # Input configuration parameters
    _parser = argparse.ArgumentParser(description='Segments Engine')

    # Application only parameters
    _parser.add_argument(
        '-V', '--version', version='%(prog)s ' + __version__,
        action='version')
    _pasrser.add_argument(
        '-d', '--debug', action='store_true')

    return _parser

测试用例如下:

class TestCli(unittest.TestCase):
    """ Test the cli.py module """

    def __init__(self, *args, **kwargs):
        """ Initialize Unit Test """
        super(TestCli, self).__init__(*args, **kwargs)

    def setup(self):
        """ Setup before each test case """
        setup_config(app)
        setup_logging(app)

    def teardown(self):
        """ Tear down after each test case """
        pass

    def test_version(self):
        parser = create_parser()
        with pytest.raises(SystemExit):
            args = vars(parser.parse_args(['', '-V']))

        assert args.version == __version__

    def test_debug(self):
        parser = create_parser()
        args = parser.parse_args(['-d'])

        assert args.debug

然后我执行如下:

pytest tests/test_cli.py

我收到以下错误,我做错了什么?

======================================================================================= test session starts =========================================================================================
platform darwin -- Python 3.4.6, pytest-3.1.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/francisco.benavides/Documents/src/segments-engine, inifile:
collected 1 item s

tests/test_cli.py F

self = <tests.test_cli.TestCli testMethod=test_version>

    def test_version(self):
        parser = create_parser()
>       args = vars(parser.parse_args(['', '-V']))

tests/test_cli.py:29:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1728: in parse_args
args, argv = self.parse_known_args(args, namespace)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1760: in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1966: in _parse_known_args
start_index = consume_optional(start_index)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1906: in consume_optional
take_action(action, args, option_string)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1834: in take_action
action(self, namespace, argument_values, option_string)
../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:1043: in __call__
parser.exit()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = ArgumentParser(prog='pytest', usage=None, description='Segments Engine', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True), status = 0, message = None

def exit(self, status=0, message=None):
    if message:
        self._print_message(message, _sys.stderr)
>       _sys.exit(status)
E       SystemExit: 0

../../../.pyenv/versions/3.4.6/lib/python3.4/argparse.py:2373: SystemExit
---------------------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------------------
pytest 0.0.1

我尝试了几种在谷歌上搜索的方法,但到目前为止没有任何帮助。

【问题讨论】:

【参考方案1】:

只是猜测,因为您还没有向我们展示您的 create_parser 实现:

-V是一个“版本”类型的命令(?),如果你阅读the docs版本是为了

“[打印]版本信息并在调用时[退出]”。

您需要捕获exit,这是一种方法:

with pytest.raises(SystemExit):
    parser.parse_args(['', '-V'])

# maybe use `capsys` to verify that the version was printed
out, err = capsys.readouterr()
# ...

【讨论】:

以上是关于pytest argparse 测试用例不起作用的主要内容,如果未能解决你的问题,请参考以下文章

pytest--fixture之参数化

pytest-26-运行上次失败用例(--lf 和 --ff)

Pytest测试用例介绍

pytest简介

python-pytest学习(十八)-运行上次失败用例(--lf和--ff)

python-pytest学习(十八)-运行上次失败用例(--lf和--ff)