首页 > 解决方案 > 使用 Pytest 框架进行 Argparse 测试

问题描述

我正在尝试为我的 argparse 模块编写单元测试用例。但是,测试没有按预期工作。我的代码如下:

import argparse

def create_parser():
    PARSER = argparse.ArgumentParser(prog='traffic_problem_one', \
   orbit2_traffic_speed', description='Geek Trust traffic problem', \
    allow_abbrev=False)

    PARSER.add_argument('Climate', metavar='--climate', action='store', type=str, help='Climate condition')
    PARSER.add_argument('Orbit1', metavar='--orbit1', action='store', type=int, help='Orbit 1 traffic speed')
    PARSER.add_argument('Orbit2', metavar='--orbit2', action='store', type=int, help='Orbit 2 traffic speed')

    return PARSER

PARSER = create_parser()
ARGS = PARSER.parse_args()

input = [ARGS.Climate, ARGS.Orbit1, ARGS.Orbit2]

对应的测试文件如下:

import sys
import os

sys.path.append(os.path.dirname(__file__)+"/../")
from src.main import *
from unittest import TestCase

class CommandLineTestCase(TestCase):
    """
    Base TestCase class, sets up a CLI parser
    """
    @classmethod
    def setUpClass(cls):
        parser = create_parser()
        cls.parser = parser

当我使用命令执行时,pytest test_main.py显示以下错误:

latform darwin -- Python 3.7.0, pytest-3.8.0, py-1.6.0, pluggy-0.7.1 -- /Users/xyx/anaconda3/bin/python
cachedir: .pytest_cache
rootdir: /Users/xyz/Xyz/gitDownloads/geekttrustproblems, inifile:
plugins: remotedata-0.3.0, openfiles-0.3.0, doctestplus-0.1.3, arraydiff-0.2
collected 0 items / 1 errors                                                                                                                                                      

===================================================================================== ERRORS ======================================================================================
_______________________________________________________________________ ERROR collecting test/test_main.py ________________________________________________________________________
test/test_main.py:5: in <module>
    from src.main import *
src/main.py:29: in <module>
    ARGS = PARSER.parse_args()
../../../anaconda3/lib/python3.7/argparse.py:1749: in parse_args
    args, argv = self.parse_known_args(args, namespace)
../../../anaconda3/lib/python3.7/argparse.py:1781: in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
../../../anaconda3/lib/python3.7/argparse.py:2016: in _parse_known_args
    ', '.join(required_actions))
../../../anaconda3/lib/python3.7/argparse.py:2501: in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
../../../anaconda3/lib/python3.7/argparse.py:2488: in exit
    _sys.exit(status)
E   SystemExit: 2
--------------------------------------------------------------------------------- Captured stderr ---------------------------------------------------------------------------------
usage: traffic_problem_one [-h] --climate --orbit1 --orbit2
traffic_problem_one: error: the following arguments are required: --orbit1, --orbit2
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================= 1 error in 0.29 seconds =============================================================================

标签: pythonpytestargparse

解决方案


您的参数解析是在导入模块时发生的。这样做的原因是您PARSER.parse_args()在任何函数之外的顶级范围内调用。为了防止这种情况并允许正确导入您的代码,请添加__name__ == "__main__"检查:

if __name__ == "__main__":
    PARSER = create_parser()
    ARGS = PARSER.parse_args()

    input = [ARGS.Climate, ARGS.Orbit1, ARGS.Orbit2]

推荐阅读