コード例 #1
0
 def test_custom_validator_return_value(self):
     def validate(options, args):
         return options, [a.upper() for a in args]
     ap = ArgumentParser(USAGE2, validator=validate)
     opts, args = ap.parse_args(['-v', 'value', 'inp1', 'inp2'])
     assert_equals(opts['variable'], 'value')
     assert_equals(args, ['INP1', 'INP2'])
コード例 #2
0
 def test_arguments(self):
     os.environ['ROBOT_TEST_OPTIONS'] = '-o opt arg1 arg2'
     ap = ArgumentParser('Usage:\n -o --opt value',
                         env_options='ROBOT_TEST_OPTIONS')
     opts, args = ap.parse_args([])
     assert_equal(opts['opt'], 'opt')
     assert_equal(args, ['arg1', 'arg2'])
コード例 #3
0
    def setUp(self):
        os.environ['ROBOT_TEST_OPTIONS'] = '-t --value default -m1 --multi=2'
        self.ap = ArgumentParser('''Options:
 -t --toggle
 -v --value value
 -m --multi multi *
''', env_options='ROBOT_TEST_OPTIONS')
コード例 #4
0
 def test_arguments(self):
     os.environ['ROBOT_TEST_OPTIONS'] = '-o opt arg1 arg2'
     ap = ArgumentParser('Usage:\n -o --opt value',
                         env_options='ROBOT_TEST_OPTIONS')
     opts, args = ap.parse_args([])
     assert_equals(opts['opt'], 'opt')
     assert_equals(args, ['arg1', 'arg2'])
コード例 #5
0
def robot_options():
    arg_parser = ArgumentParser(USAGE,
                                auto_pythonpath=False,
                                auto_argumentfile=True,
                                env_options="ROBOT_OPTIONS")
    valid_args = filter_args(arg_parser)
    return arg_parser.parse_args(valid_args)[0]
コード例 #6
0
 def _robot_options(self):
     arg_parser = ArgumentParser(USAGE,
                                 auto_pythonpath=False,
                                 auto_argumentfile=True,
                                 env_options='ROBOT_OPTIONS')
     valid_args = self._filter_args(arg_parser)
     return arg_parser.parse_args(valid_args)[0]
コード例 #7
0
 def test_check_variable_number_of_args(self):
     ap = ArgumentParser('usage:  robot.py [options] args', arg_limits=(1,))
     ap.parse_args(['one_is_ok'])
     ap.parse_args(['two', 'ok'])
     ap.parse_args(['this', 'should', 'also', 'work', '!'])
     assert_raises_with_msg(DataError, "Expected at least 1 argument, got 0.",
                            ap.parse_args, [])
コード例 #8
0
 def test_custom_validator_return_value(self):
     def validate(options, args):
         return options, [a.upper() for a in args]
     ap = ArgumentParser(USAGE2, validator=validate)
     opts, args = ap.parse_args(['-v', 'value', 'inp1', 'inp2'])
     assert_equals(opts['variable'], 'value')
     assert_equals(args, ['INP1', 'INP2'])
コード例 #9
0
 def test_get_pythonpath(self):
     ap = ArgumentParser('ignored')
     p1 = os.path.abspath('.')
     p2 = os.path.abspath('..')
     assert_equals(ap._get_pythonpath(p1), [p1])
     assert_equals(ap._get_pythonpath([p1,p2]), [p1,p2])
     assert_equals(ap._get_pythonpath([p1 + ':' + p2]), [p1,p2])
     assert_true(p1 in ap._get_pythonpath(os.path.join(p2,'*')))
コード例 #10
0
 def test_non_ascii_chars(self):
     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', '42': False}
     exp_args = ['arg1', 'arg2']
     opts, args = ap.parse_args(inargs)
     assert_equals(opts, exp_opts)
     assert_equals(args, exp_args)
コード例 #11
0
    def test_special_options_are_removed(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --argumentfile path
 --option
''')
        opts, args = ap.parse_args(['--option'])
        assert_equal(opts, {'option': True})
コード例 #12
0
    def test_special_options_are_removed(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y *
 --argumentfile path
 --option
''')
        opts, args = ap.parse_args(['--option'])
        assert_equals(opts, {'option': True})
