0
votes

How can I read a file from a specific byte position in Robot Framework?

Let's say I have a process running for a long time writing a long log file. I want to get the current file size, then I execute something that affects the behaviour of the process and I wait until some message appears in the log file. I want to read only the portion of the file starting from the previous file size.

I am new to Robot Framework. I think this is a very common scenario, but I haven't found how to do it.

1

1 Answers

2
votes

There are no built-in keywords to do this, but writing one in python is pretty simple.

For example, create a file named "readmore.py" with the following:

from robot.libraries.BuiltIn import BuiltIn

class readmore(object):
      ROBOT_LIBRARY_SCOPE = "TEST SUITE"

      def __init__(self):
            self.fp = {}

      def read_more(self, path):
            # if we don't already know about this file, 
            # set the file pointer to zero
            if path not in self.fp:
                  BuiltIn().log("setting fp to zero", "DEBUG")
                  self.fp[path] = 0

            # open the file, move the pointer to the stored
            # position, read the file, and reset the pointer
            with open(path) as f:
                  BuiltIn().log("seeking to %s" % self.fp[path], "DEBUG")
                  f.seek(self.fp[path])
                  data = f.read()
                  self.fp[path] = f.tell()
                  BuiltIn().log("resetting fp to %s" % self.fp[path], "DEBUG")

                  return data

You can then use it like this:

*** Settings ***
| Library | readmore.py
| Library | OperatingSystem

*** test cases ***
| Example of "tail-like" reading of a file
| | # read the current contents of the file
| | ${original}= | read more | /tmp/junk.txt

| | # do something to add more data to the file
| | Append to file | /tmp/junk.txt | this is new content\n

| | # read the new data
| | ${new}=  | Read more | /tmp/junk.txt
| | Should be equal | ${new.strip()} | this is new content