• Documentation
  • Tutorials
  • Blogs
  • Product

What's on this Page

  • Keyword declaration
    • Keyword annotation
  • Keyword inputs
    • Reading the inputs in code
    • Passing inputs from code
    • Passing inputs from the Step plan
  • Keyword properties
  • Keyword outputs
    • Custom fields
    • Attachment
    • Measurements
    • Error handling
  • Keyword execution hooks
    • onError hook
    • beforeKeyword and afterKeyword hooks
  • Session
    • Storing and accessing objects
  • Keyword Proxy: plans as Code
    • How it works
  • Step
  • Developer guide
  • Keyword API
Categories: DEVELOPER GUIDE API
This article references one of our previous releases, click here to go to our latest version instead.

Keyword API

For a better understanding of the key concepts and best practices of keywords development, make sure to read first the Keyword development page.

The versatility of Step and its keyword API allows developers to implement their own custom Step’s Keywords whether they use 3rd party automation framework or their own libraries.

The Keyword API defines a clear interface to:

  • define and configure Keywords
  • access Keyword inputs, session objects, and report data (keyword outputs, performance measurements, attachments)
  • implement hooks related to keyword executions (interceptors, error management)

The Keyword API is natively available for Java, .NET and JavaScript/TypeScript.

Keyword declaration

Declaring a keyword with the API is quite simple but varies a bit depending on the target language.

    Declaring a keyword in Java requires to extend the AbstractKeyword superclass and annotate the keyword’s function with the Keyword annotation . More details about this class can be found in the javadoc.

    public class MyKeywords extends AbstractKeyword{
      @Keyword
      public void myKeyword() {
        //my automation
      }
    }

    Declaring a keyword in .Net requires to extend the class with the AbstractScript superclass. Each method defining a keyword is then annotated with the Keyword annotation, it must have no arguments and return type void.

    namespace STEP {
      public class Keywords : StepApi.AbstractScript {
        [Keyword(name = "My Keyword")]
        public void MyKeyword() {
          //your implementation
        }
      }
    }

    Javascript Keywords are defined as async functions with arguments input, output, session and properties. They must always end with an output.send statement.

    exports.MyKeyword = async (input, output, session, properties) => {
      //do some work
      output.send({ result: 'OK' })
    }

    Keyword annotation

    The Keyword annotation as following optional attributes which can be used:

    • name: the name of this keyword. If not specified the method name is used as keyword name
    • description: a text describing the keyword usage. It will be displayed in the gui
    • properties: the list of properties required by this keyword
    • optionalProperties: the list of optional properties which might be used by this keyword
    • schema: the JSON schema of the input object
    • timeout: the keyword timeout in milliseconds
    • planReference: the path to the file containing a plain text plan; used to define a composite keyword

    More details on the usage and impact of these attributes are described here.

    Keyword inputs

    A Keyword’s input is a JsonObject with opened types. Thus the developer can choose the type of their arguments but must ensure that they are read accordingly to that type, otherwise the Json reader will throw an error.
    The inputs are passed to the keyword by the caller as described in the following sections.

    Reading the inputs in code

    Inside the Keyword, you can then retrieve your inputs like this:

      String homeUrl = input.getString("url");
      int elementIndex = input.getInt("index",1);
      String homeUrl = (string)input["url"];
      var homeUrl = input['url'];

      Reading inputs from method arguments

      For Java, there is an easier alternative to define and access inputs: directly as method arguments. In such case, the schema specifying the keyword’s inputs is also generated automatically.

      In this case, the @Input annotation is used for each method parameters. This annotation supports following properties:

      • name: the name of input (must be defined for method parameter)
      • defaultValue - the default value to be used if the input is not defined when calling the keyword (optional)
      • required - if true, the value of this input must always be provided (false by default)

      You can annotate the following method arguments with @Input:

      • String
      • Integer (or int)
      • Long (or long)
      • Double (or double)
      • BigDecimal
      • BigInteger
      • Array or Collection with any of supported types
      • Object: any serializable object such as maps

      Some examples explaining how to the @Input annotation:

        public class KeywordTestClass extends AbstractKeyword {
            @Keyword
            public void MyKeywordWithInputAnnotation(
                    @Input(name = "myRequiredInputNumber", required = true) int myRequiredInputNumber,
                    @Input(name = "myInputNumber", defaultValue = "3") int myInputNumber,
                    @Input(name="myInputBoolean", defaultValue = "true") boolean myInputBoolean,
                    @Input(name = "myInputString", defaultValue = "default string value") String myInputString,
                    @Input(name = "stringListInput", defaultValue = "string1;string2") List<String> stringList,
                    @Input(name = "mapStringInput", defaultValue = "{\"key1\":\"valueStr1\",\"key2\":\"valueStr2\"}") Map<String, String> stringMap,
                    @Input(name = "longListInput", defaultValue = "1223456;55555") List<Long> longList,
                    @Input(name = "mapLongInput", defaultValue = "{\"key\":3}") Map<String, Long> longMap,
                    @Input(name = "booleanListInput", defaultValue = "true;false;true") List<Boolean> booleanList,
                    @Input(name = "mapBooleanInput", defaultValue = "{\"key\":true}") Map<String, Boolean> booleangMap) {
            }
        }

        Passing inputs from code

        When calling the keyword from your code (for instance in JUnit), you can pass the input as parameter:

          ExecutionContext ctx = KeywordRunner.getExecutionContext(properties, this.getClass());
          // { "url" : "http://step.dev", "index" : 3 }
          Output<JsonObject> output = ctx.run("MyKeyword", "{\"url\":\"http://www.exense.ch\", \"index\" : 3 }");

          Passing inputs from the Step plan

          When calling the Keyword from a plan, you can pass the input as parameter as shown in below screenshots. More details can be found in the dedicated documentation for Plans: Screenshot showing example keyword inputs

          If the Keyword has an attached schema required and optional inputs can be defined

          Keyword properties

          Keywords can also access a map of properties which contains all variables in the scope of execution. This includes variables defined:

          • In the properties of the agent executing the keyword
          • In the plan calling the keyword using “Set”
          • In the parameters defined in the controller
          • In the Keyword configuration such as:
          • $keywordName: the name of the keyword
          • $keywordTimeout: the defined execution timeout of this keyword
          Note that if the same variable is defined at multiple places the values in agent properties override the one in plan which overrides the one in parameter.

          You can retrieve the properties in your keywords from the properties map

            properties.get("myVar");
            properties["myVar"]
            properties['myVar']

            Keyword outputs

            Each keyword can define the content of its output by using the herited “output” object from its parent class. This output builder object is mainly used to:

            • add any key/value pair information for example:
              • for functional checks in plan
              • required for workflow execution
            • set keyword execution status
            • add attachments (pdf, screenshots, exception stack trace as text file…)
            • define custom response time measurements for analytics

            The method of the OutputBuilder class can be found in the javadoc. The same methods are available for .net. For node.js, you may refer to the source code on github.

            Custom fields

            Below are example on how to add key/value pair information to your keyword’s output object.

              You can refer to the javadoc for the full list of available method. Below is an example for adding a field with a String value:

              output.add("field_name", "field_value");
              output.add("field_name", "field_value");
              output.add("field_name","field_value")

              Attachment

              Below is an example for attaching files to the Keyword’s output:

                byte[] bytes = Files.readAllBytes(file.toPath());
                Attachment attachment = AttachmentHelper.generateAttachmentFromByteArray(bytes, outputName+".log");
                output.addAttachment(attachment);    
                Attachment a = AttachmentBuilder.generateAttachmentForException(exception);
                output.addAttachment(a);
                output.attach({ name: 'screenshot.png', hexContent: data })

                Attachment size

                The Step controller limit the size of the attachment by default to 50 Mbytes, this can be changed with following step.properties

                grid.client.max.string.length.bytes=50000000
                

                Measurements

                Measurements are automatically created by the controller when executing a keyword. This represents the keyword execution time from the controller view (but excluding any delegation time to the agents). You can create custom response time measurements inside your keyword to have finer granularity and/or to enrich the measurements with any key/value pair for analytics purposes.

                The measurements are opened in a stack mode, i.e. when calling the close method, the most recent opened one get closed.

                Refer to the OutputBuilder class’s javadoc for all available methods.

                Example:

                  output.startMeasure("CustomMeasureInKeyword");
                  //Do some automation work
                  output.startMeasure("CustomMeasureInKeyword_Inner");
                  //Do some further work to be measured with finer granularity
                  output.stopMeasure();//this stop the lasted opened measurement: "CustomMeasureInKeyword_Inner"
                  //Add some values to the measurement for analytics and close the measurement "CustomMeasureInKeyword"
                  Map<String,String> measurementData = new HashMap<String,String>();
                  measurementData.put("username","Smith");
                  output.stopMeasure(measurementData);
                    output.startMeasure("Navigate");
                    //do something
                    output.stopMeasure();
                  Measurement API is currently not available in node.js

                  Error handling

                  Step makes a difference between errors which are internal (status “TECHNICAL_ERROR”) and business errors (status “FAILED”). Any unhandled exception raised during the execution of a keyword will end up in the status “TECHNICAL_ERROR”. In order to produce clean reports and leverage this distinction, we highly recommend catching any exception being thrown from within your keywords and handle the situation adequately.

                  Errors can be handled directly withing the keyword’s function or by implementing the on error.

                  Technical Errors

                  In case your still want your keyword to end up in a technical error state, you may use one of the setError methods available in all supported languages. Likewise, any exception which is thrown from the Keyword will result in a technical error. Remember that this is not the preferred approach as internal error should be reserved for Step technical errors.

                  Business errors

                  To manage properly any errors related to the system or application which is being automated, you may use the setBusinessError method. This will automatically set the status of the keyword execution to “FAILED”.

                  If the status as to be determined outside of the keyword, add any meaningful values to the output and perform the check in the caller (i.e. in a Step plan).

                  In case of exception, you can attach the detailed information to the output object such as the exception message. You can even attach binary content or the exception stack trace to the object by doing so:

                    output.add("ExceptionMessage",e.getMessage());
                    output.addAttachment(AttachmentHelper.generateAttachmentForException(e));
                    Attachment a = AttachmentBuilder.generateAttachmentForException(exception);
                    output.addAttachment(a);
                    output.attach({ name: 'exception.log', hexContent: data })

                    Keyword execution hooks

                    onError hook

                    For each language, overriding the onError hook offers a last chance to manage unhandled exceptions. Each time your keyword function throws an exception, this function will be called with the exception as argument. The return value of this function determine if the exception should be re-thrown (return true) or ignored (return false):

                    • If re-thrown, the status of the execution will be reported as a “TECHNICAL_ERROR” and an attachment of the exception trace will be added
                    • If ignored, the status will be set as “PASSED” and no error will be reported

                    Overriding this function is done as follow:

                      @Override
                      public boolean onError(Exception e) {
                        /* do here cleanup or exception reporting */
                        return false;
                      }
                      public override bool onError(Exception e)
                      {
                        /* do here cleanup or exception reporting */
                        return false;
                      }
                      exports.onError = async (exception, input, output, session, properties) => {
                        /* do here cleanup or exception reporting */
                        return false;
                      }

                      beforeKeyword and afterKeyword hooks

                      For each language, overriding the beforeKeyword or afterKeyword hooks allow you to execute management code before or after a keyword is called. Note that the afterKeyword function will always be called, even if an exception occurs during the keyword execution or during the beforeKeyword call. The onError call is called before the afterKeyword in case of exception.

                      Overriding these functions is done as follow:

                        @Override
                        public void beforeKeyword(String keywordName, Keyword annotation) {
                          /* do here some management */
                          System.out.println("Calling "+keywordName);
                        }
                        @Override
                        public void afterKeyword(String keywordName, Keyword annotation) {
                          /* do here some management */
                          takeScreenshot();
                        }
                        public override void BeforeKeyword(string KeywordName, Keyword Annotation)
                        {
                          /* do here some management */
                          Console.WriteLine("Calling "+keywordName);
                        }
                        
                        public override void AfterKeyword(string KeywordName, Keyword Annotation)
                        {
                          /* do here some management */
                          TakeScreenshot();
                        }

                        Not available for the node js agent

                        Session

                        Step provides the ability to store data in a session object. This object usually only makes sense when a Session control is used inside the test plan. The session object becomes very useful when passing information or technical objects between keywords (see for example the way we use Selenium’s driver in the next section), especially if the data is difficult or impossible to serialize and de-serialize via the input/output mechanism.

                        Storing and accessing objects

                        Storing by name

                        You can set any kind of data (primitive types or collections) in the session object as follow :

                          @Keyword(name="PutToSession")
                          public void putToSession(){
                            session.put("string_key", "Here is my value");
                            session.put("int_key", 3);
                          }
                          session.put("driver", new Wrapper(driver));
                          session.driver_wrapper = createdDriver_wrapper

                          You can then access your data from another keyword the same way, but you’ll have to cast the data manually back to its original type :

                            @Keyword(name="GetFromSession")
                            public void getFromSession() {
                              output.add("my_string_value", (String) session.get("string_key"));
                              output.add("my_int_value", (int) session.get("int_key"));
                            }
                            Wrapper wrapper = (Wrapper)session.get("driver");
                            const driver = session.driver_wrapper.driver

                            If you’re using a collection, see the method Arrays.copyOf to convert all of its content at once back to the original type.

                            You can then create a test plan using the “Session” control in order to pass the session information trough different Keywords. Note that we also included a keyword outside a session to see what’s append when no session exist but the keyword try to access it anyway:

                            A step session

                            Once you executed the plan you can see as a result that the session objects have been properly retrieved and displayed as output. The last keyword throws an error because it is outside a session and cannot retrieve the objects anymore as the session was closed:

                            A step execution, with a session

                            Storing by class name

                            You can also store your data using the class of the object. You will not need to cast it back but can only store one object per type :

                              @Keyword(name="PutToSession")
                              public void putToSession(){
                                MyObject obj = new MyObject();
                                session.put(obj);
                              }

                              this functionality is not available with the dotnet agent

                              this functionality is not available with the node agent

                              You can then access your data from another keyword without having to cast your object:

                                @Keyword(name="GetFromSession")
                                public void getFromSession() {
                                  MyObject obj = session.get(MyObject.class);
                                }

                                this functionality is not available with the dotnet agent

                                this functionality is not available with the node agent

                                Releasing session objects

                                When putting objects in session, it can be useful to have a way to free any resources used by this objects. A typical example will be to quit a Selenium driver when this driver is not used anymore.

                                This can be done by having the object in session implements Closable:

                                  public class DriverWrapper implements Closeable {
                                    final WebDriver driver;
                                    public DriverWrapper(WebDriver driver) {
                                      super();
                                      this.driver = driver;
                                    }
                                    @Override
                                    public void close() {
                                      driver.quit();
                                    }
                                    public WebDriver getDriver() {
                                      return driver;
                                    }
                                  }
                                  public class DriverWrapper : ICloseable
                                  {
                                    private IWebDriver Driver;
                                    public DriverWrapper(IWebDriver driver) {
                                      this.Driver = Driver;
                                    }
                                    public void Close() {
                                      Driver?.Quit();
                                    }
                                    public void GetDriver() {
                                      return Driver;
                                    }
                                  }
                                  session.driver_wrapper = {
                                    'driver': driver,
                                    'close': function () {
                                      this.driver.quit()
                                    }
                                  }

                                  When such object is put into a session, the close function will be called when the session finish. For example, when executing a chrome scenario using our step-library-kw-selenium/ library:

                                  A step plan, executing a selenium test

                                  The first call to “Navigate_to” will succeed, but the second one will fail as the chrome driver is closed by then:

                                  An execution of a selenium test

                                  Keyword Proxy: plans as Code

                                  The Keyword Proxy is a powerful mechanism that allows developers to invoke keywords directly from within another keyword, enabling the creation of workflows directly in automation code

                                  The keyword proxy is currently only supported by the Java API.

                                  How it works

                                  The Keyword Proxy acts as an intermediary that enables a “parent” keyword to call one or more “child” keywords seamlessly. The main features are:

                                  • Automatically share the parent keyword’s context (Session, properties…) to the nested keyword calls
                                  • Manage how to propagate the keyword’s output (either by merging all individuals outputs or manually setting the final outputs)
                                  • Automatically creating measurements for all individual keywords calls

                                  Here is a sample to illustrate how it works

                                      /**
                                       * WorkflowAsCode is a Step's Keyword making use of the Keyword proxy to invoke other keywords and to create a 
                                       * workflow directly as code. As any other keywords, it can be called from a Step's plan, receiving inputs and returning outputs.
                                       */
                                      @Plan
                                      @Keyword
                                      public void WorkflowAsCode() {
                                          //Create a keyword proxy inheriting the current keyword context (i.e. session, properties...)
                                          //Pass true as 2nd parameter to instruct the proxy to merge all outputs to the current keyword's output, false otherwise
                                          KeywordProxy keywordProxy = new KeywordProxy(this, true);
                                          //Get the proxy for the class containing the keywords to be invoked
                                          KeywordExample proxy = keywordProxy.getProxy(KeywordExample.class);
                                          //Retrieves inputs passed by the plan calling the WorkflowAsCode keyword (defaulting to properties)
                                          String myInputString = getInputOrProperty("myInputString");
                                          // Call nested keywords by directly invoking the keyword method and passing inputs as method arguments
                                          proxy.myFirstKeyword(3, false, myInputString);
                                          // The output of the nested keyword calls can be retrieved with the getLastOutput function
                                          Output<JsonObject> lastOutput = keywordProxy.getLastOutput();
                                          if (lastOutput.getPayload().getBoolean("shouldFail")) {
                                              output.appendError("The call to myFirstKeyword returned a failure message");
                                              return;
                                          }
                                          // Call further nested keywords 
                                          proxy.mySecondKeyword();
                                          proxy.myThirdKeyword(List.of("value1", "value2"), Map.of("key1", "val1"));
                                      }
                                  

                                  See Also

                                  • Keyword Development
                                  • Controls
                                  • Using variables in Plans
                                  • Automation Package descriptor
                                  • Automation Package in Java
                                  • Home
                                  • Whats new?
                                  • Set up
                                  • Administration
                                  • SaaS guide
                                  • User guide
                                  • Developer guide
                                    • Development Overview
                                    • Keyword Development
                                    • Keyword API
                                    • Step client API
                                    • REST API
                                    • Event Broker API
                                  • DevOps
                                  • Plugins
                                  • Libraries
                                  Step Logo
                                    • Documentation
                                    • Tutorials
                                    • Blogs
                                    • Product
                                    • Home
                                    • Whats new?
                                    • Set up
                                    • Administration
                                    • SaaS guide
                                    • User guide
                                    • Developer guide
                                      • Development Overview
                                      • Keyword Development
                                      • Keyword API
                                      • Step client API
                                      • REST API
                                      • Event Broker API
                                    • DevOps
                                    • Plugins
                                    • Libraries