Skip to content

robot.result.model

Module implementing result related model objects.

During test execution these objects are created internally by various runners. At that time they can be inspected and modified by listeners__.

When results are parsed from XML output files after execution to be able to create logs and reports, these objects are created by the :func:~.resultbuilder.ExecutionResult factory method. At that point they can be inspected and modified by pre-Rebot modifiers__.

The :func:~.resultbuilder.ExecutionResult factory method can also be used by custom scripts and tools. In such usage it is often easiest to inspect and modify these objects using the :mod:visitor interface <robot.model.visitor>.

If classes defined here are needed, for example, as type hints, they can be imported via the :mod:robot.running module.

__ http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#listener-interface __ http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#programmatic-modification-of-results

StatusMixin

start_time property writable

start_time: datetime | None

Execution start time as a datetime or as a None if not set.

If start time is not set, it is calculated based :attr:end_time and :attr:elapsed_time if possible.

Can be set either directly as a datetime or as a string in ISO 8601 format.

New in Robot Framework 6.1. Heavily enhanced in Robot Framework 7.0.

end_time property writable

end_time: datetime | None

Execution end time as a datetime or as a None if not set.

If end time is not set, it is calculated based :attr:start_time and :attr:elapsed_time if possible.

Can be set either directly as a datetime or as a string in ISO 8601 format.

New in Robot Framework 6.1. Heavily enhanced in Robot Framework 7.0.

elapsed_time property writable

elapsed_time: timedelta

Total execution time as a timedelta.

If not set, calculated based on :attr:start_time and :attr:end_time if possible. If that fails, calculated based on the elapsed time of child items.

Can be set either directly as a timedelta or as an integer or a float representing seconds.

New in Robot Framework 6.1. Heavily enhanced in Robot Framework 7.0.

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

Var

