Robot Framework equivalent of pytest.fixture
-
21-12-2019 - |
Question
A feature I like a lot with pytest is pytest.fixture which permits dependency injection. As an example, I can have a fixture injecting a new random string silly_string
into any function needing it:
conftest.py:
@pytest.fixture(scope='function')
def silly_string(request):
return ''.join(random.choice(string.ascii_lowercase) for _ in range(5))
test_strings.py
def test_string_length(self, silly_string)
assert len(silly_string) == 5
Contrived example, obviously.
I am not aware of any equivalent functionality within Robot Framework. Currently, I create a new variable using a keyword, and then pass that variable as a parameter. It would be nice to have the parameter automatically injected.
Is there a mechanism within Robot Framework to similarly perform dependency injection?
Solution
No, there is nothing built-in to robot to do what you want.
If what you're after is strings generated at runtime, you can leverage robot's extended variable syntax. For example, if you have a robot variable ${v}
that holds a reference to a python object, you can do something like this:
| | ${v}= | Get reference to v
| | log | Hello ${v.silly_string()}`
The above will call the silly_string
method on the object pointed to by ${v}
. The keyword Get reference to v
would be a python-based keyword that you write that returns an object with the silly_string
method.