From e614dd62c1a915df171f325de08e32fc98f8e5e3 Mon Sep 17 00:00:00 2001 From: noname Date: Tue, 4 Jun 2019 16:23:02 +0300 Subject: [PATCH 1/2] Handle wrong type, add FileType fail case test --- Lib/argparse.py | 4 ++++ Lib/test/test_argparse.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/Lib/argparse.py b/Lib/argparse.py index ef888f063b3286..9a67b41ae00ead 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1361,6 +1361,10 @@ def add_argument(self, *args, **kwargs): if not callable(type_func): raise ValueError('%r is not callable' % (type_func,)) + if type_func is FileType: + raise ValueError('%r is a FileType class object, instance of it' + ' must be passed' % (type_func,)) + # raise an error if the metavar does not match the type if hasattr(self, "_get_formatter"): try: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 9d68f40571fe6f..bcf2cc9b26a319 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -1619,6 +1619,24 @@ def test_open_args(self): m.assert_called_with('foo', *args) +class TestFileTypeMissingInitialization(TestCase): + """ + Test that add_argument throws an error if FileType class + object was passed instead of instance of FileType + """ + + def test(self): + parser = argparse.ArgumentParser() + with self.assertRaises(ValueError) as cm: + parser.add_argument('-x', type=argparse.FileType) + + self.assertEqual( + '%r is a FileType class object, instance of it must be passed' + % (argparse.FileType,), + str(cm.exception) + ) + + class TestTypeCallable(ParserTestCase): """Test some callables as option/argument types""" From b7bbf0fd5a7b04c075093d0567288b001c234e21 Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" Date: Tue, 4 Jun 2019 14:44:43 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../NEWS.d/next/Library/2019-06-04-14-44-41.bpo-37150.TTzHxj.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2019-06-04-14-44-41.bpo-37150.TTzHxj.rst diff --git a/Misc/NEWS.d/next/Library/2019-06-04-14-44-41.bpo-37150.TTzHxj.rst b/Misc/NEWS.d/next/Library/2019-06-04-14-44-41.bpo-37150.TTzHxj.rst new file mode 100644 index 00000000000000..c5be46e1e5d3f4 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2019-06-04-14-44-41.bpo-37150.TTzHxj.rst @@ -0,0 +1 @@ +`argparse._ActionsContainer.add_argument` now throws error, if someone accidentally pass FileType class object instead of instance of FileType as `type` argument \ No newline at end of file