コード例 #13
0
 def test_flag_option_with_no_prefix(self):
     ap = ArgumentParser(' -S --nostatusrc\n --name name')
     for inargs, exp in [('', None), ('--name whatever', None),
                         ('--nostatusrc', False), ('-S', False),
                         ('--nostatusrc -S --nostatusrc -S -S', False),
                         ('--statusrc', True),
                         ('--statusrc --statusrc -S', False),
                         ('--nostatusrc --nostatusrc -S --statusrc', True)]:
         opts, args = ap.parse_args(inargs.split() + ['arg'])
         assert_equal(opts['statusrc'], exp, inargs)
         assert_equal(args, ['arg'])
コード例 #14
0
    def test_special_options_can_be_turned_to_normal_optios(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y
 --argumentfile path
''', auto_help=False, auto_version=False, auto_escape=False,
     auto_pythonpath=False, auto_argumentfile=False)
        opts, args = ap.parse_args(['--help', '-v', '--escape', 'xxx'])
        assert_equals(opts, {'help': True, 'version': True, 'pythonpath': None,
                             'escape': 'xxx', 'argumentfile': None})
コード例 #15
0
    def test_special_options_can_be_turned_to_normal_optios(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y
 --argumentfile path
''', auto_help=False, auto_version=False, auto_escape=False,
     auto_pythonpath=False, auto_argumentfile=False)
        opts, args = ap.parse_args(['--help', '-v', '--escape', 'xxx'])
        assert_equals(opts, {'help': True, 'version': True, 'pythonpath': None,
                             'escape': 'xxx', 'argumentfile': None})
コード例 #16
0
 def test_flag_option_with_no_prefix(self):
     ap = ArgumentParser(' -S --nostatusrc\n --name name')
     for inargs, exp in [('', None),
                         ('--name whatever', None),
                         ('--nostatusrc', False),
                         ('-S', False),
                         ('--nostatusrc -S --nostatusrc -S -S', False),
                         ('--statusrc', True),
                         ('--statusrc --statusrc -S', False),
                         ('--nostatusrc --nostatusrc -S --statusrc', True)]:
         opts, args = ap.parse_args(inargs.split() + ['arg'])
         assert_equals(opts['statusrc'], exp, inargs)
         assert_equals(args, ['arg'])
コード例 #17
0
 def test_split_pythonpath(self):
     ap = ArgumentParser('ignored')
     data = [(['path'], ['path']), (['path1', 'path2'], ['path1', 'path2']),
             (['path1:path2'], ['path1', 'path2']),
             (['p1:p2:p3', 'p4', '.'], ['p1', 'p2', 'p3', 'p4', '.'])]
     if os.sep == '\\':
         data += [(['c:\\path'], ['c:\\path']),
                  (['c:\\path', 'd:\\path'], ['c:\\path', 'd:\\path']),
                  (['c:\\path:d:\\path'], ['c:\\path', 'd:\\path']),
                  (['c:/path:x:yy:d:\\path', 'c', '.', 'x:/xxx'],
                   ['c:\\path', 'x', 'yy', 'd:\\path', 'c', '.',
                    'x:\\xxx'])]
     for inp, exp in data:
         assert_equals(ap._split_pythonpath(inp), exp)
コード例 #18
0
 def test_split_pythonpath(self):
     ap = ArgumentParser('ignored')
     data = [(['path'], ['path']),
             (['path1','path2'], ['path1','path2']),
             (['path1:path2'], ['path1','path2']),
             (['p1:p2:p3','p4','.'], ['p1','p2','p3','p4','.'])]
     if os.sep == '\\':
         data += [(['c:\\path'], ['c:\\path']),
                  (['c:\\path','d:\\path'], ['c:\\path','d:\\path']),
                  (['c:\\path:d:\\path'], ['c:\\path','d:\\path']),
                  (['c:/path:x:yy:d:\\path','c','.','x:/xxx'],
                   ['c:\\path', 'x', 'yy', 'd:\\path', 'c', '.', 'x:\\xxx'])]
     for inp, exp in data:
         assert_equals(ap._split_pythonpath(inp), exp)
