Author: laukpe
Date: Tue Nov 25 10:24:42 2008
New Revision: 1112
Modified:
trunk/src/robot/__init__.py
trunk/src/robot/utils/argumentparser.py
trunk/utest/utils/test_argumentparser.py
Log:
cleanup, arg parser nowadayws automatically globs arguments
Modified: trunk/src/robot/__init__.py
==============================================================================
--- trunk/src/robot/__init__.py (original)
+++ trunk/src/robot/__init__.py Tue Nov 25 10:24:42 2008
@@ -13,9 +13,7 @@
# limitations under the License.
-from robot.errors import Information
import sys
-import glob
if __name__ == '__main__':
sys.stderr.write("Use 'runner' or 'rebot' for executing.\n")
@@ -56,8 +54,8 @@
suite = rebot(*datasources, **options)
except DataError:
_exit(DATA_ERROR, *utils.get_error_details())
- except (STOPPED_BY_USER, SystemExit):
- _exit(DATA_ERROR, 'Log/report generation stopped by user')
+ except (KeyboardInterrupt, SystemExit):
+ _exit(STOPPED_BY_USER, 'Log/report generation stopped by user')
except:
_exit(FRAMEWORK_ERROR, 'Unexpected error in log/report generation',
'\n'.join(utils.get_error_details()))
@@ -137,30 +135,16 @@
def _process_arguments(cliargs, usage, who):
ap = utils.ArgumentParser(usage % {'VERSION': utils.get_version()},
utils.get_full_version(who))
- ppath = who == 'Robot' and 'pythonpath' or None
try:
- opts, args = ap.parse_args(cliargs, argfile='argumentfile',
- unescape='escape', pythonpath=ppath,
- help='help', version='version',
check_args=True)
+ return ap.parse_args(cliargs, argfile='argumentfile',
unescape='escape',
+ pythonpath=who == 'Robot' and 'pythonpath' or
None,
+ help='help', version='version',
check_args=True)
except Information, msg:
print msg
_exit(INFO_PRINTED)
except DataError, err:
_exit(DATA_ERROR, str(err))
- return opts, _glob_datasources(args)
-
-def _glob_datasources(sources):
- # TODO: move to argumentparser
- temp = []
- for path in sources:
- paths = glob.glob(path)
- if paths:
- temp.extend(paths)
- else:
- temp.append(path)
- return temp
-
def _exit(rc_or_suite, error=None, details=None):
"""Exits with given rc or rc from given output. Syslogs error if given.
Modified: trunk/src/robot/utils/argumentparser.py
==============================================================================
--- trunk/src/robot/utils/argumentparser.py (original)
+++ trunk/src/robot/utils/argumentparser.py Tue Nov 25 10:24:42 2008
@@ -20,37 +20,19 @@
import glob
import string
-from robot.errors import DataError, FrameworkError, Information
+from robot.errors import DataError, Information, FrameworkError
from misc import seq2str, plural_or_not
from robottypes import is_list, is_boolean
-ESCAPES = { 'space' : ' ',
- 'apos' : "'",
- 'quot' : '"',
- 'lt' : '<',
- 'gt' : '>',
- 'pipe' : '|',
- 'star' : '*',
- 'comma' : ',',
- 'bslash' : '\\',
- 'slash' : '/',
- 'semic' : ';',
- 'colon' : ':',
- 'quest' : '?',
- 'hash' : '#',
- 'amp' : '&',
- 'dollar' : '$',
- 'percent' : '%',
- 'at' : '@',
- 'exclam' : '!',
- 'paren1' : '(',
- 'paren2' : ')',
- 'square1' : '[',
- 'square2' : ']',
- 'curly1' : '{',
- 'curly2' : '}',
-}
+
+ESCAPES =
{ 'space' : ' ', 'apos' : "'", 'quot' : '"', 'lt' : '<',
+ 'gt' : '>', 'pipe' : '|', 'star' : '*', 'comma' : ',',
+ 'slash' : '/', 'semic' : ';', 'colon' : ':', 'quest' : '?',
+ 'hash' : '#', 'amp' : '&', 'dollar' : '$', 'percent' : '%',
+ 'at' : '@', 'exclam' : '!', 'paren1' : '(', 'paren2' : ')',
+ 'square1' : '[', 'square2' : ']', 'curly1' : '{', 'curly2' : '}',
+ 'bslash' : '\\' }
def get_escapes():
@@ -151,11 +133,10 @@
def _parse_args(self, args):
args = [ a.startswith('--') and a.lower() or a for a in args ]
try:
- opt_tuple, args = getopt.getopt(args, self._short_opts,
self._long_opts)
+ opts, args = getopt.getopt(args, self._short_opts,
self._long_opts)
except getopt.GetoptError, err:
raise DataError(err)
- opts = self._process_opts(opt_tuple)
- return opts, args
+ return self._process_opts(opts), self._glob_args(args)
def check_args(self, args):
if len(args) == len(self._expected_args):
@@ -167,10 +148,9 @@
else:
msg = 'Too many arguments.'
msg += ' Expected %s' % seq2str(self._expected_args)
- if len(args) > 0:
+ if args:
msg += ' but got %s' % seq2str(args)
- msg += '.'
- raise DataError(msg)
+ raise DataError(msg + '.')
def _unescape_opts_and_args(self, opts, args, escape_opt):
try:
@@ -185,20 +165,19 @@
return opts, args
def _add_args_from_file(self, args, argfile_opt):
- argfile_opts = [ '--'+argfile_opt ]
+ argfile_opts = ['--'+argfile_opt]
for sopt, lopt in self._short_to_long.items():
if lopt == argfile_opt:
argfile_opts.append('-'+sopt)
- index = -1
- path = None
for opt in argfile_opts:
try:
index = args.index(opt)
path = args[index+1]
+ except (ValueError, IndexError):
+ path = None
+ else:
break
- except:
- pass
- if path is not None:
+ if path:
args[index:index+2] = self._get_args_from_file(path)
return args
@@ -208,13 +187,11 @@
except IOError, err:
raise DataError("Opening argument file '%s' failed: %s" %
(path, err))
args = []
- for line in argfile.read().splitlines():
+ for line in argfile.readlines():
line = line.strip()
- if line == '' or line.startswith('#'):
- continue
- elif line.startswith('-'):
+ if line.startswith('-'):
args.extend(line.split(' ', 1))
- else:
+ elif line and not line.startswith('#'):
args.append(line)
argfile.close()
return args
@@ -254,6 +231,16 @@
else:
opts[name] = value
return opts
+
+ def _glob_args(self, args):
+ temp = []
+ for path in args:
+ paths = glob.glob(path)
+ if paths:
+ temp.extend(paths)
+ else:
+ temp.append(path)
+ return temp
def _init_opts(self):
opts = {}
Modified: trunk/utest/utils/test_argumentparser.py
==============================================================================
--- trunk/utest/utils/test_argumentparser.py (original)
+++ trunk/utest/utils/test_argumentparser.py Tue Nov 25 10:24:42 2008
@@ -5,7 +5,8 @@
from robot.utils.asserts import *
from robot.errors import *
-usage = """
+
+USAGE = """
usage: robot.py [options] datafile
options:
@@ -30,7 +31,7 @@
* denotes options that can be set multiple times
"""
-usage2 = """
+USAGE2 = """
usage: robot.py [options] arg1 arg2
options:
@@ -42,7 +43,7 @@
class TestArgumentParserInit(unittest.TestCase):
def setUp(self):
- self.ap = ArgumentParser(usage)
+ self.ap = ArgumentParser(USAGE)
def test_short_options(self):
assert_equals(self.ap._short_opts, 'd:r:E:v:N:h?')
@@ -77,7 +78,7 @@
class TestArgumentParserParseArgs(unittest.TestCase):
def setUp(self):
- self.ap = ArgumentParser(usage)
+ self.ap = ArgumentParser(USAGE)
def test_single_options(self):
inargs = '-d reports --reportfile report.html -? arg'.split()
@@ -117,7 +118,7 @@
assert_equals(args, ['arg'])
def test_non_ascii_chars(self):
- ap = ArgumentParser(usage2)
+ ap = ArgumentParser(USAGE2)
inargs = '-x foo=bar --variable a=1,2,3 arg1 arg2'.split()
exp_opts = { 'var-able':'foo=bar', 'variable':'a=1,2,3' }
exp_args = [ 'arg1', 'arg2' ]
@@ -172,14 +173,24 @@
assert_equals(ap._get_pythonpath([p1 + ':' + p2]), [p1,p2])
assert_true(p1 in ap._get_pythonpath(os.path.join(p2,'*')))
+ def test_arguments_are_globbed(self):
+ _, args = self.ap.parse_args([__file__.replace('test_', '?????')])
+ assert_equals(args, [__file__])
+ _, args = self.ap.parse_args(['*'])
+ assert_true(len(args) > 1)
+
+ def
test_arguments_with_glob_patterns_arent_removed_if_they_dont_match(self):
+ _, args = self.ap.parse_args(['*.non.existing', 'non.ex.??'])
+ assert_equals(args, ['*.non.existing', 'non.ex.??'])
+
class TestPrintHelpAndVersion(unittest.TestCase):
def setUp(self):
- self.ap = ArgumentParser(usage, version='testing 1.0')
+ self.ap = ArgumentParser(USAGE, version='testing 1.0')
def test_print_help(self):
- assert_raises_with_msg(Information, usage,
+ assert_raises_with_msg(Information, USAGE,
self.ap.parse_args, ['--help'], help='help')
def test_print_version(self):
@@ -187,7 +198,7 @@
self.ap.parse_args, ['--version'],
version='version')
def test_print_version_when_version_not_set(self):
- ap = ArgumentParser(usage)
+ ap = ArgumentParser(USAGE)
assert_raises_with_msg(Information, "No version information
available",
ap.parse_args, ['--version'],
version='version')