[3.13] gh-86357: argparse: use str() consistently and explicitly to print choices (GH-117766) (GH-125431)

(cherry picked from commit 66b3922b97)

Signed-off-by: Jan Chren ~rindeal <dev.rindeal@gmail.com>
Co-authored-by: rindeal <dev.rindeal@gmail.com>
This commit is contained in:
Serhiy Storchaka 2024-10-14 10:09:06 +03:00 committed by GitHub
parent 1279be610d
commit d3d306a9d6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 36 additions and 8 deletions

View file

@ -15,6 +15,7 @@ import unittest
import argparse
import warnings
from enum import StrEnum
from test.support import os_helper, captured_stderr
from unittest import mock
@ -1021,6 +1022,34 @@ class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
]
class TestStrEnumChoices(TestCase):
class Color(StrEnum):
RED = "red"
GREEN = "green"
BLUE = "blue"
def test_parse_enum_value(self):
parser = argparse.ArgumentParser()
parser.add_argument('--color', choices=self.Color)
args = parser.parse_args(['--color', 'red'])
self.assertEqual(args.color, self.Color.RED)
def test_help_message_contains_enum_choices(self):
parser = argparse.ArgumentParser()
parser.add_argument('--color', choices=self.Color, help='Choose a color')
self.assertIn('[--color {red,green,blue}]', parser.format_usage())
self.assertIn(' --color {red,green,blue}', parser.format_help())
def test_invalid_enum_value_raises_error(self):
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument('--color', choices=self.Color)
self.assertRaisesRegex(
argparse.ArgumentError,
r"invalid choice: 'yellow' \(choose from red, green, blue\)",
parser.parse_args,
['--color', 'yellow'],
)
# ================
# Positional tests
# ================
@ -2486,7 +2515,7 @@ class TestAddSubparsers(TestCase):
parser.parse_args(('baz',))
self.assertRegex(
excinfo.exception.stderr,
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from foo, bar\)\n$"
)
def test_optional_subparsers(self):