コード例 #19
0
    def test_special_options_can_be_turned_to_normal_options(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --argumentfile path
''',
                            auto_help=False,
                            auto_version=False,
                            auto_argumentfile=False)
        opts, args = ap.parse_args(['--help', '-v', '--arg', 'xxx'])
        assert_equal(opts, {
            'help': True,
            'version': True,
            'argumentfile': 'xxx'
        })
コード例 #20
0
    def test_non_list_args(self):
        ap = ArgumentParser('''Options:
 -t --toggle
 -v --value value
 -m --multi multi *
''')
        opts, args = ap.parse_args(())
        assert_equals(opts, {'toggle': False,
                             'value': None,
                             'multi': []})
        assert_equals(args, [])
        opts, args = ap.parse_args(('-t', '-v', 'xxx', '-m', '1', '-m2', 'arg'))
        assert_equals(opts, {'toggle': True,
                             'value': 'xxx',
                             'multi': ['1', '2']})
        assert_equals(args, ['arg'])
コード例 #21
0
 def test_same_option_multiple_times_with_no_prefix(self):
     for usage in [' --foo\n --nofoo\n',
                   ' --nofoo\n --foo\n'
                   ' --nose size\n --se\n']:
         assert_raises(FrameworkError, ArgumentParser, usage)
     ap = ArgumentParser(' --foo value\n --nofoo value\n')
     self.assert_long_opts(['foo=', 'nofoo='], ap)
コード例 #22
0
 def test_auto_pythonpath_is_deprecated(self):
     with warnings.catch_warnings(record=True) as w:
         ArgumentParser('-x', auto_pythonpath=False)
     assert_equal(
         str(w[0].message),
         "ArgumentParser option 'auto_pythonpath' is deprecated "
         "since Robot Framework 5.0.")
コード例 #23
0
class TestDefaultsFromEnvironmentVariables(unittest.TestCase):

    def setUp(self):
        os.environ['ROBOT_TEST_OPTIONS'] = '-t --value default -m1 --multi=2'
        self.ap = ArgumentParser('''Options:
 -t --toggle
 -v --value value
 -m --multi multi *
''', env_options='ROBOT_TEST_OPTIONS')

    def tearDown(self):
        os.environ.pop('ROBOT_TEST_OPTIONS')

    def test_toggle(self):
        opts, args = self.ap.parse_args([])
        assert_equals(opts['toggle'], True)
        opts, args = self.ap.parse_args(['--toggle'])
        assert_equals(opts['toggle'], False)

    def test_value(self):
        opts, args = self.ap.parse_args([])
        assert_equals(opts['value'], 'default')
        opts, args = self.ap.parse_args(['--value', 'given'])
        assert_equals(opts['value'], 'given')

    def test_multi_value(self):
        opts, args = self.ap.parse_args([])
        assert_equals(opts['multi'], ['1', '2'])
        opts, args = self.ap.parse_args(['-m3', '--multi', '4'])
        assert_equals(opts['multi'], ['1', '2', '3', '4'])

    def test_arguments(self):
        os.environ['ROBOT_TEST_OPTIONS'] = '-o opt arg1 arg2'
        ap = ArgumentParser('Usage:\n -o --opt value',
                            env_options='ROBOT_TEST_OPTIONS')
        opts, args = ap.parse_args([])
        assert_equals(opts['opt'], 'opt')
        assert_equals(args, ['arg1', 'arg2'])

    def test_environment_variable_not_set(self):
        ap = ArgumentParser('Usage:\n -o --opt value', env_options='NOT_SET')
        opts, args = ap.parse_args(['arg'])
        assert_equals(opts['opt'], None)
        assert_equals(args, ['arg'])

    def test_non_list_args(self):
        opts, args = self.ap.parse_args(())
        assert_equals(opts, {'toggle': True,
                             'value': 'default',
                             'multi': ['1', '2']})
        assert_equals(args, [])
        opts, args = self.ap.parse_args(('-t', '-v', 'given', '-m3', 'a', 'b'))
        assert_equals(opts, {'toggle': False,
                             'value': 'given',
                             'multi': ['1', '2', '3']})
        assert_equals(args, ['a', 'b'])
コード例 #24
0
 def _get_invalid_message(self, args):
     try:
         args = args.encode(SYSTEM_ENCODING)
         _, invalid = ArgumentParser(USAGE).parse_args(args.split())
         if bool(invalid):
             return 'Unknown option(s): '+' '.join(invalid)
         return None
     except DataError, e:
         return e.message
コード例 #25
0
 def test_same_option_multiple_times(self):
     for my_usage in [
             ' --foo\n --foo\n', ' --foo\n -f --Foo\n',
             ' -x --foo xxx\n -y --Foo yyy\n', ' -f --foo\n -f --bar\n'
     ]:
         assert_raises(FrameworkError, ArgumentParser, my_usage)
     ap = ArgumentParser(' -f --foo\n -F --bar\n')
     assert_equals(ap._short_opts, 'fF')
     assert_equals(ap._long_opts, ['foo', 'bar'])
コード例 #26
0
 def test_same_option_multiple_times(self):
     for usage in [
             ' --foo\n --foo\n', ' --foo\n -f --Foo\n',
             ' -x --foo xxx\n -y --Foo yyy\n', ' -f --foo\n -f --bar\n'
     ]:
         assert_raises(FrameworkError, ArgumentParser, usage)
     ap = ArgumentParser(' -f --foo\n -F --bar\n')
     self.assert_short_opts('fF', ap)
     self.assert_long_opts(['foo', 'bar'], ap)
コード例 #27
0
    def test_options_over_4_spaces_from_left_are_ignored(self):
        assert_equals(
            ArgumentParser('''Name
1234567890
--opt1
    --opt2        This option is 4 spaces from left -> included
    -o --opt3 argument  It doesn't matter how far the option gets.
     --notopt     This option is 5 spaces from left -> not included
     -i --ignored
                     --not-in-either
        ''')._long_opts, ['opt1', 'opt2', 'opt3='])
コード例 #28
0
    def test_options_must_be_indented_by_1_to_four_spaces(self):
        ap = ArgumentParser('''Name
1234567890
--notin  this option is not indented at all and thus ignored
 --opt1
    --opt2        This option is 4 spaces from left -> included
    -o --opt3 argument  It doesn't matter how far the option gets.
     --notopt     This option is 5 spaces from left -> not included
     -i --ignored
                     --not-in-either
    --included  back in four space indentation''')
        assert_equals(ap._long_opts, ['opt1', 'opt2', 'opt3=', 'included'])
コード例 #29
0
 def test_argument_range(self):
     ap = ArgumentParser('usage:  test.py [options] args',
                         arg_limits=(2, 4))
     ap.parse_args(['1', '2'])
     ap.parse_args(['1', '2', '3', '4'])
     assert_raises_with_msg(DataError, "Expected 2 to 4 arguments, got 1.",
                            ap.parse_args, ['one is not enough'])
コード例 #30
0
 def test_check_variable_number_of_args(self):
     ap = ArgumentParser('usage:  robot.py [options] args', arg_limits=(1,))
     ap.parse_args(['one_is_ok'])
     ap.parse_args(['two', 'ok'])
     ap.parse_args(['this', 'should', 'also', 'work', '!'])
     assert_raises_with_msg(DataError, "Expected at least 1 argument, got 0.",
                            ap.parse_args, [])
コード例 #31
0
 def test_get_pythonpath(self):
     ap = ArgumentParser('ignored')
     p1 = os.path.abspath('.')
     p2 = os.path.abspath('..')
     assert_equals(ap._get_pythonpath(p1), [p1])
     assert_equals(ap._get_pythonpath([p1, p2]), [p1, p2])
     assert_equals(ap._get_pythonpath([p1 + ':' + p2]), [p1, p2])
     assert_true(p1 in ap._get_pythonpath(os.path.join(p2, '*')))
コード例 #32
0
    def test_escapes_are_replaced_in_help(self):
        usage = """Name
 --escape x:y      blaa blaa .............................................. end
                   <-----------------------ESCAPES---------------------------->
                   -- next line --
 --help"""
        expected = """Name
 --escape x:y      blaa blaa .............................................. end
                   Available escapes: amp (&), apos ('), at (@), bslash (\),
                   colon (:), comma (,), curly1 ({), curly2 (}), dollar ($),
                   exclam (!), gt (>), hash (#), lt (<), paren1 ((), paren2
                   ()), percent (%), pipe (|), quest (?), quot ("), semic (;),
                   slash (/), space ( ), square1 ([), square2 (]), star (*)
                   -- next line --
 --help"""
        assert_raises_with_msg(Information, expected,
                               ArgumentParser(usage).parse_args, ['--help'])
コード例 #33
0
ファイル: robot-parallel.py プロジェクト: rickypc/dotfiles
 def __init__(self):
     """Initializes robot parallel class."""
     self._ap = ArgumentParser(USAGE, arg_limits=(1,),
                               env_options='ROBOT_OPTIONS',
                               validator=self._validate)
     self.inputs = {
         'args': [],
         'datas': [],
         'output': None,
         'output_dir': None,
         'outputs': [],
         'rerun': False,
         'root_name': None,
         'shell': sep == '\\',
         'start_time': self._get_timestamp()
     }
     self.logger = None
     self.responses = None
コード例 #34
0
 def test_default_validation(self):
     ap = ArgumentParser(USAGE)
     for args in [(), ('1',), ('m', 'a', 'n', 'y')]:
         assert_equals(ap.parse_args(args)[1], list(args))
コード例 #35
0
 def test_check_args_with_correct_args(self):
     for arg_limits in [None, (1, 1), 1, (1,)]:
         ap = ArgumentParser(USAGE, arg_limits=arg_limits)
         assert_equals(ap.parse_args(['hello'])[1], ['hello'])
コード例 #36
0
 def test_environment_variable_not_set(self):
     ap = ArgumentParser('Usage:\n -o --opt value', env_options='NOT_SET')
     opts, args = ap.parse_args(['arg'])
     assert_equals(opts['opt'], None)
     assert_equals(args, ['arg'])
コード例 #37
0
 def setUp(self):
     self.ap = ArgumentParser(USAGE)
コード例 #38
0
class TestArgumentParserParseArgs(unittest.TestCase):
    def setUp(self):
        self.ap = ArgumentParser(USAGE)

    def test_missing_argument_file_throws_data_error(self):
        inargs = '--argumentfile missing_argument_file_that_really_is_not_there.txt'.split(
        )
        self.assertRaises(DataError, self.ap.parse_args, inargs)

    def test_single_options(self):
        inargs = '-d reports --reportfile report.html -T arg'.split()
        opts, args = self.ap.parse_args(inargs)
        assert_equals(
            opts, {
                'reportdir': 'reports',
                'reportfile': 'report.html',
                'variable': [],
                'name': None,
                'toggle': True
            })

    def test_multi_options(self):
        inargs = '-v a:1 -v b:2 --name my_name --variable c:3 arg'.split()
        opts, args = self.ap.parse_args(inargs)
        assert_equals(
            opts, {
                'variable': ['a:1', 'b:2', 'c:3'],
                'name': 'my_name',
                'reportdir': None,
                'reportfile': None,
                'toggle': False
            })
        assert_equals(args, ['arg'])

    def test_toggle_options(self):
        for inargs, exp in [('arg', False), ('--toggle arg', True),
                            ('--toggle --name whatever -t arg', False),
                            ('-t -T --toggle arg', True)]:
            opts, args = self.ap.parse_args(inargs.split())
            assert_equals(opts['toggle'], exp)
            assert_equals(args, ['arg'])

    def test_single_option_multiple_times(self):
        for inargs in [
                '--name Foo -N Bar arg', '-N Zap --name Foo --name Bar arg',
                '-N 1 -N 2 -N 3 -t --variable foo -N 4 --name Bar arg'
        ]:
            opts, args = self.ap.parse_args(inargs.split())
            assert_equals(opts['name'], 'Bar')
            assert_equals(args, ['arg'])

    def test_case_insensitive_long_options(self):
        opts, args = self.ap.parse_args('--VarIable X:y --TOGGLE arg'.split())
        assert_equals(opts['variable'], ['X:y'])
        assert_equals(opts['toggle'], True)
        assert_equals(args, ['arg'])

    def test_case_insensitive_long_options_with_equal_sign(self):
        opts, args = self.ap.parse_args(
            '--VariAble=X:y --VARIABLE=ZzZ'.split())
        assert_equals(opts['variable'], ['X:y', 'ZzZ'])
        assert_equals(args, [])

    def test_unescape_options(self):
        cli = '--escape quot:Q -E space:SP -E lt:LT -E gt:GT ' \
                + '-N QQQLTmySPfineSPnameGTQQQ sourceSPwithSPspaces'
        opts, args = self.ap.parse_args(cli.split())
        assert_equals(opts['name'], '"""<my fine name>"""')
        assert_equals(args, ['source with spaces'])
        assert_true('escape' not in opts)

    def test_split_pythonpath(self):
        ap = ArgumentParser('ignored')
        data = [(['path'], ['path']), (['path1', 'path2'], ['path1', 'path2']),
                (['path1:path2'], ['path1', 'path2']),
                (['p1:p2:p3', 'p4', '.'], ['p1', 'p2', 'p3', 'p4', '.'])]
        if os.sep == '\\':
            data += [(['c:\\path'], ['c:\\path']),
                     (['c:\\path', 'd:\\path'], ['c:\\path', 'd:\\path']),
                     (['c:\\path:d:\\path'], ['c:\\path', 'd:\\path']),
                     (['c:/path:x:yy:d:\\path', 'c', '.', 'x:/xxx'],
                      ['c:\\path', 'x', 'yy', 'd:\\path', 'c', '.',
                       'x:\\xxx'])]
        for inp, exp in data:
            assert_equals(ap._split_pythonpath(inp), exp)

    def test_get_pythonpath(self):
        ap = ArgumentParser('ignored')
        p1 = os.path.abspath('.')
        p2 = os.path.abspath('..')
        assert_equals(ap._get_pythonpath(p1), [p1])
        assert_equals(ap._get_pythonpath([p1, p2]), [p1, p2])
        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__])
        # Needed to ensure that the globbed directory contains files
        globexpr = os.path.join(os.path.dirname(__file__), '*')
        _, args = self.ap.parse_args([globexpr])
        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.??'])

    def test_special_options_are_removed(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y *
 --argumentfile path
 --option
''')
        opts, args = ap.parse_args(['--option'])
        assert_equals(opts, {'option': True})

    def test_special_options_can_be_turned_to_normal_optios(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y
 --argumentfile path
''',
                            auto_help=False,
                            auto_version=False,
                            auto_escape=False,
                            auto_pythonpath=False,
                            auto_argumentfile=False)
        opts, args = ap.parse_args(['--help', '-v', '--escape', 'xxx'])
        assert_equals(
            opts, {
                'help': True,
                'version': True,
                'pythonpath': None,
                'escape': 'xxx',
                'argumentfile': None
            })
コード例 #39
0
 def test_name_and_version_can_be_given(self):
     ap = ArgumentParser(USAGE, name='Kakkonen', version='2')
     assert_equals(ap.name, 'Kakkonen')
     assert_equals(ap.version, '2')
コード例 #40
0
ファイル: robot-parallel.py プロジェクト: rickypc/dotfiles
class RobotParallel(object):
    """Robot framework parallel run for given data sources."""

    def __init__(self):
        """Initializes robot parallel class."""
        self._ap = ArgumentParser(USAGE, arg_limits=(1,),
                                  env_options='ROBOT_OPTIONS',
                                  validator=self._validate)
        self.inputs = {
            'args': [],
            'datas': [],
            'output': None,
            'output_dir': None,
            'outputs': [],
            'rerun': False,
            'root_name': None,
            'shell': sep == '\\',
            'start_time': self._get_timestamp()
        }
        self.logger = None
        self.responses = None

    def execute(self, processor, processes=None, max_tasks=4):
        """Executes all prepared commands in their own respective worker."""
        pool = Pool(processes=processes, maxtasksperchild=max_tasks)
        try:
            self.responses = pool.imap(processor, self.inputs['datas'])
            pool.close()
        except KeyboardInterrupt:
            try:
                pool.terminate()
                pool.join()
            # pylint: disable=undefined-variable
            except WindowsError:
                pass

    @staticmethod
    def exit(exit_code):
        """Exit from this run with given exit code."""
        exit(exit_code)

    def flush_stdout(self):
        """Flush stdout responses."""
        for response in self.responses:
            if not isfile(response['output']):
                self.inputs['outputs'].remove(response['output'])
            output = response['stdout']
            if output != '':
                if self.inputs['shell']:
                    output = output.replace('\r\n', '\n')
                print(output)
                # self.logger.console(output)

    def merge_results(self):
        """Merges all output results into one output."""
        root_name = self.inputs['root_name']
        options = {
            'endtime': self._get_timestamp(),
            'name': root_name,
            'output': self.inputs['output'],
            'outputdir': self.inputs['output_dir'],
            'starttime': self.inputs['start_time']
        }
        if self.inputs['rerun']:
            options['prerebotmodifier'] = RenameTestSuite(root_name)
        settings = RebotSettings(**options)
        result = Results(settings, *self.inputs['outputs']).result
        suite = ParallelTestSuite(name=options['name'],
                                  statistics=result.statistics.total)
        # pylint: disable=protected-access
        self.logger._writer.suite_separator()
        self.logger.end_suite(suite)
        return ResultWriter(*(result,)).write_results(settings)

    def parse_arguments(self, cli_args):
        """Parses data inputs dictionary from given CLI arguments."""
        options, arguments = self._ap.parse_args(cli_args)
        self.logger = ConsoleOutput(colors=options.get('consolecolors',
                                                       'AUTO'),
                                    stderr=options.get('stderr', None),
                                    stdout=options.get('stdout', None))
        self.inputs['root_name'] = options.get('name',
                                               self._get_name(arguments[0]))
        self.inputs['output'] = options.pop('output', 'output.xml')
        self.inputs['output_dir'] = abspath(options.pop('outputdir', '.'))
        self.inputs['rerun'] = 'rerunfailed' in options
        self.inputs['args'] = self._generate_worker_arguments(options)
        self._generate_worker_inputs(arguments)

    @staticmethod
    def _validate(options, arguments):
        """Validates options and arguments."""
        return dict((name, value) for name, value in options.items()
                    if value not in (None, [])), arguments

    def _append_worker_data(self, source):
        """Append source as part of worker data."""
        output = 'output-%s.xml' % hexlify(urandom(16))
        output_path = join(self.inputs['output_dir'], output)
        commands = self.inputs['args'][:]
        if self.inputs['rerun']:
            commands += ['--name', '%s.%s' % (self.inputs['root_name'],
                                              self._get_name(source, False))]
        commands += ['--output', output, source]
        self.inputs['datas'].append({'commands': commands,
                                     'output': output_path})
        self.inputs['outputs'].append(output_path)

    def _generate_worker_arguments(self, options):
        """Returns generated worker CLI arguments."""
        responses = [executable, '-m', 'robot']
        options['log'] = 'NONE'
        options.pop('name', None)
        options['nostatusrc'] = True
        options['outputdir'] = self.inputs['output_dir']
        options['report'] = 'NONE'
        if self.inputs['rerun']:
            options['runemptysuite'] = True
        options['variable'] = options.get('variable', [])
        options['variable'].append('ROBOT_PARALLEL:True')
        for key, value in options.iteritems():
            if isinstance(value, bool):
                responses.append('--%s' % key)
            elif isinstance(value, list):
                for item in value:
                    responses.append('--%s' % key)
                    responses.append(item)
            else:
                responses.append('--%s' % key)
                responses.append(value)
        return responses

    def _generate_worker_inputs(self, paths):
        """Generates worker data inputs."""
        for path in paths:
            if isdir(path):
                for file_name in listdir(path):
                    file_path = join(path, file_name)
                    if isfile(file_path):
                        self._append_worker_data(file_path)
            else:
                self._append_worker_data(path)

    @staticmethod
    def _get_name(path, top_level=True):
        """Returns suite name created from data source path."""
        file_path = splitext(path)[0]
        target = dirname(file_path) or file_path if top_level else file_path
        tail = basename(target)
        name = tail.split('__', 1)[-1].replace('_', ' ')
        return name.strip().title()

    @staticmethod
    def _get_timestamp():
        """Returns timestamp."""
        return datetime.now().strftime('%Y%m%d%H%M%S%f')
コード例 #41
0
 def setUp(self):
     self.ap = ArgumentParser(USAGE)
コード例 #42
0
 def test_argument_range(self):
     ap = ArgumentParser('usage:  test.py [options] args', arg_limits=(2,4))
     ap.parse_args(['1', '2'])
     ap.parse_args(['1', '2', '3', '4'])
     assert_raises_with_msg(DataError, "Expected 2 to 4 arguments, got 1.",
                            ap.parse_args, ['one is not enough'])
コード例 #43
0
 def setUp(self):
     self.ap = ArgumentParser(USAGE, version='1.0 alpha')
     self.ap2 = ArgumentParser(USAGE2)
コード例 #44
0
 def test_no_arguments(self):
     ap = ArgumentParser('usage:  test.py [options]', arg_limits=(0, 0))
     ap.parse_args([])
     assert_raises_with_msg(DataError, "Expected 0 arguments, got 2.",
                            ap.parse_args, ['1', '2'])
コード例 #45
0
 def test_print_version_when_version_not_set(self):
     ap = ArgumentParser(' --version', name='Kekkonen')
     msg = assert_raises(Information, ap.parse_args, ['--version'])
     assert_equals(unicode(msg), 'Kekkonen %s' % get_full_version())
コード例 #46
0
class TestArgumentParserParseArgs(unittest.TestCase):

    def setUp(self):
        self.ap = ArgumentParser(USAGE)

    def test_missing_argument_file_throws_data_error(self):
        inargs = '--argumentfile missing_argument_file_that_really_is_not_there.txt'.split()
        self.assertRaises(DataError, self.ap.parse_args, inargs)

    def test_single_options(self):
        inargs = '-d reports --reportfile report.html -T arg'.split()
        opts, args = self.ap.parse_args(inargs)
        assert_equals(opts, {'reportdir':'reports', 'reportfile':'report.html',
                             'variable':[], 'name':None, 'toggle': True})

    def test_multi_options(self):
        inargs = '-v a:1 -v b:2 --name my_name --variable c:3 arg'.split()
        opts, args = self.ap.parse_args(inargs)
        assert_equals(opts, {'variable':['a:1','b:2','c:3'], 'name':'my_name',
                             'reportdir':None, 'reportfile':None,
                             'toggle': False})
        assert_equals(args, ['arg'])

    def test_toggle_options(self):
        for inargs, exp in [('arg', False),
                            ('--toggle arg', True),
                            ('--toggle --name whatever -t arg', False),
                            ('-t -T --toggle arg', True)]:
            opts, args = self.ap.parse_args(inargs.split())
            assert_equals(opts['toggle'], exp)
            assert_equals(args, ['arg'])

    def test_single_option_multiple_times(self):
        for inargs in ['--name Foo -N Bar arg',
                       '-N Zap --name Foo --name Bar arg',
                       '-N 1 -N 2 -N 3 -t --variable foo -N 4 --name Bar arg']:
            opts, args = self.ap.parse_args(inargs.split())
            assert_equals(opts['name'], 'Bar')
            assert_equals(args, ['arg'])

    def test_case_insensitive_long_options(self):
        opts, args = self.ap.parse_args('--VarIable X:y --TOGGLE arg'.split())
        assert_equals(opts['variable'], ['X:y'])
        assert_equals(opts['toggle'], True)
        assert_equals(args, ['arg'])

    def test_case_insensitive_long_options_with_equal_sign(self):
        opts, args = self.ap.parse_args('--VariAble=X:y --VARIABLE=ZzZ'.split())
        assert_equals(opts['variable'], ['X:y', 'ZzZ'])
        assert_equals(args, [])

    def test_unescape_options(self):
        cli = '--escape quot:Q -E space:SP -E lt:LT -E gt:GT ' \
                + '-N QQQLTmySPfineSPnameGTQQQ sourceSPwithSPspaces'
        opts, args = self.ap.parse_args(cli.split())
        assert_equals(opts['name'], '"""<my fine name>"""')
        assert_equals(args, ['source with spaces'])
        assert_true('escape' not in opts)

    def test_split_pythonpath(self):
        ap = ArgumentParser('ignored')
        data = [(['path'], ['path']),
                (['path1','path2'], ['path1','path2']),
                (['path1:path2'], ['path1','path2']),
                (['p1:p2:p3','p4','.'], ['p1','p2','p3','p4','.'])]
        if os.sep == '\\':
            data += [(['c:\\path'], ['c:\\path']),
                     (['c:\\path','d:\\path'], ['c:\\path','d:\\path']),
                     (['c:\\path:d:\\path'], ['c:\\path','d:\\path']),
                     (['c:/path:x:yy:d:\\path','c','.','x:/xxx'],
                      ['c:\\path', 'x', 'yy', 'd:\\path', 'c', '.', 'x:\\xxx'])]
        for inp, exp in data:
            assert_equals(ap._split_pythonpath(inp), exp)

    def test_get_pythonpath(self):
        ap = ArgumentParser('ignored')
        p1 = os.path.abspath('.')
        p2 = os.path.abspath('..')
        assert_equals(ap._get_pythonpath(p1), [p1])
        assert_equals(ap._get_pythonpath([p1,p2]), [p1,p2])
        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__])
        # Needed to ensure that the globbed directory contains files
        globexpr = os.path.join(os.path.dirname(__file__), '*')
        _, args = self.ap.parse_args([globexpr])
        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.??'])

    def test_special_options_are_removed(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y *
 --argumentfile path
 --option
''')
        opts, args = ap.parse_args(['--option'])
        assert_equals(opts, {'option': True})

    def test_special_options_can_be_turned_to_normal_optios(self):
        ap = ArgumentParser('''Usage:
 -h --help
 -v --version
 --pythonpath path
 --escape x:y
 --argumentfile path
''', auto_help=False, auto_version=False, auto_escape=False,
     auto_pythonpath=False, auto_argumentfile=False)
        opts, args = ap.parse_args(['--help', '-v', '--escape', 'xxx'])
        assert_equals(opts, {'help': True, 'version': True, 'pythonpath': None,
                             'escape': 'xxx', 'argumentfile': None})
コード例 #47
0
 def test_case_insensitive_long_options(self):
     ap = ArgumentParser(' -f --foo\n -B --BAR\n')
     assert_equals(ap._short_opts, 'fB')
     assert_equals(ap._long_opts, ['foo', 'bar'])