Var(
    name: str = "",
    value: str | Sequence[str] = (),
    scope: str | None = None,
    separator: str | None = None,
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Var, StatusMixin, DeprecatedAttributesMixin

Source code in src/robot/result/model.py
def __init__(self, name: str = '',
             value: 'str|Sequence[str]' = (),
             scope: 'str|None' = None,
             separator: 'str|None' = None,
             status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(name, value, scope, separator, parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

id property

id: str | None

Item id in format like s1-t3-k1.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

id is None only in these special cases:

  • Keyword uses a placeholder for setup or teardown when a setup or teardown is not actually used.
  • With :class:~robot.model.control.If and :class:~robot.model.control.Try instances representing IF/TRY structure roots.

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Child keywords and messages as a :class:~.Body object.

Typically empty. Only contains something if running VAR has failed due to a syntax error or listeners have logged messages or executed keywords.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Child keywords and messages as a :class:`~.Body` object.

    Typically empty. Only contains something if running VAR has failed
    due to a syntax error or listeners have logged messages or executed
    keywords.
    """
    return self.body_class(self, body)

Return

1
2
3
4
5
6
7
8
9
Return(
    values: Sequence[str] = (),
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Return, StatusMixin, DeprecatedAttributesMixin

Source code in src/robot/result/model.py
def __init__(self, values: Sequence[str] = (),
             status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(values, parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

id property

id: str | None

Item id in format like s1-t3-k1.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

id is None only in these special cases:

  • Keyword uses a placeholder for setup or teardown when a setup or teardown is not actually used.
  • With :class:~robot.model.control.If and :class:~robot.model.control.Try instances representing IF/TRY structure roots.

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Child keywords and messages as a :class:~.Body object.

Typically empty. Only contains something if running RETURN has failed due to a syntax error or listeners have logged messages or executed keywords.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Child keywords and messages as a :class:`~.Body` object.

    Typically empty. Only contains something if running RETURN has failed
    due to a syntax error or listeners have logged messages or executed
    keywords.
    """
    return self.body_class(self, body)

Continue

1
2
3
4
5
6
7
8
Continue(
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Continue, StatusMixin, DeprecatedAttributesMixin

Source code in src/robot/result/model.py
def __init__(self, status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

id property

id: str | None

Item id in format like s1-t3-k1.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

id is None only in these special cases:

  • Keyword uses a placeholder for setup or teardown when a setup or teardown is not actually used.
  • With :class:~robot.model.control.If and :class:~robot.model.control.Try instances representing IF/TRY structure roots.

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Child keywords and messages as a :class:~.Body object.

Typically empty. Only contains something if running CONTINUE has failed due to a syntax error or listeners have logged messages or executed keywords.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Child keywords and messages as a :class:`~.Body` object.

    Typically empty. Only contains something if running CONTINUE has failed
    due to a syntax error or listeners have logged messages or executed
    keywords.
    """
    return self.body_class(self, body)

Break

1
2
3
4
5
6
7
8
Break(
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Break, StatusMixin, DeprecatedAttributesMixin

Source code in src/robot/result/model.py
def __init__(self, status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

id property

id: str | None

Item id in format like s1-t3-k1.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

id is None only in these special cases:

  • Keyword uses a placeholder for setup or teardown when a setup or teardown is not actually used.
  • With :class:~robot.model.control.If and :class:~robot.model.control.Try instances representing IF/TRY structure roots.

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Child keywords and messages as a :class:~.Body object.

Typically empty. Only contains something if running BREAK has failed due to a syntax error or listeners have logged messages or executed keywords.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Child keywords and messages as a :class:`~.Body` object.

    Typically empty. Only contains something if running BREAK has failed
    due to a syntax error or listeners have logged messages or executed
    keywords.
    """
    return self.body_class(self, body)

Error

1
2
3
4
5
6
7
8
9
Error(
    values: Sequence[str] = (),
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Error, StatusMixin, DeprecatedAttributesMixin

Source code in src/robot/result/model.py
def __init__(self, values: Sequence[str] = (),
             status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(values, parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

id property

id: str | None

Item id in format like s1-t3-k1.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

id is None only in these special cases:

  • Keyword uses a placeholder for setup or teardown when a setup or teardown is not actually used.
  • With :class:~robot.model.control.If and :class:~robot.model.control.Try instances representing IF/TRY structure roots.

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Messages as a :class:~.Body object.

Typically contains the message that caused the error.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Messages as a :class:`~.Body` object.

    Typically contains the message that caused the error.
    """
    return self.body_class(self, body)

Keyword

Keyword(
    name: str | None = "",
    owner: str | None = None,
    source_name: str | None = None,
    doc: str = "",
    args: Sequence[str] = (),
    assign: Sequence[str] = (),
    tags: Sequence[str] = (),
    timeout: str | None = None,
    type: str = KEYWORD,
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: BodyItemParent = None,
)

Bases: Keyword, StatusMixin

Represents an executed library or user keyword.

Source code in src/robot/result/model.py
def __init__(self, name: 'str|None' = '',
             owner: 'str|None' = None,
             source_name: 'str|None' = None,
             doc: str = '',
             args: Sequence[str] = (),
             assign: Sequence[str] = (),
             tags: Sequence[str] = (),
             timeout: 'str|None' = None,
             type: str = BodyItem.KEYWORD,
             status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: BodyItemParent = None):
    super().__init__(name, args, assign, type, parent)
    #: Name of the library or resource containing this keyword.
    self.owner = owner
    #: Original name of keyword with embedded arguments.
    self.source_name = source_name
    self.doc = doc
    self.tags = tags
    self.timeout = timeout
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time
    self._setup = None
    self._teardown = None
    self.body = ()

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

not_run property writable

not_run: bool

True when :attr:status is 'NOT RUN', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

visit

visit(visitor: SuiteVisitor)

:mod:Visitor interface <robot.model.visitor> entry-point.

Source code in src/robot/model/keyword.py
def visit(self, visitor: 'SuiteVisitor'):
    """:mod:`Visitor interface <robot.model.visitor>` entry-point."""
    if self:
        visitor.visit_keyword(self)

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Possible keyword body as a :class:~.Body object.

Body can consist of child keywords, messages, and control structures such as IF/ELSE. Library keywords typically have an empty body.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Possible keyword body as a :class:`~.Body` object.

    Body can consist of child keywords, messages, and control structures
    such as IF/ELSE. Library keywords typically have an empty body.
    """
    return self.body_class(self, body)

messages property

messages: list[Message]

Keyword's messages.

Starting from Robot Framework 4.0 this is a list generated from messages in :attr:body.

full_name property

full_name: str | None

Keyword name in format owner.name.

Just name if :attr:owner is not set. In practice this is the case only with user keywords in the suite file.

Cannot be set directly. Set :attr:name and :attr:owner separately instead.

Notice that prior to Robot Framework 7.0, the name attribute contained the full name and keyword and owner names were in kwname and libname, respectively.

kwname property writable

kwname: str | None

Deprecated since Robot Framework 7.0. Use :attr:name instead.

libname property writable

libname: str | None

Deprecated since Robot Framework 7.0. Use :attr:owner instead.

sourcename property writable

sourcename: str

Deprecated since Robot Framework 7.0. Use :attr:source_name instead.

setup property writable

setup: Keyword

Keyword setup as a :class:Keyword object.

See :attr:teardown for more information. New in Robot Framework 7.0.

has_setup property

has_setup: bool

Check does a keyword have a setup without creating a setup object.

See :attr:has_teardown for more information. New in Robot Framework 7.0.

teardown property writable

teardown: Keyword

Keyword teardown as a :class:Keyword object.

Teardown can be modified by setting attributes directly::

1
2
keyword.teardown.name = 'Example'
keyword.teardown.args = ('First', 'Second')

Alternatively the :meth:config method can be used to set multiple attributes in one call::

1
keyword.teardown.config(name='Example', args=('First', 'Second'))

The easiest way to reset the whole teardown is setting it to None. It will automatically recreate the underlying Keyword object::

1
keyword.teardown = None

This attribute is a Keyword object also when a keyword has no teardown but in that case its truth value is False. If there is a need to just check does a keyword have a teardown, using the :attr:has_teardown attribute avoids creating the Keyword object and is thus more memory efficient.

New in Robot Framework 4.0. Earlier teardown was accessed like keyword.keywords.teardown. :attr:has_teardown is new in Robot Framework 4.1.2.

has_teardown property

has_teardown: bool

Check does a keyword have a teardown without creating a teardown object.

A difference between using if kw.has_teardown: and if kw.teardown: is that accessing the :attr:teardown attribute creates a :class:Keyword object representing a teardown even when the keyword actually does not have one. This typically does not matter, but with bigger suite structures having lots of keywords it can have a considerable effect on memory usage.

New in Robot Framework 4.1.2.

tags

tags(tags: Sequence[str]) -> Tags

Keyword tags as a :class:~.model.tags.Tags object.

Source code in src/robot/result/model.py
@setter
def tags(self, tags: Sequence[str]) -> model.Tags:
    """Keyword tags as a :class:`~.model.tags.Tags` object."""
    return Tags(tags)

TestCase

TestCase(
    name: str = "",
    doc: str = "",
    tags: Sequence[str] = (),
    timeout: str | None = None,
    lineno: int | None = None,
    status: str = "FAIL",
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: TestSuite | None = None,
)

Bases: TestCase[Keyword], StatusMixin

Represents results of a single test case.

See the base class for documentation of attributes not documented here.

Source code in src/robot/result/model.py
def __init__(self, name: str = '',
             doc: str = '',
             tags: Sequence[str] = (),
             timeout: 'str|None' = None,
             lineno: 'int|None' = None,
             status: str = 'FAIL',
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: 'TestSuite|None' = None):
    super().__init__(name, doc, tags, timeout, lineno, parent)
    self.status = status
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

passed property writable

passed: bool

True when :attr:status is 'PASS', False otherwise.

failed property writable

failed: bool

True when :attr:status is 'FAIL', False otherwise.

skipped property writable

skipped: bool

True when :attr:status is 'SKIP', False otherwise.

Setting to False value is ambiguous and raises an exception.

from_dict classmethod

from_dict(data: DataDict) -> T

Create this object based on data in a dictionary.

Data can be got from the :meth:to_dict method or created externally.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_dict(cls: Type[T], data: DataDict) -> T:
    """Create this object based on data in a dictionary.

    Data can be got from the :meth:`to_dict` method or created externally.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        return cls().config(**data)
    except (AttributeError, TypeError) as err:
        raise DataError(f"Creating '{full_name(cls)}' object from dictionary "
                        f"failed: {err}")

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> T

Create this object based on JSON data.

The data is given as the source parameter. It can be:

  • a string (or bytes) containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

The JSON data is first converted to a Python dictionary and the object created using the :meth:from_dict method.

Notice that the source is considered to be JSON data if it is a string and contains {. If you need to use { in a file system path, pass it in as a pathlib.Path instance.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

Source code in src/robot/model/modelobject.py
@classmethod
def from_json(cls: Type[T], source: 'str|bytes|TextIO|Path') -> T:
    """Create this object based on JSON data.

    The data is given as the ``source`` parameter. It can be:

    - a string (or bytes) containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    The JSON data is first converted to a Python dictionary and the object
    created using the :meth:`from_dict` method.

    Notice that the ``source`` is considered to be JSON data if it is
    a string and contains ``{``. If you need to use ``{`` in a file system
    path, pass it in as a ``pathlib.Path`` instance.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.
    """
    try:
        data = JsonLoader().load(source)
    except (TypeError, ValueError) as err:
        raise DataError(f'Loading JSON data failed: {err}')
    return cls.from_dict(data)

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

tags

tags(tags: Tags | Sequence[str]) -> Tags

Test tags as a :class:~.model.tags.Tags object.

Source code in src/robot/model/testcase.py
@setter
def tags(self, tags: 'Tags|Sequence[str]') -> Tags:
    """Test tags as a :class:`~.model.tags.Tags` object."""
    return Tags(tags)

setup property writable

setup: KW

Test setup as a :class:~.model.keyword.Keyword object.

This attribute is a Keyword object also when a test has no setup but in that case its truth value is False.

Setup can be modified by setting attributes directly::

1
2
test.setup.name = 'Example'
test.setup.args = ('First', 'Second')

Alternatively the :meth:config method can be used to set multiple attributes in one call::

1
test.setup.config(name='Example', args=('First', 'Second'))

The easiest way to reset the whole setup is setting it to None. It will automatically recreate the underlying Keyword object::

1
test.setup = None

New in Robot Framework 4.0. Earlier setup was accessed like test.keywords.setup.

has_setup property

has_setup: bool

Check does a suite have a setup without creating a setup object.

A difference between using if test.has_setup: and if test.setup: is that accessing the :attr:setup attribute creates a :class:Keyword object representing the setup even when the test actually does not have one. This typically does not matter, but with bigger suite structures containing a huge about of tests it can have an effect on memory usage.

New in Robot Framework 5.0.

teardown property writable

teardown: KW

Test teardown as a :class:~.model.keyword.Keyword object.

See :attr:setup for more information.

has_teardown property

has_teardown: bool

Check does a test have a teardown without creating a teardown object.

See :attr:has_setup for more information.

New in Robot Framework 5.0.

id property

id: str

Test case id in format like s1-t3.

See :attr:TestSuite.id <robot.model.testsuite.TestSuite.id> for more information.

full_name property

full_name: str

Test name prefixed with the full name of the parent suite.

longname property

longname: str

Deprecated since Robot Framework 7.0. Use :attr:full_name instead.

visit

visit(visitor: SuiteVisitor)

:mod:Visitor interface <robot.model.visitor> entry-point.

Source code in src/robot/model/testcase.py
def visit(self, visitor: 'SuiteVisitor'):
    """:mod:`Visitor interface <robot.model.visitor>` entry-point."""
    visitor.visit_test(self)

body

body(body: Sequence[BodyItem | DataDict]) -> Body

Test body as a :class:~robot.result.Body object.

Source code in src/robot/result/model.py
@setter
def body(self, body: 'Sequence[BodyItem|DataDict]') -> Body:
    """Test body as a :class:`~robot.result.Body` object."""
    return self.body_class(self, body)

TestSuite

TestSuite(
    name: str = "",
    doc: str = "",
    metadata: Mapping[str, str] | None = None,
    source: Path | str | None = None,
    rpa: bool = False,
    message: str = "",
    start_time: datetime | str | None = None,
    end_time: datetime | str | None = None,
    elapsed_time: timedelta | int | float | None = None,
    parent: TestSuite | None = None,
)

Bases: TestSuite[Keyword, TestCase], StatusMixin

Represents results of a single test suite.

See the base class for documentation of attributes not documented here.

Source code in src/robot/result/model.py
def __init__(self, name: str = '',
             doc: str = '',
             metadata: 'Mapping[str, str]|None' = None,
             source: 'Path|str|None' = None,
             rpa: bool = False,
             message: str = '',
             start_time: 'datetime|str|None' = None,
             end_time: 'datetime|str|None' = None,
             elapsed_time: 'timedelta|int|float|None' = None,
             parent: 'TestSuite|None' = None):
    super().__init__(name, doc, metadata, source, rpa, parent)
    #: Possible suite setup or teardown error message.
    self.message = message
    self.start_time = start_time
    self.end_time = end_time
    self.elapsed_time = elapsed_time

starttime property writable

starttime: str | None

Execution start time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:start_time should be used instead.

endtime property writable

endtime: str | None

Execution end time as a string or as a None if not set.

The string format is %Y%m%d %H:%M:%S.%f.

Considered deprecated starting from Robot Framework 7.0. :attr:end_time should be used instead.

elapsedtime property

elapsedtime: int

Total execution time in milliseconds.

Considered deprecated starting from Robot Framework 7.0. :attr:elapsed_time should be used instead.

to_json

1
2
3
4
5
6
7
to_json(
    file: None = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str
1
2
3
4
5
6
7
to_json(
    file: TextIO | Path | str,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> None
1
2
3
4
5
6
7
to_json(
    file: None | TextIO | Path | str = None,
    *,
    ensure_ascii: bool = False,
    indent: int = 0,
    separators: tuple[str, str] = (",", ":")
) -> str | None

Serialize this object into JSON.

The object is first converted to a Python dictionary using the :meth:to_dict method and then the dictionary is converted to JSON.

The file parameter controls what to do with the resulting JSON data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

JSON formatting can be configured using optional parameters that are passed directly to the underlying json__ module. Notice that the defaults differ from what json uses.

With robot.running model objects new in Robot Framework 6.1, with robot.result new in Robot Framework 7.0.

__ https://docs.python.org/3/library/json.html

Source code in src/robot/model/modelobject.py
def to_json(self, file: 'None|TextIO|Path|str' = None, *,
            ensure_ascii: bool = False, indent: int = 0,
            separators: 'tuple[str, str]' = (',', ':')) -> 'str|None':
    """Serialize this object into JSON.

    The object is first converted to a Python dictionary using the
    :meth:`to_dict` method and then the dictionary is converted to JSON.

    The ``file`` parameter controls what to do with the resulting JSON data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    JSON formatting can be configured using optional parameters that
    are passed directly to the underlying json__ module. Notice that
    the defaults differ from what ``json`` uses.

    With ``robot.running`` model objects new in Robot Framework 6.1,
    with ``robot.result`` new in Robot Framework 7.0.

    __ https://docs.python.org/3/library/json.html
    """
    return JsonDumper(ensure_ascii=ensure_ascii, indent=indent,
                      separators=separators).dump(self.to_dict(), file)

config

config(**attributes) -> T

Configure model object with given attributes.

obj.config(name='Example', doc='Something') is equivalent to setting obj.name = 'Example' and obj.doc = 'Something'.

New in Robot Framework 4.0.

Source code in src/robot/model/modelobject.py
def config(self: T, **attributes) -> T:
    """Configure model object with given attributes.

    ``obj.config(name='Example', doc='Something')`` is equivalent to setting
    ``obj.name = 'Example'`` and ``obj.doc = 'Something'``.

    New in Robot Framework 4.0.
    """
    for name, value in attributes.items():
        try:
            orig = getattr(self, name)
        except AttributeError:
            raise AttributeError(f"'{full_name(self)}' object does not have "
                                 f"attribute '{name}'")
        # Preserve tuples. Main motivation is converting lists with `from_json`.
        if isinstance(orig, tuple) and not isinstance(value, tuple):
            try:
                value = tuple(value)
            except TypeError:
                raise TypeError(f"'{full_name(self)}' object attribute '{name}' "
                                f"is 'tuple', got '{type_name(value)}'.")
        try:
            setattr(self, name, value)
        except AttributeError as err:
            # Ignore error setting attribute if the object already has it.
            # Avoids problems with `from_dict` with body items having
            # un-settable `type` attribute that is needed in dict data.
            if value != orig:
                raise AttributeError(f"Setting attribute '{name}' failed: {err}")
    return self

copy

copy(**attributes) -> T

Return a shallow copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.copy(name='New name').

See also :meth:deepcopy. The difference between copy and deepcopy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def copy(self: T, **attributes) -> T:
    """Return a shallow copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.copy(name='New name')``.

    See also :meth:`deepcopy`. The difference between ``copy`` and
    ``deepcopy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.copy(self).config(**attributes)

deepcopy

deepcopy(**attributes) -> T

Return a deep copy of this object.

:param attributes: Attributes to be set to the returned copy. For example, obj.deepcopy(name='New name').

See also :meth:copy. The difference between deepcopy and copy is the same as with the methods having same names in the copy__ module.

__ https://docs.python.org/3/library/copy.html

Source code in src/robot/model/modelobject.py
def deepcopy(self: T, **attributes) -> T:
    """Return a deep copy of this object.

    :param attributes: Attributes to be set to the returned copy.
        For example, ``obj.deepcopy(name='New name')``.

    See also :meth:`copy`. The difference between ``deepcopy`` and
    ``copy`` is the same as with the methods having same names in
    the copy__ module.

    __ https://docs.python.org/3/library/copy.html
    """
    return copy.deepcopy(self).config(**attributes)

metadata

metadata(metadata: Mapping[str, str] | None) -> Metadata

Free suite metadata as a :class:~.metadata.Metadata object.

Source code in src/robot/model/testsuite.py
@setter
def metadata(self, metadata: 'Mapping[str, str]|None') -> Metadata:
    """Free suite metadata as a :class:`~.metadata.Metadata` object."""
    return Metadata(metadata)

name_from_source staticmethod

1
2
3
name_from_source(
    source: Path | str | None, extension: Sequence[str] = ()
) -> str

Create suite name based on the given source.

This method is used by Robot Framework itself when it builds suites. External parsers and other tools that want to produce suites with names matching names created by Robot Framework can use this method as well. This method is also used if :attr:name is not set and someone accesses it.

The algorithm is as follows:

  • If the source is None or empty, return an empty string.
  • Get the base name of the source. Read more below.
  • Remove possible prefix separated with __.
  • Convert underscores to spaces.
  • If the name is all lower case, title case it.

The base name of files is got by calling Path.stem__ that drops the file extension. It typically works fine, but gives wrong result if the extension has multiple parts like in tests.robot.zip. That problem can be avoided by giving valid file extension or extensions as the optional extension argument.

Examples::

1
2
3
TestSuite.name_from_source(source)
TestSuite.name_from_source(source, extension='.robot.zip')
TestSuite.name_from_source(source, ('.robot', '.robot.zip'))

__ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem

Source code in src/robot/model/testsuite.py
@staticmethod
def name_from_source(source: 'Path|str|None', extension: Sequence[str] = ()) -> str:
    """Create suite name based on the given ``source``.

    This method is used by Robot Framework itself when it builds suites.
    External parsers and other tools that want to produce suites with
    names matching names created by Robot Framework can use this method as
    well. This method is also used if :attr:`name` is not set and someone
    accesses it.

    The algorithm is as follows:

    - If the source is ``None`` or empty, return an empty string.
    - Get the base name of the source. Read more below.
    - Remove possible prefix separated with ``__``.
    - Convert underscores to spaces.
    - If the name is all lower case, title case it.

    The base name of files is got by calling `Path.stem`__ that drops
    the file extension. It typically works fine, but gives wrong result
    if the extension has multiple parts like in ``tests.robot.zip``.
    That problem can be avoided by giving valid file extension or extensions
    as the optional ``extension`` argument.

    Examples::

        TestSuite.name_from_source(source)
        TestSuite.name_from_source(source, extension='.robot.zip')
        TestSuite.name_from_source(source, ('.robot', '.robot.zip'))

    __ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem
    """
    if not source:
        return ''
    if not isinstance(source, Path):
        source = Path(source)
    name = TestSuite._get_base_name(source, extension)
    if '__' in name:
        name = name.split('__', 1)[1] or name
    name = name.replace('_', ' ').strip()
    return name.title() if name.islower() else name

name property writable

name: str

Suite name.

If name is not set, it is constructed from source. If source is not set, name is constructed from child suite names by concatenating them with &. If there are no child suites, name is an empty string.

adjust_source

1
2
3
4
adjust_source(
    relative_to: Path | str | None = None,
    root: Path | str | None = None,
)

Adjust suite source and child suite sources, recursively.

:param relative_to: Make suite source relative to the given path. Calls pathlib.Path.relative_to()__ internally. Raises ValueError if creating a relative path is not possible. :param root: Make given path a new root directory for the source. Raises ValueError if suite source is absolute.

Adjusting the source is especially useful when moving data around as JSON::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from robot.api import TestSuite

# Create a suite, adjust source and convert to JSON.
suite = TestSuite.from_file_system('/path/to/data')
suite.adjust_source(relative_to='/path/to')
suite.to_json('data.rbt')

# Recreate suite elsewhere and adjust source accordingly.
suite = TestSuite.from_json('data.rbt')
suite.adjust_source(root='/new/path/to')

New in Robot Framework 6.1.

__ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.relative_to

Source code in src/robot/model/testsuite.py
def adjust_source(self, relative_to: 'Path|str|None' = None,
                  root: 'Path|str|None' = None):
    """Adjust suite source and child suite sources, recursively.

    :param relative_to: Make suite source relative to the given path. Calls
        `pathlib.Path.relative_to()`__ internally. Raises ``ValueError``
        if creating a relative path is not possible.
    :param root: Make given path a new root directory for the source. Raises
        ``ValueError`` if suite source is absolute.

    Adjusting the source is especially useful when moving data around as JSON::

        from robot.api import TestSuite

        # Create a suite, adjust source and convert to JSON.
        suite = TestSuite.from_file_system('/path/to/data')
        suite.adjust_source(relative_to='/path/to')
        suite.to_json('data.rbt')

        # Recreate suite elsewhere and adjust source accordingly.
        suite = TestSuite.from_json('data.rbt')
        suite.adjust_source(root='/new/path/to')

    New in Robot Framework 6.1.

    __ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.relative_to
    """
    if not self.source:
        raise ValueError('Suite has no source.')
    if relative_to:
        self.source = self.source.relative_to(relative_to)
    if root:
        if self.source.is_absolute():
            raise ValueError(f"Cannot set root for absolute source '{self.source}'.")
        self.source = root / self.source
    for suite in self.suites:
        suite.adjust_source(relative_to, root)

full_name property

full_name: str

Suite name prefixed with the full name of the possible parent suite.

Just :attr:name of the suite if it has no :attr:parent.

longname property

longname: str

Deprecated since Robot Framework 7.0. Use :attr:full_name instead.

validate_execution_mode

validate_execution_mode() -> bool | None

Validate that suite execution mode is set consistently.

Raise an exception if the execution mode is not set (i.e. the :attr:rpa attribute is None) and child suites have conflicting execution modes.

The execution mode is returned. New in RF 6.1.1.

Source code in src/robot/model/testsuite.py
def validate_execution_mode(self) -> 'bool|None':
    """Validate that suite execution mode is set consistently.

    Raise an exception if the execution mode is not set (i.e. the :attr:`rpa`
    attribute is ``None``) and child suites have conflicting execution modes.

    The execution mode is returned. New in RF 6.1.1.
    """
    if self.rpa is None:
        rpa = name = None
        for suite in self.suites:
            suite.validate_execution_mode()
            if rpa is None:
                rpa = suite.rpa
                name = suite.full_name
            elif rpa is not suite.rpa:
                mode1, mode2 = ('tasks', 'tests') if rpa else ('tests', 'tasks')
                raise DataError(
                    f"Conflicting execution modes: Suite '{name}' has {mode1} but "
                    f"suite '{suite.full_name}' has {mode2}. Resolve the conflict "
                    f"or use '--rpa' or '--norpa' options to set the execution "
                    f"mode explicitly."
                )
        self.rpa = rpa
    return self.rpa

setup property writable

setup: KW

Suite setup.

This attribute is a Keyword object also when a suite has no setup but in that case its truth value is False. The preferred way to check does a suite have a setup is using :attr:has_setup.

Setup can be modified by setting attributes directly::

1
2
suite.setup.name = 'Example'
suite.setup.args = ('First', 'Second')

Alternatively the :meth:config method can be used to set multiple attributes in one call::

1
suite.setup.config(name='Example', args=('First', 'Second'))

The easiest way to reset the whole setup is setting it to None. It will automatically recreate the underlying Keyword object::

1
suite.setup = None

New in Robot Framework 4.0. Earlier setup was accessed like suite.keywords.setup.

has_setup property

has_setup: bool

Check does a suite have a setup without creating a setup object.

A difference between using if suite.has_setup: and if suite.setup: is that accessing the :attr:setup attribute creates a :class:Keyword object representing the setup even when the suite actually does not have one. This typically does not matter, but with bigger suite structures it can have some effect on memory usage.

New in Robot Framework 5.0.

teardown property writable

teardown: KW

Suite teardown.

See :attr:setup for more information.

has_teardown property

has_teardown: bool

Check does a suite have a teardown without creating a teardown object.

See :attr:has_setup for more information.

New in Robot Framework 5.0.

id property

id: str

An automatically generated unique id.

The root suite has id s1, its child suites have ids s1-s1, s1-s2, ..., their child suites get ids s1-s1-s1, s1-s1-s2, ..., s1-s2-s1, ..., and so on.

The first test in a suite has an id like s1-t1, the second has an id s1-t2, and so on. Similarly, keywords in suites (setup/teardown) and in tests get ids like s1-k1, s1-t1-k1, and s1-s4-t2-k5.

all_tests property

all_tests: Iterator[TestCase]

Yields all tests this suite and its child suites contain.

New in Robot Framework 6.1.

test_count property

test_count: int

Total number of the tests in this suite and in its child suites.

set_tags

1
2
3
4
5
set_tags(
    add: Sequence[str] = (),
    remove: Sequence[str] = (),
    persist: bool = False,
)

Add and/or remove specified tags to the tests in this suite.

:param add: Tags to add as a list or, if adding only one, as a single string. :param remove: Tags to remove as a list or as a single string. Can be given as patterns where * and ? work as wildcards. :param persist: Add/remove specified tags also to new tests added to this suite in the future.

Source code in src/robot/model/testsuite.py
def set_tags(self, add: Sequence[str] = (), remove: Sequence[str] = (),
             persist: bool = False):
    """Add and/or remove specified tags to the tests in this suite.

    :param add: Tags to add as a list or, if adding only one,
        as a single string.
    :param remove: Tags to remove as a list or as a single string.
        Can be given as patterns where ``*`` and ``?`` work as wildcards.
    :param persist: Add/remove specified tags also to new tests added
        to this suite in the future.
    """
    setter = TagSetter(add, remove)
    self.visit(setter)
    if persist:
        self._my_visitors.append(setter)

filter

1
2
3
4
5
6
filter(
    included_suites: Sequence[str] | None = None,
    included_tests: Sequence[str] | None = None,
    included_tags: Sequence[str] | None = None,
    excluded_tags: Sequence[str] | None = None,
)

Select test cases and remove others from this suite.

Parameters have the same semantics as --suite, --test, --include, and --exclude command line options. All of them can be given as a list of strings, or when selecting only one, as a single string.

Child suites that contain no tests after filtering are automatically removed.

Example::

1
2
suite.filter(included_tests=['Test 1', '* Example'],
             included_tags='priority-1')
Source code in src/robot/model/testsuite.py
def filter(self, included_suites: 'Sequence[str]|None' = None,
           included_tests: 'Sequence[str]|None' = None,
           included_tags: 'Sequence[str]|None' = None,
           excluded_tags: 'Sequence[str]|None' = None):
    """Select test cases and remove others from this suite.

    Parameters have the same semantics as ``--suite``, ``--test``,
    ``--include``, and ``--exclude`` command line options. All of them
    can be given as a list of strings, or when selecting only one, as
    a single string.

    Child suites that contain no tests after filtering are automatically
    removed.

    Example::

        suite.filter(included_tests=['Test 1', '* Example'],
                     included_tags='priority-1')
    """
    self.visit(Filter(included_suites, included_tests,
                      included_tags, excluded_tags))

remove_empty_suites

remove_empty_suites(preserve_direct_children: bool = False)

Removes all child suites not containing any tests, recursively.

Source code in src/robot/model/testsuite.py
def remove_empty_suites(self, preserve_direct_children: bool = False):
    """Removes all child suites not containing any tests, recursively."""
    self.visit(EmptySuiteRemover(preserve_direct_children))

visit

visit(visitor: SuiteVisitor)

:mod:Visitor interface <robot.model.visitor> entry-point.

Source code in src/robot/model/testsuite.py
def visit(self, visitor: SuiteVisitor):
    """:mod:`Visitor interface <robot.model.visitor>` entry-point."""
    visitor.visit_suite(self)

passed property

passed: bool

True if no test has failed but some have passed, False otherwise.

failed property

failed: bool

True if any test has failed, False otherwise.

skipped property

skipped: bool

True if there are no passed or failed tests, False otherwise.

status property

status: Literal['PASS', 'SKIP', 'FAIL']

'PASS', 'FAIL' or 'SKIP' depending on test statuses.

  • If any test has failed, status is 'FAIL'.
  • If no test has failed but at least some test has passed, status is 'PASS'.
  • If there are no failed or passed tests, status is 'SKIP'. This covers both the case when all tests have been skipped and when there are no tests.

statistics property

statistics: TotalStatistics

Suite statistics as a :class:~robot.model.totalstatistics.TotalStatistics object.

Recreated every time this property is accessed, so saving the results to a variable and inspecting it is often a good idea::

1
2
3
4
stats = suite.statistics
print(stats.failed)
print(stats.total)
print(stats.message)

full_message property

full_message: str

Combination of :attr:message and :attr:stat_message.

stat_message property

stat_message: str

String representation of the :attr:statistics.

remove_keywords

remove_keywords(how: str)

Remove keywords based on the given condition.

:param how: Which approach to use when removing keywords. Either ALL, PASSED, FOR, WUKS, or NAME:<pattern>.

For more information about the possible values see the documentation of the --removekeywords command line option.

Source code in src/robot/result/model.py
def remove_keywords(self, how: str):
    """Remove keywords based on the given condition.

    :param how: Which approach to use when removing keywords. Either
        ``ALL``, ``PASSED``, ``FOR``, ``WUKS``, or ``NAME:<pattern>``.

    For more information about the possible values see the documentation
    of the ``--removekeywords`` command line option.
    """
    self.visit(KeywordRemover.from_config(how))

filter_messages

filter_messages(log_level: str = 'TRACE')

Remove log messages below the specified log_level.

Source code in src/robot/result/model.py
def filter_messages(self, log_level: str = 'TRACE'):
    """Remove log messages below the specified ``log_level``."""
    self.visit(MessageFilter(log_level))

configure

configure(**options)

A shortcut to configure a suite using one method call.

Can only be used with the root test suite.

:param options: Passed to :class:~robot.result.configurer.SuiteConfigurer that will then set suite attributes, call :meth:filter, etc. as needed.

Example::

1
2
suite.configure(remove_keywords='PASSED',
                doc='Smoke test results.')

Not to be confused with :meth:config method that suites, tests, and keywords have to make it possible to set multiple attributes in one call.

Source code in src/robot/result/model.py
def configure(self, **options):
    """A shortcut to configure a suite using one method call.

    Can only be used with the root test suite.

    :param options: Passed to
        :class:`~robot.result.configurer.SuiteConfigurer` that will then
        set suite attributes, call :meth:`filter`, etc. as needed.

    Example::

        suite.configure(remove_keywords='PASSED',
                        doc='Smoke test results.')

    Not to be confused with :meth:`config` method that suites, tests,
    and keywords have to make it possible to set multiple attributes in
    one call.
    """
    super().configure()    # Parent validates is call allowed.
    self.visit(SuiteConfigurer(**options))

handle_suite_teardown_failures

handle_suite_teardown_failures()

Internal usage only.

Source code in src/robot/result/model.py
def handle_suite_teardown_failures(self):
    """Internal usage only."""
    self.visit(SuiteTeardownFailureHandler())

suite_teardown_failed

suite_teardown_failed(message: str)

Internal usage only.

Source code in src/robot/result/model.py
def suite_teardown_failed(self, message: str):
    """Internal usage only."""
    self.visit(SuiteTeardownFailed(message))

suite_teardown_skipped

suite_teardown_skipped(message: str)

Internal usage only.

Source code in src/robot/result/model.py
def suite_teardown_skipped(self, message: str):
    """Internal usage only."""
    self.visit(SuiteTeardownFailed(message, skipped=True))

from_dict classmethod

from_dict(data: DataDict) -> TestSuite

Create suite based on result data in a dictionary.

data can either contain only the suite data got, for example, from the :meth:to_dict method, or it can contain full result data with execution errors and other such information in addition to the suite data. In the latter case only the suite data is used, though.

Support for full result data is new in Robot Framework 7.2.

Source code in src/robot/result/model.py
@classmethod
def from_dict(cls, data: DataDict) -> 'TestSuite':
    """Create suite based on result data in a dictionary.

    ``data`` can either contain only the suite data got, for example, from
    the :meth:`to_dict` method, or it can contain full result data with
    execution errors and other such information in addition to the suite data.
    In the latter case only the suite data is used, though.

    Support for full result data is new in Robot Framework 7.2.
    """
    if 'suite' in data:
        data = data['suite']
    return super().from_dict(data)

from_json classmethod

from_json(source: str | bytes | TextIO | Path) -> TestSuite

Create suite based on results in JSON.

The data is given as the source parameter. It can be:

  • a string containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

Supports JSON produced by :meth:to_json that contains only the suite information, as well as full result JSON that contains also execution errors and other information. In the latter case errors and all other information is silently ignored, though. If that is a problem, :class:~robot.result.resultbuilder.ExecutionResult should be used instead.

Support for full result JSON is new in Robot Framework 7.2.

Source code in src/robot/result/model.py
@classmethod
def from_json(cls, source: 'str|bytes|TextIO|Path') -> 'TestSuite':
    """Create suite based on results in JSON.

    The data is given as the ``source`` parameter. It can be:

    - a string containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    Supports JSON produced by :meth:`to_json` that contains only the suite
    information, as well as full result JSON that contains also execution
    errors and other information. In the latter case errors and all other
    information is silently ignored, though. If that is a problem,
    :class:`~robot.result.resultbuilder.ExecutionResult` should be used
    instead.

    Support for full result JSON is new in Robot Framework 7.2.
    """
    return super().from_json(source)

to_xml

to_xml(file: None = None) -> str
to_xml(file: TextIO | Path | str) -> None
1
2
3
to_xml(
    file: None | TextIO | Path | str = None,
) -> str | None

Serialize suite into XML.

The format is the same that is used with normal output.xml files, but the <robot> root node is omitted and the result contains only the <suite> structure.

The file parameter controls what to do with the resulting XML data. It can be:

  • None (default) to return the data as a string,
  • an open file object where to write the data to, or
  • a path (pathlib.Path or string) to a file where to write the data using UTF-8 encoding.

A serialized suite can be recreated by using the :meth:from_xml method.

New in Robot Framework 7.0.

Source code in src/robot/result/model.py
def to_xml(self, file: 'None|TextIO|Path|str' = None) -> 'str|None':
    """Serialize suite into XML.

    The format is the same that is used with normal output.xml files, but
    the ``<robot>`` root node is omitted and the result contains only
    the ``<suite>`` structure.

    The ``file`` parameter controls what to do with the resulting XML data.
    It can be:

    - ``None`` (default) to return the data as a string,
    - an open file object where to write the data to, or
    - a path (``pathlib.Path`` or string) to a file where to write
      the data using UTF-8 encoding.

    A serialized suite can be recreated by using the :meth:`from_xml` method.

    New in Robot Framework 7.0.
    """
    from robot.reporting.outputwriter import OutputWriter

    output, close = self._get_output(file)
    try:
        self.visit(OutputWriter(output, suite_only=True))
    finally:
        if close:
            output.close()
    return output.getvalue() if file is None else None

from_xml classmethod

from_xml(source: str | TextIO | Path) -> TestSuite

Create suite based on results in XML.

The data is given as the source parameter. It can be:

  • a string containing the data directly,
  • an open file object where to read the data from, or
  • a path (pathlib.Path or string) to a UTF-8 encoded file to read.

Supports both normal output.xml files and files containing only the <suite> structure created, for example, with the :meth:to_xml method. When using normal output.xml files, possible execution errors listed in <errors> are silently ignored. If that is a problem, :class:~robot.result.resultbuilder.ExecutionResult should be used instead.

New in Robot Framework 7.0.

Source code in src/robot/result/model.py
@classmethod
def from_xml(cls, source: 'str|TextIO|Path') -> 'TestSuite':
    """Create suite based on results in XML.

    The data is given as the ``source`` parameter. It can be:

    - a string containing the data directly,
    - an open file object where to read the data from, or
    - a path (``pathlib.Path`` or string) to a UTF-8 encoded file to read.

    Supports both normal output.xml files and files containing only the
    ``<suite>`` structure created, for example, with the :meth:`to_xml`
    method. When using normal output.xml files, possible execution errors
    listed in ``<errors>`` are silently ignored. If that is a problem,
    :class:`~robot.result.resultbuilder.ExecutionResult` should be used
    instead.

    New in Robot Framework 7.0.
    """
    from .resultbuilder import ExecutionResult

    return ExecutionResult(source).suite