Пример #1
0
 def __init__(self):
     variables = GLOBAL_VARIABLES.copy()
     self._suite = self.current = variables
     self._test = None
     self._uk_handlers = []    # FIXME: Better name
     self._set_test_vars = Varz()
     self._set_kw_vars = Varz()
Пример #2
0
def import_varfile(varfile_path, args):
    temp = RobotVariables()
    try:
        temp.set_from_file(varfile_path, args)
    except SystemExit:
        raise DataError('Variable file import failed')
    return [(name, _format_value(value), varfile_path) for (name, value) in temp.items()]
Пример #3
0
def set_from_file(queue, varfile_path, args):
    try:
        temp = RobotVariables()
        temp.set_from_file(varfile_path, args)
        for (name, value) in temp.items():
            queue.put((name, value, varfile_path))
    except DataError, e:
        queue.put((e,))
def import_varfile(varfile_path, args):
    temp = RobotVariables()
    try:
        temp.set_from_file(varfile_path, args)
    except SystemExit:
        raise DataError('Variable file import failed')
    return [(name, _format_value(value), varfile_path)
            for (name, value) in temp.items()]
 def test_ignore_error(self):
     v = Variables()
     v['${X}'] = 'x'
     v['@{Y}'] = [1, 2, 3]
     for item in [
             '${foo}', 'foo${bar}', '${foo}', '@{zap}', '${Y}[7]', '${inv',
             '${{inv}', '${var}[inv', '${var}[key][inv'
     ]:
         x_at_end = 'x' if (item.count('{') == item.count('}') and
                            item.count('[') == item.count(']')) else '${x}'
         assert_equal(v.replace_string(item, ignore_errors=True), item)
         assert_equal(
             v.replace_string('${x}' + item + '${x}', ignore_errors=True),
             'x' + item + x_at_end)
         assert_equal(v.replace_scalar(item, ignore_errors=True), item)
         assert_equal(
             v.replace_scalar('${x}' + item + '${x}', ignore_errors=True),
             'x' + item + x_at_end)
         assert_equal(v.replace_list([item], ignore_errors=True), [item])
         assert_equal(
             v.replace_list(['${X}', item, '@{Y}'], ignore_errors=True),
             ['x', item, 1, 2, 3])
         assert_equal(
             v.replace_list(['${x}' + item + '${x}', '@{NON}'],
                            ignore_errors=True),
             ['x' + item + x_at_end, '@{NON}'])
Пример #6
0
    def _load_config(self):
        """Load config.py as a variable file in a way that the individual
        variables can be overriden on command line as if it was loaded
        explicitly as a variables file.
        """

        source_dir = os.path.dirname(os.path.abspath(__file__))

        # Config file is meant to live in the output directory...
        config_file = os.path.abspath('config.py')
        if not os.path.exists(config_file):
            # ...but look also into the sources to allow RED to do its job
            config_file = os.path.join(source_dir, 'config.py')

        if not os.path.exists(config_file):
            configure = os.path.join(source_dir, 'configure')
            configure = os.path.relpath(configure)
            raise ConfigurationError("Configuration file not found. Forgot to run '{}'?"
                    .format(configure))

        config = Variables()
        config.set_from_file(config_file)

        try:
            global_variables = BuiltIn().get_variables()
            for name in config.as_dict():
                if name in global_variables:
                    config[name] = global_variables[name]
        except RobotNotRunningError:
            # Use the defaults when the IDE queries variables
            pass

        return DotDict(config.as_dict(decoration=False))
Пример #7
0
 def test_ignore_error(self):
     v = Variables()
     v['${X}'] = 'x'
     v['@{Y}'] = [1, 2, 3]
     for item in ['${foo}', 'foo${bar}', '${foo}', '@{zap}', '@{Y}[7]']:
         assert_equal(v.replace_string(item, ignore_errors=True), item)
         assert_equal(
             v.replace_string('${x}' + item + '${x}', ignore_errors=True),
             'x' + item + 'x')
         assert_equal(v.replace_scalar(item, ignore_errors=True), item)
         assert_equal(
             v.replace_scalar('${x}' + item + '${x}', ignore_errors=True),
             'x' + item + 'x')
         assert_equal(v.replace_list([item], ignore_errors=True), [item])
         assert_equal(
             v.replace_list(['${X}', item, '@{Y}'], ignore_errors=True),
             ['x', item, 1, 2, 3])
 def test_ignore_error(self):
     v = Variables()
     v['${X}'] = 'x'
     v['@{Y}'] = [1, 2, 3]
     for item in ['${foo}', 'foo${bar}', '${foo}', '@{zap}', '@{Y}[7]']:
         assert_equal(v.replace_string(item, ignore_errors=True), item)
         assert_equal(v.replace_string('${x}'+item+'${x}', ignore_errors=True),
                      'x'+item+'x')
         assert_equal(v.replace_scalar(item, ignore_errors=True), item)
         assert_equal(v.replace_scalar('${x}'+item+'${x}', ignore_errors=True),
                      'x'+item+'x')
         assert_equal(v.replace_list([item], ignore_errors=True), [item])
         assert_equal(v.replace_list(['${X}', item, '@{Y}'], ignore_errors=True),
                      ['x', item, 1, 2, 3])
Пример #9
0
    def _load_config(self):
        """Load config.py as a variable file in a way that the individual
        variables can be overriden on command line as if it was loaded
        explicitly as a variables file.
        """

        config_dir = os.path.dirname(os.path.abspath(__file__))
        config_file = os.path.join(config_dir, 'config.py')

        config = Variables()
        config.set_from_file(config_file)

        try:
            global_variables = BuiltIn().get_variables()
            for name in config.as_dict():
                if name in global_variables:
                    config[name] = global_variables[name]
        except RobotNotRunningError:
            # Use the defaults when the IDE queries variables
            pass

        return DotDict(config.as_dict(decoration=False))
Пример #10
0
 def __init__(self):
     self._vars = RobotVariables()
     self._sources = {}
     for k, v in self.global_variables.iteritems():
         self.set(k, v, 'built-in')
Пример #11
0
class _VariableStash(object):
    # Global variables copied from robot.variables.__init__.py
    global_variables =  {'${TEMPDIR}': os.path.normpath(tempfile.gettempdir()),
                         '${EXECDIR}': os.path.abspath('.'),
                         '${/}': os.sep,
                         '${:}': os.pathsep,
                         '${SPACE}': ' ',
                         '${EMPTY}': '',
                         '${True}': True,
                         '${False}': False,
                         '${None}': None,
                         '${null}': None,
                         '${OUTPUT_DIR}': '',
                         '${OUTPUT_FILE}': '',
                         '${SUMMARY_FILE}': '',
                         '${REPORT_FILE}': '',
                         '${LOG_FILE}': '',
                         '${DEBUG_FILE}': '',
                         '${PREV_TEST_NAME}': '',
                         '${PREV_TEST_STATUS}': '',
                         '${PREV_TEST_MESSAGE}': '',
                         '${CURDIR}': '.',
                         '${TEST_NAME}': '',
                         '@{TEST_TAGS}': '',
                         '${TEST_STATUS}': '',
                         '${TEST_MESSAGE}': '',
                         '${SUITE_NAME}': '',
                         '${SUITE_SOURCE}': '',
                         '${SUITE_STATUS}': '',
                         '${SUITE_MESSAGE}': ''}

    ARGUMENT_SOURCE = object()

    def __init__(self):
        self._vars = RobotVariables()
        self._sources = {}
        for k, v in self.global_variables.iteritems():
            self.set(k, v, 'built-in')

    def set(self, name, value, source):
        self._vars[name] = value
        self._sources[name] = source

    def set_argument(self, name, value):
        self.set(name, value, self.ARGUMENT_SOURCE)

    def replace_variables(self, value):
        try:
            return self._vars.replace_scalar(value)
        except DataError:
            return self._vars.replace_string(value, ignore_errors=True)

    def set_from_variable_table(self, variable_table):
        for variable in variable_table:
            try:
                if not self._vars.has_key(variable.name):
                    _, value = self._vars._get_var_table_name_and_value(
                        variable.name,
                        variable.value)
                    self.set(variable.name, value, variable_table.source)
            except DataError:
                if is_var(variable.name):
                    self.set(variable.name, '', variable_table.source)

    def set_from_file(self, varfile_path, args):
        temp = RobotVariables()
        temp.set_from_file(varfile_path, args)
        for (name, value) in temp.items():
            self.set(name, value, varfile_path)

    def __iter__(self):
        for name, value in self._vars.items():
            source = self._sources[name]
            if source == self.ARGUMENT_SOURCE:
                yield ArgumentInfo(name, value)
            else:
                yield VariableInfo(name, value, source)
