@@ -140,6 +140,48 @@ def test_parse_args(self):
140140 )
141141
142142
143+ class TestArgumentParserCopiable (unittest .TestCase ):
144+ def _get_parser (self ):
145+ parser = argparse .ArgumentParser (exit_on_error = False )
146+ parser .add_argument ('--foo' , type = int , default = 42 )
147+ parser .add_argument ('bar' , nargs = '?' , default = 'baz' )
148+ return parser
149+
150+ @force_not_colorized
151+ def test_copiable (self ):
152+ import copy
153+ parser = self ._get_parser ()
154+ parser2 = copy .copy (parser )
155+ ns = parser2 .parse_args (['--foo' , '123' , 'quux' ])
156+ self .assertEqual (ns .foo , 123 )
157+ self .assertEqual (ns .bar , 'quux' )
158+ ns2 = parser2 .parse_args ([])
159+ self .assertEqual (ns2 .foo , 42 )
160+ self .assertEqual (ns2 .bar , 'baz' )
161+
162+ # Test shallow copy also gets new arguments
163+ parser .add_argument ("--extra" )
164+ ns3 = parser2 .parse_args (["--extra" , "bar" ])
165+ self .assertEqual (ns3 .extra , "bar" )
166+
167+ @force_not_colorized
168+ def test_deepcopiable (self ):
169+ import copy
170+ parser = self ._get_parser ()
171+ parser2 = copy .deepcopy (parser )
172+ ns = parser2 .parse_args (['--foo' , '123' , 'quux' ])
173+ self .assertEqual (ns .foo , 123 )
174+ self .assertEqual (ns .bar , 'quux' )
175+ ns2 = parser2 .parse_args ([])
176+ self .assertEqual (ns2 .foo , 42 )
177+ self .assertEqual (ns2 .bar , 'baz' )
178+
179+ # Test deep copy does not get new arguments
180+ parser .add_argument ("--extra" )
181+ with self .assertRaises (argparse .ArgumentError ):
182+ parser2 .parse_args (["--extra" , "bar" ])
183+
184+
143185class TestArgumentParserPickleable (unittest .TestCase ):
144186
145187 @force_not_colorized
@@ -7863,12 +7905,25 @@ def fake_can_colorize(*, file=None):
78637905
78647906 def test_fake_color_theme_matches_real (self ):
78657907 from argparse import _colorless_theme
7908+
7909+ # Check the attributes match those of the 'real' theme
78667910 _colorize_nocolor = _colorize .get_theme (force_no_color = True ).argparse
78677911 for k in _colorize_nocolor :
78687912 self .assertEqual (
78697913 getattr (_colorless_theme , k ), getattr (_colorize_nocolor , k )
78707914 )
78717915
7916+ def test_fake_color_theme_raises (self ):
7917+ from argparse import _colorless_theme
7918+
7919+ # Make sure the _colorless_theme doesn't return empty strings
7920+ # for magic methods or private attributes
7921+ with self .assertRaises (AttributeError ):
7922+ _colorless_theme .__unknown_dunder__
7923+
7924+ with self .assertRaises (AttributeError ):
7925+ _colorless_theme ._private_attribute
7926+
78727927
78737928class TestModule (unittest .TestCase ):
78747929 def test_deprecated__version__ (self ):
0 commit comments