Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | # |
| 4 | # Test suite for Optik. Supplied by Johannes Gijsbers |
| 5 | # (taradino@softhome.net) -- translated from the original Optik |
| 6 | # test suite to this PyUnit-based version. |
| 7 | # |
| 8 | # $Id$ |
| 9 | # |
| 10 | |
| 11 | import sys |
| 12 | import os |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 13 | import re |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 14 | import copy |
| 15 | import unittest |
| 16 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 17 | from StringIO import StringIO |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 18 | from pprint import pprint |
| 19 | from test import test_support |
| 20 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 21 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 22 | from optparse import make_option, Option, IndentedHelpFormatter, \ |
| 23 | TitledHelpFormatter, OptionParser, OptionContainer, OptionGroup, \ |
| 24 | SUPPRESS_HELP, SUPPRESS_USAGE, OptionError, OptionConflictError, \ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 25 | BadOptionError, OptionValueError, Values |
| 26 | from optparse import _match_abbrev |
| 27 | from optparse import _parse_num |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 28 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 29 | retype = type(re.compile('')) |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 30 | |
| 31 | class InterceptedError(Exception): |
| 32 | def __init__(self, |
| 33 | error_message=None, |
| 34 | exit_status=None, |
| 35 | exit_message=None): |
| 36 | self.error_message = error_message |
| 37 | self.exit_status = exit_status |
| 38 | self.exit_message = exit_message |
| 39 | |
| 40 | def __str__(self): |
| 41 | return self.error_message or self.exit_message or "intercepted error" |
| 42 | |
| 43 | class InterceptingOptionParser(OptionParser): |
| 44 | def exit(self, status=0, msg=None): |
| 45 | raise InterceptedError(exit_status=status, exit_message=msg) |
| 46 | |
| 47 | def error(self, msg): |
| 48 | raise InterceptedError(error_message=msg) |
| 49 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 50 | |
| 51 | class BaseTest(unittest.TestCase): |
| 52 | def assertParseOK(self, args, expected_opts, expected_positional_args): |
| 53 | """Assert the options are what we expected when parsing arguments. |
| 54 | |
| 55 | Otherwise, fail with a nicely formatted message. |
| 56 | |
| 57 | Keyword arguments: |
| 58 | args -- A list of arguments to parse with OptionParser. |
| 59 | expected_opts -- The options expected. |
| 60 | expected_positional_args -- The positional arguments expected. |
| 61 | |
| 62 | Returns the options and positional args for further testing. |
| 63 | """ |
| 64 | |
| 65 | (options, positional_args) = self.parser.parse_args(args) |
| 66 | optdict = vars(options) |
| 67 | |
| 68 | self.assertEqual(optdict, expected_opts, |
| 69 | """ |
| 70 | Options are %(optdict)s. |
| 71 | Should be %(expected_opts)s. |
| 72 | Args were %(args)s.""" % locals()) |
| 73 | |
| 74 | self.assertEqual(positional_args, expected_positional_args, |
| 75 | """ |
| 76 | Positional arguments are %(positional_args)s. |
| 77 | Should be %(expected_positional_args)s. |
| 78 | Args were %(args)s.""" % locals ()) |
| 79 | |
| 80 | return (options, positional_args) |
| 81 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 82 | def assertRaises(self, |
| 83 | func, |
| 84 | args, |
| 85 | kwargs, |
| 86 | expected_exception, |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 87 | expected_message): |
| 88 | """ |
| 89 | Assert that the expected exception is raised when calling a |
| 90 | function, and that the right error message is included with |
| 91 | that exception. |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 92 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 93 | Arguments: |
| 94 | func -- the function to call |
| 95 | args -- positional arguments to `func` |
| 96 | kwargs -- keyword arguments to `func` |
| 97 | expected_exception -- exception that should be raised |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 98 | expected_message -- expected exception message (or pattern |
| 99 | if a compiled regex object) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 100 | |
| 101 | Returns the exception raised for further testing. |
| 102 | """ |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 103 | if args is None: |
| 104 | args = () |
| 105 | if kwargs is None: |
| 106 | kwargs = {} |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 107 | |
| 108 | try: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 109 | func(*args, **kwargs) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 110 | except expected_exception as err: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 111 | actual_message = str(err) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 112 | if isinstance(expected_message, retype): |
| 113 | self.assert_(expected_message.search(actual_message), |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 114 | """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 115 | expected exception message pattern: |
| 116 | /%s/ |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 117 | actual exception message: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 118 | '''%s''' |
| 119 | """ % (expected_message.pattern, actual_message)) |
| 120 | else: |
| 121 | self.assertEqual(actual_message, |
| 122 | expected_message, |
| 123 | """\ |
| 124 | expected exception message: |
| 125 | '''%s''' |
| 126 | actual exception message: |
| 127 | '''%s''' |
| 128 | """ % (expected_message, actual_message)) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 129 | |
| 130 | return err |
| 131 | else: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 132 | self.fail("""expected exception %(expected_exception)s not raised |
| 133 | called %(func)r |
| 134 | with args %(args)r |
| 135 | and kwargs %(kwargs)r |
| 136 | """ % locals ()) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 137 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 138 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 139 | # -- Assertions used in more than one class -------------------- |
| 140 | |
| 141 | def assertParseFail(self, cmdline_args, expected_output): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 142 | """ |
| 143 | Assert the parser fails with the expected message. Caller |
| 144 | must ensure that self.parser is an InterceptingOptionParser. |
| 145 | """ |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 146 | try: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 147 | self.parser.parse_args(cmdline_args) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 148 | except InterceptedError as err: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 149 | self.assertEqual(err.error_message, expected_output) |
| 150 | else: |
| 151 | self.assertFalse("expected parse failure") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 152 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 153 | def assertOutput(self, |
| 154 | cmdline_args, |
| 155 | expected_output, |
| 156 | expected_status=0, |
| 157 | expected_error=None): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 158 | """Assert the parser prints the expected output on stdout.""" |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 159 | save_stdout = sys.stdout |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 160 | encoding = getattr(save_stdout, 'encoding', None) |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 161 | try: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 162 | try: |
| 163 | sys.stdout = StringIO() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 164 | if encoding: |
| 165 | sys.stdout.encoding = encoding |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 166 | self.parser.parse_args(cmdline_args) |
| 167 | finally: |
| 168 | output = sys.stdout.getvalue() |
| 169 | sys.stdout = save_stdout |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 170 | |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 171 | except InterceptedError as err: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 172 | self.assert_( |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 173 | isinstance(output, str), |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 174 | "expected output to be an ordinary string, not %r" |
| 175 | % type(output)) |
| 176 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 177 | if output != expected_output: |
| 178 | self.fail("expected: \n'''\n" + expected_output + |
| 179 | "'''\nbut got \n'''\n" + output + "'''") |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 180 | self.assertEqual(err.exit_status, expected_status) |
| 181 | self.assertEqual(err.exit_message, expected_error) |
| 182 | else: |
| 183 | self.assertFalse("expected parser.exit()") |
| 184 | |
| 185 | def assertTypeError(self, func, expected_message, *args): |
| 186 | """Assert that TypeError is raised when executing func.""" |
| 187 | self.assertRaises(func, args, None, TypeError, expected_message) |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 188 | |
| 189 | def assertHelp(self, parser, expected_help): |
| 190 | actual_help = parser.format_help() |
| 191 | if actual_help != expected_help: |
| 192 | raise self.failureException( |
| 193 | 'help text failure; expected:\n"' + |
| 194 | expected_help + '"; got:\n"' + |
| 195 | actual_help + '"\n') |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 196 | |
| 197 | # -- Test make_option() aka Option ------------------------------------- |
| 198 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 199 | # It's not necessary to test correct options here. All the tests in the |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 200 | # parser.parse_args() section deal with those, because they're needed |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 201 | # there. |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 202 | |
| 203 | class TestOptionChecks(BaseTest): |
| 204 | def setUp(self): |
| 205 | self.parser = OptionParser(usage=SUPPRESS_USAGE) |
| 206 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 207 | def assertOptionError(self, expected_message, args=[], kwargs={}): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 208 | self.assertRaises(make_option, args, kwargs, |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 209 | OptionError, expected_message) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 210 | |
| 211 | def test_opt_string_empty(self): |
| 212 | self.assertTypeError(make_option, |
| 213 | "at least one option string must be supplied") |
| 214 | |
| 215 | def test_opt_string_too_short(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 216 | self.assertOptionError( |
| 217 | "invalid option string 'b': must be at least two characters long", |
| 218 | ["b"]) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 219 | |
| 220 | def test_opt_string_short_invalid(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 221 | self.assertOptionError( |
| 222 | "invalid short option string '--': must be " |
| 223 | "of the form -x, (x any non-dash char)", |
| 224 | ["--"]) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 225 | |
| 226 | def test_opt_string_long_invalid(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 227 | self.assertOptionError( |
| 228 | "invalid long option string '---': " |
| 229 | "must start with --, followed by non-dash", |
| 230 | ["---"]) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 231 | |
| 232 | def test_attr_invalid(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 233 | self.assertOptionError( |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 234 | "option -b: invalid keyword arguments: bar, foo", |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 235 | ["-b"], {'foo': None, 'bar': None}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 236 | |
| 237 | def test_action_invalid(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 238 | self.assertOptionError( |
| 239 | "option -b: invalid action: 'foo'", |
| 240 | ["-b"], {'action': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 241 | |
| 242 | def test_type_invalid(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 243 | self.assertOptionError( |
| 244 | "option -b: invalid option type: 'foo'", |
| 245 | ["-b"], {'type': 'foo'}) |
| 246 | self.assertOptionError( |
| 247 | "option -b: invalid option type: 'tuple'", |
| 248 | ["-b"], {'type': tuple}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 249 | |
| 250 | def test_no_type_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 251 | self.assertOptionError( |
| 252 | "option -b: must not supply a type for action 'count'", |
| 253 | ["-b"], {'action': 'count', 'type': 'int'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 254 | |
| 255 | def test_no_choices_list(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 256 | self.assertOptionError( |
| 257 | "option -b/--bad: must supply a list of " |
| 258 | "choices for type 'choice'", |
| 259 | ["-b", "--bad"], {'type': "choice"}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 260 | |
| 261 | def test_bad_choices_list(self): |
| 262 | typename = type('').__name__ |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 263 | self.assertOptionError( |
| 264 | "option -b/--bad: choices must be a list of " |
| 265 | "strings ('%s' supplied)" % typename, |
| 266 | ["-b", "--bad"], |
| 267 | {'type': "choice", 'choices':"bad choices"}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 268 | |
| 269 | def test_no_choices_for_type(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 270 | self.assertOptionError( |
| 271 | "option -b: must not supply choices for type 'int'", |
| 272 | ["-b"], {'type': 'int', 'choices':"bad"}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 273 | |
| 274 | def test_no_const_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 275 | self.assertOptionError( |
| 276 | "option -b: 'const' must not be supplied for action 'store'", |
| 277 | ["-b"], {'action': 'store', 'const': 1}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 278 | |
| 279 | def test_no_nargs_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 280 | self.assertOptionError( |
| 281 | "option -b: 'nargs' must not be supplied for action 'count'", |
| 282 | ["-b"], {'action': 'count', 'nargs': 2}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 283 | |
| 284 | def test_callback_not_callable(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 285 | self.assertOptionError( |
| 286 | "option -b: callback not callable: 'foo'", |
| 287 | ["-b"], {'action': 'callback', |
| 288 | 'callback': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 289 | |
| 290 | def dummy(self): |
| 291 | pass |
| 292 | |
| 293 | def test_callback_args_no_tuple(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 294 | self.assertOptionError( |
| 295 | "option -b: callback_args, if supplied, " |
| 296 | "must be a tuple: not 'foo'", |
| 297 | ["-b"], {'action': 'callback', |
| 298 | 'callback': self.dummy, |
| 299 | 'callback_args': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 300 | |
| 301 | def test_callback_kwargs_no_dict(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 302 | self.assertOptionError( |
| 303 | "option -b: callback_kwargs, if supplied, " |
| 304 | "must be a dict: not 'foo'", |
| 305 | ["-b"], {'action': 'callback', |
| 306 | 'callback': self.dummy, |
| 307 | 'callback_kwargs': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 308 | |
| 309 | def test_no_callback_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 310 | self.assertOptionError( |
| 311 | "option -b: callback supplied ('foo') for non-callback option", |
| 312 | ["-b"], {'action': 'store', |
| 313 | 'callback': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 314 | |
| 315 | def test_no_callback_args_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 316 | self.assertOptionError( |
| 317 | "option -b: callback_args supplied for non-callback option", |
| 318 | ["-b"], {'action': 'store', |
| 319 | 'callback_args': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 320 | |
| 321 | def test_no_callback_kwargs_for_action(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 322 | self.assertOptionError( |
| 323 | "option -b: callback_kwargs supplied for non-callback option", |
| 324 | ["-b"], {'action': 'store', |
| 325 | 'callback_kwargs': 'foo'}) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 326 | |
| 327 | class TestOptionParser(BaseTest): |
| 328 | def setUp(self): |
| 329 | self.parser = OptionParser() |
| 330 | self.parser.add_option("-v", "--verbose", "-n", "--noisy", |
| 331 | action="store_true", dest="verbose") |
| 332 | self.parser.add_option("-q", "--quiet", "--silent", |
| 333 | action="store_false", dest="verbose") |
| 334 | |
| 335 | def test_add_option_no_Option(self): |
| 336 | self.assertTypeError(self.parser.add_option, |
| 337 | "not an Option instance: None", None) |
| 338 | |
| 339 | def test_add_option_invalid_arguments(self): |
| 340 | self.assertTypeError(self.parser.add_option, |
| 341 | "invalid arguments", None, None) |
| 342 | |
| 343 | def test_get_option(self): |
| 344 | opt1 = self.parser.get_option("-v") |
| 345 | self.assert_(isinstance(opt1, Option)) |
| 346 | self.assertEqual(opt1._short_opts, ["-v", "-n"]) |
| 347 | self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"]) |
| 348 | self.assertEqual(opt1.action, "store_true") |
| 349 | self.assertEqual(opt1.dest, "verbose") |
| 350 | |
| 351 | def test_get_option_equals(self): |
| 352 | opt1 = self.parser.get_option("-v") |
| 353 | opt2 = self.parser.get_option("--verbose") |
| 354 | opt3 = self.parser.get_option("-n") |
| 355 | opt4 = self.parser.get_option("--noisy") |
| 356 | self.assert_(opt1 is opt2 is opt3 is opt4) |
| 357 | |
| 358 | def test_has_option(self): |
| 359 | self.assert_(self.parser.has_option("-v")) |
| 360 | self.assert_(self.parser.has_option("--verbose")) |
| 361 | |
| 362 | def assert_removed(self): |
| 363 | self.assert_(self.parser.get_option("-v") is None) |
| 364 | self.assert_(self.parser.get_option("--verbose") is None) |
| 365 | self.assert_(self.parser.get_option("-n") is None) |
| 366 | self.assert_(self.parser.get_option("--noisy") is None) |
| 367 | |
| 368 | self.failIf(self.parser.has_option("-v")) |
| 369 | self.failIf(self.parser.has_option("--verbose")) |
| 370 | self.failIf(self.parser.has_option("-n")) |
| 371 | self.failIf(self.parser.has_option("--noisy")) |
| 372 | |
| 373 | self.assert_(self.parser.has_option("-q")) |
| 374 | self.assert_(self.parser.has_option("--silent")) |
| 375 | |
| 376 | def test_remove_short_opt(self): |
| 377 | self.parser.remove_option("-n") |
| 378 | self.assert_removed() |
| 379 | |
| 380 | def test_remove_long_opt(self): |
| 381 | self.parser.remove_option("--verbose") |
| 382 | self.assert_removed() |
| 383 | |
| 384 | def test_remove_nonexistent(self): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 385 | self.assertRaises(self.parser.remove_option, ('foo',), None, |
| 386 | ValueError, "no such option 'foo'") |
| 387 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 388 | def test_refleak(self): |
| 389 | # If an OptionParser is carrying around a reference to a large |
| 390 | # object, various cycles can prevent it from being GC'd in |
| 391 | # a timely fashion. destroy() breaks the cycles to ensure stuff |
| 392 | # can be cleaned up. |
| 393 | big_thing = [42] |
| 394 | refcount = sys.getrefcount(big_thing) |
| 395 | parser = OptionParser() |
| 396 | parser.add_option("-a", "--aaarggh") |
| 397 | parser.big_thing = big_thing |
| 398 | |
| 399 | parser.destroy() |
| 400 | #self.assertEqual(refcount, sys.getrefcount(big_thing)) |
| 401 | del parser |
| 402 | self.assertEqual(refcount, sys.getrefcount(big_thing)) |
| 403 | |
| 404 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 405 | class TestOptionValues(BaseTest): |
| 406 | def setUp(self): |
| 407 | pass |
| 408 | |
| 409 | def test_basics(self): |
| 410 | values = Values() |
| 411 | self.assertEqual(vars(values), {}) |
| 412 | self.assertEqual(values, {}) |
| 413 | self.assertNotEqual(values, {"foo": "bar"}) |
| 414 | self.assertNotEqual(values, "") |
| 415 | |
| 416 | dict = {"foo": "bar", "baz": 42} |
| 417 | values = Values(defaults=dict) |
| 418 | self.assertEqual(vars(values), dict) |
| 419 | self.assertEqual(values, dict) |
| 420 | self.assertNotEqual(values, {"foo": "bar"}) |
| 421 | self.assertNotEqual(values, {}) |
| 422 | self.assertNotEqual(values, "") |
| 423 | self.assertNotEqual(values, []) |
| 424 | |
| 425 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 426 | class TestTypeAliases(BaseTest): |
| 427 | def setUp(self): |
| 428 | self.parser = OptionParser() |
| 429 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 430 | def test_str_aliases_string(self): |
| 431 | self.parser.add_option("-s", type="str") |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 432 | self.assertEquals(self.parser.get_option("-s").type, "string") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 433 | |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 434 | def test_type_object(self): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 435 | self.parser.add_option("-s", type=str) |
| 436 | self.assertEquals(self.parser.get_option("-s").type, "string") |
| 437 | self.parser.add_option("-x", type=int) |
| 438 | self.assertEquals(self.parser.get_option("-x").type, "int") |
| 439 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 440 | |
| 441 | # Custom type for testing processing of default values. |
| 442 | _time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 } |
| 443 | |
| 444 | def _check_duration(option, opt, value): |
| 445 | try: |
| 446 | if value[-1].isdigit(): |
| 447 | return int(value) |
| 448 | else: |
| 449 | return int(value[:-1]) * _time_units[value[-1]] |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 450 | except ValueError as IndexError: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 451 | raise OptionValueError( |
| 452 | 'option %s: invalid duration: %r' % (opt, value)) |
| 453 | |
| 454 | class DurationOption(Option): |
| 455 | TYPES = Option.TYPES + ('duration',) |
| 456 | TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) |
| 457 | TYPE_CHECKER['duration'] = _check_duration |
| 458 | |
| 459 | class TestDefaultValues(BaseTest): |
| 460 | def setUp(self): |
| 461 | self.parser = OptionParser() |
| 462 | self.parser.add_option("-v", "--verbose", default=True) |
| 463 | self.parser.add_option("-q", "--quiet", dest='verbose') |
| 464 | self.parser.add_option("-n", type="int", default=37) |
| 465 | self.parser.add_option("-m", type="int") |
| 466 | self.parser.add_option("-s", default="foo") |
| 467 | self.parser.add_option("-t") |
| 468 | self.parser.add_option("-u", default=None) |
| 469 | self.expected = { 'verbose': True, |
| 470 | 'n': 37, |
| 471 | 'm': None, |
| 472 | 's': "foo", |
| 473 | 't': None, |
| 474 | 'u': None } |
| 475 | |
| 476 | def test_basic_defaults(self): |
| 477 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 478 | |
| 479 | def test_mixed_defaults_post(self): |
| 480 | self.parser.set_defaults(n=42, m=-100) |
| 481 | self.expected.update({'n': 42, 'm': -100}) |
| 482 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 483 | |
| 484 | def test_mixed_defaults_pre(self): |
| 485 | self.parser.set_defaults(x="barf", y="blah") |
| 486 | self.parser.add_option("-x", default="frob") |
| 487 | self.parser.add_option("-y") |
| 488 | |
| 489 | self.expected.update({'x': "frob", 'y': "blah"}) |
| 490 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 491 | |
| 492 | self.parser.remove_option("-y") |
| 493 | self.parser.add_option("-y", default=None) |
| 494 | self.expected.update({'y': None}) |
| 495 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 496 | |
| 497 | def test_process_default(self): |
| 498 | self.parser.option_class = DurationOption |
| 499 | self.parser.add_option("-d", type="duration", default=300) |
| 500 | self.parser.add_option("-e", type="duration", default="6m") |
| 501 | self.parser.set_defaults(n="42") |
| 502 | self.expected.update({'d': 300, 'e': 360, 'n': 42}) |
| 503 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 504 | |
| 505 | self.parser.set_process_default_values(False) |
| 506 | self.expected.update({'d': 300, 'e': "6m", 'n': "42"}) |
| 507 | self.assertEqual(self.parser.get_default_values(), self.expected) |
| 508 | |
| 509 | |
| 510 | class TestProgName(BaseTest): |
| 511 | """ |
| 512 | Test that %prog expands to the right thing in usage, version, |
| 513 | and help strings. |
| 514 | """ |
| 515 | |
| 516 | def assertUsage(self, parser, expected_usage): |
| 517 | self.assertEqual(parser.get_usage(), expected_usage) |
| 518 | |
| 519 | def assertVersion(self, parser, expected_version): |
| 520 | self.assertEqual(parser.get_version(), expected_version) |
| 521 | |
| 522 | |
| 523 | def test_default_progname(self): |
| 524 | # Make sure that program name taken from sys.argv[0] by default. |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 525 | save_argv = sys.argv[:] |
| 526 | try: |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 527 | sys.argv[0] = os.path.join("foo", "bar", "baz.py") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 528 | parser = OptionParser("%prog ...", version="%prog 1.2") |
| 529 | expected_usage = "Usage: baz.py ...\n" |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 530 | self.assertUsage(parser, expected_usage) |
| 531 | self.assertVersion(parser, "baz.py 1.2") |
| 532 | self.assertHelp(parser, |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 533 | expected_usage + "\n" + |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 534 | "Options:\n" |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 535 | " --version show program's version number and exit\n" |
| 536 | " -h, --help show this help message and exit\n") |
Tim Peters | 579f735 | 2004-07-31 21:14:28 +0000 | [diff] [blame] | 537 | finally: |
| 538 | sys.argv[:] = save_argv |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 539 | |
| 540 | def test_custom_progname(self): |
| 541 | parser = OptionParser(prog="thingy", |
| 542 | version="%prog 0.1", |
| 543 | usage="%prog arg arg") |
| 544 | parser.remove_option("-h") |
| 545 | parser.remove_option("--version") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 546 | expected_usage = "Usage: thingy arg arg\n" |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 547 | self.assertUsage(parser, expected_usage) |
| 548 | self.assertVersion(parser, "thingy 0.1") |
| 549 | self.assertHelp(parser, expected_usage + "\n") |
| 550 | |
| 551 | |
| 552 | class TestExpandDefaults(BaseTest): |
| 553 | def setUp(self): |
| 554 | self.parser = OptionParser(prog="test") |
| 555 | self.help_prefix = """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 556 | Usage: test [options] |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 557 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 558 | Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 559 | -h, --help show this help message and exit |
| 560 | """ |
| 561 | self.file_help = "read from FILE [default: %default]" |
| 562 | self.expected_help_file = self.help_prefix + \ |
| 563 | " -f FILE, --file=FILE read from FILE [default: foo.txt]\n" |
| 564 | self.expected_help_none = self.help_prefix + \ |
| 565 | " -f FILE, --file=FILE read from FILE [default: none]\n" |
| 566 | |
| 567 | def test_option_default(self): |
| 568 | self.parser.add_option("-f", "--file", |
| 569 | default="foo.txt", |
| 570 | help=self.file_help) |
| 571 | self.assertHelp(self.parser, self.expected_help_file) |
| 572 | |
| 573 | def test_parser_default_1(self): |
| 574 | self.parser.add_option("-f", "--file", |
| 575 | help=self.file_help) |
| 576 | self.parser.set_default('file', "foo.txt") |
| 577 | self.assertHelp(self.parser, self.expected_help_file) |
| 578 | |
| 579 | def test_parser_default_2(self): |
| 580 | self.parser.add_option("-f", "--file", |
| 581 | help=self.file_help) |
| 582 | self.parser.set_defaults(file="foo.txt") |
| 583 | self.assertHelp(self.parser, self.expected_help_file) |
| 584 | |
| 585 | def test_no_default(self): |
| 586 | self.parser.add_option("-f", "--file", |
| 587 | help=self.file_help) |
| 588 | self.assertHelp(self.parser, self.expected_help_none) |
| 589 | |
| 590 | def test_default_none_1(self): |
| 591 | self.parser.add_option("-f", "--file", |
| 592 | default=None, |
| 593 | help=self.file_help) |
| 594 | self.assertHelp(self.parser, self.expected_help_none) |
Tim Peters | 10d59f3 | 2004-10-27 02:43:25 +0000 | [diff] [blame] | 595 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 596 | def test_default_none_2(self): |
| 597 | self.parser.add_option("-f", "--file", |
| 598 | help=self.file_help) |
| 599 | self.parser.set_defaults(file=None) |
| 600 | self.assertHelp(self.parser, self.expected_help_none) |
| 601 | |
| 602 | def test_float_default(self): |
| 603 | self.parser.add_option( |
| 604 | "-p", "--prob", |
| 605 | help="blow up with probability PROB [default: %default]") |
| 606 | self.parser.set_defaults(prob=0.43) |
| 607 | expected_help = self.help_prefix + \ |
| 608 | " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n" |
| 609 | self.assertHelp(self.parser, expected_help) |
| 610 | |
| 611 | def test_alt_expand(self): |
| 612 | self.parser.add_option("-f", "--file", |
| 613 | default="foo.txt", |
| 614 | help="read from FILE [default: *DEFAULT*]") |
| 615 | self.parser.formatter.default_tag = "*DEFAULT*" |
| 616 | self.assertHelp(self.parser, self.expected_help_file) |
| 617 | |
| 618 | def test_no_expand(self): |
| 619 | self.parser.add_option("-f", "--file", |
| 620 | default="foo.txt", |
| 621 | help="read from %default file") |
| 622 | self.parser.formatter.default_tag = None |
| 623 | expected_help = self.help_prefix + \ |
| 624 | " -f FILE, --file=FILE read from %default file\n" |
| 625 | self.assertHelp(self.parser, expected_help) |
| 626 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 627 | |
| 628 | # -- Test parser.parse_args() ------------------------------------------ |
| 629 | |
| 630 | class TestStandard(BaseTest): |
| 631 | def setUp(self): |
| 632 | options = [make_option("-a", type="string"), |
| 633 | make_option("-b", "--boo", type="int", dest='boo'), |
| 634 | make_option("--foo", action="append")] |
| 635 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 636 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
| 637 | option_list=options) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 638 | |
| 639 | def test_required_value(self): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 640 | self.assertParseFail(["-a"], "-a option requires an argument") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 641 | |
| 642 | def test_invalid_integer(self): |
| 643 | self.assertParseFail(["-b", "5x"], |
| 644 | "option -b: invalid integer value: '5x'") |
| 645 | |
| 646 | def test_no_such_option(self): |
| 647 | self.assertParseFail(["--boo13"], "no such option: --boo13") |
| 648 | |
| 649 | def test_long_invalid_integer(self): |
| 650 | self.assertParseFail(["--boo=x5"], |
| 651 | "option --boo: invalid integer value: 'x5'") |
| 652 | |
| 653 | def test_empty(self): |
| 654 | self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, []) |
| 655 | |
| 656 | def test_shortopt_empty_longopt_append(self): |
| 657 | self.assertParseOK(["-a", "", "--foo=blah", "--foo="], |
| 658 | {'a': "", 'boo': None, 'foo': ["blah", ""]}, |
| 659 | []) |
| 660 | |
| 661 | def test_long_option_append(self): |
| 662 | self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"], |
| 663 | {'a': None, |
| 664 | 'boo': None, |
| 665 | 'foo': ["bar", "", "x"]}, |
| 666 | []) |
| 667 | |
| 668 | def test_option_argument_joined(self): |
| 669 | self.assertParseOK(["-abc"], |
| 670 | {'a': "bc", 'boo': None, 'foo': None}, |
| 671 | []) |
| 672 | |
| 673 | def test_option_argument_split(self): |
| 674 | self.assertParseOK(["-a", "34"], |
| 675 | {'a': "34", 'boo': None, 'foo': None}, |
| 676 | []) |
| 677 | |
| 678 | def test_option_argument_joined_integer(self): |
| 679 | self.assertParseOK(["-b34"], |
| 680 | {'a': None, 'boo': 34, 'foo': None}, |
| 681 | []) |
| 682 | |
| 683 | def test_option_argument_split_negative_integer(self): |
| 684 | self.assertParseOK(["-b", "-5"], |
| 685 | {'a': None, 'boo': -5, 'foo': None}, |
| 686 | []) |
| 687 | |
| 688 | def test_long_option_argument_joined(self): |
| 689 | self.assertParseOK(["--boo=13"], |
| 690 | {'a': None, 'boo': 13, 'foo': None}, |
| 691 | []) |
| 692 | |
| 693 | def test_long_option_argument_split(self): |
| 694 | self.assertParseOK(["--boo", "111"], |
| 695 | {'a': None, 'boo': 111, 'foo': None}, |
| 696 | []) |
| 697 | |
| 698 | def test_long_option_short_option(self): |
| 699 | self.assertParseOK(["--foo=bar", "-axyz"], |
| 700 | {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, |
| 701 | []) |
| 702 | |
| 703 | def test_abbrev_long_option(self): |
| 704 | self.assertParseOK(["--f=bar", "-axyz"], |
| 705 | {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, |
| 706 | []) |
| 707 | |
| 708 | def test_defaults(self): |
| 709 | (options, args) = self.parser.parse_args([]) |
| 710 | defaults = self.parser.get_default_values() |
| 711 | self.assertEqual(vars(defaults), vars(options)) |
| 712 | |
| 713 | def test_ambiguous_option(self): |
| 714 | self.parser.add_option("--foz", action="store", |
| 715 | type="string", dest="foo") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 716 | self.assertParseFail(["--f=bar"], |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 717 | "ambiguous option: --f (--foo, --foz?)") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 718 | |
| 719 | |
| 720 | def test_short_and_long_option_split(self): |
| 721 | self.assertParseOK(["-a", "xyz", "--foo", "bar"], |
| 722 | {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, |
| 723 | []), |
| 724 | |
| 725 | def test_short_option_split_long_option_append(self): |
| 726 | self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"], |
| 727 | {'a': None, 'boo': 123, 'foo': ["bar", "baz"]}, |
| 728 | []) |
| 729 | |
| 730 | def test_short_option_split_one_positional_arg(self): |
| 731 | self.assertParseOK(["-a", "foo", "bar"], |
| 732 | {'a': "foo", 'boo': None, 'foo': None}, |
| 733 | ["bar"]), |
| 734 | |
| 735 | def test_short_option_consumes_separator(self): |
| 736 | self.assertParseOK(["-a", "--", "foo", "bar"], |
| 737 | {'a': "--", 'boo': None, 'foo': None}, |
| 738 | ["foo", "bar"]), |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 739 | self.assertParseOK(["-a", "--", "--foo", "bar"], |
| 740 | {'a': "--", 'boo': None, 'foo': ["bar"]}, |
| 741 | []), |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 742 | |
| 743 | def test_short_option_joined_and_separator(self): |
| 744 | self.assertParseOK(["-ab", "--", "--foo", "bar"], |
| 745 | {'a': "b", 'boo': None, 'foo': None}, |
| 746 | ["--foo", "bar"]), |
| 747 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 748 | def test_hyphen_becomes_positional_arg(self): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 749 | self.assertParseOK(["-ab", "-", "--foo", "bar"], |
| 750 | {'a': "b", 'boo': None, 'foo': ["bar"]}, |
| 751 | ["-"]) |
| 752 | |
| 753 | def test_no_append_versus_append(self): |
| 754 | self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"], |
| 755 | {'a': None, 'boo': 5, 'foo': ["bar", "baz"]}, |
| 756 | []) |
| 757 | |
| 758 | def test_option_consumes_optionlike_string(self): |
| 759 | self.assertParseOK(["-a", "-b3"], |
| 760 | {'a': "-b3", 'boo': None, 'foo': None}, |
| 761 | []) |
| 762 | |
| 763 | class TestBool(BaseTest): |
| 764 | def setUp(self): |
| 765 | options = [make_option("-v", |
| 766 | "--verbose", |
| 767 | action="store_true", |
| 768 | dest="verbose", |
| 769 | default=''), |
| 770 | make_option("-q", |
| 771 | "--quiet", |
| 772 | action="store_false", |
| 773 | dest="verbose")] |
| 774 | self.parser = OptionParser(option_list = options) |
| 775 | |
| 776 | def test_bool_default(self): |
| 777 | self.assertParseOK([], |
| 778 | {'verbose': ''}, |
| 779 | []) |
| 780 | |
| 781 | def test_bool_false(self): |
| 782 | (options, args) = self.assertParseOK(["-q"], |
| 783 | {'verbose': 0}, |
| 784 | []) |
| 785 | if hasattr(__builtins__, 'False'): |
| 786 | self.failUnless(options.verbose is False) |
| 787 | |
| 788 | def test_bool_true(self): |
| 789 | (options, args) = self.assertParseOK(["-v"], |
| 790 | {'verbose': 1}, |
| 791 | []) |
| 792 | if hasattr(__builtins__, 'True'): |
| 793 | self.failUnless(options.verbose is True) |
| 794 | |
| 795 | def test_bool_flicker_on_and_off(self): |
| 796 | self.assertParseOK(["-qvq", "-q", "-v"], |
| 797 | {'verbose': 1}, |
| 798 | []) |
| 799 | |
| 800 | class TestChoice(BaseTest): |
| 801 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 802 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 803 | self.parser.add_option("-c", action="store", type="choice", |
| 804 | dest="choice", choices=["one", "two", "three"]) |
| 805 | |
| 806 | def test_valid_choice(self): |
| 807 | self.assertParseOK(["-c", "one", "xyz"], |
| 808 | {'choice': 'one'}, |
| 809 | ["xyz"]) |
| 810 | |
| 811 | def test_invalid_choice(self): |
| 812 | self.assertParseFail(["-c", "four", "abc"], |
| 813 | "option -c: invalid choice: 'four' " |
| 814 | "(choose from 'one', 'two', 'three')") |
| 815 | |
| 816 | def test_add_choice_option(self): |
| 817 | self.parser.add_option("-d", "--default", |
| 818 | choices=["four", "five", "six"]) |
| 819 | opt = self.parser.get_option("-d") |
| 820 | self.assertEqual(opt.type, "choice") |
| 821 | self.assertEqual(opt.action, "store") |
| 822 | |
| 823 | class TestCount(BaseTest): |
| 824 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 825 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 826 | self.v_opt = make_option("-v", action="count", dest="verbose") |
| 827 | self.parser.add_option(self.v_opt) |
| 828 | self.parser.add_option("--verbose", type="int", dest="verbose") |
| 829 | self.parser.add_option("-q", "--quiet", |
| 830 | action="store_const", dest="verbose", const=0) |
| 831 | |
| 832 | def test_empty(self): |
| 833 | self.assertParseOK([], {'verbose': None}, []) |
| 834 | |
| 835 | def test_count_one(self): |
| 836 | self.assertParseOK(["-v"], {'verbose': 1}, []) |
| 837 | |
| 838 | def test_count_three(self): |
| 839 | self.assertParseOK(["-vvv"], {'verbose': 3}, []) |
| 840 | |
| 841 | def test_count_three_apart(self): |
| 842 | self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, []) |
| 843 | |
| 844 | def test_count_override_amount(self): |
| 845 | self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, []) |
| 846 | |
| 847 | def test_count_override_quiet(self): |
| 848 | self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, []) |
| 849 | |
| 850 | def test_count_overriding(self): |
| 851 | self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], |
| 852 | {'verbose': 1}, []) |
| 853 | |
| 854 | def test_count_interspersed_args(self): |
| 855 | self.assertParseOK(["--quiet", "3", "-v"], |
| 856 | {'verbose': 1}, |
| 857 | ["3"]) |
| 858 | |
| 859 | def test_count_no_interspersed_args(self): |
| 860 | self.parser.disable_interspersed_args() |
| 861 | self.assertParseOK(["--quiet", "3", "-v"], |
| 862 | {'verbose': 0}, |
| 863 | ["3", "-v"]) |
| 864 | |
| 865 | def test_count_no_such_option(self): |
| 866 | self.assertParseFail(["-q3", "-v"], "no such option: -3") |
| 867 | |
| 868 | def test_count_option_no_value(self): |
| 869 | self.assertParseFail(["--quiet=3", "-v"], |
| 870 | "--quiet option does not take a value") |
| 871 | |
| 872 | def test_count_with_default(self): |
| 873 | self.parser.set_default('verbose', 0) |
| 874 | self.assertParseOK([], {'verbose':0}, []) |
| 875 | |
| 876 | def test_count_overriding_default(self): |
| 877 | self.parser.set_default('verbose', 0) |
| 878 | self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], |
| 879 | {'verbose': 1}, []) |
| 880 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 881 | class TestMultipleArgs(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 882 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 883 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 884 | self.parser.add_option("-p", "--point", |
| 885 | action="store", nargs=3, type="float", dest="point") |
| 886 | |
| 887 | def test_nargs_with_positional_args(self): |
| 888 | self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"], |
| 889 | {'point': (1.0, 2.5, -4.3)}, |
| 890 | ["foo", "xyz"]) |
| 891 | |
| 892 | def test_nargs_long_opt(self): |
| 893 | self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"], |
| 894 | {'point': (-1.0, 2.5, -0.0)}, |
| 895 | ["xyz"]) |
| 896 | |
| 897 | def test_nargs_invalid_float_value(self): |
| 898 | self.assertParseFail(["-p", "1.0", "2x", "3.5"], |
| 899 | "option -p: " |
| 900 | "invalid floating-point value: '2x'") |
| 901 | |
| 902 | def test_nargs_required_values(self): |
| 903 | self.assertParseFail(["--point", "1.0", "3.5"], |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 904 | "--point option requires 3 arguments") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 905 | |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 906 | class TestMultipleArgsAppend(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 907 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 908 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 909 | self.parser.add_option("-p", "--point", action="store", nargs=3, |
| 910 | type="float", dest="point") |
| 911 | self.parser.add_option("-f", "--foo", action="append", nargs=2, |
| 912 | type="int", dest="foo") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 913 | self.parser.add_option("-z", "--zero", action="append_const", |
| 914 | dest="foo", const=(0, 0)) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 915 | |
| 916 | def test_nargs_append(self): |
| 917 | self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"], |
| 918 | {'point': None, 'foo': [(4, -3), (1, 666)]}, |
| 919 | ["blah"]) |
| 920 | |
| 921 | def test_nargs_append_required_values(self): |
| 922 | self.assertParseFail(["-f4,3"], |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 923 | "-f option requires 2 arguments") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 924 | |
| 925 | def test_nargs_append_simple(self): |
| 926 | self.assertParseOK(["--foo=3", "4"], |
| 927 | {'point': None, 'foo':[(3, 4)]}, |
| 928 | []) |
| 929 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 930 | def test_nargs_append_const(self): |
| 931 | self.assertParseOK(["--zero", "--foo", "3", "4", "-z"], |
| 932 | {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]}, |
| 933 | []) |
| 934 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 935 | class TestVersion(BaseTest): |
| 936 | def test_version(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 937 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
| 938 | version="%prog 0.1") |
| 939 | save_argv = sys.argv[:] |
| 940 | try: |
| 941 | sys.argv[0] = os.path.join(os.curdir, "foo", "bar") |
| 942 | self.assertOutput(["--version"], "bar 0.1\n") |
| 943 | finally: |
| 944 | sys.argv[:] = save_argv |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 945 | |
| 946 | def test_no_version(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 947 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 948 | self.assertParseFail(["--version"], |
| 949 | "no such option: --version") |
| 950 | |
| 951 | # -- Test conflicting default values and parser.parse_args() ----------- |
| 952 | |
| 953 | class TestConflictingDefaults(BaseTest): |
| 954 | """Conflicting default values: the last one should win.""" |
| 955 | def setUp(self): |
| 956 | self.parser = OptionParser(option_list=[ |
| 957 | make_option("-v", action="store_true", dest="verbose", default=1)]) |
| 958 | |
| 959 | def test_conflict_default(self): |
| 960 | self.parser.add_option("-q", action="store_false", dest="verbose", |
| 961 | default=0) |
| 962 | self.assertParseOK([], {'verbose': 0}, []) |
| 963 | |
| 964 | def test_conflict_default_none(self): |
| 965 | self.parser.add_option("-q", action="store_false", dest="verbose", |
| 966 | default=None) |
| 967 | self.assertParseOK([], {'verbose': None}, []) |
| 968 | |
| 969 | class TestOptionGroup(BaseTest): |
| 970 | def setUp(self): |
| 971 | self.parser = OptionParser(usage=SUPPRESS_USAGE) |
| 972 | |
| 973 | def test_option_group_create_instance(self): |
| 974 | group = OptionGroup(self.parser, "Spam") |
| 975 | self.parser.add_option_group(group) |
| 976 | group.add_option("--spam", action="store_true", |
| 977 | help="spam spam spam spam") |
| 978 | self.assertParseOK(["--spam"], {'spam': 1}, []) |
| 979 | |
| 980 | def test_add_group_no_group(self): |
| 981 | self.assertTypeError(self.parser.add_option_group, |
| 982 | "not an OptionGroup instance: None", None) |
| 983 | |
| 984 | def test_add_group_invalid_arguments(self): |
| 985 | self.assertTypeError(self.parser.add_option_group, |
| 986 | "invalid arguments", None, None) |
| 987 | |
| 988 | def test_add_group_wrong_parser(self): |
| 989 | group = OptionGroup(self.parser, "Spam") |
| 990 | group.parser = OptionParser() |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 991 | self.assertRaises(self.parser.add_option_group, (group,), None, |
| 992 | ValueError, "invalid OptionGroup (wrong parser)") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 993 | |
| 994 | def test_group_manipulate(self): |
| 995 | group = self.parser.add_option_group("Group 2", |
| 996 | description="Some more options") |
| 997 | group.set_title("Bacon") |
| 998 | group.add_option("--bacon", type="int") |
| 999 | self.assert_(self.parser.get_option_group("--bacon"), group) |
| 1000 | |
| 1001 | # -- Test extending and parser.parse_args() ---------------------------- |
| 1002 | |
| 1003 | class TestExtendAddTypes(BaseTest): |
| 1004 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1005 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
| 1006 | option_class=self.MyOption) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1007 | self.parser.add_option("-a", None, type="string", dest="a") |
| 1008 | self.parser.add_option("-f", "--file", type="file", dest="file") |
| 1009 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1010 | def tearDown(self): |
| 1011 | if os.path.isdir(test_support.TESTFN): |
| 1012 | os.rmdir(test_support.TESTFN) |
| 1013 | elif os.path.isfile(test_support.TESTFN): |
| 1014 | os.unlink(test_support.TESTFN) |
| 1015 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1016 | class MyOption (Option): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1017 | def check_file(option, opt, value): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1018 | if not os.path.exists(value): |
| 1019 | raise OptionValueError("%s: file does not exist" % value) |
| 1020 | elif not os.path.isfile(value): |
| 1021 | raise OptionValueError("%s: not a regular file" % value) |
| 1022 | return value |
| 1023 | |
| 1024 | TYPES = Option.TYPES + ("file",) |
| 1025 | TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) |
| 1026 | TYPE_CHECKER["file"] = check_file |
| 1027 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1028 | def test_filetype_ok(self): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1029 | open(test_support.TESTFN, "w").close() |
| 1030 | self.assertParseOK(["--file", test_support.TESTFN, "-afoo"], |
| 1031 | {'file': test_support.TESTFN, 'a': 'foo'}, |
| 1032 | []) |
| 1033 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1034 | def test_filetype_noexist(self): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1035 | self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], |
| 1036 | "%s: file does not exist" % |
| 1037 | test_support.TESTFN) |
| 1038 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1039 | def test_filetype_notfile(self): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1040 | os.mkdir(test_support.TESTFN) |
| 1041 | self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], |
| 1042 | "%s: not a regular file" % |
| 1043 | test_support.TESTFN) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1044 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1045 | |
| 1046 | class TestExtendAddActions(BaseTest): |
| 1047 | def setUp(self): |
| 1048 | options = [self.MyOption("-a", "--apple", action="extend", |
| 1049 | type="string", dest="apple")] |
| 1050 | self.parser = OptionParser(option_list=options) |
| 1051 | |
| 1052 | class MyOption (Option): |
| 1053 | ACTIONS = Option.ACTIONS + ("extend",) |
| 1054 | STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) |
| 1055 | TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) |
| 1056 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1057 | def take_action(self, action, dest, opt, value, values, parser): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1058 | if action == "extend": |
| 1059 | lvalue = value.split(",") |
| 1060 | values.ensure_value(dest, []).extend(lvalue) |
| 1061 | else: |
| 1062 | Option.take_action(self, action, dest, opt, parser, value, |
| 1063 | values) |
| 1064 | |
| 1065 | def test_extend_add_action(self): |
| 1066 | self.assertParseOK(["-afoo,bar", "--apple=blah"], |
| 1067 | {'apple': ["foo", "bar", "blah"]}, |
| 1068 | []) |
| 1069 | |
| 1070 | def test_extend_add_action_normal(self): |
| 1071 | self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"], |
| 1072 | {'apple': ["foo", "bar", "x", "y"]}, |
| 1073 | []) |
| 1074 | |
| 1075 | # -- Test callbacks and parser.parse_args() ---------------------------- |
| 1076 | |
| 1077 | class TestCallback(BaseTest): |
| 1078 | def setUp(self): |
| 1079 | options = [make_option("-x", |
| 1080 | None, |
| 1081 | action="callback", |
| 1082 | callback=self.process_opt), |
| 1083 | make_option("-f", |
| 1084 | "--file", |
| 1085 | action="callback", |
| 1086 | callback=self.process_opt, |
| 1087 | type="string", |
| 1088 | dest="filename")] |
| 1089 | self.parser = OptionParser(option_list=options) |
| 1090 | |
| 1091 | def process_opt(self, option, opt, value, parser_): |
| 1092 | if opt == "-x": |
| 1093 | self.assertEqual(option._short_opts, ["-x"]) |
| 1094 | self.assertEqual(option._long_opts, []) |
| 1095 | self.assert_(parser_ is self.parser) |
| 1096 | self.assert_(value is None) |
| 1097 | self.assertEqual(vars(parser_.values), {'filename': None}) |
| 1098 | |
| 1099 | parser_.values.x = 42 |
| 1100 | elif opt == "--file": |
| 1101 | self.assertEqual(option._short_opts, ["-f"]) |
| 1102 | self.assertEqual(option._long_opts, ["--file"]) |
| 1103 | self.assert_(parser_ is self.parser) |
| 1104 | self.assertEqual(value, "foo") |
| 1105 | self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42}) |
| 1106 | |
| 1107 | setattr(parser_.values, option.dest, value) |
| 1108 | else: |
| 1109 | self.fail("Unknown option %r in process_opt." % opt) |
| 1110 | |
| 1111 | def test_callback(self): |
| 1112 | self.assertParseOK(["-x", "--file=foo"], |
| 1113 | {'filename': "foo", 'x': 42}, |
| 1114 | []) |
| 1115 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1116 | def test_callback_help(self): |
| 1117 | # This test was prompted by SF bug #960515 -- the point is |
| 1118 | # not to inspect the help text, just to make sure that |
| 1119 | # format_help() doesn't crash. |
| 1120 | parser = OptionParser(usage=SUPPRESS_USAGE) |
| 1121 | parser.remove_option("-h") |
| 1122 | parser.add_option("-t", "--test", action="callback", |
| 1123 | callback=lambda: None, type="string", |
| 1124 | help="foo") |
| 1125 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1126 | expected_help = ("Options:\n" |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1127 | " -t TEST, --test=TEST foo\n") |
| 1128 | self.assertHelp(parser, expected_help) |
| 1129 | |
| 1130 | |
| 1131 | class TestCallbackExtraArgs(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1132 | def setUp(self): |
| 1133 | options = [make_option("-p", "--point", action="callback", |
| 1134 | callback=self.process_tuple, |
| 1135 | callback_args=(3, int), type="string", |
| 1136 | dest="points", default=[])] |
| 1137 | self.parser = OptionParser(option_list=options) |
| 1138 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1139 | def process_tuple(self, option, opt, value, parser_, len, type): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1140 | self.assertEqual(len, 3) |
| 1141 | self.assert_(type is int) |
| 1142 | |
| 1143 | if opt == "-p": |
| 1144 | self.assertEqual(value, "1,2,3") |
| 1145 | elif opt == "--point": |
| 1146 | self.assertEqual(value, "4,5,6") |
| 1147 | |
| 1148 | value = tuple(map(type, value.split(","))) |
| 1149 | getattr(parser_.values, option.dest).append(value) |
| 1150 | |
| 1151 | def test_callback_extra_args(self): |
| 1152 | self.assertParseOK(["-p1,2,3", "--point", "4,5,6"], |
| 1153 | {'points': [(1,2,3), (4,5,6)]}, |
| 1154 | []) |
| 1155 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1156 | class TestCallbackMeddleArgs(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1157 | def setUp(self): |
| 1158 | options = [make_option(str(x), action="callback", |
| 1159 | callback=self.process_n, dest='things') |
| 1160 | for x in range(-1, -6, -1)] |
| 1161 | self.parser = OptionParser(option_list=options) |
| 1162 | |
| 1163 | # Callback that meddles in rargs, largs |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1164 | def process_n(self, option, opt, value, parser_): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1165 | # option is -3, -5, etc. |
| 1166 | nargs = int(opt[1:]) |
| 1167 | rargs = parser_.rargs |
| 1168 | if len(rargs) < nargs: |
| 1169 | self.fail("Expected %d arguments for %s option." % (nargs, opt)) |
| 1170 | dest = parser_.values.ensure_value(option.dest, []) |
| 1171 | dest.append(tuple(rargs[0:nargs])) |
| 1172 | parser_.largs.append(nargs) |
| 1173 | del rargs[0:nargs] |
| 1174 | |
| 1175 | def test_callback_meddle_args(self): |
| 1176 | self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"], |
| 1177 | {'things': [("foo",), ("bar", "baz", "qux")]}, |
| 1178 | [1, 3]) |
| 1179 | |
| 1180 | def test_callback_meddle_args_separator(self): |
| 1181 | self.assertParseOK(["-2", "foo", "--"], |
| 1182 | {'things': [('foo', '--')]}, |
| 1183 | [2]) |
| 1184 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1185 | class TestCallbackManyArgs(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1186 | def setUp(self): |
| 1187 | options = [make_option("-a", "--apple", action="callback", nargs=2, |
| 1188 | callback=self.process_many, type="string"), |
| 1189 | make_option("-b", "--bob", action="callback", nargs=3, |
| 1190 | callback=self.process_many, type="int")] |
| 1191 | self.parser = OptionParser(option_list=options) |
| 1192 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1193 | def process_many(self, option, opt, value, parser_): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1194 | if opt == "-a": |
| 1195 | self.assertEqual(value, ("foo", "bar")) |
| 1196 | elif opt == "--apple": |
| 1197 | self.assertEqual(value, ("ding", "dong")) |
| 1198 | elif opt == "-b": |
| 1199 | self.assertEqual(value, (1, 2, 3)) |
| 1200 | elif opt == "--bob": |
| 1201 | self.assertEqual(value, (-666, 42, 0)) |
| 1202 | |
| 1203 | def test_many_args(self): |
| 1204 | self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong", |
| 1205 | "-b", "1", "2", "3", "--bob", "-666", "42", |
| 1206 | "0"], |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1207 | {"apple": None, "bob": None}, |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1208 | []) |
| 1209 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1210 | class TestCallbackCheckAbbrev(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1211 | def setUp(self): |
| 1212 | self.parser = OptionParser() |
| 1213 | self.parser.add_option("--foo-bar", action="callback", |
| 1214 | callback=self.check_abbrev) |
| 1215 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1216 | def check_abbrev(self, option, opt, value, parser): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1217 | self.assertEqual(opt, "--foo-bar") |
| 1218 | |
| 1219 | def test_abbrev_callback_expansion(self): |
| 1220 | self.assertParseOK(["--foo"], {}, []) |
| 1221 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1222 | class TestCallbackVarArgs(BaseTest): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1223 | def setUp(self): |
| 1224 | options = [make_option("-a", type="int", nargs=2, dest="a"), |
| 1225 | make_option("-b", action="store_true", dest="b"), |
| 1226 | make_option("-c", "--callback", action="callback", |
| 1227 | callback=self.variable_args, dest="c")] |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1228 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
| 1229 | option_list=options) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1230 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1231 | def variable_args(self, option, opt, value, parser): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1232 | self.assert_(value is None) |
| 1233 | done = 0 |
| 1234 | value = [] |
| 1235 | rargs = parser.rargs |
| 1236 | while rargs: |
| 1237 | arg = rargs[0] |
| 1238 | if ((arg[:2] == "--" and len(arg) > 2) or |
| 1239 | (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): |
| 1240 | break |
| 1241 | else: |
| 1242 | value.append(arg) |
| 1243 | del rargs[0] |
| 1244 | setattr(parser.values, option.dest, value) |
| 1245 | |
| 1246 | def test_variable_args(self): |
| 1247 | self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"], |
| 1248 | {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]}, |
| 1249 | []) |
| 1250 | |
| 1251 | def test_consume_separator_stop_at_option(self): |
| 1252 | self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"], |
| 1253 | {'a': None, |
| 1254 | 'b': True, |
| 1255 | 'c': ["37", "--", "xxx"]}, |
| 1256 | ["hello"]) |
| 1257 | |
| 1258 | def test_positional_arg_and_variable_args(self): |
| 1259 | self.assertParseOK(["hello", "-c", "foo", "-", "bar"], |
| 1260 | {'a': None, |
| 1261 | 'b': None, |
| 1262 | 'c':["foo", "-", "bar"]}, |
| 1263 | ["hello"]) |
| 1264 | |
| 1265 | def test_stop_at_option(self): |
| 1266 | self.assertParseOK(["-c", "foo", "-b"], |
| 1267 | {'a': None, 'b': True, 'c': ["foo"]}, |
| 1268 | []) |
| 1269 | |
| 1270 | def test_stop_at_invalid_option(self): |
| 1271 | self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5") |
| 1272 | |
| 1273 | |
| 1274 | # -- Test conflict handling and parser.parse_args() -------------------- |
| 1275 | |
| 1276 | class ConflictBase(BaseTest): |
| 1277 | def setUp(self): |
| 1278 | options = [make_option("-v", "--verbose", action="count", |
| 1279 | dest="verbose", help="increment verbosity")] |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1280 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
| 1281 | option_list=options) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1282 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1283 | def show_version(self, option, opt, value, parser): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1284 | parser.values.show_version = 1 |
| 1285 | |
| 1286 | class TestConflict(ConflictBase): |
| 1287 | """Use the default conflict resolution for Optik 1.2: error.""" |
| 1288 | def assert_conflict_error(self, func): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1289 | err = self.assertRaises( |
| 1290 | func, ("-v", "--version"), {'action' : "callback", |
| 1291 | 'callback' : self.show_version, |
| 1292 | 'help' : "show version"}, |
| 1293 | OptionConflictError, |
| 1294 | "option -v/--version: conflicting option string(s): -v") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1295 | |
| 1296 | self.assertEqual(err.msg, "conflicting option string(s): -v") |
| 1297 | self.assertEqual(err.option_id, "-v/--version") |
| 1298 | |
| 1299 | def test_conflict_error(self): |
| 1300 | self.assert_conflict_error(self.parser.add_option) |
| 1301 | |
| 1302 | def test_conflict_error_group(self): |
| 1303 | group = OptionGroup(self.parser, "Group 1") |
| 1304 | self.assert_conflict_error(group.add_option) |
| 1305 | |
| 1306 | def test_no_such_conflict_handler(self): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1307 | self.assertRaises( |
| 1308 | self.parser.set_conflict_handler, ('foo',), None, |
| 1309 | ValueError, "invalid conflict_resolution value 'foo'") |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1310 | |
| 1311 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1312 | class TestConflictResolve(ConflictBase): |
| 1313 | def setUp(self): |
| 1314 | ConflictBase.setUp(self) |
| 1315 | self.parser.set_conflict_handler("resolve") |
| 1316 | self.parser.add_option("-v", "--version", action="callback", |
| 1317 | callback=self.show_version, help="show version") |
| 1318 | |
| 1319 | def test_conflict_resolve(self): |
| 1320 | v_opt = self.parser.get_option("-v") |
| 1321 | verbose_opt = self.parser.get_option("--verbose") |
| 1322 | version_opt = self.parser.get_option("--version") |
| 1323 | |
| 1324 | self.assert_(v_opt is version_opt) |
| 1325 | self.assert_(v_opt is not verbose_opt) |
| 1326 | self.assertEqual(v_opt._long_opts, ["--version"]) |
| 1327 | self.assertEqual(version_opt._short_opts, ["-v"]) |
| 1328 | self.assertEqual(version_opt._long_opts, ["--version"]) |
| 1329 | self.assertEqual(verbose_opt._short_opts, []) |
| 1330 | self.assertEqual(verbose_opt._long_opts, ["--verbose"]) |
| 1331 | |
| 1332 | def test_conflict_resolve_help(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1333 | self.assertOutput(["-h"], """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1334 | Options: |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1335 | --verbose increment verbosity |
| 1336 | -h, --help show this help message and exit |
| 1337 | -v, --version show version |
| 1338 | """) |
| 1339 | |
| 1340 | def test_conflict_resolve_short_opt(self): |
| 1341 | self.assertParseOK(["-v"], |
| 1342 | {'verbose': None, 'show_version': 1}, |
| 1343 | []) |
| 1344 | |
| 1345 | def test_conflict_resolve_long_opt(self): |
| 1346 | self.assertParseOK(["--verbose"], |
| 1347 | {'verbose': 1}, |
| 1348 | []) |
| 1349 | |
| 1350 | def test_conflict_resolve_long_opts(self): |
| 1351 | self.assertParseOK(["--verbose", "--version"], |
| 1352 | {'verbose': 1, 'show_version': 1}, |
| 1353 | []) |
| 1354 | |
| 1355 | class TestConflictOverride(BaseTest): |
| 1356 | def setUp(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1357 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1358 | self.parser.set_conflict_handler("resolve") |
| 1359 | self.parser.add_option("-n", "--dry-run", |
| 1360 | action="store_true", dest="dry_run", |
| 1361 | help="don't do anything") |
| 1362 | self.parser.add_option("--dry-run", "-n", |
| 1363 | action="store_const", const=42, dest="dry_run", |
| 1364 | help="dry run mode") |
| 1365 | |
| 1366 | def test_conflict_override_opts(self): |
| 1367 | opt = self.parser.get_option("--dry-run") |
| 1368 | self.assertEqual(opt._short_opts, ["-n"]) |
| 1369 | self.assertEqual(opt._long_opts, ["--dry-run"]) |
| 1370 | |
| 1371 | def test_conflict_override_help(self): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1372 | self.assertOutput(["-h"], """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1373 | Options: |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1374 | -h, --help show this help message and exit |
| 1375 | -n, --dry-run dry run mode |
| 1376 | """) |
| 1377 | |
| 1378 | def test_conflict_override_args(self): |
| 1379 | self.assertParseOK(["-n"], |
| 1380 | {'dry_run': 42}, |
| 1381 | []) |
| 1382 | |
| 1383 | # -- Other testing. ---------------------------------------------------- |
| 1384 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1385 | _expected_help_basic = """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1386 | Usage: bar.py [options] |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1387 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1388 | Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1389 | -a APPLE throw APPLEs at basket |
| 1390 | -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the |
| 1391 | evil spirits that cause trouble and mayhem) |
| 1392 | --foo=FOO store FOO in the foo list for later fooing |
| 1393 | -h, --help show this help message and exit |
| 1394 | """ |
| 1395 | |
| 1396 | _expected_help_long_opts_first = """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1397 | Usage: bar.py [options] |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1398 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1399 | Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1400 | -a APPLE throw APPLEs at basket |
| 1401 | --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the |
| 1402 | evil spirits that cause trouble and mayhem) |
| 1403 | --foo=FOO store FOO in the foo list for later fooing |
| 1404 | --help, -h show this help message and exit |
| 1405 | """ |
| 1406 | |
| 1407 | _expected_help_title_formatter = """\ |
| 1408 | Usage |
| 1409 | ===== |
| 1410 | bar.py [options] |
| 1411 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1412 | Options |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1413 | ======= |
| 1414 | -a APPLE throw APPLEs at basket |
| 1415 | --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the |
| 1416 | evil spirits that cause trouble and mayhem) |
| 1417 | --foo=FOO store FOO in the foo list for later fooing |
| 1418 | --help, -h show this help message and exit |
| 1419 | """ |
| 1420 | |
| 1421 | _expected_help_short_lines = """\ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1422 | Usage: bar.py [options] |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1423 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1424 | Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1425 | -a APPLE throw APPLEs at basket |
| 1426 | -b NUM, --boo=NUM shout "boo!" NUM times (in order to |
| 1427 | frighten away all the evil spirits |
| 1428 | that cause trouble and mayhem) |
| 1429 | --foo=FOO store FOO in the foo list for later |
| 1430 | fooing |
| 1431 | -h, --help show this help message and exit |
| 1432 | """ |
| 1433 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1434 | class TestHelp(BaseTest): |
| 1435 | def setUp(self): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1436 | self.parser = self.make_parser(80) |
| 1437 | |
| 1438 | def make_parser(self, columns): |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1439 | options = [ |
| 1440 | make_option("-a", type="string", dest='a', |
| 1441 | metavar="APPLE", help="throw APPLEs at basket"), |
| 1442 | make_option("-b", "--boo", type="int", dest='boo', |
| 1443 | metavar="NUM", |
| 1444 | help= |
| 1445 | "shout \"boo!\" NUM times (in order to frighten away " |
| 1446 | "all the evil spirits that cause trouble and mayhem)"), |
| 1447 | make_option("--foo", action="append", type="string", dest='foo', |
| 1448 | help="store FOO in the foo list for later fooing"), |
| 1449 | ] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1450 | |
| 1451 | # We need to set COLUMNS for the OptionParser constructor, but |
| 1452 | # we must restore its original value -- otherwise, this test |
| 1453 | # screws things up for other tests when it's part of the Python |
| 1454 | # test suite. |
| 1455 | orig_columns = os.environ.get('COLUMNS') |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1456 | os.environ['COLUMNS'] = str(columns) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1457 | try: |
| 1458 | return InterceptingOptionParser(option_list=options) |
| 1459 | finally: |
| 1460 | if orig_columns is None: |
| 1461 | del os.environ['COLUMNS'] |
| 1462 | else: |
| 1463 | os.environ['COLUMNS'] = orig_columns |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1464 | |
| 1465 | def assertHelpEquals(self, expected_output): |
Greg Ward | 48aa84b | 2004-10-27 02:20:04 +0000 | [diff] [blame] | 1466 | save_argv = sys.argv[:] |
| 1467 | try: |
| 1468 | # Make optparse believe bar.py is being executed. |
| 1469 | sys.argv[0] = os.path.join("foo", "bar.py") |
| 1470 | self.assertOutput(["-h"], expected_output) |
| 1471 | finally: |
| 1472 | sys.argv[:] = save_argv |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1473 | |
| 1474 | def test_help(self): |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1475 | self.assertHelpEquals(_expected_help_basic) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1476 | |
| 1477 | def test_help_old_usage(self): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1478 | self.parser.set_usage("Usage: %prog [options]") |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1479 | self.assertHelpEquals(_expected_help_basic) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1480 | |
| 1481 | def test_help_long_opts_first(self): |
| 1482 | self.parser.formatter.short_first = 0 |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1483 | self.assertHelpEquals(_expected_help_long_opts_first) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1484 | |
| 1485 | def test_help_title_formatter(self): |
Thomas Wouters | fc7bb8c | 2007-01-15 15:49:28 +0000 | [diff] [blame] | 1486 | save = os.environ.get("COLUMNS") |
| 1487 | try: |
| 1488 | os.environ["COLUMNS"] = "80" |
| 1489 | self.parser.formatter = TitledHelpFormatter() |
| 1490 | self.assertHelpEquals(_expected_help_title_formatter) |
| 1491 | finally: |
| 1492 | if save is not None: |
| 1493 | os.environ["COLUMNS"] = save |
| 1494 | else: |
| 1495 | del os.environ["COLUMNS"] |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1496 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1497 | def test_wrap_columns(self): |
| 1498 | # Ensure that wrapping respects $COLUMNS environment variable. |
| 1499 | # Need to reconstruct the parser, since that's the only time |
| 1500 | # we look at $COLUMNS. |
| 1501 | self.parser = self.make_parser(60) |
| 1502 | self.assertHelpEquals(_expected_help_short_lines) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1503 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1504 | def test_help_unicode(self): |
| 1505 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1506 | self.parser.add_option("-a", action="store_true", help="ol\u00E9!") |
| 1507 | expect = """\ |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1508 | Options: |
| 1509 | -h, --help show this help message and exit |
| 1510 | -a ol\u00E9! |
| 1511 | """ |
| 1512 | self.assertHelpEquals(expect) |
| 1513 | |
| 1514 | def test_help_unicode_description(self): |
| 1515 | self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 1516 | description="ol\u00E9!") |
| 1517 | expect = """\ |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1518 | ol\u00E9! |
| 1519 | |
| 1520 | Options: |
| 1521 | -h, --help show this help message and exit |
| 1522 | """ |
| 1523 | self.assertHelpEquals(expect) |
| 1524 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1525 | def test_help_description_groups(self): |
| 1526 | self.parser.set_description( |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1527 | "This is the program description for %prog. %prog has " |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1528 | "an option group as well as single options.") |
| 1529 | |
| 1530 | group = OptionGroup( |
| 1531 | self.parser, "Dangerous Options", |
| 1532 | "Caution: use of these options is at your own risk. " |
| 1533 | "It is believed that some of them bite.") |
| 1534 | group.add_option("-g", action="store_true", help="Group option.") |
| 1535 | self.parser.add_option_group(group) |
| 1536 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1537 | expect = """\ |
| 1538 | Usage: bar.py [options] |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1539 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1540 | This is the program description for bar.py. bar.py has an option group as |
| 1541 | well as single options. |
| 1542 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1543 | Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1544 | -a APPLE throw APPLEs at basket |
| 1545 | -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the |
| 1546 | evil spirits that cause trouble and mayhem) |
| 1547 | --foo=FOO store FOO in the foo list for later fooing |
| 1548 | -h, --help show this help message and exit |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1549 | |
| 1550 | Dangerous Options: |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1551 | Caution: use of these options is at your own risk. It is believed |
| 1552 | that some of them bite. |
| 1553 | |
| 1554 | -g Group option. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1555 | """ |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1556 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1557 | self.assertHelpEquals(expect) |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1558 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1559 | self.parser.epilog = "Please report bugs to /dev/null." |
| 1560 | self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n") |
Tim Peters | 10d59f3 | 2004-10-27 02:43:25 +0000 | [diff] [blame] | 1561 | |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1562 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1563 | class TestMatchAbbrev(BaseTest): |
| 1564 | def test_match_abbrev(self): |
| 1565 | self.assertEqual(_match_abbrev("--f", |
| 1566 | {"--foz": None, |
| 1567 | "--foo": None, |
| 1568 | "--fie": None, |
| 1569 | "--f": None}), |
| 1570 | "--f") |
| 1571 | |
| 1572 | def test_match_abbrev_error(self): |
| 1573 | s = "--f" |
| 1574 | wordmap = {"--foz": None, "--foo": None, "--fie": None} |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1575 | self.assertRaises( |
| 1576 | _match_abbrev, (s, wordmap), None, |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 1577 | BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)") |
Greg Ward | eba20e6 | 2004-07-31 16:15:44 +0000 | [diff] [blame] | 1578 | |
| 1579 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1580 | class TestParseNumber(BaseTest): |
| 1581 | def setUp(self): |
| 1582 | self.parser = InterceptingOptionParser() |
| 1583 | self.parser.add_option("-n", type=int) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 1584 | self.parser.add_option("-l", type=int) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1585 | |
| 1586 | def test_parse_num_fail(self): |
| 1587 | self.assertRaises( |
| 1588 | _parse_num, ("", int), {}, |
| 1589 | ValueError, |
| 1590 | re.compile(r"invalid literal for int().*: '?'?")) |
| 1591 | self.assertRaises( |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 1592 | _parse_num, ("0xOoops", int), {}, |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1593 | ValueError, |
Guido van Rossum | b4e87e3 | 2007-07-09 10:08:42 +0000 | [diff] [blame] | 1594 | re.compile(r"invalid literal for int().*: s?'?0xOoops'?")) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1595 | |
| 1596 | def test_parse_num_ok(self): |
| 1597 | self.assertEqual(_parse_num("0", int), 0) |
| 1598 | self.assertEqual(_parse_num("0x10", int), 16) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 1599 | self.assertEqual(_parse_num("0XA", int), 10) |
| 1600 | self.assertEqual(_parse_num("010", int), 8) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1601 | self.assertEqual(_parse_num("0b11", int), 3) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 1602 | self.assertEqual(_parse_num("0b", int), 0) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1603 | |
| 1604 | def test_numeric_options(self): |
| 1605 | self.assertParseOK(["-n", "42", "-l", "0x20"], |
| 1606 | { "n": 42, "l": 0x20 }, []) |
| 1607 | self.assertParseOK(["-n", "0b0101", "-l010"], |
| 1608 | { "n": 5, "l": 8 }, []) |
| 1609 | self.assertParseFail(["-n008"], |
| 1610 | "option -n: invalid integer value: '008'") |
| 1611 | self.assertParseFail(["-l0b0123"], |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 1612 | "option -l: invalid integer value: '0b0123'") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1613 | self.assertParseFail(["-l", "0x12x"], |
Guido van Rossum | ddefaf3 | 2007-01-14 03:31:43 +0000 | [diff] [blame] | 1614 | "option -l: invalid integer value: '0x12x'") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1615 | |
| 1616 | |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1617 | def test_main(): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1618 | test_support.run_unittest(__name__) |
Greg Ward | 5549322 | 2003-04-21 02:41:25 +0000 | [diff] [blame] | 1619 | |
| 1620 | if __name__ == '__main__': |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1621 | test_main() |