Пример #12
0
 def setUp(self):
     self.varz = Variables()
Пример #13
0
class TestVariables(unittest.TestCase):

    def setUp(self):
        self.varz = Variables()

    def test_set(self):
        value = ['value']
        for var in SCALARS + LISTS:
            self.varz[var] = value
            assert_equal(self.varz[var], value)
            assert_equal(self.varz[var.lower().replace(' ', '')] , value)
            self.varz.clear()

    def test_set_invalid(self):
        for var in NOKS:
            assert_raises(DataError, self.varz.__setitem__, var, 'value')

    def test_set_scalar(self):
        for var in SCALARS:
            for value in ['string', '', 10, ['hi', 'u'], ['hi', 2],
                          {'a': 1, 'b': 2}, self, None, unittest.TestCase]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)

    def test_set_list(self):
        for var in LISTS:
            for value in [[], [''], ['str'], [10], ['hi', 'u'], ['hi', 2],
                          [{'a': 1, 'b': 2}, self, None]]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)
                self.varz.clear()

    def test_replace_scalar(self):
        self.varz['${foo}'] = 'bar'
        self.varz['${a}'] = 'ari'
        for inp, exp in [('${foo}', 'bar'),
                         ('${a}', 'ari'),
                         ('${a', '${a'),
                         ('', ''),
                         ('hii', 'hii'),
                         ("Let's go to ${foo}!", "Let's go to bar!"),
                         ('${foo}ba${a}-${a}', 'barbaari-ari')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_replace_list(self):
        self.varz['@{L}'] = ['v1', 'v2']
        self.varz['@{E}'] = []
        self.varz['@{S}'] = ['1', '2', '3']
        for inp, exp in [(['@{L}'], ['v1', 'v2']),
                         (['@{L}', 'v3'], ['v1', 'v2', 'v3']),
                         (['v0', '@{L}', '@{E}', 'v@{S}[2]'], ['v0', 'v1', 'v2', 'v3']),
                         ([], []),
                         (['hi u', 'hi 2', 3], ['hi u','hi 2', 3])]:
            assert_equal(self.varz.replace_list(inp), exp)

    def test_replace_list_in_scalar_context(self):
        self.varz['@{list}'] = ['v1', 'v2']
        assert_equal(self.varz.replace_list(['@{list}']), ['v1', 'v2'])
        assert_equal(self.varz.replace_list(['-@{list}-']), ["-['v1', 'v2']-"])

    def test_replace_list_item(self):
        self.varz['@{L}'] = ['v0', 'v1']
        assert_equal(self.varz.replace_list(['@{L}[0]']), ['v0'])
        assert_equal(self.varz.replace_scalar('@{L}[1]'), 'v1')
        assert_equal(self.varz.replace_scalar('-@{L}[0]@{L}[1]@{L}[0]-'), '-v0v1v0-')
        self.varz['@{L2}'] = ['v0', ['v11', 'v12']]
        assert_equal(self.varz.replace_list(['@{L2}[0]']), ['v0'])
        assert_equal(self.varz.replace_list(['@{L2}[1]']), [['v11', 'v12']])
        assert_equal(self.varz.replace_scalar('@{L2}[0]'), 'v0')
        assert_equal(self.varz.replace_scalar('@{L2}[1]'), ['v11', 'v12'])
        assert_equal(self.varz.replace_list(['@{L}[0]', '@{L2}[1]']), ['v0', ['v11', 'v12']])

    def test_replace_dict_item(self):
        self.varz['&{D}'] = {'a': 1, 2: 'b'}
        assert_equal(self.varz.replace_list(['&{D}[a]']), [1])
        assert_equal(self.varz.replace_scalar('&{D}[${2}]'), 'b')

    def test_replace_non_strings(self):
        self.varz['${d}'] = {'a': 1, 'b': 2}
        self.varz['${n}'] = None
        assert_equal(self.varz.replace_scalar('${d}'), {'a': 1, 'b': 2})
        assert_equal(self.varz.replace_scalar('${n}'), None)

    def test_replace_non_strings_inside_string(self):
        class Example:
            def __str__(self):
                return 'Hello'
        self.varz['${h}'] = Example()
        self.varz['${w}'] = 'world'
        res = self.varz.replace_scalar('Another "${h} ${w}" example')
        assert_equal(res, 'Another "Hello world" example')

    def test_replace_list_item_invalid(self):
        self.varz['@{L}'] = ['v0','v1','v3']
        for inv in ['@{L}[3]', '@{NON}[0]', '@{L[2]}']:
            self.assertRaises(DataError, self.varz.replace_list, [inv])

    def test_replace_non_existing_list(self):
        self.assertRaises(DataError, self.varz.replace_list, ['${nonexisting}'])

    def test_replace_non_existing_scalar(self):
        self.assertRaises(DataError, self.varz.replace_scalar, '${nonexisting}')

    def test_replace_non_existing_string(self):
        self.assertRaises(DataError, self.varz.replace_string, '${nonexisting}')

    def test_replace_escaped(self):
        self.varz['${foo}'] = 'bar'
        for inp, exp in [(r'\${foo}', r'${foo}'),
                         (r'\\${foo}', r'\bar'),
                         (r'\\\${foo}', r'\${foo}'),
                         (r'\\\\${foo}', r'\\bar'),
                         (r'\\\\\${foo}', r'\\${foo}')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_variables_in_value(self):
        self.varz['${exists}'] = 'Variable exists but is still not replaced'
        self.varz['${test}'] = '${exists} & ${does_not_exist}'
        assert_equal(self.varz['${test}'], '${exists} & ${does_not_exist}')
        self.varz['@{test}'] = ['${exists}', '&', '${does_not_exist}']
        assert_equal(self.varz['@{test}'], '${exists} & ${does_not_exist}'.split())

    def test_variable_as_object(self):
        obj = PythonObject('a', 1)
        self.varz['${obj}'] = obj
        assert_equal(self.varz['${obj}'], obj)
        expected = ['Some text here %s and %s there' % (obj, obj)]
        actual = self.varz.replace_list(['Some text here ${obj} and ${obj} there'])
        assert_equal(actual, expected)

    def test_extended_variables(self):
        # Extended variables are vars like ${obj.name} when we have var ${obj}
        obj = PythonObject('a', [1, 2, 3])
        dic = {'a': 1, 'o': obj}
        self.varz['${obj}'] = obj
        self.varz['${dic}'] = dic
        assert_equal(self.varz.replace_scalar('${obj.a}'), 'a')
        assert_equal(self.varz.replace_scalar('${obj.b}'), [1, 2, 3])
        assert_equal(self.varz.replace_scalar('${obj.b[0]}-${obj.b[1]}'), '1-2')
        assert_equal(self.varz.replace_scalar('${dic["a"]}'), 1)
        assert_equal(self.varz.replace_scalar('${dic["o"]}'), obj)
        assert_equal(self.varz.replace_scalar('-${dic["o"].b[2]}-'), '-3-')

    def test_space_is_not_ignored_after_newline_in_extend_variable_syntax(self):
        self.varz['${x}'] = 'test string'
        self.varz['${lf}'] = '\\n'
        self.varz['${lfs}'] = '\\n '
        for inp, exp in [('${x.replace(" ", """\\n""")}', 'test\nstring'),
                         ('${x.replace(" ", """\\n """)}', 'test\n string'),
                         ('${x.replace(" ", """${lf}""")}', 'test\nstring'),
                         ('${x.replace(" ", """${lfs}""")}', 'test\n string')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_escaping_with_extended_variable_syntax(self):
        self.varz['${p}'] = 'c:\\temp'
        assert self.varz['${p}'] == 'c:\\temp'
        assert_equal(self.varz.replace_scalar('${p + "\\\\foo.txt"}'),
                     'c:\\temp\\foo.txt')

    def test_internal_variables(self):
        # Internal variables are variables like ${my${name}}
        self.varz['${name}'] = 'name'
        self.varz['${my name}'] = 'value'
        assert_equal(self.varz.replace_scalar('${my${name}}'), 'value')
        self.varz['${whos name}'] = 'my'
        assert_equal(self.varz.replace_scalar('${${whos name} ${name}}'), 'value')
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'), 'value')
        self.varz['${my name}'] = [1, 2, 3]
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'), [1, 2, 3])
        assert_equal(self.varz.replace_scalar('- ${${whos${name}}${name}} -'), '- [1, 2, 3] -')

    def test_math_with_internal_vars(self):
        assert_equal(self.varz.replace_scalar('${${1}+${2}}'), 3)
        assert_equal(self.varz.replace_scalar('${${1}-${2}}'), -1)
        assert_equal(self.varz.replace_scalar('${${1}*${2}}'), 2)
        assert_equal(self.varz.replace_scalar('${${1}/${2}}'), 0)

    def test_math_with_internal_vars_with_spaces(self):
        assert_equal(self.varz.replace_scalar('${${1} + ${2.5}}'), 3.5)
        assert_equal(self.varz.replace_scalar('${${1} - ${2} + 1}'), 0)
        assert_equal(self.varz.replace_scalar('${${1} * ${2} - 1}'), 1)
        assert_equal(self.varz.replace_scalar('${${1} / ${2.0}}'), 0.5)

    def test_math_with_internal_vars_does_not_work_if_first_var_is_float(self):
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1}+${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1} - ${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1} * ${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1}/${2}}')

    def test_list_variable_as_scalar(self):
        self.varz['@{name}'] = exp = ['spam', 'eggs']
        assert_equal(self.varz.replace_scalar('${name}'), exp)
        assert_equal(self.varz.replace_list(['${name}', 42]), [exp, 42])
        assert_equal(self.varz.replace_string('${name}'), str(exp))

    def test_copy(self):
        varz = Variables()
        varz['${foo}'] = 'bar'
        copy = varz.copy()
        assert_equal(copy['${foo}'], 'bar')

    if JYTHON:

        def test_variable_as_object_in_java(self):
            obj = JavaObject('hello')
            self.varz['${obj}'] = obj
            assert_equal(self.varz['${obj}'], obj)
            assert_equal(self.varz.replace_scalar('${obj} world'), 'hello world')

        def test_extended_variables_in_java(self):
            obj = JavaObject('my name')
            self.varz['${obj}'] = obj
            assert_equal(self.varz.replace_list(['${obj.name}']), ['my name'])
Пример #14
0
 def test_copy(self):
     varz = Variables()
     varz['${foo}'] = 'bar'
     copy = varz.copy()
     assert_equal(copy['${foo}'], 'bar')
Пример #15
0
class _VariableStash(object):
    # Global variables copied from robot.variables.__init__.py
    global_variables = {
        '${TEMPDIR}': os.path.normpath(tempfile.gettempdir()),
        '${EXECDIR}': os.path.abspath('.'),
        '${/}': os.sep,
        '${:}': os.pathsep,
        '${SPACE}': ' ',
        '${EMPTY}': '',
        '${True}': True,
        '${False}': False,
        '${None}': None,
        '${null}': None,
        '${OUTPUT_DIR}': '',
        '${OUTPUT_FILE}': '',
        '${SUMMARY_FILE}': '',
        '${REPORT_FILE}': '',
        '${LOG_FILE}': '',
        '${DEBUG_FILE}': '',
        '${PREV_TEST_NAME}': '',
        '${PREV_TEST_STATUS}': '',
        '${PREV_TEST_MESSAGE}': '',
        '${CURDIR}': '.',
        '${TEST_NAME}': '',
        '@{TEST_TAGS}': '',
        '${TEST_STATUS}': '',
        '${TEST_MESSAGE}': '',
        '${SUITE_NAME}': '',
        '${SUITE_SOURCE}': '',
        '${SUITE_STATUS}': '',
        '${SUITE_MESSAGE}': ''
    }

    ARGUMENT_SOURCE = object()

    def __init__(self):
        self._vars = RobotVariables()
        self._sources = {}
        for k, v in self.global_variables.iteritems():
            self.set(k, v, 'built-in')

    def set(self, name, value, source):
        self._vars[name] = value
        self._sources[name] = source

    def set_argument(self, name, value):
        self.set(name, value, self.ARGUMENT_SOURCE)

    def replace_variables(self, value):
        try:
            return self._vars.replace_scalar(value)
        except DataError:
            return self._vars.replace_string(value, ignore_errors=True)

    def set_from_variable_table(self, variable_table):
        for variable in variable_table:
            try:
                if not self._vars.has_key(variable.name):
                    _, value = self._vars._get_var_table_name_and_value(
                        variable.name, variable.value)
                    self.set(variable.name, value, variable_table.source)
            except DataError:
                if is_var(variable.name):
                    self.set(variable.name, '', variable_table.source)

    def set_from_file(self, varfile_path, args):
        for item in variablefetcher.import_varfile(varfile_path, args):
            self.set(*item)

    def __iter__(self):
        for name, value in self._vars.items():
            source = self._sources[name]
            if source == self.ARGUMENT_SOURCE:
                yield ArgumentInfo(name, value)
            else:
                yield VariableInfo(name, value, source)
Пример #16
0
 def setUp(self):
     self.varz = Variables()
Пример #17
0
class TestVariables(unittest.TestCase):
    def setUp(self):
        self.varz = Variables()

    def test_set(self):
        value = ['value']
        for var in SCALARS + LISTS:
            self.varz[var] = value
            assert_equal(self.varz[var], value)
            assert_equal(self.varz[var.lower().replace(' ', '')], value)
            self.varz.clear()

    def test_set_invalid(self):
        for var in NOKS:
            assert_raises(DataError, self.varz.__setitem__, var, 'value')

    def test_set_scalar(self):
        for var in SCALARS:
            for value in [
                    'string', '', 10, ['hi', 'u'], ['hi', 2], {
                        'a': 1,
                        'b': 2
                    }, self, None, unittest.TestCase
            ]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)

    def test_set_list(self):
        for var in LISTS:
            for value in [[], [''], ['str'], [10], ['hi', 'u'], ['hi', 2],
                          [{
                              'a': 1,
                              'b': 2
                          }, self, None]]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)
                self.varz.clear()

    def test_replace_scalar(self):
        self.varz['${foo}'] = 'bar'
        self.varz['${a}'] = 'ari'
        for inp, exp in [('${foo}', 'bar'), ('${a}', 'ari'), ('${a', '${a'),
                         ('', ''), ('hii', 'hii'),
                         ("Let's go to ${foo}!", "Let's go to bar!"),
                         ('${foo}ba${a}-${a}', 'barbaari-ari')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_replace_list(self):
        self.varz['@{L}'] = ['v1', 'v2']
        self.varz['@{E}'] = []
        self.varz['@{S}'] = ['1', '2', '3']
        for inp, exp in [(['@{L}'], ['v1', 'v2']),
                         (['@{L}', 'v3'], ['v1', 'v2', 'v3']),
                         (['v0', '@{L}', '@{E}',
                           'v@{S}[2]'], ['v0', 'v1', 'v2', 'v3']), ([], []),
                         (['hi u', 'hi 2', 3], ['hi u', 'hi 2', 3])]:
            assert_equal(self.varz.replace_list(inp), exp)

    def test_replace_list_in_scalar_context(self):
        self.varz['@{list}'] = ['v1', 'v2']
        assert_equal(self.varz.replace_list(['@{list}']), ['v1', 'v2'])
        assert_equal(self.varz.replace_list(['-@{list}-']), ["-['v1', 'v2']-"])

    def test_replace_list_item(self):
        self.varz['@{L}'] = ['v0', 'v1']
        assert_equal(self.varz.replace_list(['@{L}[0]']), ['v0'])
        assert_equal(self.varz.replace_scalar('@{L}[1]'), 'v1')
        assert_equal(self.varz.replace_scalar('-@{L}[0]@{L}[1]@{L}[0]-'),
                     '-v0v1v0-')
        self.varz['@{L2}'] = ['v0', ['v11', 'v12']]
        assert_equal(self.varz.replace_list(['@{L2}[0]']), ['v0'])
        assert_equal(self.varz.replace_list(['@{L2}[1]']), [['v11', 'v12']])
        assert_equal(self.varz.replace_scalar('@{L2}[0]'), 'v0')
        assert_equal(self.varz.replace_scalar('@{L2}[1]'), ['v11', 'v12'])
        assert_equal(self.varz.replace_list(['@{L}[0]', '@{L2}[1]']),
                     ['v0', ['v11', 'v12']])

    def test_replace_non_strings(self):
        self.varz['${d}'] = {'a': 1, 'b': 2}
        self.varz['${n}'] = None
        assert_equal(self.varz.replace_scalar('${d}'), {'a': 1, 'b': 2})
        assert_equal(self.varz.replace_scalar('${n}'), None)

    def test_replace_non_strings_inside_string(self):
        class Example:
            def __str__(self):
                return 'Hello'

        self.varz['${h}'] = Example()
        self.varz['${w}'] = 'world'
        res = self.varz.replace_scalar('Another "${h} ${w}" example')
        assert_equal(res, 'Another "Hello world" example')

    def test_replace_list_item_invalid(self):
        self.varz['@{L}'] = ['v0', 'v1', 'v3']
        for inv in ['@{L}[3]', '@{NON}[0]', '@{L[2]}']:
            self.assertRaises(DataError, self.varz.replace_list, [inv])

    def test_replace_non_existing_list(self):
        self.assertRaises(DataError, self.varz.replace_list,
                          ['${nonexisting}'])

    def test_replace_non_existing_scalar(self):
        self.assertRaises(DataError, self.varz.replace_scalar,
                          '${nonexisting}')

    def test_replace_non_existing_string(self):
        self.assertRaises(DataError, self.varz.replace_string,
                          '${nonexisting}')

    def test_replace_escaped(self):
        self.varz['${foo}'] = 'bar'
        for inp, exp in [(r'\${foo}', r'${foo}'), (r'\\${foo}', r'\bar'),
                         (r'\\\${foo}', r'\${foo}'), (r'\\\\${foo}', r'\\bar'),
                         (r'\\\\\${foo}', r'\\${foo}')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_variables_in_value(self):
        self.varz['${exists}'] = 'Variable exists but is still not replaced'
        self.varz['${test}'] = '${exists} & ${does_not_exist}'
        assert_equal(self.varz['${test}'], '${exists} & ${does_not_exist}')
        self.varz['@{test}'] = ['${exists}', '&', '${does_not_exist}']
        assert_equal(self.varz['@{test}'],
                     '${exists} & ${does_not_exist}'.split())

    def test_variable_as_object(self):
        obj = PythonObject('a', 1)
        self.varz['${obj}'] = obj
        assert_equal(self.varz['${obj}'], obj)
        expected = ['Some text here %s and %s there' % (obj, obj)]
        actual = self.varz.replace_list(
            ['Some text here ${obj} and ${obj} there'])
        assert_equal(actual, expected)

    def test_extended_variables(self):
        # Extended variables are vars like ${obj.name} when we have var ${obj}
        obj = PythonObject('a', [1, 2, 3])
        dic = {'a': 1, 'o': obj}
        self.varz['${obj}'] = obj
        self.varz['${dic}'] = dic
        assert_equal(self.varz.replace_scalar('${obj.a}'), 'a')
        assert_equal(self.varz.replace_scalar('${obj.b}'), [1, 2, 3])
        assert_equal(self.varz.replace_scalar('${obj.b[0]}-${obj.b[1]}'),
                     '1-2')
        assert_equal(self.varz.replace_scalar('${dic["a"]}'), 1)
        assert_equal(self.varz.replace_scalar('${dic["o"]}'), obj)
        assert_equal(self.varz.replace_scalar('-${dic["o"].b[2]}-'), '-3-')

    def test_space_is_not_ignored_after_newline_in_extend_variable_syntax(
            self):
        self.varz['${x}'] = 'test string'
        self.varz['${lf}'] = '\\n'
        self.varz['${lfs}'] = '\\n '
        for inp, exp in [('${x.replace(" ", """\\n""")}', 'test\nstring'),
                         ('${x.replace(" ", """\\n """)}', 'test\n string'),
                         ('${x.replace(" ", """${lf}""")}', 'test\nstring'),
                         ('${x.replace(" ", """${lfs}""")}', 'test\n string')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_escaping_with_extended_variable_syntax(self):
        self.varz['${p}'] = 'c:\\temp'
        assert self.varz['${p}'] == 'c:\\temp'
        assert_equal(self.varz.replace_scalar('${p + "\\\\foo.txt"}'),
                     'c:\\temp\\foo.txt')

    def test_internal_variables(self):
        # Internal variables are variables like ${my${name}}
        self.varz['${name}'] = 'name'
        self.varz['${my name}'] = 'value'
        assert_equal(self.varz.replace_scalar('${my${name}}'), 'value')
        self.varz['${whos name}'] = 'my'
        assert_equal(self.varz.replace_scalar('${${whos name} ${name}}'),
                     'value')
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'),
                     'value')
        self.varz['${my name}'] = [1, 2, 3]
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'),
                     [1, 2, 3])
        assert_equal(self.varz.replace_scalar('- ${${whos${name}}${name}} -'),
                     '- [1, 2, 3] -')

    def test_math_with_internal_vars(self):
        assert_equal(self.varz.replace_scalar('${${1}+${2}}'), 3)
        assert_equal(self.varz.replace_scalar('${${1}-${2}}'), -1)
        assert_equal(self.varz.replace_scalar('${${1}*${2}}'), 2)
        assert_equal(self.varz.replace_scalar('${${1}/${2}}'), 0)

    def test_math_with_internal_vars_with_spaces(self):
        assert_equal(self.varz.replace_scalar('${${1} + ${2.5}}'), 3.5)
        assert_equal(self.varz.replace_scalar('${${1} - ${2} + 1}'), 0)
        assert_equal(self.varz.replace_scalar('${${1} * ${2} - 1}'), 1)
        assert_equal(self.varz.replace_scalar('${${1} / ${2.0}}'), 0.5)

    def test_math_with_internal_vars_does_not_work_if_first_var_is_float(self):
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1}+${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1} - ${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1} * ${2}}')
        assert_raises(DataError, self.varz.replace_scalar, '${${1.1}/${2}}')

    def test_list_variable_as_scalar(self):
        self.varz['@{name}'] = exp = ['spam', 'eggs']
        assert_equal(self.varz.replace_scalar('${name}'), exp)
        assert_equal(self.varz.replace_list(['${name}', 42]), [exp, 42])
        assert_equal(self.varz.replace_string('${name}'), str(exp))

    def test_copy(self):
        varz = Variables()
        varz['${foo}'] = 'bar'
        copy = varz.copy()
        assert_equal(copy['${foo}'], 'bar')

    if sys.platform.startswith('java'):

        def test_variable_as_object_in_java(self):
            obj = JavaObject('hello')
            self.varz['${obj}'] = obj
            assert_equal(self.varz['${obj}'], obj)
            assert_equal(self.varz.replace_scalar('${obj} world'),
                         'hello world')

        def test_extended_variables_in_java(self):
            obj = JavaObject('my name')
            self.varz['${obj}'] = obj
            assert_equal(self.varz.replace_list(['${obj.name}']), ['my name'])
