Call Robot Keywords from *.py file and run it with Pytest

Hi,
I would like to know how to call a keywords from a robot file in *.py file.
And I would like to run the python script with pytest.

I tried with below script but receiving error.

from robot.libraries.BuiltIn import BuiltIn

def test_capital_case():
BuiltIn().import_resource(‘ValidLogin.robot’)
#BuiltIn().run_keyword(‘TC_ValidLoginToTheApplication’)
BuiltIn().call_method(‘K_LoginToTheApplication’)

Error Received:
======================================================================== FAILURES ========================================================================
___________________________________________________________________ test_capital_case ____________________________________________________________________

def test_capital_case():
  BuiltIn().import_resource('ValidLogin.robot')

test_example.py:8:


…\venv\lib\site-packages\robot\libraries\BuiltIn.py:2988: in import_resource
self._namespace.import_resource(path)
…\venv\lib\site-packages\robot\libraries\BuiltIn.py:74: in _namespace
return self._get_context().namespace


self = <robot.libraries.BuiltIn.BuiltIn object at 0x000001720CC50F40>, top = False

def _get_context(self, top=False):
    ctx = EXECUTION_CONTEXTS.current if not top else EXECUTION_CONTEXTS.top
    if ctx is None:
      raise RobotNotRunningError('Cannot access execution context')

E robot.libraries.BuiltIn.RobotNotRunningError: Cannot access execution context

…\venv\lib\site-packages\robot\libraries\BuiltIn.py:69: RobotNotRunningError
================================================================ short test summary info =================================================================
FAILED test_example.py::test_capital_case - robot.libraries.BuiltIn.RobotNotRunningError: Cannot access execution context

Hi Senthilnathan,

I’ve never used this functionality, so my answer is based on what I read in the documentation for module-robot.libraries.BuiltIn.import_resource

The given path must be absolute or found from search path. Forward slashes can be used as path separator regardless the operating system.

I’m guessing that your robot file is not found in the search path? so I suspect you just need to add the path before the robot file, see below:

from robot.libraries.BuiltIn import BuiltIn

def test_capital_case():
    #BuiltIn().import_resource(‘ValidLogin.robot’)
    BuiltIn().import_resource(‘/path/to/ValidLogin.robot’)
    #BuiltIn().run_keyword(‘TC_ValidLoginToTheApplication’)
    BuiltIn().call_method(‘K_LoginToTheApplication’)

I would try this first, and at least rule it out, if you don’t want paths hard coded in your code (totally understandable), then you can use a python variable for the path and pass that in or you can investigate why the robot file is not in the search path.

Hope this helps,

Dave.