def is_var(string, identifiers='$@&'): if not string or not is_string(string) or len(string) < 4: return False if string[0] not in identifiers or string[1] != '{' or string[-1] != '}': return False body = string[2:-1] return '{' not in body and '}' not in body
def replace_string(self, string, ignore_errors=False): """Replaces variables from a string. Result is always a string.""" if not is_string(string): return unic(string) if self._cannot_have_variables(string): return unescape(string) return self._replace_string(string, ignore_errors=ignore_errors)
def TestSuiteFactory(datasources, **options): settings = RobotSettings(options) if is_string(datasources): datasources = [datasources] suite = TestSuiteBuilder().build(*datasources) suite.configure(**settings.suite_config) return suite
def _get_matches_in_iterable(iterable, pattern, case_insensitive=False, whitespace_insensitive=False): if not is_string(pattern): raise TypeError("Pattern must be string, got '%s'." % type_name(pattern)) regexp = False if pattern.startswith('regexp='): pattern = pattern[7:] regexp = True elif pattern.startswith('glob='): pattern = pattern[5:] matcher = Matcher(pattern, caseless=is_truthy(case_insensitive), spaceless=is_truthy(whitespace_insensitive), regexp=regexp) return [string for string in iterable if is_string(string) and matcher.match(string)]
def _write_file(self, path, config, template): outfile = open(path, 'w') \ if is_string(path) else path # unit test hook with outfile: model_writer = RobotModelWriter(outfile, self._js_model, config) writer = HtmlFileWriter(outfile, model_writer) writer.write(template)
def _format_values(self, values): separator = None if is_string(values): values = [values] elif values and values[0].startswith('SEPARATOR='): separator = values.pop(0)[10:] return separator, values
def should_not_be_string(self, item, msg=None): """Fails if the given ``item`` is a string. The default error message can be overridden with the optional ``msg`` argument. """ if is_string(item): self._fail(msg, "'%s' is a string.", item)
def get_library(self, name_or_instance): try: if is_string(name_or_instance): return self.libraries[name_or_instance.replace(' ', '')] else: return self._get_lib_by_instance(name_or_instance) except KeyError: raise DataError("No library '%s' found." % name_or_instance)
def _convert_to_datetime(self, date, input_format): if isinstance(date, datetime): return date if is_number(date): return self._seconds_to_datetime(date) if is_string(date): return self._string_to_datetime(date, input_format) raise ValueError("Unsupported input '%s'." % date)
def _convert_date_to_seconds(self, date, input_format): if is_string(date): return self._string_to_epoch(date, input_format) elif isinstance(date, datetime): return self._mktime_with_millis(date) elif is_number(date): return float(date) raise ValueError("Unsupported input '%s'." % date)
def is_var(string, identifiers='$@&'): if not is_string(string): return False length = len(string) return (length > 3 and string[0] in identifiers and string.rfind('{') == 1 and string.find('}') == length - 1)
def _convert_to_list(self, return_value): if return_value is None: return [None] * self._min_count if is_string(return_value): self._raise_expected_list(return_value) try: return list(return_value) except TypeError: self._raise_expected_list(return_value)
def coerce(self, argument, dryrun=False): if not is_string(argument) \ or (dryrun and contains_var(argument)): return argument try: return self._coerce(argument) except ValueError: raise ValueError('Argument at position %d cannot be coerced to %s.' % (self._position, self._name))
def __init__(self, parent, name, value, comment=None): self.parent = parent self.name = name.rstrip('= ') if name.startswith('$') and value == []: value = '' if is_string(value): value = [value] self.value = value self.comment = Comment(comment)
def __setitem__(self, key, item): if not is_string(key) and not isinstance(key, tuple): raise FrameworkError('Invalid key for ImportCache') key = self._norm_path_key(key) if key not in self._keys: self._keys.append(key) self._items.append(item) else: self._items[self._keys.index(key)] = item
def __setitem__(self, key, item): if not is_string(key) and not isinstance(key, tuple): raise FrameworkError("Invalid key for ImportCache") key = self._norm_path_key(key) if key not in self._keys: self._keys.append(key) self._items.append(item) else: self._items[self._keys.index(key)] = item
def __init__(self, log_path=None, split_log=False, prune_input=False): # log_path can be a custom object in unit tests self._log_dir = dirname(log_path) if is_string(log_path) else None self._split_log = split_log self._prune_input = prune_input self._strings = self._top_level_strings = StringCache() self.basemillis = None self.split_results = [] self.min_level = 'NONE' self._msg_links = {}
def _import_listener(self, listener): if not is_string(listener): # Modules have `__name__`, with others better to use `type_name`. name = getattr(listener, '__name__', None) or type_name(listener) return listener, name name, args = split_args_from_name_or_path(listener) importer = Importer('listener') listener = importer.import_class_or_module(os.path.normpath(name), instantiate_with_args=args) return listener, name
def _yield_visitors(self, visitors): importer = Importer('model modifier') for visitor in visitors: try: if not is_string(visitor): yield visitor else: name, args = split_args_from_name_or_path(visitor) yield importer.import_class_or_module(name, args) except DataError as err: self._log_error(unicode(err))
def _import_listeners(self, listener_data): listeners = [] for listener in listener_data: try: listeners.append(ListenerProxy(listener)) except DataError as err: if not is_string(listener): listener = type_name(listener) LOGGER.error("Taking listener '%s' into use failed: %s" % (listener, unicode(err))) return listeners
def should_not_be_string(self, item, msg=None): """Fails if the given ``item`` is a string. See `Should Be String` for more details about Unicode strings and byte strings. The default error message can be overridden with the optional ``msg`` argument. """ if is_string(item): self._fail(msg, "'%s' is a string.", item)
def _yield_visitors(self, visitors): importer = Importer('model modifier') for visitor in visitors: try: if not is_string(visitor): yield visitor else: name, args = split_args_from_name_or_path(visitor) yield importer.import_class_or_module(name, args) except DataError as err: self._log_error(err.message)
def should_be_string(self, item, msg=None): """Fails if the given ``item`` is not a string. This keyword passes regardless is the ``item`` is a Unicode string or a byte string. Use `Should Be Unicode String` or `Should Be Byte String` if you want to restrict the string type. The default error message can be overridden with the optional ``msg`` argument. """ if not is_string(item): self._fail(msg, "'%s' is not a string.", item)
def __init__(self, listener): if is_string(listener): name, args = split_args_from_name_or_path(listener) listener = self._import_listener(name, args) else: name = type_name(listener) AbstractLoggerProxy.__init__(self, listener) self.name = name self.version = self._get_version(listener) if self.version == 1: LOGGER.warn("Listener '%s' uses deprecated API version 1. " "Switch to API version 2 instead." % self.name)
def _get_matches_in_iterable(iterable, pattern, case_insensitive=False, whitespace_insensitive=False): if not is_string(pattern): raise TypeError("Pattern must be string, got '%s'." % type_name(pattern)) regexp = False if pattern.startswith('regexp='): pattern = pattern[7:] regexp = True elif pattern.startswith('glob='): pattern = pattern[5:] matcher = Matcher(pattern, caseless=is_truthy(case_insensitive), spaceless=is_truthy(whitespace_insensitive), regexp=regexp) return [ string for string in iterable if is_string(string) and matcher.match(string) ]
def _get_handler(self, name): handler = None if not name: raise DataError('Keyword name cannot be empty.') if not is_string(name): raise DataError('Keyword name must be a string.') if '.' in name: handler = self._get_explicit_handler(name) if not handler: handler = self._get_implicit_handler(name) if not handler: handler = self._get_bdd_style_handler(name) return handler
def _get_runner(self, name): if not name: raise DataError('Keyword name cannot be empty.') if not is_string(name): raise DataError('Keyword name must be a string.') runner = self._get_runner_from_test_case_file(name) if not runner and '.' in name: runner = self._get_explicit_runner(name) if not runner: runner = self._get_implicit_runner(name) if not runner: runner = self._get_bdd_style_runner(name) return runner
def import_listeners(cls, listeners, method_names, prefix=None, raise_on_error=False): imported = [] for listener in listeners: try: imported.append(cls(listener, method_names, prefix)) except DataError as err: name = listener if is_string(listener) else type_name(listener) msg = "Taking listener '%s' into use failed: %s" % (name, err) if raise_on_error: raise DataError(msg) LOGGER.error(msg) return imported
def _is_named(self, arg, variables=None): if not (is_string(arg) and '=' in arg): return False name, value = split_from_equals(arg) if value is None: return False if self._argspec.kwargs or self._argspec.kwonlyargs: return True if not self._argspec.supports_named: return False if variables: name = variables.replace_scalar(name) return name in self._argspec.positional
def _is_named(self, arg, variables=None): if not (is_string(arg) and '=' in arg): return False name, value = split_from_equals(arg) if value is None: return False if self._argspec.kwargs: return True if not self._argspec.supports_named: return False if variables: name = variables.replace_scalar(name) return name in self._argspec.positional
def __init__(self, string, identifiers='$@%&*'): self.identifier = None self.base = None self.items = [] self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False if not is_string(string): self._max_end = -1 return self._max_end = len(string) if self._split(string): self._finalize()
def _import_if_needed(self, path_or_variables, args=None): if not is_string(path_or_variables): return path_or_variables LOGGER.info("Importing variable file '%s' with args %s" % (path_or_variables, args)) if path_or_variables.lower().endswith('.yaml'): importer = YamlImporter() else: importer = PythonImporter() try: return importer.import_variables(path_or_variables, args) except: args = 'with arguments %s ' % seq2str2(args) if args else '' raise DataError("Processing variable file '%s' %sfailed: %s" % (path_or_variables, args, get_error_message()))
def __init__(self, string, identifiers='$@%&*'): self.identifier = None self.base = None self.index = None self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False if not is_string(string): self._max_end = -1 return self._max_end = len(string) try: self._split(string) except ValueError: pass else: self._finalize()
def should_be_string(self, item, msg=None): """Fails if the given ``item`` is not a string. With Python 2, except with IronPython, this keyword passes regardless is the ``item`` a Unicode string or a byte string. Use `Should Be Unicode String` or `Should Be Byte String` if you want to restrict the string type. Notice that with Python 2, except with IronPython, ``'string'`` creates a byte string and ``u'unicode'`` must be used to create a Unicode string. With Python 3 and IronPython, this keyword passes if the string is a Unicode string but fails if it is bytes. Notice that with both Python 3 and IronPython, ``'string'`` creates a Unicode string, and ``b'bytes'`` must be used to create a byte string. The default error message can be overridden with the optional ``msg`` argument. """ if not is_string(item): self._fail(msg, "'%s' is not a string.", item)
def __init__(self, source, source_type=RESOURCE_FILE_TYPE): if is_string(source): resource = ResourceFileBuilder().build(source) else: resource = source source = resource.source basename = os.path.basename(source) if source else None self.name = os.path.splitext(basename)[0] \ if source_type == self.RESOURCE_FILE_TYPE else None self.doc = resource.doc self.handlers = HandlerStore(basename, source_type) self.source = source self.source_type = source_type for kw in resource.keywords: try: handler = self._create_handler(kw) except DataError as error: handler = UserErrorHandler(error, kw.name, self.name) self._log_creating_failed(handler, error) embedded = isinstance(handler, EmbeddedArgumentsHandler) try: self.handlers.add(handler, embedded) except DataError as error: self._log_creating_failed(handler, error)
def _import_resource_if_needed(self, path_or_data): if not is_string(path_or_data): return path_or_data, path_or_data.source return ResourceData(path_or_data).populate(), path_or_data