28 get_env_var, get_env_vars, get_time, is_truthy,
29 is_unicode, normpath, parse_time, plural_or_not,
30 secs_to_timestamp, secs_to_timestr, seq2str,
31 set_env_var, timestr_to_secs, unic, CONSOLE_ENCODING,
32 IRONPYTHON, JYTHON, PY2, PY3, SYSTEM_ENCODING, WINDOWS)
35 PROCESSES = ConnectionCache(
'No active processes.')
141 ROBOT_LIBRARY_SCOPE =
'GLOBAL'
142 ROBOT_LIBRARY_VERSION = __version__
180 return self.
_run_run(command)[1]
207 return self.
_run_run(command)[0]
229 return self.
_run_run(command)
233 self.
_info_info(
"Running command '%s'." % process)
234 stdout = process.read()
265 def get_file(self, path, encoding='UTF-8', encoding_errors='strict'):
267 self.
_link_link(
"Getting file '%s'.", path)
271 with open(path)
as f:
272 content = f.read().decode(encoding, encoding_errors)
274 with io.open(path, encoding=encoding, errors=encoding_errors,
277 return content.replace(
'\r\n',
'\n')
281 if PY3
and encoding.upper() ==
'SYSTEM':
283 return {
'SYSTEM': SYSTEM_ENCODING,
284 'CONSOLE': CONSOLE_ENCODING}.get(encoding.upper(), encoding)
293 self.
_link_link(
"Getting file '%s'.", path)
294 with open(path,
'rb')
as f:
295 return bytes(f.read())
319 def grep_file(self, path, pattern, encoding='UTF-8', encoding_errors='strict'):
320 pattern =
'*%s*' % pattern
324 self.
_link_link(
"Reading file '%s'.", path)
325 with io.open(path, encoding=encoding, errors=encoding_errors)
as f:
326 for line
in f.readlines():
328 line = line.rstrip(
'\r\n')
329 if fnmatch.fnmatchcase(line, pattern):
331 self.
_info_info(
'%d out of %d lines matched' % (len(lines), total_lines))
332 return '\n'.join(lines)
343 def log_file(self, path, encoding='UTF-8', encoding_errors='strict'):
344 content = self.
get_fileget_file(path, encoding, encoding_errors)
345 self.
_info_info(content)
358 if not self.
_glob_glob(path):
359 self.
_fail_fail(msg,
"Path '%s' does not exist." % path)
360 self.
_link_link(
"Path '%s' exists.", path)
370 matches = self.
_glob_glob(path)
373 self.
_link_link(
"Path '%s' does not exist.", path)
376 return glob.glob(path)
if not os.path.exists(path)
else [path]
380 return "%s '%s' exists." % (what, path)
381 return "%s '%s' matches %s." % (what, path,
seq2str(sorted(matches)))
384 return '*' in path
or '?' in path
or (
'[' in path
and ']' in path)
394 matches = [p
for p
in self.
_glob_glob(path)
if os.path.isfile(p)]
396 self.
_fail_fail(msg,
"File '%s' does not exist." % path)
397 self.
_link_link(
"File '%s' exists.", path)
407 matches = [p
for p
in self.
_glob_glob(path)
if os.path.isfile(p)]
410 self.
_link_link(
"File '%s' does not exist.", path)
420 matches = [p
for p
in self.
_glob_glob(path)
if os.path.isdir(p)]
422 self.
_fail_fail(msg,
"Directory '%s' does not exist." % path)
423 self.
_link_link(
"Directory '%s' exists.", path)
433 matches = [p
for p
in self.
_glob_glob(path)
if os.path.isdir(p)]
436 self.
_link_link(
"Directory '%s' does not exist.", path)
458 maxtime = time.time() + timeout
459 while self.
_glob_glob(path):
460 if timeout >= 0
and time.time() > maxtime:
461 self.
_fail_fail(
"'%s' was not removed in %s."
464 self.
_link_link(
"'%s' was removed.", path)
484 maxtime = time.time() + timeout
485 while not self.
_glob_glob(path):
486 if timeout >= 0
and time.time() > maxtime:
487 self.
_fail_fail(
"'%s' was not created in %s."
490 self.
_link_link(
"'%s' was created.", path)
502 self.
_fail_fail(msg,
"Directory '%s' is not empty. Contents: %s."
503 % (path,
seq2str(items, lastsep=
', ')))
504 self.
_link_link(
"Directory '%s' is empty.", path)
514 self.
_fail_fail(msg,
"Directory '%s' is empty." % path)
515 self.
_link_link(
"Directory '%%s' contains %d item%s."
524 if not os.path.isfile(path):
525 self.
_error_error(
"File '%s' does not exist." % path)
526 size = os.stat(path).st_size
529 "File '%s' is not empty. Size: %d bytes." % (path, size))
530 self.
_link_link(
"File '%s' is empty.", path)
538 if not os.path.isfile(path):
539 self.
_error_error(
"File '%s' does not exist." % path)
540 size = os.stat(path).st_size
542 self.
_fail_fail(msg,
"File '%s' is empty." % path)
543 self.
_link_link(
"File '%%s' contains %d bytes." % size, path)
575 self.
_link_link(
"Created file '%s'.", path)
579 parent = os.path.dirname(path)
580 if not os.path.exists(parent):
584 if PY2
and isinstance(content, str)
and 'b' not in mode:
588 with io.open(path, mode, encoding=encoding)
as f:
614 content = bytes(bytearray(ord(c)
for c
in content))
615 path = self.
_write_to_file_write_to_file(path, content, mode=
'wb')
616 self.
_link_link(
"Created binary file '%s'.", path)
631 path = self.
_write_to_file_write_to_file(path, content, encoding, mode=
'a')
632 self.
_link_link(
"Appended to file '%s'.", path)
645 matches = self.
_glob_glob(path)
647 self.
_link_link(
"File '%s' does not exist.", path)
648 for match
in matches:
649 if not os.path.isfile(match):
650 self.
_error_error(
"Path '%s' is not a file." % match)
652 self.
_link_link(
"Removed file '%s'.", match)
671 for item
in self.
_list_dir_list_dir(path, absolute=
True):
672 if os.path.isdir(item):
676 self.
_link_link(
"Emptied directory '%s'.", path)
686 if os.path.isdir(path):
687 self.
_link_link(
"Directory '%s' already exists.", path )
688 elif os.path.exists(path):
689 self.
_error_error(
"Path '%s' is not a directory." % path)
692 self.
_link_link(
"Created directory '%s'.", path)
705 if not os.path.exists(path):
706 self.
_link_link(
"Directory '%s' does not exist.", path)
707 elif not os.path.isdir(path):
708 self.
_error_error(
"Path '%s' is not a directory." % path)
714 path,
"Directory '%s' is not empty." % path)
716 self.
_link_link(
"Removed directory '%s'.", path)
747 source, destination = \
750 source, destination = self.
_atomic_copy_atomic_copy(source, destination)
751 self.
_link_link(
"Copied file from '%s' to '%s'.", source, destination)
757 if os.path.isdir(destination):
758 destination = os.path.join(destination, os.path.basename(source))
759 return source, destination
762 source = self.
_absnorm_absnorm(source)
763 sources = self.
_glob_glob(source)
765 self.
_error_error(
"Multiple matches with source pattern '%s'." % source)
768 if not os.path.exists(source):
769 self.
_error_error(
"Source file '%s' does not exist." % source)
770 if not os.path.isfile(source):
771 self.
_error_error(
"Source file '%s' is not a regular file." % source)
775 is_dir = os.path.isdir(destination)
or destination.endswith((
'/',
'\\'))
776 destination = self.
_absnorm_absnorm(destination)
777 directory = destination
if is_dir
else os.path.dirname(destination)
782 if not os.path.exists(path):
784 elif not os.path.isdir(path):
785 self.
_error_error(
"Destination '%s' exists and is not a directory." % path)
789 self.
_link_link(
"Source '%s' and destination '%s' point to the same "
790 "file.", source, destination)
797 return os.path.realpath(
normpath(path, case_normalize=
True))
816 temp_directory = tempfile.mkdtemp(dir=os.path.dirname(destination))
817 temp_file = os.path.join(temp_directory, os.path.basename(source))
819 shutil.copy(source, temp_file)
820 if os.path.exists(destination):
821 os.remove(destination)
822 shutil.move(temp_file, destination)
824 shutil.rmtree(temp_directory)
825 return source, destination
839 source, destination = \
842 shutil.move(source, destination)
843 self.
_link_link(
"Moved file from '%s' to '%s'.", source, destination)
862 sources, destination \
864 for source
in sources:
865 self.
copy_filecopy_file(source, destination)
869 self.
_error_error(
'Must contain destination and at least one source.')
871 destination = self.
_absnorm_absnorm(items[-1])
873 return sources, destination
877 for pattern
in patterns:
878 files.extend(self.
_glob_glob(self.
_absnorm_absnorm(pattern)))
888 sources, destination \
890 for source
in sources:
891 self.
move_filemove_file(source, destination)
900 source, destination \
903 shutil.copytree(source, destination)
906 if not (WINDOWS
and JYTHON):
908 self.
_link_link(
"Copied directory from '%s' to '%s'.", source, destination)
911 source = self.
_absnorm_absnorm(source)
912 destination = self.
_absnorm_absnorm(destination)
913 if not os.path.exists(source):
914 self.
_error_error(
"Source '%s' does not exist." % source)
915 if not os.path.isdir(source):
916 self.
_error_error(
"Source '%s' is not a directory." % source)
917 if os.path.exists(destination)
and not os.path.isdir(destination):
918 self.
_error_error(
"Destination '%s' is not a directory." % destination)
919 if os.path.exists(destination):
920 base = os.path.basename(source)
921 destination = os.path.join(destination, base)
923 parent = os.path.dirname(destination)
924 if not os.path.exists(parent):
926 return source, destination
935 source, destination \
937 shutil.move(source, destination)
938 self.
_link_link(
"Moved directory from '%s' to '%s'.", source, destination)
956 self.
_error_error(
"Environment variable '%s' does not exist." % name)
966 self.
_info_info(
"Environment variable '%s' set to value '%s'."
992 if initial
is not sentinel:
993 values = (initial,) + values
994 separator = config.pop(
'separator', os.pathsep)
996 config = [
'='.join(i)
for i
in sorted(config.items())]
997 self.
_error_error(
'Configuration %s not accepted.'
998 %
seq2str(config, lastsep=
' or '))
1012 self.
_info_info(
"Environment variable '%s' deleted." % name)
1014 self.
_info_info(
"Environment variable '%s' does not exist." % name)
1023 self.
_fail_fail(msg,
"Environment variable '%s' is not set." % name)
1024 self.
_info_info(
"Environment variable '%s' is set to '%s'." % (name, value))
1033 self.
_fail_fail(msg,
"Environment variable '%s' is set to '%s'."
1035 self.
_info_info(
"Environment variable '%s' is not set." % name)
1053 for name
in sorted(variables, key=
lambda item: item.lower()):
1054 self.
_log_log(
'%s = %s' % (name, variables[name]), level)
1079 base = base.replace(
'/', os.sep)
1080 parts = [p.replace(
'/', os.sep)
for p
in parts]
1081 return self.
normalize_pathnormalize_path(os.path.join(base, *parts))
1097 return [self.
join_pathjoin_path(base, path)
for path
in paths]
1124 path = os.path.normpath(os.path.expanduser(path.replace(
'/', os.sep)))
1130 path = os.path.normcase(path)
1179 basename = os.path.basename(path)
1180 if basename.startswith(
'.' * basename.count(
'.')):
1182 if path.endswith(
'.'):
1183 path2 = path.rstrip(
'.')
1184 trailing_dots =
'.' * (len(path) - len(path2))
1188 basepath, extension = os.path.splitext(path)
1189 if extension.startswith(
'.'):
1190 extension = extension[1:]
1192 extension += trailing_dots
1194 basepath += trailing_dots
1195 return basepath, extension
1235 if not os.path.exists(path):
1236 self.
_error_error(
"Path '%s' does not exist." % path)
1237 mtime =
get_time(format, os.stat(path).st_mtime)
1238 self.
_link_link(
"Last modified time of '%%s' is %s." % mtime, path)
1279 if not os.path.exists(path):
1280 self.
_error_error(
"File '%s' does not exist." % path)
1281 if not os.path.isfile(path):
1282 self.
_error_error(
"Path '%s' is not a regular file." % path)
1283 os.utime(path, (mtime, mtime))
1286 self.
_link_link(
"Set modified time of '%%s' to %s." % tstamp, path)
1291 if not os.path.isfile(path):
1292 self.
_error_error(
"File '%s' does not exist." % path)
1293 size = os.stat(path).st_size
1295 self.
_link_link(
"Size of file '%%s' is %d byte%s." % (size, plural), path)
1320 items = self.
_list_dir_list_dir(path, pattern, absolute)
1335 self.
_info_info(
'%d director%s:\n%s' % (len(dirs),
1336 'y' if len(dirs) == 1
else 'ies',
1347 count = len(self.
_list_dir_list_dir(path, pattern))
1360 self.
_info_info(
"%s director%s." % (count,
'y' if count == 1
else 'ies'))
1365 self.
_link_link(
"Listing contents of directory '%s'.", path)
1366 if not os.path.isdir(path):
1367 self.
_error_error(
"Directory '%s' does not exist." % path)
1369 items = sorted(
unic(item)
for item
in os.listdir(path))
1371 items = [i
for i
in items
if fnmatch.fnmatchcase(i, pattern)]
1373 path = os.path.normpath(path)
1374 items = [os.path.join(path, item)
for item
in items]
1378 return [item
for item
in self.
_list_dir_list_dir(path, pattern, absolute)
1379 if os.path.isfile(os.path.join(path, item))]
1382 return [item
for item
in self.
_list_dir_list_dir(path, pattern, absolute)
1383 if os.path.isdir(os.path.join(path, item))]
1395 if os.path.isdir(path):
1396 self.
_error_error(
"Cannot touch '%s' because it is a directory." % path)
1397 if not os.path.exists(os.path.dirname(path)):
1398 self.
_error_error(
"Cannot touch '%s' because its parent directory does "
1399 "not exist." % path)
1400 if os.path.exists(path):
1401 mtime = round(time.time())
1402 os.utime(path, (mtime, mtime))
1403 self.
_link_link(
"Touched existing file '%s'.", path)
1405 open(path,
'w').close()
1406 self.
_link_link(
"Touched new file '%s'.", path)
1419 raise RuntimeError(msg)
1422 self.
_log_log(msg,
'INFO')
1425 paths = tuple(
'<a href="file://%s">%s</a>' % (p, p)
for p
in paths)
1426 self.
_log_log(msg % paths,
'HTML')
1429 self.
_log_log(msg,
'WARN')
1432 logger.write(msg, level)
1460 if WINDOWS
or JYTHON:
1465 if '>' not in command:
1466 if command.endswith(
'&'):
1467 command = command[:-1] +
' 2>&1 &'
1473 enc = sys.getfilesystemencoding()
if PY2
else None
1474 return string.encode(enc)
if enc
else string
1477 if '\r\n' in output:
1478 output = output.replace(
'\r\n',
'\n')
1479 if output.endswith(
'\n'):
1480 output = output[:-1]
A test library providing keywords for OS related tasks.
def get_file_size(self, path)
Returns and logs file size as an integer in bytes.
def environment_variable_should_be_set(self, name, msg=None)
Fails if the specified environment variable is not set.
def should_not_exist(self, path, msg=None)
Fails if the given path (file or directory) exists.
def _force_normalize(self, path)
def remove_file(self, path)
Removes a file with the given path.
def create_directory(self, path)
Creates the specified directory.
def wait_until_removed(self, path, timeout='1 minute')
Waits until the given file or directory is removed.
def directory_should_be_empty(self, path, msg=None)
Fails unless the specified directory is empty.
def _fail(self, *messages)
def create_binary_file(self, path, content)
Creates a binary file with the given content.
def touch(self, path)
Emulates the UNIX touch command.
def remove_files(self, *paths)
Uses Remove File to remove multiple files one-by-one.
def file_should_not_exist(self, path, msg=None)
Fails if the given path points to an existing file.
def copy_files(self, *sources_and_destination)
Copies specified files to the target directory.
def get_environment_variable(self, name, default=None)
Returns the value of an environment variable with the given name.
def log_file(self, path, encoding='UTF-8', encoding_errors='strict')
Wrapper for Get File that also logs the returned file.
def _prepare_copy_and_move_directory(self, source, destination)
def move_file(self, source, destination)
Moves the source file into the destination.
def set_modified_time(self, path, mtime)
Sets the file modification and access times.
def get_environment_variables(self)
Returns currently available environment variables as a dictionary.
def _get_matches_error(self, what, path, matches)
def _glob_files(self, patterns)
def file_should_not_be_empty(self, path, msg=None)
Fails if the specified directory is empty.
def _list_dir(self, path, pattern=None, absolute=False)
def run_and_return_rc_and_output(self, command)
Runs the given command in the system and returns the RC and output.
def run(self, command)
Runs the given command in the system and returns the output.
def file_should_be_empty(self, path, msg=None)
Fails unless the specified file is empty.
def should_exist(self, path, msg=None)
Fails unless the given path (file or directory) exists.
def list_files_in_directory(self, path, pattern=None, absolute=False)
Wrapper for List Directory that returns only files.
def _map_encoding(self, encoding)
def environment_variable_should_not_be_set(self, name, msg=None)
Fails if the specified environment variable is set.
def _log(self, msg, level)
def log_environment_variables(self, level='INFO')
Logs all environment variables using the given log level.
def _list_files_in_dir(self, path, pattern=None, absolute=False)
def set_environment_variable(self, name, value)
Sets an environment variable to a specified value.
def _normalize_copy_and_move_destination(self, destination)
def normalize_path(self, path, case_normalize=False)
Normalizes the given path.
def _link(self, msg, *paths)
def move_files(self, *sources_and_destination)
Moves specified files to the target directory.
def join_paths(self, base, *paths)
Joins given paths with base and returns resulted paths.
def split_extension(self, path)
Splits the extension from the given path.
def append_to_environment_variable(self, name, *values, **config)
Appends given values to environment variable name.
def _list_dirs_in_dir(self, path, pattern=None, absolute=False)
def _are_source_and_destination_same_file(self, source, destination)
def get_file(self, path, encoding='UTF-8', encoding_errors='strict')
Returns the contents of a specified file.
def file_should_exist(self, path, msg=None)
Fails unless the given path points to an existing file.
def _prepare_copy_and_move_file(self, source, destination)
def wait_until_created(self, path, timeout='1 minute')
Waits until the given file or directory is created.
def get_modified_time(self, path, format='timestamp')
Returns the last modification time of a file or directory.
def _is_glob_path(self, path)
def directory_should_not_be_empty(self, path, msg=None)
Fails if the specified directory is empty.
def copy_directory(self, source, destination)
Copies the source directory into the destination.
def count_items_in_directory(self, path, pattern=None)
Returns and logs the number of all items in the given directory.
def move_directory(self, source, destination)
Moves the source directory into a destination.
def run_and_return_rc(self, command)
Runs the given command in the system and returns the return code.
def _prepare_copy_and_move_files(self, items)
def remove_environment_variable(self, *names)
Deletes the specified environment variable.
def join_path(self, base, *parts)
Joins the given path part(s) to the given base path.
def append_to_file(self, path, content, encoding='UTF-8')
Appends the given content to the specified file.
def _normalize_copy_and_move_source(self, source)
def grep_file(self, path, pattern, encoding='UTF-8', encoding_errors='strict')
Returns the lines of the specified file that match the pattern.
def _ensure_destination_directory_exists(self, path)
def get_binary_file(self, path)
Returns the contents of a specified file.
def list_directory(self, path, pattern=None, absolute=False)
Returns and logs items in a directory, optionally filtered with pattern.
def directory_should_exist(self, path, msg=None)
Fails unless the given path points to an existing directory.
def create_file(self, path, content='', encoding='UTF-8')
Creates a file with the given content and encoding.
def list_directories_in_directory(self, path, pattern=None, absolute=False)
Wrapper for List Directory that returns only directories.
def directory_should_not_exist(self, path, msg=None)
Fails if the given path points to an existing file.
def empty_directory(self, path)
Deletes all the content from the given directory.
def remove_directory(self, path, recursive=False)
Removes the directory pointed to by the given path.
def split_path(self, path)
Splits the given path from the last path separator (/ or \\).
def _atomic_copy(self, source, destination)
Copy file atomically (or at least try to).
def count_directories_in_directory(self, path, pattern=None)
Wrapper for Count Items In Directory returning only directory count.
def _write_to_file(self, path, content, encoding=None, mode='w')
def copy_file(self, source, destination)
Copies the source file into the destination.
def count_files_in_directory(self, path, pattern=None)
Wrapper for Count Items In Directory returning only file count.
def __init__(self, command)
def _encode_to_file_system(self, string)
def _process_command(self, command)
def _process_output(self, output)
unicode
Exceptions and return codes used internally.
def console_decode(string, encoding=CONSOLE_ENCODING, force=False)
Decodes bytes from console encoding to Unicode.
def seq2str(sequence, quote="'", sep=', ', lastsep=' and ')
Returns sequence in format ‘'item 1’, 'item 2' and 'item 3'`.
def get_env_vars(upper=os.sep !='/')
def set_env_var(name, value)
def get_env_var(name, default=None)
def abspath(path, case_normalize=False)
Replacement for os.path.abspath with some enhancements and bug fixes.
def normpath(path, case_normalize=False)
Replacement for os.path.normpath with some enhancements.
def secs_to_timestamp(secs, seps=None, millis=False)
def get_time(format='timestamp', time_=None)
Return the given or current time in requested format.
def secs_to_timestr(secs, compact=False)
Converts time in seconds to a string representation.
def parse_time(timestr)
Parses the time string and returns its value as seconds since epoch.
def timestr_to_secs(timestr, round_to=3)
Parses time like '1h 10s', '01:00:10' or '42' and returns seconds.
def is_truthy(item)
Returns True or False depending is the item considered true or not.
def get_version(naked=False)