How to import and use user defined classes in a robot structure using python

Suppose I have a class in python:

class TestClass(object): def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 def print_args(self): print arg1, arg2 

I want to use robotframework to implement my test scripts. I want to make an instance from the class above and call its methods. How to do it? I know how to import lib; it should be like this:

 Library TestClass 

I do not know how to initialize an object from this class and call class methods through this object. If I wanted to implement it with python, I would write a piece of code like this:

 import TestClass test = TestClass('ARG1', 'ARG2') test.print_args() 

Now I want to know how to write this in a robotframework . Any help?

+7
python testing robotframework
source share
2 answers

To import a library with arguments, simply add them after the library name :

 Library TestClass ARG1 ARG2 

Thus, the β€œimport” and instantiation are performed in one shot. Now what can be tricky is to understand the volume of your instance. This is well explained in the "User Guide" section of the Test Library area :

A new instance is created for each test case. [...] This is the default value.

Note that if you want to import the same library several times with different arguments and, therefore, have difference instances of your classes, you will have to name them when importing:

 Library TestClass ARG1 ARG2 WITH NAME First_lib Library TestClass ARG3 ARG4 WITH NAME Second_lib 

And then in your tests you should prefix the keywords:

 *** Test Cases *** MyTest First_lib.mykeyword foo bar Second_lib.mykeyword john doe 

This is explained in this section of the User Guide .

+11
source share

I managed to create instances of python classes on demand (i.e. not only hardcoded arguments, as in the Library method).

I used a helper method to create the class. I was unable to get the Robot script to call the constructor of the class directly, however it can call functions in Python, so we can create a class or namedtuple by providing a functional interface:

 File: resource_MakeMyClass.robot *** Settings *** Library myClass *** Keywords *** _MakeMyClass [Arguments] ${arg1} ${arg2} ${result} = makeMyClass ${arg1} ${arg2} [Return] ${result} ----------------------------------------------------- File: myClass.py class MyClass(object): def __init__(self, arg1, arg2): self.arg1 = arg1 self.arg2 = arg2 def makeMyClass(arg1, arg2): return MyClass(arg1, arg2) 
+1
source share

All Articles