Robot Framework中如何将执行传入的标签名传递给Python函数
Hey there! Let's walk through how to pass the tag you specify via the Robot Framework command line to your Python function. I've got two solid approaches for you to choose from:
Approach 1: Fetch the tag directly in your Python function (using Robot's internal context)
This method lets your Python code pull the tag right from Robot's runtime context, no extra work needed in your test suite file.
First, create your Python library file (e.g., custom_functions.py):
from robot.running.context import EXECUTION_CONTEXT def pyfunction(): # Grab the current test suite from Robot's execution context current_suite = EXECUTION_CONTEXT.suite # Extract the tags specified with the `-i` flag included_tags = current_suite.include_tags # Handle cases where multiple tags are passed (e.g., `-i Sanity -i Regression`) if included_tags: tagname = included_tags[0] # Take the first tag, adjust as needed print(f"Successfully received tag: {tagname}") # Add your custom logic here using the tagname else: print("No tags were specified via the command line")
Then, reference this library in your Robot test suite (testsuite.robot):
*** Settings *** Library custom_functions.py *** Test Cases *** Sample Sanity Test [Tags] Sanity Pyfunction
When you run robot -i Sanity testsuite.robot, your Python function will automatically pick up the Sanity tag.
Approach 2: Parse command line options in Robot, then pass the tag to Python
If you prefer to avoid relying on Robot's internal APIs (which might change between versions), you can parse Robot's built-in ${ROBOT_OPTIONS} variable to extract the tag, then pass it to your Python function explicitly.
First, update your Python function to accept the tag as a parameter:
def pyfunction(tagname): print(f"Successfully received tag: {tagname}") # Add your custom logic here using the tagname
Then, modify your Robot test suite to parse the command line options:
*** Settings *** Library custom_functions.py Library String *** Test Cases *** Sample Sanity Test [Tags] Sanity # Get the full command line options passed to Robot ${robot_options} Get Variable Value ${ROBOT_OPTIONS} # Use regex to extract the tag after `-i` ${matched_tags} Get Regexp Matches ${robot_options} -i\s+(\w+) 1 # Pass the first matched tag to your Python function Pyfunction ${matched_tags[0]}
Run it the same way: robot -i Sanity testsuite.robot, and the tag will be passed to pyfunction.
Quick Notes
- If you pass multiple tags with
-i(e.g.,robot -i Sanity -i Regression testsuite.robot), both methods will capture all tags in a list. Adjust your code to handle multiple values if needed. - For Approach 1: The
EXECUTION_CONTEXTobject only exists while Robot is running tests. Don't try to run the Python function outside of a Robot execution—you'll get an error.
内容的提问来源于stack exchange,提问作者user1619472