Пример #18
0
 def test_copy(self):
     varz = Variables()
     varz['${foo}'] = 'bar'
     copy = varz.copy()
     assert_equal(copy['${foo}'], 'bar')
Пример #19
0
class _VariableStash(object):

    # Since Robot 2.8 some robot.variables classes and methods
    # expect an error_reporter argument.
    # The following attribute can be used to determine how they must be called:
    _error_reporting = 'error_reporter' in getargspec(
        RobotVariables._get_var_table_name_and_value
        ).args

    # Global variables copied from robot.variables.__init__.py
    global_variables =  {'${TEMPDIR}': os.path.normpath(tempfile.gettempdir()),
                         '${EXECDIR}': os.path.abspath('.'),
                         '${/}': os.sep,
                         '${:}': os.pathsep,
                         '${SPACE}': ' ',
                         '${EMPTY}': '',
                         '${True}': True,
                         '${False}': False,
                         '${None}': None,
                         '${null}': None,
                         '${OUTPUT_DIR}': '',
                         '${OUTPUT_FILE}': '',
                         '${SUMMARY_FILE}': '',
                         '${REPORT_FILE}': '',
                         '${LOG_FILE}': '',
                         '${DEBUG_FILE}': '',
                         '${PREV_TEST_NAME}': '',
                         '${PREV_TEST_STATUS}': '',
                         '${PREV_TEST_MESSAGE}': '',
                         '${CURDIR}': '.',
                         '${TEST_NAME}': '',
                         '@{TEST_TAGS}': '',
                         '${TEST_STATUS}': '',
                         '${TEST_MESSAGE}': '',
                         '${SUITE_NAME}': '',
                         '${SUITE_SOURCE}': '',
                         '${SUITE_STATUS}': '',
                         '${SUITE_MESSAGE}': ''}

    ARGUMENT_SOURCE = object()

    def __init__(self):
        self._vars = RobotVariables()
        self._sources = {}
        for k, v in self.global_variables.iteritems():
            self.set(k, v, 'built-in')

    def set(self, name, value, source):
        self._vars[name] = value
        self._sources[name] = source

    def set_argument(self, name, value):
        self.set(name, value, self.ARGUMENT_SOURCE)

    def replace_variables(self, value):
        try:
            return self._vars.replace_scalar(value)
        except DataError:
            return self._vars.replace_string(value, ignore_errors=True)

    def set_from_variable_table(self, variable_table):
        for variable in variable_table:
            try:
                if not self._vars.has_key(variable.name):
                    if self._error_reporting: # Robot 2.8+
                        _, value = self._vars._get_var_table_name_and_value(
                            variable.name,
                            variable.value,
                            variable.report_invalid_syntax)
                    else:
                        _, value = self._vars._get_var_table_name_and_value(
                            variable.name,
                            variable.value)
                    self.set(variable.name, value, variable_table.source)
            except DataError:
                if is_var(variable.name):
                    self.set(variable.name, '', variable_table.source)

    def set_from_file(self, varfile_path, args):
        for item in variablefetcher.import_varfile(varfile_path, args):
            self.set(*item)

    def __iter__(self):
        for name, value in self._vars.items():
            source = self._sources[name]
            if source == self.ARGUMENT_SOURCE:
                yield ArgumentInfo(name, value)
            else:
                yield VariableInfo(name, value, source)
