简体   繁体   English

使用Pytest框架进行Argparse测试

[英]Argparse testing with Pytest framework

I am trying to write unit test cases for my argparse module. 我正在尝试为argparse模块编写单元测试用例。 However, the test is not working as expected. 但是,该测试无法正常工作。 My code is below: 我的代码如下:

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]

The corresponding test file is as follows: 相应的测试文件如下:

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

When I execute with the command pytest test_main.py the below error is shown: 当我使用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 =============================================================================

Your argument parsing is happening on import of your module. 参数解析是在模块导入时进行的。 The reason for this is that you are calling PARSER.parse_args() at a top level scope outside of any functions. 原因是您在任何函数之外的顶级范围内调用PARSER.parse_args() To prevent this and allow your code to be properly imported, add a __name__ == "__main__" check: 为了防止这种情况并允许您的代码正确导入,请添加__name__ == "__main__"检查:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM