Robot Framework
BuiltIn.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 from collections import OrderedDict
17 import difflib
18 import re
19 import time
20 
21 from robot.api import logger, SkipExecution
22 from robot.api.deco import keyword
23 from robot.errors import (BreakLoop, ContinueLoop, DataError, ExecutionFailed,
24  ExecutionFailures, ExecutionPassed, PassExecution,
25  ReturnFromKeyword, VariableError)
26 from robot.running import Keyword, RUN_KW_REGISTER
27 from robot.running.context import EXECUTION_CONTEXTS
28 from robot.running.usererrorhandler import UserErrorHandler
29 from robot.utils import (DotDict, escape, format_assign_message, get_error_message,
30  get_time, html_escape, is_falsy, is_integer, is_list_like,
31  is_string, is_truthy, Matcher, normalize,
32  normalize_whitespace, parse_re_flags, parse_time, prepr,
33  plural_or_not as s, RERAISED_EXCEPTIONS, safe_str,
34  secs_to_timestr, seq2str, split_from_equals,
35  timestr_to_secs, type_name)
36 from robot.utils.asserts import assert_equal, assert_not_equal
37 from robot.variables import (evaluate_expression, is_dict_variable,
38  is_list_variable, search_variable,
39  DictVariableTableValue, VariableTableValue)
40 from robot.version import get_version
41 
42 
43 # FIXME: Clean-up registering run keyword variants!
44 # https://github.com/robotframework/robotframework/issues/2190
45 
46 def run_keyword_variant(resolve, dry_run=False):
47  def decorator(method):
48  RUN_KW_REGISTER.register_run_keyword('BuiltIn', method.__name__,
49  resolve, deprecation_warning=False,
50  dry_run=dry_run)
51  return method
52  return decorator
53 
54 
56 
57  @property
58  _context = property
59 
60  def _context(self):
61  return self._get_context_get_context()
62 
63  def _get_context(self, top=False):
64  ctx = EXECUTION_CONTEXTS.current if not top else EXECUTION_CONTEXTS.top
65  if ctx is None:
66  raise RobotNotRunningError('Cannot access execution context')
67  return ctx
68 
69  @property
70  _namespace = property
71 
72  def _namespace(self):
73  return self._get_context_get_context().namespace
74 
75  @property
76  _variables = property
77 
78  def _variables(self):
79  return self._namespace_namespace_namespace.variables
80 
81  def _matches(self, string, pattern, caseless=False):
82  # Must use this instead of fnmatch when string may contain newlines.
83  matcher = Matcher(pattern, caseless=caseless, spaceless=False)
84  return matcher.match(string)
85 
86  def _is_true(self, condition):
87  if is_string(condition):
88  condition = self.evaluate(condition)
89  return bool(condition)
90 
91  def _log_types(self, *args):
92  self._log_types_at_level_log_types_at_level('DEBUG', *args)
93 
94  def _log_types_at_level(self, level, *args):
95  msg = ["Argument types are:"] + [self._get_type_get_type(a) for a in args]
96  self.log('\n'.join(msg), level)
97 
98  def _get_type(self, arg):
99  return str(type(arg))
100 
101 
103 
104 
129  def convert_to_integer(self, item, base=None):
130  self._log_types_log_types(item)
131  return self._convert_to_integer_convert_to_integer(item, base)
132 
133  def _convert_to_integer(self, orig, base=None):
134  try:
135  item, base = self._get_base_get_base(orig, base)
136  if base:
137  return int(item, self._convert_to_integer_convert_to_integer(base))
138  return int(item)
139  except:
140  raise RuntimeError("'%s' cannot be converted to an integer: %s"
141  % (orig, get_error_message()))
142 
143  def _get_base(self, item, base):
144  if not is_string(item):
145  return item, base
146  item = normalize(item)
147  if item.startswith(('-', '+')):
148  sign = item[0]
149  item = item[1:]
150  else:
151  sign = ''
152  bases = {'0b': 2, '0o': 8, '0x': 16}
153  if base or not item.startswith(tuple(bases)):
154  return sign+item, base
155  return sign+item[2:], bases[item[:2]]
156 
157 
176  def convert_to_binary(self, item, base=None, prefix=None, length=None):
177  return self._convert_to_bin_oct_hex_convert_to_bin_oct_hex(item, base, prefix, length, 'b')
178 
179 
198  def convert_to_octal(self, item, base=None, prefix=None, length=None):
199  return self._convert_to_bin_oct_hex_convert_to_bin_oct_hex(item, base, prefix, length, 'o')
200 
201 
224  def convert_to_hex(self, item, base=None, prefix=None, length=None,
225  lowercase=False):
226  spec = 'x' if lowercase else 'X'
227  return self._convert_to_bin_oct_hex_convert_to_bin_oct_hex(item, base, prefix, length, spec)
228 
229  def _convert_to_bin_oct_hex(self, item, base, prefix, length, format_spec):
230  self._log_types_log_types(item)
231  ret = format(self._convert_to_integer_convert_to_integer(item, base), format_spec)
232  prefix = prefix or ''
233  if ret[0] == '-':
234  prefix = '-' + prefix
235  ret = ret[1:]
236  if length:
237  ret = ret.rjust(self._convert_to_integer_convert_to_integer(length), '0')
238  return prefix + ret
239 
240 
269  def convert_to_number(self, item, precision=None):
270  self._log_types_log_types(item)
271  return self._convert_to_number_convert_to_number(item, precision)
272 
273  def _convert_to_number(self, item, precision=None):
274  number = self._convert_to_number_without_precision_convert_to_number_without_precision(item)
275  if precision is not None:
276  number = float(round(number, self._convert_to_integer_convert_to_integer(precision)))
277  return number
278 
280  try:
281  return float(item)
282  except:
283  error = get_error_message()
284  try:
285  return float(self._convert_to_integer_convert_to_integer(item))
286  except RuntimeError:
287  raise RuntimeError("'%s' cannot be converted to a floating "
288  "point number: %s" % (item, error))
289 
290 
300  def convert_to_string(self, item):
301  self._log_types_log_types(item)
302  return safe_str(item)
303 
304 
311  def convert_to_boolean(self, item):
312  self._log_types_log_types(item)
313  if is_string(item):
314  if item.upper() == 'TRUE':
315  return True
316  if item.upper() == 'FALSE':
317  return False
318  return bool(item)
319 
320 
364  def convert_to_bytes(self, input, input_type='text'):
365  try:
366  try:
367  ordinals = getattr(self, '_get_ordinals_from_%s' % input_type)
368  except AttributeError:
369  raise RuntimeError("Invalid input type '%s'." % input_type)
370  return bytes(bytearray(o for o in ordinals(input)))
371  except:
372  raise RuntimeError("Creating bytes failed: %s" % get_error_message())
373 
374  def _get_ordinals_from_text(self, input):
375  for char in input:
376  ordinal = char if is_integer(char) else ord(char)
377  yield self._test_ordinal_test_ordinal(ordinal, char, 'Character')
378 
379  def _test_ordinal(self, ordinal, original, type):
380  if 0 <= ordinal <= 255:
381  return ordinal
382  raise RuntimeError("%s '%s' cannot be represented as a byte."
383  % (type, original))
384 
385  def _get_ordinals_from_int(self, input):
386  if is_string(input):
387  input = input.split()
388  elif is_integer(input):
389  input = [input]
390  for integer in input:
391  ordinal = self._convert_to_integer_convert_to_integer(integer)
392  yield self._test_ordinal_test_ordinal(ordinal, integer, 'Integer')
393 
394  def _get_ordinals_from_hex(self, input):
395  for token in self._input_to_tokens_input_to_tokens(input, length=2):
396  ordinal = self._convert_to_integer_convert_to_integer(token, base=16)
397  yield self._test_ordinal_test_ordinal(ordinal, token, 'Hex value')
398 
399  def _get_ordinals_from_bin(self, input):
400  for token in self._input_to_tokens_input_to_tokens(input, length=8):
401  ordinal = self._convert_to_integer_convert_to_integer(token, base=2)
402  yield self._test_ordinal_test_ordinal(ordinal, token, 'Binary value')
403 
404  def _input_to_tokens(self, input, length):
405  if not is_string(input):
406  return input
407  input = ''.join(input.split())
408  if len(input) % length != 0:
409  raise RuntimeError('Expected input to be multiple of %d.' % length)
410  return (input[i:i+length] for i in range(0, len(input), length))
411 
412 
422  def create_list(self, *items):
423  return list(items)
424 
425  @run_keyword_variant(resolve=0)
426 
456  def create_dictionary(self, *items):
457  separate, combined = self._split_dict_items_split_dict_items(items)
458  result = DotDict(self._format_separate_dict_items_format_separate_dict_items(separate))
459  combined = DictVariableTableValue(combined).resolve(self._variables_variables_variables)
460  result.update(combined)
461  return result
462 
463  def _split_dict_items(self, items):
464  separate = []
465  for item in items:
466  name, value = split_from_equals(item)
467  if value is not None or is_dict_variable(item):
468  break
469  separate.append(item)
470  return separate, items[len(separate):]
471 
472  def _format_separate_dict_items(self, separate):
473  separate = self._variables_variables_variables.replace_list(separate)
474  if len(separate) % 2 != 0:
475  raise DataError('Expected even number of keys and values, got %d.'
476  % len(separate))
477  return [separate[i:i+2] for i in range(0, len(separate), 2)]
478 
479 
481 
482  def _set_and_remove_tags(self, tags):
483  set_tags = [tag for tag in tags if not tag.startswith('-')]
484  remove_tags = [tag[1:] for tag in tags if tag.startswith('-')]
485  if remove_tags:
486  self.remove_tags(*remove_tags)
487  if set_tags:
488  self.set_tags(*set_tags)
489 
490 
512  def fail(self, msg=None, *tags):
513  self._set_and_remove_tags_set_and_remove_tags(tags)
514  raise AssertionError(msg) if msg else AssertionError()
515 
516 
524  def fatal_error(self, msg=None):
525  error = AssertionError(msg) if msg else AssertionError()
526  error.ROBOT_EXIT_ON_FAILURE = True
527  raise error
528 
529 
534  def should_not_be_true(self, condition, msg=None):
535  if self._is_true_is_true(condition):
536  raise AssertionError(msg or "'%s' should not be true." % condition)
537 
538 
565  def should_be_true(self, condition, msg=None):
566  if not self._is_true_is_true(condition):
567  raise AssertionError(msg or "'%s' should be true." % condition)
568 
569 
608  def should_be_equal(self, first, second, msg=None, values=True,
609  ignore_case=False, formatter='str', strip_spaces=False,
610  collapse_spaces=False):
611  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
612  if is_string(first) and is_string(second):
613  if ignore_case:
614  first = first.lower()
615  second = second.lower()
616  if strip_spaces:
617  first = self._strip_spaces_strip_spaces(first, strip_spaces)
618  second = self._strip_spaces_strip_spaces(second, strip_spaces)
619  if collapse_spaces:
620  first = self._collapse_spaces_collapse_spaces(first)
621  second = self._collapse_spaces_collapse_spaces(second)
622  self._should_be_equal_should_be_equal(first, second, msg, values, formatter)
623 
624  def _should_be_equal(self, first, second, msg, values, formatter='str'):
625  include_values = self._include_values_include_values(values)
626  formatter = self._get_formatter(formatter)
627  if first == second:
628  return
629  if include_values and is_string(first) and is_string(second):
630  self._raise_multi_diff_raise_multi_diff(first, second, msg, formatter)
631  assert_equal(first, second, msg, include_values, formatter)
632 
633  def _log_types_at_info_if_different(self, first, second):
634  level = 'DEBUG' if type(first) == type(second) else 'INFO'
635  self._log_types_at_level_log_types_at_level(level, first, second)
636 
637  def _raise_multi_diff(self, first, second, msg, formatter):
638  first_lines = first.splitlines(True) # keepends
639  second_lines = second.splitlines(True)
640  if len(first_lines) < 3 or len(second_lines) < 3:
641  return
642  self.log("%s\n\n!=\n\n%s" % (first.rstrip(), second.rstrip()))
643  diffs = list(difflib.unified_diff(first_lines, second_lines,
644  fromfile='first', tofile='second',
645  lineterm=''))
646  diffs[3:] = [item[0] + formatter(item[1:]).rstrip() for item in diffs[3:]]
647  prefix = 'Multiline strings are different:'
648  if msg:
649  prefix = '%s: %s' % (msg, prefix)
650  raise AssertionError('\n'.join([prefix] + diffs))
651 
652  def _include_values(self, values):
653  return is_truthy(values) and str(values).upper() != 'NO VALUES'
654 
655  def _strip_spaces(self, value, strip_spaces):
656  if not is_string(value):
657  return value
658  if not is_string(strip_spaces):
659  return value.strip() if strip_spaces else value
660  if strip_spaces.upper() == 'LEADING':
661  return value.lstrip()
662  if strip_spaces.upper() == 'TRAILING':
663  return value.rstrip()
664  return value.strip() if is_truthy(strip_spaces) else value
665 
666  def _collapse_spaces(self, value):
667  return re.sub(r'\s+', ' ', value) if is_string(value) else value
668 
669 
690  def should_not_be_equal(self, first, second, msg=None, values=True,
691  ignore_case=False, strip_spaces=False,
692  collapse_spaces=False):
693  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
694  if is_string(first) and is_string(second):
695  if ignore_case:
696  first = first.lower()
697  second = second.lower()
698  if strip_spaces:
699  first = self._strip_spaces_strip_spaces(first, strip_spaces)
700  second = self._strip_spaces_strip_spaces(second, strip_spaces)
701  if collapse_spaces:
702  first = self._collapse_spaces_collapse_spaces(first)
703  second = self._collapse_spaces_collapse_spaces(second)
704  self._should_not_be_equal_should_not_be_equal(first, second, msg, values)
705 
706  def _should_not_be_equal(self, first, second, msg, values):
707  assert_not_equal(first, second, msg, self._include_values_include_values(values))
708 
709 
719  def should_not_be_equal_as_integers(self, first, second, msg=None,
720  values=True, base=None):
721  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
722  self._should_not_be_equal_should_not_be_equal(self._convert_to_integer(first, base),
723  self._convert_to_integer(second, base),
724  msg, values)
725 
726 
739  def should_be_equal_as_integers(self, first, second, msg=None, values=True,
740  base=None):
741  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
742  self._should_be_equal_should_be_equal(self._convert_to_integer(first, base),
743  self._convert_to_integer(second, base),
744  msg, values)
745 
746 
756  def should_not_be_equal_as_numbers(self, first, second, msg=None,
757  values=True, precision=6):
758  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
759  first = self._convert_to_number(first, precision)
760  second = self._convert_to_number(second, precision)
761  self._should_not_be_equal_should_not_be_equal(first, second, msg, values)
762 
763 
794  def should_be_equal_as_numbers(self, first, second, msg=None, values=True,
795  precision=6):
796  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
797  first = self._convert_to_number(first, precision)
798  second = self._convert_to_number(second, precision)
799  self._should_be_equal_should_be_equal(first, second, msg, values)
800 
801 
825  def should_not_be_equal_as_strings(self, first, second, msg=None, values=True,
826  ignore_case=False, strip_spaces=False,
827  collapse_spaces=False):
828  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
829  first = safe_str(first)
830  second = safe_str(second)
831  if ignore_case:
832  first = first.lower()
833  second = second.lower()
834  if strip_spaces:
835  first = self._strip_spaces_strip_spaces(first, strip_spaces)
836  second = self._strip_spaces_strip_spaces(second, strip_spaces)
837  if collapse_spaces:
838  first = self._collapse_spaces_collapse_spaces(first)
839  second = self._collapse_spaces_collapse_spaces(second)
840  self._should_not_be_equal_should_not_be_equal(first, second, msg, values)
841 
842 
866  def should_be_equal_as_strings(self, first, second, msg=None, values=True,
867  ignore_case=False, strip_spaces=False,
868  formatter='str', collapse_spaces=False):
869  self._log_types_at_info_if_different_log_types_at_info_if_different(first, second)
870  first = safe_str(first)
871  second = safe_str(second)
872  if ignore_case:
873  first = first.lower()
874  second = second.lower()
875  if strip_spaces:
876  first = self._strip_spaces_strip_spaces(first, strip_spaces)
877  second = self._strip_spaces_strip_spaces(second, strip_spaces)
878  if collapse_spaces:
879  first = self._collapse_spaces_collapse_spaces(first)
880  second = self._collapse_spaces_collapse_spaces(second)
881  self._should_be_equal_should_be_equal(first, second, msg, values, formatter)
882 
883 
889  def should_not_start_with(self, str1, str2, msg=None, values=True,
890  ignore_case=False, strip_spaces=False,
891  collapse_spaces=False):
892  if ignore_case:
893  str1 = str1.lower()
894  str2 = str2.lower()
895  if strip_spaces:
896  str1 = self._strip_spaces_strip_spaces(str1, strip_spaces)
897  str2 = self._strip_spaces_strip_spaces(str2, strip_spaces)
898  if collapse_spaces:
899  str1 = self._collapse_spaces_collapse_spaces(str1)
900  str2 = self._collapse_spaces_collapse_spaces(str2)
901  if str1.startswith(str2):
902  raise AssertionError(self._get_string_msg_get_string_msg(str1, str2, msg, values,
903  'starts with'))
904 
905 
911  def should_start_with(self, str1, str2, msg=None, values=True,
912  ignore_case=False, strip_spaces=False, collapse_spaces=False):
913  if ignore_case:
914  str1 = str1.lower()
915  str2 = str2.lower()
916  if strip_spaces:
917  str1 = self._strip_spaces_strip_spaces(str1, strip_spaces)
918  str2 = self._strip_spaces_strip_spaces(str2, strip_spaces)
919  if collapse_spaces:
920  str1 = self._collapse_spaces_collapse_spaces(str1)
921  str2 = self._collapse_spaces_collapse_spaces(str2)
922  if not str1.startswith(str2):
923  raise AssertionError(self._get_string_msg_get_string_msg(str1, str2, msg, values,
924  'does not start with'))
925 
926 
932  def should_not_end_with(self, str1, str2, msg=None, values=True,
933  ignore_case=False, strip_spaces=False,
934  collapse_spaces=False):
935  if ignore_case:
936  str1 = str1.lower()
937  str2 = str2.lower()
938  if strip_spaces:
939  str1 = self._strip_spaces_strip_spaces(str1, strip_spaces)
940  str2 = self._strip_spaces_strip_spaces(str2, strip_spaces)
941  if collapse_spaces:
942  str1 = self._collapse_spaces_collapse_spaces(str1)
943  str2 = self._collapse_spaces_collapse_spaces(str2)
944  if str1.endswith(str2):
945  raise AssertionError(self._get_string_msg_get_string_msg(str1, str2, msg, values,
946  'ends with'))
947 
948 
954  def should_end_with(self, str1, str2, msg=None, values=True,
955  ignore_case=False, strip_spaces=False, collapse_spaces=False):
956  if ignore_case:
957  str1 = str1.lower()
958  str2 = str2.lower()
959  if strip_spaces:
960  str1 = self._strip_spaces_strip_spaces(str1, strip_spaces)
961  str2 = self._strip_spaces_strip_spaces(str2, strip_spaces)
962  if collapse_spaces:
963  str1 = self._collapse_spaces_collapse_spaces(str1)
964  str2 = self._collapse_spaces_collapse_spaces(str2)
965  if not str1.endswith(str2):
966  raise AssertionError(self._get_string_msg_get_string_msg(str1, str2, msg, values,
967  'does not end with'))
968 
969 
995  def should_not_contain(self, container, item, msg=None, values=True,
996  ignore_case=False, strip_spaces=False,
997  collapse_spaces=False):
998  # TODO: It is inconsistent that errors show original case in 'container'
999  # 'item' is in lower case. Should rather show original case everywhere
1000  # and add separate '(case-insensitive)' not to the error message.
1001  # This same logic should be used with all keywords supporting
1002  # case-insensitive comparisons.
1003  orig_container = container
1004  if ignore_case and is_string(item):
1005  item = item.lower()
1006  if is_string(container):
1007  container = container.lower()
1008  elif is_list_like(container):
1009  container = set(x.lower() if is_string(x) else x for x in container)
1010  if strip_spaces and is_string(item):
1011  item = self._strip_spaces_strip_spaces(item, strip_spaces)
1012  if is_string(container):
1013  container = self._strip_spaces_strip_spaces(container, strip_spaces)
1014  elif is_list_like(container):
1015  container = set(self._strip_spaces_strip_spaces(x, strip_spaces) for x in container)
1016  if collapse_spaces and is_string(item):
1017  item = self._collapse_spaces_collapse_spaces(item)
1018  if is_string(container):
1019  container = self._collapse_spaces_collapse_spaces(container)
1020  elif is_list_like(container):
1021  container = set(self._collapse_spaces_collapse_spaces(x) for x in container)
1022  if item in container:
1023  raise AssertionError(self._get_string_msg_get_string_msg(orig_container, item, msg,
1024  values, 'contains'))
1025 
1026 
1057  def should_contain(self, container, item, msg=None, values=True,
1058  ignore_case=False, strip_spaces=False, collapse_spaces=False):
1059  orig_container = container
1060  if ignore_case and is_string(item):
1061  item = item.lower()
1062  if is_string(container):
1063  container = container.lower()
1064  elif is_list_like(container):
1065  container = set(x.lower() if is_string(x) else x for x in container)
1066  if strip_spaces and is_string(item):
1067  item = self._strip_spaces_strip_spaces(item, strip_spaces)
1068  if is_string(container):
1069  container = self._strip_spaces_strip_spaces(container, strip_spaces)
1070  elif is_list_like(container):
1071  container = set(self._strip_spaces_strip_spaces(x, strip_spaces) for x in container)
1072  if collapse_spaces and is_string(item):
1073  item = self._collapse_spaces_collapse_spaces(item)
1074  if is_string(container):
1075  container = self._collapse_spaces_collapse_spaces(container)
1076  elif is_list_like(container):
1077  container = set(self._collapse_spaces_collapse_spaces(x) for x in container)
1078  if item not in container:
1079  raise AssertionError(self._get_string_msg_get_string_msg(orig_container, item, msg,
1080  values, 'does not contain'))
1081 
1082 
1103  def should_contain_any(self, container, *items, **configuration):
1104  msg = configuration.pop('msg', None)
1105  values = configuration.pop('values', True)
1106  ignore_case = is_truthy(configuration.pop('ignore_case', False))
1107  strip_spaces = configuration.pop('strip_spaces', False)
1108  collapse_spaces = is_truthy(configuration.pop('collapse_spaces', False))
1109  if configuration:
1110  raise RuntimeError("Unsupported configuration parameter%s: %s."
1111  % (s(configuration), seq2str(sorted(configuration))))
1112  if not items:
1113  raise RuntimeError('One or more items required.')
1114  orig_container = container
1115  if ignore_case:
1116  items = [x.lower() if is_string(x) else x for x in items]
1117  if is_string(container):
1118  container = container.lower()
1119  elif is_list_like(container):
1120  container = set(x.lower() if is_string(x) else x for x in container)
1121  if strip_spaces:
1122  items = [self._strip_spaces_strip_spaces(x, strip_spaces) for x in items]
1123  if is_string(container):
1124  container = self._strip_spaces_strip_spaces(container, strip_spaces)
1125  elif is_list_like(container):
1126  container = set(self._strip_spaces_strip_spaces(x, strip_spaces) for x in container)
1127  if collapse_spaces:
1128  items = [self._collapse_spaces_collapse_spaces(x) for x in items]
1129  if is_string(container):
1130  container = self._collapse_spaces_collapse_spaces(container)
1131  elif is_list_like(container):
1132  container = set(self._collapse_spaces_collapse_spaces(x) for x in container)
1133  if not any(item in container for item in items):
1134  msg = self._get_string_msg_get_string_msg(orig_container,
1135  seq2str(items, lastsep=' or '),
1136  msg, values,
1137  'does not contain any of',
1138  quote_item2=False)
1139  raise AssertionError(msg)
1140 
1141 
1161  def should_not_contain_any(self, container, *items, **configuration):
1162  msg = configuration.pop('msg', None)
1163  values = configuration.pop('values', True)
1164  ignore_case = is_truthy(configuration.pop('ignore_case', False))
1165  strip_spaces = configuration.pop('strip_spaces', False)
1166  collapse_spaces = is_truthy(configuration.pop('collapse_spaces', False))
1167  if configuration:
1168  raise RuntimeError("Unsupported configuration parameter%s: %s."
1169  % (s(configuration), seq2str(sorted(configuration))))
1170  if not items:
1171  raise RuntimeError('One or more items required.')
1172  orig_container = container
1173  if ignore_case:
1174  items = [x.lower() if is_string(x) else x for x in items]
1175  if is_string(container):
1176  container = container.lower()
1177  elif is_list_like(container):
1178  container = set(x.lower() if is_string(x) else x for x in container)
1179  if strip_spaces:
1180  items = [self._strip_spaces_strip_spaces(x, strip_spaces) for x in items]
1181  if is_string(container):
1182  container = self._strip_spaces_strip_spaces(container, strip_spaces)
1183  elif is_list_like(container):
1184  container = set(self._strip_spaces_strip_spaces(x, strip_spaces) for x in container)
1185  if collapse_spaces:
1186  items = [self._collapse_spaces_collapse_spaces(x) for x in items]
1187  if is_string(container):
1188  container = self._collapse_spaces_collapse_spaces(container)
1189  elif is_list_like(container):
1190  container = set(self._collapse_spaces_collapse_spaces(x) for x in container)
1191  if any(item in container for item in items):
1192  msg = self._get_string_msg_get_string_msg(orig_container,
1193  seq2str(items, lastsep=' or '),
1194  msg, values,
1195  'contains one or more of',
1196  quote_item2=False)
1197  raise AssertionError(msg)
1198 
1199 
1227  def should_contain_x_times(self, container, item, count, msg=None,
1228  ignore_case=False, strip_spaces=False,
1229  collapse_spaces=False):
1230  count = self._convert_to_integer(count)
1231  orig_container = container
1232  if is_string(item):
1233  if ignore_case:
1234  item = item.lower()
1235  if is_string(container):
1236  container = container.lower()
1237  elif is_list_like(container):
1238  container = [x.lower() if is_string(x) else x for x in container]
1239  if strip_spaces:
1240  item = self._strip_spaces_strip_spaces(item, strip_spaces)
1241  if is_string(container):
1242  container = self._strip_spaces_strip_spaces(container, strip_spaces)
1243  elif is_list_like(container):
1244  container = [self._strip_spaces_strip_spaces(x, strip_spaces) for x in container]
1245  if collapse_spaces:
1246  item = self._collapse_spaces_collapse_spaces(item)
1247  if is_string(container):
1248  container = self._collapse_spaces_collapse_spaces(container)
1249  elif is_list_like(container):
1250  container = [self._collapse_spaces_collapse_spaces(x) for x in container]
1251  x = self.get_countget_count(container, item)
1252  if not msg:
1253  msg = "%r contains '%s' %d time%s, not %d time%s." \
1254  % (orig_container, item, x, s(x), count, s(count))
1255  self.should_be_equal_as_integersshould_be_equal_as_integers(x, count, msg, values=False)
1256 
1257 
1266  def get_count(self, container, item):
1267  if not hasattr(container, 'count'):
1268  try:
1269  container = list(container)
1270  except:
1271  raise RuntimeError("Converting '%s' to list failed: %s"
1272  % (container, get_error_message()))
1273  count = container.count(item)
1274  self.log('Item found from container %d time%s.' % (count, s(count)))
1275  return count
1276 
1277 
1289  def should_not_match(self, string, pattern, msg=None, values=True,
1290  ignore_case=False):
1291  if self._matches_matches(string, pattern, caseless=ignore_case):
1292  raise AssertionError(self._get_string_msg_get_string_msg(string, pattern, msg,
1293  values, 'matches'))
1294 
1295 
1308  def should_match(self, string, pattern, msg=None, values=True,
1309  ignore_case=False):
1310  if not self._matches_matches(string, pattern, caseless=ignore_case):
1311  raise AssertionError(self._get_string_msg_get_string_msg(string, pattern, msg,
1312  values, 'does not match'))
1313 
1314 
1352  def should_match_regexp(self, string, pattern, msg=None, values=True, flags=None):
1353  res = re.search(pattern, string, flags=parse_re_flags(flags))
1354  if res is None:
1355  raise AssertionError(self._get_string_msg_get_string_msg(string, pattern, msg,
1356  values, 'does not match'))
1357  match = res.group(0)
1358  groups = res.groups()
1359  if groups:
1360  return [match] + list(groups)
1361  return match
1362 
1363 
1367  def should_not_match_regexp(self, string, pattern, msg=None, values=True, flags=None):
1368  if re.search(pattern, string, flags=parse_re_flags(flags)) is not None:
1369  raise AssertionError(self._get_string_msg_get_string_msg(string, pattern, msg,
1370  values, 'matches'))
1371 
1372 
1392  def get_length(self, item):
1393  length = self._get_length_get_length(item)
1394  self.log('Length is %d' % length)
1395  return length
1396 
1397  def _get_length(self, item):
1398  try:
1399  return len(item)
1400  except RERAISED_EXCEPTIONS:
1401  raise
1402  except:
1403  try:
1404  return item.length()
1405  except RERAISED_EXCEPTIONS:
1406  raise
1407  except:
1408  try:
1409  return item.size()
1410  except RERAISED_EXCEPTIONS:
1411  raise
1412  except:
1413  try:
1414  return item.length
1415  except RERAISED_EXCEPTIONS:
1416  raise
1417  except:
1418  raise RuntimeError("Could not get length of '%s'." % item)
1419 
1420 
1425  def length_should_be(self, item, length, msg=None):
1426  length = self._convert_to_integer(length)
1427  actual = self.get_lengthget_length(item)
1428  if actual != length:
1429  raise AssertionError(msg or "Length of '%s' should be %d but is %d."
1430  % (item, length, actual))
1431 
1432 
1437  def should_be_empty(self, item, msg=None):
1438  if self.get_lengthget_length(item) > 0:
1439  raise AssertionError(msg or "'%s' should be empty." % (item,))
1440 
1441 
1446  def should_not_be_empty(self, item, msg=None):
1447  if self.get_lengthget_length(item) == 0:
1448  raise AssertionError(msg or "'%s' should not be empty." % (item,))
1449 
1450  def _get_string_msg(self, item1, item2, custom_message, include_values,
1451  delimiter, quote_item1=True, quote_item2=True):
1452  if custom_message and not self._include_values_include_values(include_values):
1453  return custom_message
1454  item1 = "'%s'" % safe_str(item1) if quote_item1 else safe_str(item1)
1455  item2 = "'%s'" % safe_str(item2) if quote_item2 else safe_str(item2)
1456  default_message = '%s %s %s' % (item1, delimiter, item2)
1457  if not custom_message:
1458  return default_message
1459  return '%s: %s' % (custom_message, default_message)
1460 
1461 
1463 
1464 
1489  def get_variables(self, no_decoration=False):
1490  return self._variables_variables_variables.as_dict(decoration=is_falsy(no_decoration))
1491 
1492  @keyword(types=None)
1493  @run_keyword_variant(resolve=0)
1494 
1510  def get_variable_value(self, name, default=None):
1511  try:
1512  name = self._get_var_name_get_var_name(name, require_assign=False)
1513  return self._variables_variables_variables.replace_scalar(name)
1514  except VariableError:
1515  return self._variables_variables_variables.replace_scalar(default)
1516 
1517 
1518  def log_variables(self, level='INFO'):
1519  variables = self.get_variablesget_variables()
1520  for name in sorted(variables, key=lambda s: s[2:-1].lower()):
1521  name, value = self._get_logged_variable_get_logged_variable(name, variables)
1522  msg = format_assign_message(name, value, cut_long=False)
1523  self.log(msg, level)
1524 
1525  def _get_logged_variable(self, name, variables):
1526  value = variables[name]
1527  try:
1528  if name[0] == '@':
1529  value = list(value)
1530  if name[0] == '&':
1531  value = OrderedDict(value)
1532  except RERAISED_EXCEPTIONS:
1533  raise
1534  except:
1535  name = '$' + name[1:]
1536  return name, value
1537 
1538  @run_keyword_variant(resolve=0)
1539 
1550  def variable_should_exist(self, name, msg=None):
1551  name = self._get_var_name_get_var_name(name)
1552  try:
1553  self._variables_variables_variables.replace_scalar(name)
1554  except VariableError:
1555  raise AssertionError(self._variables_variables_variables.replace_string(msg)
1556  if msg else "Variable '%s' does not exist." % name)
1557 
1558  @run_keyword_variant(resolve=0)
1559 
1570  def variable_should_not_exist(self, name, msg=None):
1571  name = self._get_var_name_get_var_name(name)
1572  try:
1573  self._variables_variables_variables.replace_scalar(name)
1574  except VariableError:
1575  pass
1576  else:
1577  raise AssertionError(self._variables_variables_variables.replace_string(msg)
1578  if msg else "Variable '%s' exists." % name)
1579 
1580 
1596  def replace_variables(self, text):
1597  return self._variables_variables_variables.replace_scalar(text)
1598 
1599 
1618  def set_variable(self, *values):
1619  if len(values) == 0:
1620  return ''
1621  elif len(values) == 1:
1622  return values[0]
1623  else:
1624  return list(values)
1625 
1626  @run_keyword_variant(resolve=0)
1627 
1657  def set_local_variable(self, name, *values):
1658  name = self._get_var_name_get_var_name(name)
1659  value = self._get_var_value_get_var_value(name, values)
1660  self._variables_variables_variables.set_local_variable(name, value)
1661  self._log_set_variable_log_set_variable(name, value)
1662 
1663  @run_keyword_variant(resolve=0)
1664 
1683  def set_test_variable(self, name, *values):
1684  name = self._get_var_name_get_var_name(name)
1685  value = self._get_var_value_get_var_value(name, values)
1686  self._variables_variables_variables.set_test(name, value)
1687  self._log_set_variable_log_set_variable(name, value)
1688 
1689  @run_keyword_variant(resolve=0)
1690 
1695  def set_task_variable(self, name, *values):
1696  self.set_test_variableset_test_variable(name, *values)
1697 
1698  @run_keyword_variant(resolve=0)
1699 
1747  def set_suite_variable(self, name, *values):
1748  name = self._get_var_name_get_var_name(name)
1749  if values and is_string(values[-1]) and values[-1].startswith('children='):
1750  children = self._variables_variables_variables.replace_scalar(values[-1][9:])
1751  children = is_truthy(children)
1752  values = values[:-1]
1753  else:
1754  children = False
1755  value = self._get_var_value_get_var_value(name, values)
1756  self._variables_variables_variables.set_suite(name, value, children=children)
1757  self._log_set_variable_log_set_variable(name, value)
1758 
1759  @run_keyword_variant(resolve=0)
1760 
1780  def set_global_variable(self, name, *values):
1781  name = self._get_var_name_get_var_name(name)
1782  value = self._get_var_value_get_var_value(name, values)
1783  self._variables_variables_variables.set_global(name, value)
1784  self._log_set_variable_log_set_variable(name, value)
1785 
1786  # Helpers
1787 
1788  def _get_var_name(self, original, require_assign=True):
1789  try:
1790  replaced = self._variables_variables_variables.replace_string(original)
1791  except VariableError:
1792  replaced = original
1793  try:
1794  name = self._resolve_var_name_resolve_var_name(replaced)
1795  except ValueError:
1796  name = original
1797  match = search_variable(name, identifiers='$@&')
1798  match.resolve_base(self._variables_variables_variables)
1799  valid = match.is_assign() if require_assign else match.is_variable()
1800  if not valid:
1801  raise DataError("Invalid variable name '%s'." % name)
1802  return str(match)
1803 
1804  def _resolve_var_name(self, name):
1805  if name.startswith('\\'):
1806  name = name[1:]
1807  if len(name) < 2 or name[0] not in '$@&':
1808  raise ValueError
1809  if name[1] != '{':
1810  name = '%s{%s}' % (name[0], name[1:])
1811  match = search_variable(name, identifiers='$@&', ignore_errors=True)
1812  match.resolve_base(self._variables_variables_variables)
1813  if not match.is_assign():
1814  raise ValueError
1815  return str(match)
1816 
1817  def _get_var_value(self, name, values):
1818  if not values:
1819  return self._variables_variables_variables[name]
1820  if name[0] == '$':
1821  # We could consider catenating values similarly as when creating
1822  # scalar variables in the variable table, but that would require
1823  # handling non-string values somehow. For details see
1824  # https://github.com/robotframework/robotframework/issues/1919
1825  if len(values) != 1 or is_list_variable(values[0]):
1826  raise DataError("Setting list value to scalar variable '%s' "
1827  "is not supported anymore. Create list "
1828  "variable '@%s' instead." % (name, name[1:]))
1829  return self._variables_variables_variables.replace_scalar(values[0])
1830  return VariableTableValue(values, name).resolve(self._variables_variables_variables)
1831 
1832  def _log_set_variable(self, name, value):
1833  self.log(format_assign_message(name, value))
1834 
1835 
1837 
1838  # If you use any of these run keyword variants from another library, you
1839  # should register those keywords with 'register_run_keyword' method. See
1840  # the documentation of that method at the end of this file. There are also
1841  # other run keyword variant keywords in BuiltIn which can also be seen
1842  # at the end of this file.
1843 
1844  @run_keyword_variant(resolve=0, dry_run=True)
1845 
1851  def run_keyword(self, name, *args):
1852  if (is_string(name)
1853  and not self._context_context_context.dry_run
1854  and not self._accepts_embedded_arguments_accepts_embedded_arguments(name)):
1855  name, args = self._replace_variables_in_name_replace_variables_in_name([name] + list(args))
1856  if not is_string(name):
1857  raise RuntimeError('Keyword name must be a string.')
1858  kw = Keyword(name, args=args)
1859  return kw.run(self._context_context_context)
1860 
1862  if '{' in name:
1863  runner = self._context_context_context.get_runner(name)
1864  if hasattr(runner, 'embedded_args'):
1865  return True
1866  return False
1867 
1868  def _replace_variables_in_name(self, name_and_args):
1869  resolved = self._variables_variables_variables.replace_list(name_and_args, replace_until=1,
1870  ignore_errors=self._context_context_context.in_teardown)
1871  if not resolved:
1872  raise DataError(f'Keyword name missing: Given arguments {name_and_args} '
1873  f'resolved to an empty list.')
1874  return resolved[0], resolved[1:]
1875 
1876  @run_keyword_variant(resolve=0, dry_run=True)
1877 
1907  def run_keywords(self, *keywords):
1908  self._run_keywords_run_keywords(self._split_run_keywords_split_run_keywords(list(keywords)))
1909 
1910  def _run_keywords(self, iterable):
1911  errors = []
1912  for kw, args in iterable:
1913  try:
1914  self.run_keywordrun_keyword(kw, *args)
1915  except ExecutionPassed as err:
1916  err.set_earlier_failures(errors)
1917  raise err
1918  except ExecutionFailed as err:
1919  errors.extend(err.get_errors())
1920  if not err.can_continue(self._context_context_context):
1921  break
1922  if errors:
1923  raise ExecutionFailures(errors)
1924 
1925  def _split_run_keywords(self, keywords):
1926  if 'AND' not in keywords:
1927  for name in self._split_run_keywords_without_and_split_run_keywords_without_and(keywords):
1928  yield name, ()
1929  else:
1930  for kw_call in self._split_run_keywords_with_and_split_run_keywords_with_and(keywords):
1931  if not kw_call:
1932  raise DataError('AND must have keyword before and after.')
1933  yield kw_call[0], kw_call[1:]
1934 
1935  def _split_run_keywords_without_and(self, keywords):
1936  replace_list = self._variables_variables_variables.replace_list
1937  ignore_errors = self._context_context_context.in_teardown
1938  # `run_keyword` resolves variables, but list variables must be expanded
1939  # here to pass it each keyword name separately.
1940  for name in keywords:
1941  if is_list_variable(name):
1942  for n in replace_list([name], ignore_errors=ignore_errors):
1943  yield escape(n)
1944  else:
1945  yield name
1946 
1947  def _split_run_keywords_with_and(self, keywords):
1948  while 'AND' in keywords:
1949  index = keywords.index('AND')
1950  yield keywords[:index]
1951  keywords = keywords[index+1:]
1952  yield keywords
1953 
1954  @run_keyword_variant(resolve=1, dry_run=True)
1955 
2013  def run_keyword_if(self, condition, name, *args):
2014  args, branch = self._split_elif_or_else_branch_split_elif_or_else_branch(args)
2015  if self._is_true_is_true(condition):
2016  return self.run_keywordrun_keyword(name, *args)
2017  return branch()
2018 
2020  if 'ELSE IF' in args:
2021  args, branch = self._split_branch_split_branch(args, 'ELSE IF', 2,
2022  'condition and keyword')
2023  return args, lambda: self.run_keyword_ifrun_keyword_if(*branch)
2024  if 'ELSE' in args:
2025  args, branch = self._split_branch_split_branch(args, 'ELSE', 1, 'keyword')
2026  return args, lambda: self.run_keywordrun_keyword(*branch)
2027  return args, lambda: None
2028 
2029  def _split_branch(self, args, control_word, required, required_error):
2030  index = list(args).index(control_word)
2031  branch = self._variables_variables_variables.replace_list(args[index+1:], required)
2032  if len(branch) < required:
2033  raise DataError('%s requires %s.' % (control_word, required_error))
2034  return args[:index], branch
2035 
2036  @run_keyword_variant(resolve=1, dry_run=True)
2037 
2044  def run_keyword_unless(self, condition, name, *args):
2045  if not self._is_true_is_true(condition):
2046  return self.run_keywordrun_keyword(name, *args)
2047 
2048  @run_keyword_variant(resolve=0, dry_run=True)
2049 
2066  def run_keyword_and_ignore_error(self, name, *args):
2067  try:
2068  return 'PASS', self.run_keywordrun_keyword(name, *args)
2069  except ExecutionFailed as err:
2070  if err.dont_continue or err.skip:
2071  raise
2072  return 'FAIL', str(err)
2073 
2074  @run_keyword_variant(resolve=0, dry_run=True)
2075 
2087  def run_keyword_and_warn_on_failure(self, name, *args):
2088  status, message = self.run_keyword_and_ignore_errorrun_keyword_and_ignore_error(name, *args)
2089  if status == 'FAIL':
2090  logger.warn("Executing keyword '%s' failed:\n%s" % (name, message))
2091  return status, message
2092 
2093  @run_keyword_variant(resolve=0, dry_run=True)
2094 
2110  def run_keyword_and_return_status(self, name, *args):
2111  status, _ = self.run_keyword_and_ignore_errorrun_keyword_and_ignore_error(name, *args)
2112  return status == 'PASS'
2113 
2114  @run_keyword_variant(resolve=0, dry_run=True)
2115 
2126  def run_keyword_and_continue_on_failure(self, name, *args):
2127  try:
2128  return self.run_keywordrun_keyword(name, *args)
2129  except ExecutionFailed as err:
2130  if not err.dont_continue:
2131  err.continue_on_failure = True
2132  raise err
2133 
2134  @run_keyword_variant(resolve=1, dry_run=True)
2135 
2183  def run_keyword_and_expect_error(self, expected_error, name, *args):
2184  try:
2185  self.run_keywordrun_keyword(name, *args)
2186  except ExecutionFailed as err:
2187  if err.dont_continue or err.skip:
2188  raise
2189  error = err.message
2190  else:
2191  raise AssertionError("Expected error '%s' did not occur."
2192  % expected_error)
2193  if not self._error_is_expected_error_is_expected(error, expected_error):
2194  raise AssertionError("Expected error '%s' but got '%s'."
2195  % (expected_error, error))
2196  return error
2197 
2198  def _error_is_expected(self, error, expected_error):
2199  glob = self._matches_matches
2200  matchers = {'GLOB': glob,
2201  'EQUALS': lambda s, p: s == p,
2202  'STARTS': lambda s, p: s.startswith(p),
2203  'REGEXP': lambda s, p: re.match(p + r'\Z', s) is not None}
2204  prefixes = tuple(prefix + ':' for prefix in matchers)
2205  if not expected_error.startswith(prefixes):
2206  return glob(error, expected_error)
2207  prefix, expected_error = expected_error.split(':', 1)
2208  return matchers[prefix](error, expected_error.lstrip())
2209 
2210  @run_keyword_variant(resolve=1, dry_run=True)
2211 
2236  def repeat_keyword(self, repeat, name, *args):
2237  try:
2238  count = self._get_repeat_count_get_repeat_count(repeat)
2239  except RuntimeError as err:
2240  timeout = self._get_repeat_timeout_get_repeat_timeout(repeat)
2241  if timeout is None:
2242  raise err
2243  keywords = self._keywords_repeated_by_timeout_keywords_repeated_by_timeout(timeout, name, args)
2244  else:
2245  keywords = self._keywords_repeated_by_count_keywords_repeated_by_count(count, name, args)
2246  self._run_keywords_run_keywords(keywords)
2247 
2248  def _get_repeat_count(self, times, require_postfix=False):
2249  times = normalize(str(times))
2250  if times.endswith('times'):
2251  times = times[:-5]
2252  elif times.endswith('x'):
2253  times = times[:-1]
2254  elif require_postfix:
2255  raise ValueError
2256  return self._convert_to_integer(times)
2257 
2258  def _get_repeat_timeout(self, timestr):
2259  try:
2260  float(timestr)
2261  except ValueError:
2262  pass
2263  else:
2264  return None
2265  try:
2266  return timestr_to_secs(timestr)
2267  except ValueError:
2268  return None
2269 
2270  def _keywords_repeated_by_count(self, count, name, args):
2271  if count <= 0:
2272  self.log("Keyword '%s' repeated zero times." % name)
2273  for i in range(count):
2274  self.log("Repeating keyword, round %d/%d." % (i + 1, count))
2275  yield name, args
2276 
2277  def _keywords_repeated_by_timeout(self, timeout, name, args):
2278  if timeout <= 0:
2279  self.log("Keyword '%s' repeated zero times." % name)
2280  repeat_round = 0
2281  maxtime = time.time() + timeout
2282  while time.time() < maxtime:
2283  repeat_round += 1
2284  self.log("Repeating keyword, round %d, %s remaining."
2285  % (repeat_round,
2286  secs_to_timestr(maxtime - time.time(), compact=True)))
2287  yield name, args
2288 
2289  @run_keyword_variant(resolve=2, dry_run=True)
2290 
2332  def wait_until_keyword_succeeds(self, retry, retry_interval, name, *args):
2333  maxtime = count = -1
2334  try:
2335  count = self._get_repeat_count_get_repeat_count(retry, require_postfix=True)
2336  except ValueError:
2337  timeout = timestr_to_secs(retry)
2338  maxtime = time.time() + timeout
2339  message = 'for %s' % secs_to_timestr(timeout)
2340  else:
2341  if count <= 0:
2342  raise ValueError('Retry count %d is not positive.' % count)
2343  message = '%d time%s' % (count, s(count))
2344  if is_string(retry_interval) and normalize(retry_interval).startswith('strict:'):
2345  retry_interval = retry_interval.split(':', 1)[1].strip()
2346  strict_interval = True
2347  else:
2348  strict_interval = False
2349  retry_interval = sleep_time = timestr_to_secs(retry_interval)
2350  while True:
2351  start_time = time.time()
2352  try:
2353  return self.run_keywordrun_keyword(name, *args)
2354  except ExecutionFailed as err:
2355  if err.dont_continue or err.skip:
2356  raise
2357  count -= 1
2358  if time.time() > maxtime > 0 or count == 0:
2359  raise AssertionError("Keyword '%s' failed after retrying %s. "
2360  "The last error was: %s" % (name, message, err))
2361  finally:
2362  if strict_interval:
2363  keyword_runtime = time.time() - start_time
2364  sleep_time = retry_interval - keyword_runtime
2365  if sleep_time < 0:
2366  logger.warn("Keyword execution time %s is longer than retry "
2367  "interval %s." % (secs_to_timestr(keyword_runtime),
2368  secs_to_timestr(retry_interval)))
2369  self._sleep_in_parts(sleep_time)
2370 
2371  @run_keyword_variant(resolve=1)
2372 
2410  def set_variable_if(self, condition, *values):
2411  values = self._verify_values_for_set_variable_if_verify_values_for_set_variable_if(list(values))
2412  if self._is_true_is_true(condition):
2413  return self._variables_variables_variables.replace_scalar(values[0])
2414  values = self._verify_values_for_set_variable_if_verify_values_for_set_variable_if(values[1:], True)
2415  if len(values) == 1:
2416  return self._variables_variables_variables.replace_scalar(values[0])
2417  return self.run_keywordrun_keyword('BuiltIn.Set Variable If', *values[0:])
2418 
2419  def _verify_values_for_set_variable_if(self, values, default=False):
2420  if not values:
2421  if default:
2422  return [None]
2423  raise RuntimeError('At least one value is required')
2424  if is_list_variable(values[0]):
2425  values[:1] = [escape(item) for item in self._variables_variables_variables[values[0]]]
2426  return self._verify_values_for_set_variable_if_verify_values_for_set_variable_if(values)
2427  return values
2428 
2429  @run_keyword_variant(resolve=0, dry_run=True)
2430 
2438  def run_keyword_if_test_failed(self, name, *args):
2439  test = self._get_test_in_teardown_get_test_in_teardown('Run Keyword If Test Failed')
2440  if test.failed:
2441  return self.run_keywordrun_keyword(name, *args)
2442 
2443  @run_keyword_variant(resolve=0, dry_run=True)
2444 
2452  def run_keyword_if_test_passed(self, name, *args):
2453  test = self._get_test_in_teardown_get_test_in_teardown('Run Keyword If Test Passed')
2454  if test.passed:
2455  return self.run_keywordrun_keyword(name, *args)
2456 
2457  @run_keyword_variant(resolve=0, dry_run=True)
2458 
2466  def run_keyword_if_timeout_occurred(self, name, *args):
2467  self._get_test_in_teardown_get_test_in_teardown('Run Keyword If Timeout Occurred')
2468  if self._context_context_context.timeout_occurred:
2469  return self.run_keywordrun_keyword(name, *args)
2470 
2471  def _get_test_in_teardown(self, kwname):
2472  ctx = self._context_context_context
2473  if ctx.test and ctx.in_test_teardown:
2474  return ctx.test
2475  raise RuntimeError(f"Keyword '{kwname}' can only be used in test teardown.")
2476 
2477  @run_keyword_variant(resolve=0, dry_run=True)
2478 
2486  def run_keyword_if_all_tests_passed(self, name, *args):
2487  suite = self._get_suite_in_teardown_get_suite_in_teardown('Run Keyword If All Tests Passed')
2488  if suite.statistics.failed == 0:
2489  return self.run_keywordrun_keyword(name, *args)
2490 
2491  @run_keyword_variant(resolve=0, dry_run=True)
2492 
2500  def run_keyword_if_any_tests_failed(self, name, *args):
2501  suite = self._get_suite_in_teardown_get_suite_in_teardown('Run Keyword If Any Tests Failed')
2502  if suite.statistics.failed > 0:
2503  return self.run_keywordrun_keyword(name, *args)
2504 
2505  def _get_suite_in_teardown(self, kwname):
2506  if not self._context_context_context.in_suite_teardown:
2507  raise RuntimeError("Keyword '%s' can only be used in suite teardown."
2508  % kwname)
2509  return self._context_context_context.suite
2510 
2511 
2513 
2514 
2519  def skip(self, msg='Skipped with Skip keyword.'):
2520  raise SkipExecution(msg)
2521 
2522 
2530  def skip_if(self, condition, msg=None):
2531  if self._is_true_is_true(condition):
2532  raise SkipExecution(msg or condition)
2533 
2534 
2565  if not self._context_context_context.allow_loop_control:
2566  raise DataError("'Continue For Loop' can only be used inside a loop.")
2567  self.log("Continuing for loop from the next iteration.")
2568  raise ContinueLoop()
2569 
2570 
2595  def continue_for_loop_if(self, condition):
2596  if not self._context_context_context.allow_loop_control:
2597  raise DataError("'Continue For Loop If' can only be used inside a loop.")
2598  if self._is_true_is_true(condition):
2599  self.continue_for_loopcontinue_for_loop()
2600 
2601 
2631  def exit_for_loop(self):
2632  if not self._context_context_context.allow_loop_control:
2633  raise DataError("'Exit For Loop' can only be used inside a loop.")
2634  self.log("Exiting for loop altogether.")
2635  raise BreakLoop()
2636 
2637 
2662  def exit_for_loop_if(self, condition):
2663  if not self._context_context_context.allow_loop_control:
2664  raise DataError("'Exit For Loop If' can only be used inside a loop.")
2665  if self._is_true_is_true(condition):
2666  self.exit_for_loopexit_for_loop()
2667 
2668  @run_keyword_variant(resolve=0)
2669 
2726  def return_from_keyword(self, *return_values):
2727  self._return_from_keyword_return_from_keyword(return_values)
2728 
2729  def _return_from_keyword(self, return_values=None, failures=None):
2730  self.log('Returning from the enclosing user keyword.')
2731  raise ReturnFromKeyword(return_values, failures)
2732 
2733  @run_keyword_variant(resolve=1)
2734 
2768  def return_from_keyword_if(self, condition, *return_values):
2769  if self._is_true_is_true(condition):
2770  self._return_from_keyword_return_from_keyword(return_values)
2771 
2772  @run_keyword_variant(resolve=0, dry_run=True)
2773 
2790  def run_keyword_and_return(self, name, *args):
2791  try:
2792  ret = self.run_keyword(name, *args)
2793  except ExecutionFailed as err:
2794  self._return_from_keyword_return_from_keyword(failures=[err])
2795  else:
2796  self._return_from_keyword_return_from_keyword(return_values=[escape(ret)])
2797 
2798  @run_keyword_variant(resolve=1, dry_run=True)
2799 
2813  def run_keyword_and_return_if(self, condition, name, *args):
2814  if self._is_true_is_true(condition):
2815  self.run_keyword_and_returnrun_keyword_and_return(name, *args)
2816 
2817 
2859  def pass_execution(self, message, *tags):
2860  message = message.strip()
2861  if not message:
2862  raise RuntimeError('Message cannot be empty.')
2863  self._set_and_remove_tags(tags)
2864  log_message, level = self._get_logged_test_message_and_level(message)
2865  self.log('Execution passed with message:\n%s' % log_message, level)
2866  raise PassExecution(message)
2867 
2868  @run_keyword_variant(resolve=1)
2869 
2882  def pass_execution_if(self, condition, message, *tags):
2883  if self._is_true_is_true(condition):
2884  message = self._variables_variables_variables.replace_string(message)
2885  tags = self._variables_variables_variables.replace_list(tags)
2886  self.pass_executionpass_execution(message, *tags)
2887 
2888 
2890 
2891 
2892  def no_operation(self):
2893 
2894 
2910  def sleep(self, time_, reason=None):
2911  seconds = timestr_to_secs(time_)
2912  # Python hangs with negative values
2913  if seconds < 0:
2914  seconds = 0
2915  self._sleep_in_parts_sleep_in_parts(seconds)
2916  self.loglog('Slept %s' % secs_to_timestr(seconds))
2917  if reason:
2918  self.loglog(reason)
2919 
2920  def _sleep_in_parts(self, seconds):
2921  # time.sleep can't be stopped in windows
2922  # to ensure that we can signal stop (with timeout)
2923  # split sleeping to small pieces
2924  endtime = time.time() + float(seconds)
2925  while True:
2926  remaining = endtime - time.time()
2927  if remaining <= 0:
2928  break
2929  time.sleep(min(remaining, 0.01))
2930 
2931 
2946  def catenate(self, *items):
2947  if not items:
2948  return ''
2949  items = [str(item) for item in items]
2950  if items[0].startswith('SEPARATOR='):
2951  sep = items[0][len('SEPARATOR='):]
2952  items = items[1:]
2953  else:
2954  sep = ' '
2955  return sep.join(items)
2956 
2957 
3008  def log(self, message, level='INFO', html=False, console=False,
3009  repr='DEPRECATED', formatter='str'):
3010  # TODO: Remove `repr` altogether in RF 7.0. It was deprecated in RF 5.0.
3011  if repr == 'DEPRECATED':
3012  formatter = self._get_formatter_get_formatter(formatter)
3013  else:
3014  logger.warn("The 'repr' argument of 'BuiltIn.Log' is deprecated. "
3015  "Use 'formatter=repr' instead.")
3016  formatter = prepr if is_truthy(repr) else self._get_formatter_get_formatter(formatter)
3017  message = formatter(message)
3018  logger.write(message, level, html)
3019  if console:
3020  logger.console(message)
3021 
3022  def _get_formatter(self, formatter):
3023  try:
3024  return {'str': safe_str,
3025  'repr': prepr,
3026  'ascii': ascii,
3027  'len': len,
3028  'type': lambda x: type(x).__name__}[formatter.lower()]
3029  except KeyError:
3030  raise ValueError("Invalid formatter '%s'. Available "
3031  "'str', 'repr', 'ascii', 'len', and 'type'." % formatter)
3032 
3033  @run_keyword_variant(resolve=0)
3034 
3045  def log_many(self, *messages):
3046  for msg in self._yield_logged_messages_yield_logged_messages(messages):
3047  self.loglog(msg)
3048 
3049  def _yield_logged_messages(self, messages):
3050  for msg in messages:
3051  match = search_variable(msg)
3052  value = self._variables_variables_variables.replace_scalar(msg)
3053  if match.is_list_variable():
3054  for item in value:
3055  yield item
3056  elif match.is_dict_variable():
3057  for name, value in value.items():
3058  yield '%s=%s' % (name, value)
3059  else:
3060  yield value
3061 
3062 
3089  def log_to_console(self, message, stream='STDOUT', no_newline=False, format=''):
3090  if format:
3091  format = "{:" + format + "}"
3092  message = format.format(message)
3093  logger.console(message, newline=is_falsy(no_newline), stream=stream)
3094 
3095  @run_keyword_variant(resolve=0)
3096 
3104  def comment(self, *messages):
3105  pass
3106 
3107 
3116  def set_log_level(self, level):
3117  try:
3118  old = self._context_context_context.output.set_log_level(level)
3119  except DataError as err:
3120  raise RuntimeError(str(err))
3121  self._namespace_namespace_namespace.variables.set_global('${LOG_LEVEL}', level.upper())
3122  self.loglog('Log level changed from %s to %s.' % (old, level.upper()))
3123  return old
3124 
3125 
3134  def reload_library(self, name_or_instance):
3135  library = self._namespace_namespace_namespace.reload_library(name_or_instance)
3136  self.loglog('Reloaded library %s with %s keywords.' % (library.name,
3137  len(library)))
3138 
3139  @run_keyword_variant(resolve=0)
3140 
3163  def import_library(self, name, *args):
3164  args, alias = self._split_alias_split_alias(args)
3165  try:
3166  self._namespace_namespace_namespace.import_library(name, args, alias)
3167  except DataError as err:
3168  raise RuntimeError(str(err))
3169 
3170  def _split_alias(self, args):
3171  if len(args) > 1 and normalize_whitespace(args[-2]) in ('WITH NAME', 'AS'):
3172  return args[:-2], args[-1]
3173  return args, None
3174 
3175  @run_keyword_variant(resolve=0)
3176 
3194  def import_variables(self, path, *args):
3195  try:
3196  self._namespace_namespace_namespace.import_variables(path, list(args), overwrite=True)
3197  except DataError as err:
3198  raise RuntimeError(str(err))
3199 
3200  @run_keyword_variant(resolve=0)
3201 
3217  def import_resource(self, path):
3218  try:
3219  self._namespace_namespace_namespace.import_resource(path)
3220  except DataError as err:
3221  raise RuntimeError(str(err))
3222 
3223 
3262  def set_library_search_order(self, *search_order):
3263  return self._namespace_namespace_namespace.set_search_order(search_order)
3264 
3265 
3275  def keyword_should_exist(self, name, msg=None):
3276  try:
3277  runner = self._namespace_namespace_namespace.get_runner(name, recommend_on_failure=False)
3278  except DataError as error:
3279  raise AssertionError(msg or error.message)
3280  if isinstance(runner, UserErrorHandler):
3281  raise AssertionError(msg or runner.error.message)
3282 
3283 
3363  def get_time(self, format='timestamp', time_='NOW'):
3364  return get_time(format, parse_time(time_))
3365 
3366 
3415  def evaluate(self, expression, modules=None, namespace=None):
3416  try:
3417  return evaluate_expression(expression, self._variables_variables_variables.current.store,
3418  modules, namespace)
3419  except DataError as err:
3420  raise RuntimeError(err.message)
3421 
3422 
3441  def call_method(self, object, method_name, *args, **kwargs):
3442  try:
3443  method = getattr(object, method_name)
3444  except AttributeError:
3445  raise RuntimeError(f"{type(object).__name__} object does not have "
3446  f"method '{method_name}'.")
3447  try:
3448  return method(*args, **kwargs)
3449  except Exception as err:
3450  msg = get_error_message()
3451  raise RuntimeError(f"Calling method '{method_name}' failed: {msg}") from err
3452 
3453 
3464  def regexp_escape(self, *patterns):
3465  if len(patterns) == 0:
3466  return ''
3467  if len(patterns) == 1:
3468  return re.escape(patterns[0])
3469  return [re.escape(p) for p in patterns]
3470 
3471 
3493  def set_test_message(self, message, append=False):
3494  test = self._context_context_context.test
3495  if not test:
3496  raise RuntimeError("'Set Test Message' keyword cannot be used in "
3497  "suite setup or teardown.")
3498  test.message = self._get_new_text_get_new_text(test.message, message,
3499  append, handle_html=True)
3500  if self._context_context_context.in_test_teardown:
3501  self._variables_variables_variables.set_test("${TEST_MESSAGE}", test.message)
3502  message, level = self._get_logged_test_message_and_level_get_logged_test_message_and_level(test.message)
3503  self.loglog('Set test message to:\n%s' % message, level)
3504 
3505  def _get_new_text(self, old, new, append, handle_html=False):
3506  if not is_string(new):
3507  new = str(new)
3508  if not (is_truthy(append) and old):
3509  return new
3510  if handle_html:
3511  if new.startswith('*HTML*'):
3512  new = new[6:].lstrip()
3513  if not old.startswith('*HTML*'):
3514  old = '*HTML* %s' % html_escape(old)
3515  elif old.startswith('*HTML*'):
3516  new = html_escape(new)
3517  return '%s %s' % (old, new)
3518 
3520  if message.startswith('*HTML*'):
3521  return message[6:].lstrip(), 'HTML'
3522  return message, 'INFO'
3523 
3524 
3534  def set_test_documentation(self, doc, append=False):
3535  test = self._context_context_context.test
3536  if not test:
3537  raise RuntimeError("'Set Test Documentation' keyword cannot be "
3538  "used in suite setup or teardown.")
3539  test.doc = self._get_new_text_get_new_text(test.doc, doc, append)
3540  self._variables_variables_variables.set_test('${TEST_DOCUMENTATION}', test.doc)
3541  self.loglog('Set test documentation to:\n%s' % test.doc)
3542 
3543 
3557  def set_suite_documentation(self, doc, append=False, top=False):
3558  suite = self._get_context_get_context(top).suite
3559  suite.doc = self._get_new_text_get_new_text(suite.doc, doc, append)
3560  self._variables_variables_variables.set_suite('${SUITE_DOCUMENTATION}', suite.doc, top)
3561  self.loglog('Set suite documentation to:\n%s' % suite.doc)
3562 
3563 
3577  def set_suite_metadata(self, name, value, append=False, top=False):
3578  if not is_string(name):
3579  name = str(name)
3580  metadata = self._get_context_get_context(top).suite.metadata
3581  original = metadata.get(name, '')
3582  metadata[name] = self._get_new_text_get_new_text(original, value, append)
3583  self._variables_variables_variables.set_suite('${SUITE_METADATA}', metadata.copy(), top)
3584  self.loglog("Set suite metadata '%s' to value '%s'." % (name, metadata[name]))
3585 
3586 
3600  def set_tags(self, *tags):
3601  ctx = self._context_context_context
3602  if ctx.test:
3603  ctx.test.tags.add(tags)
3604  ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags))
3605  elif not ctx.in_suite_teardown:
3606  ctx.suite.set_tags(tags, persist=True)
3607  else:
3608  raise RuntimeError("'Set Tags' cannot be used in suite teardown.")
3609  self.loglog('Set tag%s %s.' % (s(tags), seq2str(tags)))
3610 
3611 
3628  def remove_tags(self, *tags):
3629  ctx = self._context_context_context
3630  if ctx.test:
3631  ctx.test.tags.remove(tags)
3632  ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags))
3633  elif not ctx.in_suite_teardown:
3634  ctx.suite.set_tags(remove=tags, persist=True)
3635  else:
3636  raise RuntimeError("'Remove Tags' cannot be used in suite teardown.")
3637  self.loglog('Removed tag%s %s.' % (s(tags), seq2str(tags)))
3638 
3639 
3665  def get_library_instance(self, name=None, all=False):
3666  if all:
3667  return self._namespace_namespace_namespace.get_library_instances()
3668  try:
3669  return self._namespace_namespace_namespace.get_library_instance(name)
3670  except DataError as err:
3671  raise RuntimeError(str(err))
3672 
3673 
3674 
3945  ROBOT_LIBRARY_SCOPE = 'GLOBAL'
3946  ROBOT_LIBRARY_VERSION = get_version()
3947 
3948 
3949 
3956  pass
3957 
3958 
3959 
4016 def register_run_keyword(library, keyword, args_to_process=0, deprecation_warning=True):
4017  RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process,
4018  deprecation_warning)
Mark the executed test or task skipped.
Definition: exceptions.py:75
Used by BREAK statement.
Definition: errors.py:316
Used by CONTINUE statement.
Definition: errors.py:309
Used by 'Pass Execution' keyword.
Definition: errors.py:302
Used by 'RETURN' statement.
Definition: errors.py:323
An always available standard library with often needed keywords.
Definition: BuiltIn.py:3944
Used when something cannot be done because Robot is not running.
Definition: BuiltIn.py:3955
def _is_true(self, condition)
Definition: BuiltIn.py:86
def _get_context(self, top=False)
Definition: BuiltIn.py:63
def _matches(self, string, pattern, caseless=False)
Definition: BuiltIn.py:81
def _log_types_at_level(self, level, *args)
Definition: BuiltIn.py:94
def return_from_keyword(self, *return_values)
Returns from the enclosing user keyword.
Definition: BuiltIn.py:2726
def pass_execution(self, message, *tags)
Skips rest of the current test, setup, or teardown with PASS status.
Definition: BuiltIn.py:2859
def continue_for_loop_if(self, condition)
Skips the current FOR loop iteration if the condition is true.
Definition: BuiltIn.py:2595
def skip(self, msg='Skipped with Skip keyword.')
Skips the rest of the current test.
Definition: BuiltIn.py:2519
def return_from_keyword_if(self, condition, *return_values)
Returns from the enclosing user keyword if condition is true.
Definition: BuiltIn.py:2768
def exit_for_loop_if(self, condition)
Stops executing the enclosing FOR loop if the condition is true.
Definition: BuiltIn.py:2662
def run_keyword_and_return_if(self, condition, name, *args)
Runs the specified keyword and returns from the enclosing user keyword.
Definition: BuiltIn.py:2813
def run_keyword_and_return(self, name, *args)
Runs the specified keyword and returns from the enclosing user keyword.
Definition: BuiltIn.py:2790
def exit_for_loop(self)
Stops executing the enclosing FOR loop.
Definition: BuiltIn.py:2631
def skip_if(self, condition, msg=None)
Skips the rest of the current test if the condition is True.
Definition: BuiltIn.py:2530
def _return_from_keyword(self, return_values=None, failures=None)
Definition: BuiltIn.py:2729
def continue_for_loop(self)
Skips the current FOR loop iteration and continues from the next.
Definition: BuiltIn.py:2564
def pass_execution_if(self, condition, message, *tags)
Conditionally skips rest of the current test, setup, or teardown with PASS status.
Definition: BuiltIn.py:2882
def _get_ordinals_from_text(self, input)
Definition: BuiltIn.py:374
def _get_ordinals_from_hex(self, input)
Definition: BuiltIn.py:394
def convert_to_octal(self, item, base=None, prefix=None, length=None)
Converts the given item to an octal string.
Definition: BuiltIn.py:198
def create_list(self, *items)
Returns a list containing given items.
Definition: BuiltIn.py:422
def convert_to_string(self, item)
Converts the given item to a Unicode string.
Definition: BuiltIn.py:300
def convert_to_bytes(self, input, input_type='text')
Converts the given input to bytes according to the input_type.
Definition: BuiltIn.py:364
def convert_to_integer(self, item, base=None)
Converts the given item to an integer number.
Definition: BuiltIn.py:129
def _test_ordinal(self, ordinal, original, type)
Definition: BuiltIn.py:379
def convert_to_number(self, item, precision=None)
Converts the given item to a floating point number.
Definition: BuiltIn.py:269
def _get_ordinals_from_int(self, input)
Definition: BuiltIn.py:385
def convert_to_boolean(self, item)
Converts the given item to Boolean true or false.
Definition: BuiltIn.py:311
def _input_to_tokens(self, input, length)
Definition: BuiltIn.py:404
def _convert_to_number(self, item, precision=None)
Definition: BuiltIn.py:273
def convert_to_hex(self, item, base=None, prefix=None, length=None, lowercase=False)
Converts the given item to a hexadecimal string.
Definition: BuiltIn.py:225
def _get_base(self, item, base)
Definition: BuiltIn.py:143
def create_dictionary(self, *items)
Creates and returns a dictionary based on the given items.
Definition: BuiltIn.py:456
def convert_to_binary(self, item, base=None, prefix=None, length=None)
Converts the given item to a binary string.
Definition: BuiltIn.py:176
def _convert_to_number_without_precision(self, item)
Definition: BuiltIn.py:279
def _convert_to_integer(self, orig, base=None)
Definition: BuiltIn.py:133
def _get_ordinals_from_bin(self, input)
Definition: BuiltIn.py:399
def _format_separate_dict_items(self, separate)
Definition: BuiltIn.py:472
def _split_dict_items(self, items)
Definition: BuiltIn.py:463
def _convert_to_bin_oct_hex(self, item, base, prefix, length, format_spec)
Definition: BuiltIn.py:229
def set_suite_documentation(self, doc, append=False, top=False)
Sets documentation for the current test suite.
Definition: BuiltIn.py:3557
def _get_new_text(self, old, new, append, handle_html=False)
Definition: BuiltIn.py:3505
def get_library_instance(self, name=None, all=False)
Returns the currently active instance of the specified library.
Definition: BuiltIn.py:3665
def _yield_logged_messages(self, messages)
Definition: BuiltIn.py:3049
def log(self, message, level='INFO', html=False, console=False, repr='DEPRECATED', formatter='str')
Logs the given message with the given level.
Definition: BuiltIn.py:3009
def comment(self, *messages)
Displays the given messages in the log file as keyword arguments.
Definition: BuiltIn.py:3104
def _get_formatter(self, formatter)
Definition: BuiltIn.py:3022
def set_suite_metadata(self, name, value, append=False, top=False)
Sets metadata for the current test suite.
Definition: BuiltIn.py:3577
def remove_tags(self, *tags)
Removes given tags from the current test or all tests in a suite.
Definition: BuiltIn.py:3628
def regexp_escape(self, *patterns)
Returns each argument string escaped for use as a regular expression.
Definition: BuiltIn.py:3464
def set_tags(self, *tags)
Adds given tags for the current test or all tests in a suite.
Definition: BuiltIn.py:3600
def get_time(self, format='timestamp', time_='NOW')
Returns the given time in the requested format.
Definition: BuiltIn.py:3363
def keyword_should_exist(self, name, msg=None)
Fails unless the given keyword exists in the current scope.
Definition: BuiltIn.py:3275
def set_test_documentation(self, doc, append=False)
Sets documentation for the current test case.
Definition: BuiltIn.py:3534
def sleep(self, time_, reason=None)
Pauses the test executed for the given time.
Definition: BuiltIn.py:2910
def log_to_console(self, message, stream='STDOUT', no_newline=False, format='')
Logs the given message to the console.
Definition: BuiltIn.py:3089
def import_variables(self, path, *args)
Imports a variable file with the given path and optional arguments.
Definition: BuiltIn.py:3194
def import_library(self, name, *args)
Imports a library with the given name and optional arguments.
Definition: BuiltIn.py:3163
def _get_logged_test_message_and_level(self, message)
Definition: BuiltIn.py:3519
def log_many(self, *messages)
Logs the given messages as separate entries using the INFO level.
Definition: BuiltIn.py:3045
def set_test_message(self, message, append=False)
Sets message for the current test case.
Definition: BuiltIn.py:3493
def set_library_search_order(self, *search_order)
Sets the resolution order to use when a name matches multiple keywords.
Definition: BuiltIn.py:3262
def set_log_level(self, level)
Sets the log threshold to the specified level and returns the old level.
Definition: BuiltIn.py:3116
def _sleep_in_parts(self, seconds)
Definition: BuiltIn.py:2920
def import_resource(self, path)
Imports a resource file with the given path.
Definition: BuiltIn.py:3217
def _split_alias(self, args)
Definition: BuiltIn.py:3170
def evaluate(self, expression, modules=None, namespace=None)
Evaluates the given expression in Python and returns the result.
Definition: BuiltIn.py:3415
def reload_library(self, name_or_instance)
Rechecks what keywords the specified library provides.
Definition: BuiltIn.py:3134
def no_operation(self)
Does absolutely nothing.
Definition: BuiltIn.py:2892
def call_method(self, object, method_name, *args, **kwargs)
Calls the named method of the given object with the provided arguments.
Definition: BuiltIn.py:3441
def catenate(self, *items)
Catenates the given items together and returns the resulted string.
Definition: BuiltIn.py:2946
def run_keyword_and_expect_error(self, expected_error, name, *args)
Runs the keyword and checks that the expected error occurred.
Definition: BuiltIn.py:2183
def run_keywords(self, *keywords)
Executes all the given keywords in a sequence.
Definition: BuiltIn.py:1907
def run_keyword_and_continue_on_failure(self, name, *args)
Runs the keyword and continues execution even if a failure occurs.
Definition: BuiltIn.py:2126
def _get_suite_in_teardown(self, kwname)
Definition: BuiltIn.py:2505
def _split_elif_or_else_branch(self, args)
Definition: BuiltIn.py:2019
def repeat_keyword(self, repeat, name, *args)
Executes the specified keyword multiple times.
Definition: BuiltIn.py:2236
def run_keyword_if_timeout_occurred(self, name, *args)
Runs the given keyword if either a test or a keyword timeout has occurred.
Definition: BuiltIn.py:2466
def _replace_variables_in_name(self, name_and_args)
Definition: BuiltIn.py:1868
def wait_until_keyword_succeeds(self, retry, retry_interval, name, *args)
Runs the specified keyword and retries if it fails.
Definition: BuiltIn.py:2332
def _split_run_keywords_without_and(self, keywords)
Definition: BuiltIn.py:1935
def set_variable_if(self, condition, *values)
Sets variable based on the given condition.
Definition: BuiltIn.py:2410
def run_keyword_and_return_status(self, name, *args)
Runs the given keyword with given arguments and returns the status as a Boolean value.
Definition: BuiltIn.py:2110
def run_keyword_if_test_passed(self, name, *args)
Runs the given keyword with the given arguments, if the test passed.
Definition: BuiltIn.py:2452
def run_keyword(self, name, *args)
Executes the given keyword with the given arguments.
Definition: BuiltIn.py:1851
def run_keyword_and_warn_on_failure(self, name, *args)
Runs the specified keyword logs a warning if the keyword fails.
Definition: BuiltIn.py:2087
def _get_repeat_timeout(self, timestr)
Definition: BuiltIn.py:2258
def _split_run_keywords_with_and(self, keywords)
Definition: BuiltIn.py:1947
def _verify_values_for_set_variable_if(self, values, default=False)
Definition: BuiltIn.py:2419
def _split_branch(self, args, control_word, required, required_error)
Definition: BuiltIn.py:2029
def _keywords_repeated_by_timeout(self, timeout, name, args)
Definition: BuiltIn.py:2277
def _error_is_expected(self, error, expected_error)
Definition: BuiltIn.py:2198
def run_keyword_if_test_failed(self, name, *args)
Runs the given keyword with the given arguments, if the test failed.
Definition: BuiltIn.py:2438
def _split_run_keywords(self, keywords)
Definition: BuiltIn.py:1925
def run_keyword_if_all_tests_passed(self, name, *args)
Runs the given keyword with the given arguments, if all tests passed.
Definition: BuiltIn.py:2486
def run_keyword_unless(self, condition, name, *args)
DEPRECATED since RF 5.0.
Definition: BuiltIn.py:2044
def _get_test_in_teardown(self, kwname)
Definition: BuiltIn.py:2471
def run_keyword_if_any_tests_failed(self, name, *args)
Runs the given keyword with the given arguments, if one or more tests failed.
Definition: BuiltIn.py:2500
def run_keyword_and_ignore_error(self, name, *args)
Runs the given keyword with the given arguments and ignores possible error.
Definition: BuiltIn.py:2066
def _run_keywords(self, iterable)
Definition: BuiltIn.py:1910
def _accepts_embedded_arguments(self, name)
Definition: BuiltIn.py:1861
def _get_repeat_count(self, times, require_postfix=False)
Definition: BuiltIn.py:2248
def _keywords_repeated_by_count(self, count, name, args)
Definition: BuiltIn.py:2270
def run_keyword_if(self, condition, name, *args)
Runs the given keyword with the given arguments, if condition is true.
Definition: BuiltIn.py:2013
def variable_should_exist(self, name, msg=None)
Fails unless the given variable exists within the current scope.
Definition: BuiltIn.py:1550
def set_local_variable(self, name, *values)
Makes a variable available everywhere within the local scope.
Definition: BuiltIn.py:1657
def get_variable_value(self, name, default=None)
Returns variable value or default if the variable does not exist.
Definition: BuiltIn.py:1510
def set_test_variable(self, name, *values)
Makes a variable available everywhere within the scope of the current test.
Definition: BuiltIn.py:1683
def log_variables(self, level='INFO')
Logs all variables in the current scope with given log level.
Definition: BuiltIn.py:1518
def _get_logged_variable(self, name, variables)
Definition: BuiltIn.py:1525
def set_task_variable(self, name, *values)
Makes a variable available everywhere within the scope of the current task.
Definition: BuiltIn.py:1695
def get_variables(self, no_decoration=False)
Returns a dictionary containing all variables in the current scope.
Definition: BuiltIn.py:1489
def replace_variables(self, text)
Replaces variables in the given text with their current values.
Definition: BuiltIn.py:1596
def set_global_variable(self, name, *values)
Makes a variable available globally in all tests and suites.
Definition: BuiltIn.py:1780
def variable_should_not_exist(self, name, msg=None)
Fails if the given variable exists within the current scope.
Definition: BuiltIn.py:1570
def _resolve_var_name(self, name)
Definition: BuiltIn.py:1804
def set_suite_variable(self, name, *values)
Makes a variable available everywhere within the scope of the current suite.
Definition: BuiltIn.py:1747
def _get_var_value(self, name, values)
Definition: BuiltIn.py:1817
def _log_set_variable(self, name, value)
Definition: BuiltIn.py:1832
def _get_var_name(self, original, require_assign=True)
Definition: BuiltIn.py:1788
def set_variable(self, *values)
Returns the given values which can then be assigned to a variables.
Definition: BuiltIn.py:1618
def should_match(self, string, pattern, msg=None, values=True, ignore_case=False)
Fails if the given string does not match the given pattern.
Definition: BuiltIn.py:1309
def length_should_be(self, item, length, msg=None)
Verifies that the length of the given item is correct.
Definition: BuiltIn.py:1425
def should_not_be_empty(self, item, msg=None)
Verifies that the given item is not empty.
Definition: BuiltIn.py:1446
def get_length(self, item)
Returns and logs the length of the given item as an integer.
Definition: BuiltIn.py:1392
def _collapse_spaces(self, value)
Definition: BuiltIn.py:666
def should_not_contain_any(self, container, *items, **configuration)
Fails if container contains one or more of the *items.
Definition: BuiltIn.py:1161
def should_contain_x_times(self, container, item, count, msg=None, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if container does not contain item count times.
Definition: BuiltIn.py:1229
def fatal_error(self, msg=None)
Stops the whole test execution.
Definition: BuiltIn.py:524
def _get_string_msg(self, item1, item2, custom_message, include_values, delimiter, quote_item1=True, quote_item2=True)
Definition: BuiltIn.py:1451
def _get_length(self, item)
Definition: BuiltIn.py:1397
def _set_and_remove_tags(self, tags)
Definition: BuiltIn.py:482
def should_not_contain(self, container, item, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if container contains item one or more times.
Definition: BuiltIn.py:997
def should_not_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6)
Fails if objects are equal after converting them to real numbers.
Definition: BuiltIn.py:757
def _should_be_equal(self, first, second, msg, values, formatter='str')
Definition: BuiltIn.py:624
def get_count(self, container, item)
Returns and logs how many times item is found from container.
Definition: BuiltIn.py:1266
def should_be_true(self, condition, msg=None)
Fails if the given condition is not true.
Definition: BuiltIn.py:565
def _include_values(self, values)
Definition: BuiltIn.py:652
def should_start_with(self, str1, str2, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if the string str1 does not start with the string str2.
Definition: BuiltIn.py:912
def should_not_be_true(self, condition, msg=None)
Fails if the given condition is true.
Definition: BuiltIn.py:534
def should_not_be_equal_as_strings(self, first, second, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if objects are equal after converting them to strings.
Definition: BuiltIn.py:827
def _should_not_be_equal(self, first, second, msg, values)
Definition: BuiltIn.py:706
def should_contain_any(self, container, *items, **configuration)
Fails if container does not contain any of the *items.
Definition: BuiltIn.py:1103
def should_match_regexp(self, string, pattern, msg=None, values=True, flags=None)
Fails if string does not match pattern as a regular expression.
Definition: BuiltIn.py:1352
def should_not_be_equal_as_integers(self, first, second, msg=None, values=True, base=None)
Fails if objects are equal after converting them to integers.
Definition: BuiltIn.py:720
def should_end_with(self, str1, str2, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if the string str1 does not end with the string str2.
Definition: BuiltIn.py:955
def should_not_be_equal(self, first, second, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if the given objects are equal.
Definition: BuiltIn.py:692
def should_not_start_with(self, str1, str2, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if the string str1 starts with the string str2.
Definition: BuiltIn.py:891
def fail(self, msg=None, *tags)
Fails the test with the given message and optionally alters its tags.
Definition: BuiltIn.py:512
def should_be_equal_as_strings(self, first, second, msg=None, values=True, ignore_case=False, strip_spaces=False, formatter='str', collapse_spaces=False)
Fails if objects are unequal after converting them to strings.
Definition: BuiltIn.py:868
def _raise_multi_diff(self, first, second, msg, formatter)
Definition: BuiltIn.py:637
def should_be_empty(self, item, msg=None)
Verifies that the given item is empty.
Definition: BuiltIn.py:1437
def _log_types_at_info_if_different(self, first, second)
Definition: BuiltIn.py:633
def _strip_spaces(self, value, strip_spaces)
Definition: BuiltIn.py:655
def should_not_match(self, string, pattern, msg=None, values=True, ignore_case=False)
Fails if the given string matches the given pattern.
Definition: BuiltIn.py:1290
def should_be_equal_as_integers(self, first, second, msg=None, values=True, base=None)
Fails if objects are unequal after converting them to integers.
Definition: BuiltIn.py:740
def should_not_end_with(self, str1, str2, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if the string str1 ends with the string str2.
Definition: BuiltIn.py:934
def should_be_equal(self, first, second, msg=None, values=True, ignore_case=False, formatter='str', strip_spaces=False, collapse_spaces=False)
Fails if the given objects are unequal.
Definition: BuiltIn.py:610
def should_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6)
Fails if objects are unequal after converting them to real numbers.
Definition: BuiltIn.py:795
def should_not_match_regexp(self, string, pattern, msg=None, values=True, flags=None)
Fails if string matches pattern as a regular expression.
Definition: BuiltIn.py:1367
def should_contain(self, container, item, msg=None, values=True, ignore_case=False, strip_spaces=False, collapse_spaces=False)
Fails if container does not contain item one or more times.
Definition: BuiltIn.py:1058
def register_run_keyword(library, keyword, args_to_process=0, deprecation_warning=True)
Tell Robot Framework that this keyword runs other keywords internally.
Definition: BuiltIn.py:4016
def run_keyword_variant(resolve, dry_run=False)
Definition: BuiltIn.py:46
def assert_not_equal(first, second, msg=None, values=True, formatter=safe_str)
Fail if given objects are equal as determined by the '==' operator.
Definition: asserts.py:191
def assert_equal(first, second, msg=None, values=True, formatter=safe_str)
Fail if given objects are unequal as determined by the '==' operator.
Definition: asserts.py:185
def get_error_message()
Returns error message of the last occurred exception.
Definition: error.py:34
def escape(item)
Definition: escaping.py:31
def split_from_equals(string)
Definition: escaping.py:105
def html_escape(text, linkify=True)
Definition: markuputils.py:44
def seq2str(sequence, quote="'", sep=', ', lastsep=' and ')
Returns sequence in format ‘'item 1’, 'item 2' and 'item 3'`.
Definition: misc.py:79
def parse_re_flags(flags=None)
Definition: misc.py:128
def normalize_whitespace(string)
Definition: normalizing.py:45
def normalize(string, ignore=(), caseless=True, spaceless=True)
Normalizes given string according to given spec.
Definition: normalizing.py:27
def secs_to_timestr(secs, compact=False)
Converts time in seconds to a string representation.
Definition: robottime.py:151
def parse_time(timestr)
Parses the time string and returns its value as seconds since epoch.
Definition: robottime.py:271
def timestr_to_secs(timestr, round_to=3, accept_plain_values=True)
Parses time strings like '1h 10s', '01:00:10' and '42' and returns seconds.
Definition: robottime.py:55
def is_truthy(item)
Returns True or False depending on is the item considered true or not.
Definition: robottypes.py:162
def is_falsy(item)
Opposite of :func:is_truthy.
Definition: robottypes.py:169
def is_list_like(item)
Definition: robottypes.py:66
def format_assign_message(variable, value, cut_long=True)
Definition: text.py:91
def safe_str(item)
Definition: unic.py:21
def evaluate_expression(expression, variable_store, modules=None, namespace=None)
Definition: evaluation.py:31
def is_list_variable(string)
Definition: search.py:42
def search_variable(string, identifiers='$@&% *', ignore_errors=False)
Definition: search.py:22
def is_dict_variable(string)
Definition: search.py:46
def VariableTableValue(value, name, error_reporter=None)
Definition: tablesetter.py:48
def get_version(naked=False)
Definition: version.py:24