Пример #20
0
 def __init__(self):
     self._vars = RobotVariables()
     self._sources = {}
     for k, v in self.global_variables.iteritems():
         self.set(k, v, 'built-in')
Пример #21
0
 def set_from_file(self, varfile_path, args):
     temp = RobotVariables()
     temp.set_from_file(varfile_path, args)
     for (name, value) in temp.items():
         self.set(name, value, varfile_path)
class TestVariables(unittest.TestCase):
    def setUp(self):
        self.varz = Variables()

    def test_set(self):
        value = ['value']
        for var in SCALARS + LISTS:
            self.varz[var] = value
            assert_equal(self.varz[var], value)
            assert_equal(self.varz[var.lower().replace(' ', '')], value)
            self.varz.clear()

    def test_set_invalid(self):
        for var in NOKS:
            assert_raises(DataError, self.varz.__setitem__, var, 'value')

    def test_set_scalar(self):
        for var in SCALARS:
            for value in [
                    'string', '', 10, ['hi', 'u'], ['hi', 2], {
                        'a': 1,
                        'b': 2
                    }, self, None, unittest.TestCase
            ]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)

    def test_set_list(self):
        for var in LISTS:
            for value in [[], [''], ['str'], [10], ['hi', 'u'], ['hi', 2],
                          [{
                              'a': 1,
                              'b': 2
                          }, self, None]]:
                self.varz[var] = value
                assert_equal(self.varz[var], value)
                self.varz.clear()

    def test_replace_scalar(self):
        self.varz['${foo}'] = 'bar'
        self.varz['${a}'] = 'ari'
        for inp, exp in [('${foo}', 'bar'), ('${a}', 'ari'),
                         (r'$\{a}', '${a}'), ('', ''), ('hii', 'hii'),
                         ("Let's go to ${foo}!", "Let's go to bar!"),
                         ('${foo}ba${a}-${a}', 'barbaari-ari')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_replace_list(self):
        self.varz['@{L}'] = ['v1', 'v2']
        self.varz['@{E}'] = []
        self.varz['@{S}'] = ['1', '2', '3']
        for inp, exp in [(['@{L}'], ['v1', 'v2']),
                         (['@{L}', 'v3'], ['v1', 'v2', 'v3']),
                         (['v0', '@{L}', '@{E}',
                           'v${S}[2]'], ['v0', 'v1', 'v2', 'v3']), ([], []),
                         (['hi u', 'hi 2', 3], ['hi u', 'hi 2', 3])]:
            assert_equal(self.varz.replace_list(inp), exp)

    def test_replace_list_in_scalar_context(self):
        self.varz['@{list}'] = ['v1', 'v2']
        assert_equal(self.varz.replace_list(['@{list}']), ['v1', 'v2'])
        assert_equal(self.varz.replace_list(['-@{list}-']), ["-['v1', 'v2']-"])

    def test_replace_list_item(self):
        self.varz['@{L}'] = ['v0', 'v1']
        assert_equal(self.varz.replace_list(['${L}[0]']), ['v0'])
        assert_equal(self.varz.replace_scalar('${L}[1]'), 'v1')
        assert_equal(self.varz.replace_scalar('-${L}[0]${L}[1]${L}[0]-'),
                     '-v0v1v0-')
        self.varz['${L2}'] = ['v0', ['v11', 'v12']]
        assert_equal(self.varz.replace_list(['${L2}[0]']), ['v0'])
        assert_equal(self.varz.replace_list(['${L2}[1]']), [['v11', 'v12']])
        assert_equal(self.varz.replace_scalar('${L2}[0]'), 'v0')
        assert_equal(self.varz.replace_scalar('${L2}[1]'), ['v11', 'v12'])
        assert_equal(self.varz.replace_list(['${L}[0]', '@{L2}[1]']),
                     ['v0', 'v11', 'v12'])

    def test_replace_dict_item(self):
        self.varz['&{D}'] = {'a': 1, 2: 'b', 'nested': {'a': 1}}
        assert_equal(self.varz.replace_scalar('${D}[a]'), 1)
        assert_equal(self.varz.replace_scalar('${D}[${2}]'), 'b')
        assert_equal(self.varz.replace_scalar('${D}[nested][a]'), 1)
        assert_equal(self.varz.replace_scalar('${D}[nested]'), {'a': 1})
        assert_equal(self.varz.replace_scalar('&{D}[nested]'), {'a': 1})

    def test_replace_non_strings(self):
        self.varz['${d}'] = {'a': 1, 'b': 2}
        self.varz['${n}'] = None
        assert_equal(self.varz.replace_scalar('${d}'), {'a': 1, 'b': 2})
        assert_equal(self.varz.replace_scalar('${n}'), None)

    def test_replace_non_strings_inside_string(self):
        class Example:
            def __str__(self):
                return 'Hello'

        self.varz['${h}'] = Example()
        self.varz['${w}'] = 'world'
        res = self.varz.replace_scalar('Another "${h} ${w}" example')
        assert_equal(res, 'Another "Hello world" example')

    def test_replace_list_item_invalid(self):
        self.varz['@{L}'] = ['v0', 'v1', 'v3']
        for inv in ['@{L}[3]', '@{NON}[0]', '@{L[2]}']:
            assert_raises(VariableError, self.varz.replace_list, [inv])

    def test_replace_non_existing_list(self):
        assert_raises(VariableError, self.varz.replace_list,
                      ['${nonexisting}'])

    def test_replace_non_existing_scalar(self):
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${nonexisting}')

    def test_replace_non_existing_string(self):
        assert_raises(VariableError, self.varz.replace_string,
                      '${nonexisting}')

    def test_non_string_input(self):
        for item in [1, False, None, [], (), {}, object]:
            assert_equal(self.varz.replace_list([item]), [item])
            assert_equal(self.varz.replace_scalar(item), item)
            assert_equal(self.varz.replace_string(item), str(item))

    def test_replace_escaped(self):
        self.varz['${foo}'] = 'bar'
        for inp, exp in [(r'\${foo}', r'${foo}'), (r'\\${foo}', r'\bar'),
                         (r'\\\${foo}', r'\${foo}'), (r'\\\\${foo}', r'\\bar'),
                         (r'\\\\\${foo}', r'\\${foo}')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_variables_in_value(self):
        self.varz['${exists}'] = 'Variable exists but is still not replaced'
        self.varz['${test}'] = '${exists} & ${does_not_exist}'
        assert_equal(self.varz['${test}'], '${exists} & ${does_not_exist}')
        self.varz['@{test}'] = ['${exists}', '&', '${does_not_exist}']
        assert_equal(self.varz['@{test}'],
                     '${exists} & ${does_not_exist}'.split())

    def test_variable_as_object(self):
        obj = PythonObject('a', 1)
        self.varz['${obj}'] = obj
        assert_equal(self.varz['${obj}'], obj)
        expected = ['Some text here %s and %s there' % (obj, obj)]
        actual = self.varz.replace_list(
            ['Some text here ${obj} and ${obj} there'])
        assert_equal(actual, expected)

    def test_extended_variables(self):
        # Extended variables are vars like ${obj.name} when we have var ${obj}
        obj = PythonObject('a', [1, 2, 3])
        dic = {'a': 1, 'o': obj}
        self.varz['${obj}'] = obj
        self.varz['${dic}'] = dic
        assert_equal(self.varz.replace_scalar('${obj.a}'), 'a')
        assert_equal(self.varz.replace_scalar('${obj.b}'), [1, 2, 3])
        assert_equal(self.varz.replace_scalar('${obj.b[0]}-${obj.b[1]}'),
                     '1-2')
        assert_equal(self.varz.replace_scalar('${dic["a"]}'), 1)
        assert_equal(self.varz.replace_scalar('${dic["o"]}'), obj)
        assert_equal(self.varz.replace_scalar('-${dic["o"].b[2]}-'), '-3-')

    def test_space_is_not_ignored_after_newline_in_extend_variable_syntax(
            self):
        self.varz['${x}'] = 'test string'
        self.varz['${lf}'] = '\\n'
        self.varz['${lfs}'] = '\\n '
        for inp, exp in [('${x.replace(" ", """\\n""")}', 'test\nstring'),
                         ('${x.replace(" ", """\\n """)}', 'test\n string'),
                         ('${x.replace(" ", """${lf}""")}', 'test\nstring'),
                         ('${x.replace(" ", """${lfs}""")}', 'test\n string')]:
            assert_equal(self.varz.replace_scalar(inp), exp)

    def test_escaping_with_extended_variable_syntax(self):
        self.varz['${p}'] = 'c:\\temp'
        assert self.varz['${p}'] == 'c:\\temp'
        assert_equal(self.varz.replace_scalar('${p + "\\\\foo.txt"}'),
                     'c:\\temp\\foo.txt')

    def test_internal_variables(self):
        # Internal variables are variables like ${my${name}}
        self.varz['${name}'] = 'name'
        self.varz['${my name}'] = 'value'
        assert_equal(self.varz.replace_scalar('${my${name}}'), 'value')
        self.varz['${whos name}'] = 'my'
        assert_equal(self.varz.replace_scalar('${${whos name} ${name}}'),
                     'value')
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'),
                     'value')
        self.varz['${my name}'] = [1, 2, 3]
        assert_equal(self.varz.replace_scalar('${${whos${name}}${name}}'),
                     [1, 2, 3])
        assert_equal(self.varz.replace_scalar('- ${${whos${name}}${name}} -'),
                     '- [1, 2, 3] -')

    def test_math_with_internal_vars(self):
        assert_equal(self.varz.replace_scalar('${${1}+${2}}'), 3)
        assert_equal(self.varz.replace_scalar('${${1}-${2}}'), -1)
        assert_equal(self.varz.replace_scalar('${${1}*${2}}'), 2)
        assert_equal(self.varz.replace_scalar('${${1}//${2}}'), 0)

    def test_math_with_internal_vars_with_spaces(self):
        assert_equal(self.varz.replace_scalar('${${1} + ${2.5}}'), 3.5)
        assert_equal(self.varz.replace_scalar('${${1} - ${2} + 1}'), 0)
        assert_equal(self.varz.replace_scalar('${${1} * ${2} - 1}'), 1)
        assert_equal(self.varz.replace_scalar('${${1} / ${2.0}}'), 0.5)

    def test_math_with_internal_vars_does_not_work_if_first_var_is_float(self):
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${${1.1}+${2}}')
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${${1.1} - ${2}}')
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${${1.1} * ${2}}')
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${${1.1}/${2}}')

    def test_list_variable_as_scalar(self):
        self.varz['@{name}'] = exp = ['spam', 'eggs']
        assert_equal(self.varz.replace_scalar('${name}'), exp)
        assert_equal(self.varz.replace_list(['${name}', 42]), [exp, 42])
        assert_equal(self.varz.replace_string('${name}'), str(exp))

    def test_copy(self):
        varz = Variables()
        varz['${foo}'] = 'bar'
        copy = varz.copy()
        assert_equal(copy['${foo}'], 'bar')

    if JYTHON:

        def test_variable_as_object_in_java(self):
            obj = JavaObject('hello')
            self.varz['${obj}'] = obj
            assert_equal(self.varz['${obj}'], obj)
            assert_equal(self.varz.replace_scalar('${obj} world'),
                         'hello world')

        def test_extended_variables_in_java(self):
            obj = JavaObject('my name')
            self.varz['${obj}'] = obj
            assert_equal(self.varz.replace_list(['${obj.name}']), ['my name'])

    def test_ignore_error(self):
        v = Variables()
        v['${X}'] = 'x'
        v['@{Y}'] = [1, 2, 3]
        for item in [
                '${foo}', 'foo${bar}', '${foo}', '@{zap}', '${Y}[7]', '${inv',
                '${{inv}', '${var}[inv', '${var}[key][inv'
        ]:
            x_at_end = 'x' if (item.count('{') == item.count('}') and
                               item.count('[') == item.count(']')) else '${x}'
            assert_equal(v.replace_string(item, ignore_errors=True), item)
            assert_equal(
                v.replace_string('${x}' + item + '${x}', ignore_errors=True),
                'x' + item + x_at_end)
            assert_equal(v.replace_scalar(item, ignore_errors=True), item)
            assert_equal(
                v.replace_scalar('${x}' + item + '${x}', ignore_errors=True),
                'x' + item + x_at_end)
            assert_equal(v.replace_list([item], ignore_errors=True), [item])
            assert_equal(
                v.replace_list(['${X}', item, '@{Y}'], ignore_errors=True),
                ['x', item, 1, 2, 3])
            assert_equal(
                v.replace_list(['${x}' + item + '${x}', '@{NON}'],
                               ignore_errors=True),
                ['x' + item + x_at_end, '@{NON}'])

    def test_sequence_subscript(self):
        sequences = (
            [42, 'my', 'name'],
            (42, ['foo', 'bar'], 'name'),
            'abcDEF123#@$',
            b'abcDEF123#@$',
            bytearray(b'abcDEF123#@$'),
        )
        for var in sequences:
            self.varz['${var}'] = var
            assert_equal(self.varz.replace_scalar('${var}[0]'), var[0])
            assert_equal(self.varz.replace_scalar('${var}[-2]'), var[-2])
            assert_equal(self.varz.replace_scalar('${var}[::2]'), var[::2])
            assert_equal(self.varz.replace_scalar('${var}[1::2]'), var[1::2])
            assert_equal(self.varz.replace_scalar('${var}[1:-3:2]'),
                         var[1:-3:2])
            assert_raises(VariableError, self.varz.replace_scalar,
                          '${var}[0][1]')

    def test_dict_subscript(self):
        a_key = (42, b'key')
        var = {'foo': 'bar', 42: [4, 2], 'name': b'my-name', a_key: {4: 2}}
        self.varz['${a_key}'] = a_key
        self.varz['${var}'] = var
        assert_equal(self.varz.replace_scalar('${var}[foo][-1]'),
                     var['foo'][-1])
        assert_equal(self.varz.replace_scalar('${var}[${42}][-1]'),
                     var[42][-1])
        assert_equal(self.varz.replace_scalar('${var}[name][:3]'),
                     var['name'][:3])
        assert_equal(self.varz.replace_scalar('${var}[${a_key}][${4}]'),
                     var[a_key][4])
        assert_raises(VariableError, self.varz.replace_scalar, '${var}[1]')
        assert_raises(VariableError, self.varz.replace_scalar, '${var}[42:]')
        assert_raises(VariableError, self.varz.replace_scalar, '${var}[nonex]')

    def test_custom_class_subscriptable_like_sequence(self):
        # the two class attributes are accessible via indices 0 and 1
        # slicing should be supported here as well
        bytes_key = b'my'
        var = PythonObject([1, 2, 3, 4, 5], {bytes_key: 'myname'})
        self.varz['${bytes_key}'] = bytes_key
        self.varz['${var}'] = var
        assert_equal(self.varz.replace_scalar('${var}[${0}][2::2]'), [3, 5])
        assert_equal(self.varz.replace_scalar('${var}[0][2::2]'), [3, 5])
        assert_equal(self.varz.replace_scalar('${var}[1][${bytes_key}][2:]'),
                     'name')
        assert_equal(self.varz.replace_scalar('${var}\\[1]'), str(var) + '[1]')
        assert_equal(self.varz.replace_scalar('${var}[:][0][4]'), var[:][0][4])
        assert_equal(self.varz.replace_scalar('${var}[:-2]'), var[:-2])
        assert_equal(self.varz.replace_scalar('${var}[:7:-2]'), var[:7:-2])
        assert_equal(self.varz.replace_scalar('${var}[2::]'), ())
        assert_raises(VariableError, self.varz.replace_scalar, '${var}[${2}]')
        assert_raises(VariableError, self.varz.replace_scalar,
                      '${var}[${bytes_key}]')

    def test_non_subscriptable(self):
        assert_raises(VariableError, self.varz.replace_scalar, '${1}[1]')
Пример #23
0
 def __init__(self, **kwargs):
     Variables.__init__(self, ['$'])
     for key, value in kwargs.items():
         self['${%s}' % key] = value
Пример #24
0
def run_doc(library_name: str,
            output_filename: str,
            additional_path: str,
            additional_pythonpath_entries: List[str],
            variables: Dict[str, str],
            strip_traceback=True) -> Tuple[Any, Optional[str], Optional[str]]:

    from robot.variables import Variables
    from robot.errors import DataError
    from robot.running.testlibraries import TestLibrary
    from robot.utils import get_error_message

    from robot.libdocpkg.builder import JavaDocBuilder, RESOURCE_EXTENSIONS, SPEC_EXTENSIONS

    from robot.libdocpkg.model import LibraryDoc

    from robot.libdocpkg.robotbuilder import KeywordDocBuilder, LibraryDocBuilder, ResourceDocBuilder
    from robot.libdocpkg.specbuilder import SpecDocBuilder

    def get_robot_version():
        try:
            import robot

            v = str(robot.get_version())
        except BaseException:
            v = "unknown"
        return v

    def get_robot_major_version():
        robot_version = get_robot_version()

        major_version = 3
        try:
            if "." in robot_version:
                major_version = int(robot_version.split(".")[0])
        except BaseException:
            pass

        return major_version

    def _LibraryDocumentation(library_or_resource,
                              name=None,
                              version=None,
                              doc_format=None,
                              variables=None):
        builder = _DocumentationBuilder(library_or_resource, variables)
        try:
            libdoc = builder.build(library_or_resource)
        except DataError:
            raise
        except BaseException:
            raise DataError("Building library '%s' failed: %s" %
                            (library_or_resource, get_error_message()))
        if name:
            libdoc.name = name
        if version:
            libdoc.version = version
        if doc_format:
            libdoc.doc_format = doc_format
        return libdoc

    def _DocumentationBuilder(library_or_resource, variables):
        extension = os.path.splitext(library_or_resource)[1][1:].lower()
        if extension in RESOURCE_EXTENSIONS:
            return ResourceDocBuilder()
        if extension in SPEC_EXTENSIONS:
            return SpecDocBuilder()
        if extension == 'java':
            return JavaDocBuilder()
        return _LibraryDocBuilder(variables)

    class _LibraryDocBuilder(LibraryDocBuilder):
        def __init__(self, variables) -> None:
            super().__init__()
            self.variables = variables

        def build(self, library):
            name, args = self._split_library_name_and_args(library)
            lib = TestLibrary(name, args, variables=self.variables)
            libdoc = LibraryDoc(name=lib.name,
                                doc=self._get_doc(lib),
                                version=lib.version,
                                scope=str(lib.scope),
                                doc_format=lib.doc_format,
                                source=lib.source,
                                lineno=lib.lineno)
            libdoc.inits = self._get_initializers(lib)
            libdoc.keywords = KeywordDocBuilder().build_keywords(lib)
            return libdoc

    warning = None
    old_path = sys.path
    libdoc = None
    try:
        if additional_pythonpath_entries:
            for p in additional_pythonpath_entries:
                if p:
                    sys.path.insert(0, p)

        if additional_path:
            sys.path.insert(0, additional_path)
        vars = Variables()
        for n, v in variables.items():
            vars[n] = v

        libdoc = _LibraryDocumentation(library_name, variables=vars)
        docutils_installed = True
        if libdoc.doc_format == "REST":
            try:
                import docutils
            except:
                docutils_installed = False

        if docutils_installed:
            libdoc.convert_docs_to_html()
        else:
            warning = "reST format requires 'docutils' module to be installed."

        libdoc.save(output_filename,
                    "XML:HTML" if get_robot_major_version() < 4 else "LIBSPEC")

        return (libdoc, None, warning)
    except BaseException as e:
        msg: str = get_error_message()
        if strip_traceback:
            msg = msg[:msg.find("Traceback")].strip()
        return None, msg, warning
    finally:
        sys.path = old_path
Пример #25
0
 def _create_ctx(self):
     suite = TestSuite()
     variables = Variables()
     EXECUTION_CONTEXTS._contexts = []
     EXECUTION_CONTEXTS.start_suite(
         suite, Namespace(variables, suite, suite.resource), self._output())
Пример #26
0
class _VariableScopes:

    def __init__(self):
        variables = GLOBAL_VARIABLES.copy()
        self._suite = self.current = variables
        self._test = None
        self._uk_handlers = []    # FIXME: Better name
        self._set_test_vars = Varz()
        self._set_kw_vars = Varz()

    def __len__(self):
        return len(self.current)

    def replace_list(self, items, replace_until=None):
        return self.current.replace_list(items, replace_until)

    def replace_scalar(self, items):
        return self.current.replace_scalar(items)

    def replace_string(self, string, ignore_errors=False):
        return self.current.replace_string(string, ignore_errors=ignore_errors)

    def set_from_file(self, path, args, overwrite=False):
        variables = self._suite.set_from_file(path, args, overwrite)
        if self._test is not None:
            self._test.set_from_file(variables, overwrite=True)
        for varz, _ in self._uk_handlers:
            varz.set_from_file(variables, overwrite=True)
        if self._uk_handlers:
            self.current.set_from_file(variables, overwrite=True)

    def set_from_variable_table(self, rawvariables, overwrite=False):
        self._suite.set_from_variable_table(rawvariables, overwrite)
        if self._test is not None:
            self._test.set_from_variable_table(rawvariables, overwrite)
        for varz, _ in self._uk_handlers:
            varz.set_from_variable_table(rawvariables, overwrite)
        if self._uk_handlers:
            self.current.set_from_variable_table(rawvariables, overwrite)

    def resolve_delayed(self):
        self.current.resolve_delayed()

    def __getitem__(self, name):
        return self.current[name]

    def __setitem__(self, name, value):
        self.current[name] = value

    def end_suite(self):
        self._suite = self._test = self.current = None

    def start_test(self):
        self._test = self.current = self._suite.copy()

    def end_test(self):
        self.current = self._suite
        self._set_test_vars.clear()

    def start_uk(self):
        self._uk_handlers.append((self.current, self._set_kw_vars))
        self.current = self._suite.copy()
        self.current.update(self._set_test_vars)
        self.current.update(self._set_kw_vars)
        self._set_kw_vars = self._set_kw_vars.copy()

    def end_uk(self):
        self.current, self._set_kw_vars = self._uk_handlers.pop()

    def set_global(self, name, value):
        name, value = self._set_global_suite_or_test(GLOBAL_VARIABLES, name, value)
        for ns in EXECUTION_CONTEXTS.namespaces:
            ns.variables.set_suite(name, value)

    def set_suite(self, name, value):
        name, value = self._set_global_suite_or_test(self._suite, name, value)
        self.set_test(name, value, False)

    def set_test(self, name, value, fail_if_no_test=True):
        if self._test is not None:
            name, value = self._set_global_suite_or_test(self._test, name, value)
        elif fail_if_no_test:
            raise DataError("Cannot set test variable when no test is started")
        for varz, _ in self._uk_handlers:
            varz[name] = value
        self.current[name] = value
        self._set_test_vars[name] = value

    def set_keyword(self, name, value):
        self.current[name] = value
        self._set_kw_vars[name] = value

    def _set_global_suite_or_test(self, variables, name, value):
        variables[name] = value
        # Avoid creating new list/dict objects in different scopes.
        if name[0] != '$':
            name = '$' + name[1:]
            value = variables[name]
        return name, value

    def __iter__(self):
        return iter(self.current)

    @property
    def store(self):
        return self.current.store