小编pip*_*poo的帖子

检查 argparse.ArgumentTypeError

我想用来pytest检查是否argparse.ArgumentTypeError为不正确的参数引发异常:

import argparse
import os
import pytest


def main(argsIn):

    def configFile_validation(configFile):
        if not os.path.exists(configFile):
            msg = 'Configuration file "{}" not found!'.format(configFile)
            raise argparse.ArgumentTypeError(msg)
        return configFile

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--configFile', help='Path to configuration file', dest='configFile', required=True, type=configFile_validation)
    args = parser.parse_args(argsIn)


def test_non_existing_config_file():
    with pytest.raises(argparse.ArgumentTypeError):
        main(['--configFile', 'non_existing_config_file.json'])
Run Code Online (Sandbox Code Playgroud)

但是, runningpytestDuring handling of the above exception, another exception occurred:,因此测试失败。我究竟做错了什么?

python pytest argparse

8
推荐指数
1
解决办法
1591
查看次数

标签 统计

argparse ×1

pytest ×1

python ×1