Robot Framework's Listener feature is great for adding optional pre/post-processing that can be invoked on the command line, e.g. pybot --listener myListener.py mySuite.robot. However, I am creating a Python library for Robot Framework, and I would like to automatically register its listeners without needing to be invoked on the command line, so that those listeners are always used when my library is imported (I want the keywords and listeners to work together). Is there a way to register a listener using Python code?
Starting with robot framework 2.8.5, you can register a library as a listener. See Test Libraries as Listeners in the robot framework user's guide. The original feature request is discussed in issue 811
The following is a simple example. It is a library that provides a single keyword, "require test case". This keyword takes as an argument the name of another test case. The library is also a listener which keeps track of which test cases have run. When the keyword runs, it looks at the list of already-run tests and will fail if the required test case has not run yet or has failed.
from robot.libraries.BuiltIn import BuiltIn
class DependencyLibrary(object):
ROBOT_LISTENER_API_VERSION = 2
ROBOT_LIBRARY_SCOPE = "GLOBAL"
def __init__(self):
self.ROBOT_LIBRARY_LISTENER = self
self.test_status = {}
def require_test_case(self, name):
key = name.lower()
if (key not in self.test_status):
BuiltIn().fail("required test case can't be found: '%s'" % name)
if (self.test_status[key] != "PASS"):
BuiltIn().fail("required test case failed: '%s'" % name)
return True
def _end_test(self, name, attrs):
self.test_status[name.lower()] = attrs["status"]
Example of using this in a test case:
*** Settings ***
| Library | /path/to/DependencyLibrary.py
*** Test Cases ***
| Example of a failing test
| | fail | this test has failed
| Example of a dependent test
| | [Setup] | Require test case | Example of a failing test
| | log | hello, world
Looks like I haven't taken a good look at the docs recently enough. This exact feature is new in Robot Framework 2.8.5: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-libraries-as-listeners
来源:https://stackoverflow.com/questions/28506973/register-robot-framework-listener-within-python-library