Permalink
Browse files

don't require a docstring option at all. This is better for one-off s…

…cripts.
  • Loading branch information...
1 parent b1adb99 commit f0eee5eb2461e1ee6a012294948435619a8517c0 Dusty Phillips committed Dec 2, 2012
Showing with 43 additions and 8 deletions.
  1. +12 −8 opterator.py
  2. +31 −0 test_opterator.py
View
@@ -69,10 +69,15 @@ def opterate(func):
kw_params = []
usage_text = ''
- parameters = []
+ parameters = {}
if func.__doc__:
- parameters = func.__doc__.split(':param')
- usage_text = parameters.pop(0).strip()
+ param_doc = func.__doc__.split(':param')
+ usage_text = param_doc.pop(0).strip()
+ parameters = {}
+ for param in param_doc:
+ param_args = param.split()
+ variable_name = param_args.pop(0)[:-1]
+ parameters[variable_name] = param_args
usage = "%prog [options]"
if positional_params:
@@ -83,15 +88,14 @@ def opterate(func):
option_names = []
parser = OptionParser(usage)
- for param in parameters:
+ for variable_name in kw_params:
option_strings = []
- param_args = param.split()
- variable_name = param_args.pop(0)[:-1]
+ param_args = parameters.get(variable_name, [])
option_names.append(variable_name)
- if not param_args[0].startswith('-'):
+ if not param_args or not param_args[0].startswith('-'):
option_strings.append('--' + variable_name)
option_strings.append('-' + variable_name[0])
- while param_args[0].startswith('-'):
+ while param_args and param_args[0].startswith('-'):
option_strings.append(param_args.pop(0))
help_text = ' '.join(param_args)
View
@@ -253,6 +253,37 @@ def main(myoption='novalue'):
the myoption helptext"""
+def test_keyword_option_no_identifier_docstring():
+ result = Checker()
+
+ @opterate
+ def main(myoption="novalue"):
+ '''A script with one optional option, but no parameter in docstring.'''
+ result.myoption = myoption
+ main(['--myoption', 'avalue'])
+ assert result.myoption == 'avalue'
+
+
+def test_keyword_option_no_identifier_docstring_helptext():
+ capture = py.io.StdCapture()
+
+ @opterate
+ def main(myoption='novalue'):
+ '''A script with one optional option, but no parameter in docstring.'''
+ print("never called")
+ py.test.raises(SystemExit, main, ['-h'])
+ out, error = capture.reset()
+ assert error == ''
+ print(out.strip())
+ assert out.strip() == """Usage: py.test [options]
+
+A script with one optional option, but no parameter in docstring.
+
+Options:
+ -h, --help show this help message and exit
+ -m MYOPTION, --myoption=MYOPTION"""
+
+
def test_keyword_list_option():
result = Checker()

0 comments on commit f0eee5e

Please sign in to comment.