python - 使用 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 =============================================================================
解决方案
您的参数解析是在导入模块时发生的。这样做的原因是您PARSER.parse_args()
在任何函数之外的顶级范围内调用。为了防止这种情况并允许正确导入您的代码,请添加__name__ == "__main__"
检查:
if __name__ == "__main__":
PARSER = create_parser()
ARGS = PARSER.parse_args()
input = [ARGS.Climate, ARGS.Orbit1, ARGS.Orbit2]
推荐阅读
- c# - 如何在 HTTPTrigger Azure Function 3.x 中获取操作 ID。附上图片
- c - 为什么某些整数的双重转换(浮点数并返回整数)不保持等于其原始数字,而有些则如此?
- ios - 如何以编程方式更改 Siri 快捷方式的自定义 Intent 上的 Title 属性?
- python - 如何修复:ImportError:无法导入名称 LiveSpeech?
- typescript - 如何在 NestJS 中设置仅 HTTP cookie
- c - 哪个是最标准的:strnlen 或 strnlen_s?
- jquery - jQuery 中是否有可用的分钟选择器?
- python - s[s].index 和 s.index 之间的区别,其中 s 是一个系列
- c# - 如何优化我的 C# 并使用一个委托函数而不是两个
- postgresql - CloudFoundry .NET 5.0 上的 Steeltoe Postgres 连接器