【发布时间】:2016-12-25 23:24:08
【问题描述】:
离开Greg Haskin's answer in this question,我尝试进行单元测试以检查当我传递一些choices 中不存在的args 时argparse 是否给出了适当的错误。但是,unittest 使用下面的 try/except 语句会产生误报。
此外,当我只使用with assertRaises 语句进行测试时,argparse 会强制系统退出,程序不再执行任何测试。
我希望能够对此进行测试,但考虑到argparse 在出错时退出,这可能是多余的?
#!/usr/bin/env python3
import argparse
import unittest
class sweep_test_case(unittest.TestCase):
"""Tests that the merParse class works correctly"""
def setUp(self):
self.parser=argparse.ArgumentParser()
self.parser.add_argument(
"-c", "--color",
type=str,
choices=["yellow", "blue"],
required=True)
def test_required_unknown_TE(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
try:
self.assertRaises(argparse.ArgumentError, self.parser.parse_args(args))
except SystemExit:
print("should give a false positive pass")
def test_required_unknown(self):
"""Try to perform sweep on something that isn't an option.
Should return an attribute error if it fails.
This test incorrectly shows that the test passed, even though that must
not be true."""
args = ["--color", "NADA"]
with self.assertRaises(argparse.ArgumentError):
self.parser.parse_args(args)
if __name__ == '__main__':
unittest.main()
错误:
Usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
E
usage: temp.py [-h] -c {yellow,blue}
temp.py: error: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
should give a false positive pass
.
======================================================================
ERROR: test_required_unknown (__main__.sweep_test_case)
Try to perform sweep on something that isn't an option.
----------------------------------------------------------------------
Traceback (most recent call last): #(I deleted some lines)
File "/Users/darrin/anaconda/lib/python3.5/argparse.py", line 2310, in _check_value
raise ArgumentError(action, msg % args)
argparse.ArgumentError: argument -c/--color: invalid choice: 'NADA' (choose from 'yellow', 'blue')
During handling of the above exception, another exception occurred:
Traceback (most recent call last): #(I deleted some lines)
File "/anaconda/lib/python3.5/argparse.py", line 2372, in exit
_sys.exit(status)
SystemExit: 2
【问题讨论】:
-
test/test_argparse.py单元测试文件有大量示例,因为它测试了模块的大部分功能。sys.exit需要特殊处理。 -
谢谢@hpaulj,我在哪里可以找到我系统上的那个文件? I found what I think you're talking about here.
-
是的,就是这个文件。您可能需要 Python 的开发版本才能在自己的计算机上找到它。查找
Lib/test目录。但是从存储库下载也很好。大多数基于ParserTestCase的测试不用担心错误信息;只是案件是否运行。进一步测试文件查看错误消息。
标签: python unit-testing python-3.x argparse python-unittest