ยปCore Development>Code coverage>Lib/test/test_optparse.py

Python code coverage for Lib/test/test_optparse.py

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