Greg Haskin's answer in this questionをオフにして、choices
に存在しないargsを渡すときに、argparseが適切なエラーを出しているかどうかを確認するためにunittestを作成しようとしました。ただし、unittest
は、以下のtry/except
ステートメントを使用して偽陽性を生成します。unittestを使用してargparse - exitエラーをテストする
さらに、with assertRaises
ステートメントだけを使用してテストを行うと、は強制的にシステムを終了させ、プログラムはこれ以上テストを実行しません。
私はこのためのテストをしたいと思っていますが、エラーの際にが終了すると冗長かもしれませんか?
#!/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
ありがとう@hpaulj、どこのシステムでそのファイルを見つけることができますか? [ここであなたが話していると思っているものが見つかりました](https://hg.python.org/cpython/file/default/Lib/test/test_argparse.py)。 – conchoecia
はい、これがファイルです。 Pythonの開発版が必要な場合があります。 'Lib/test'ディレクトリを探します。しかし、リポジトリからのダウンロードも問題ありません。 'ParserTestCase'に構築されたテストのほとんどは、エラーメッセージについて心配していません。ケースが実行されるかどうかだけです。ファイルをさらに調べると、エラーメッセージが表示されます。 – hpaulj