Class UtilsGSpec


  • public class UtilsGSpec
    extends BaseGSpec
    Steps definitions for other useful functions/operations
    Author:
    Jose Fernandez
    • Constructor Detail

      • UtilsGSpec

        public UtilsGSpec​(CommonG spec)
        Default constructor.
        Parameters:
        spec - CommonG object
    • Method Detail

      • idleWait

        @When("^I wait \'(.*)\' seconds?$")
        public void idleWait​(Integer seconds)
                      throws InterruptedException
        Wait seconds.

        Static wait used to halt the execution of the feature for a given amount of seconds. After the time completes, the remaining steps in the feature are executed. This step is commonly used to wait for a background operation to complete, so next steps wont return false negatives. This step completely halts the operation of the feature for the given time and could reduce performance (increase the feature execution time) if used too frequently or if the time used is unnecessarily large. Try to use a reasonable time in your tests, or in the case of cucumber related scenarios, there is a much better alternative to the static wait: SeleniumGSpec.waitWebElementWithPooling(int, int, int, String, String, String)

         
              When I wait '10' seconds
         
         
        Parameters:
        seconds - Seconds to wait
        Throws:
        InterruptedException - InterruptedException
      • checkValue

        @Then("^\'(.*)\' (is|matches|is higher than|is lower than|contains|is different from) \'(.*)\'$")
        public void checkValue​(String envVar,
                               String operation,
                               String value)
                        throws Exception
        Check value stored in environment variable "is|matches|is higher than|is lower than|contains|is different from" to value provided
         Examples:
         
              Then '${content-type}' matches 'application/json; charset=utf-8'   //checks if the value of the variable matches the string 'application/json; charset=utf-8'
              Then '${DEFEXSTAT}' contains 'total'                               //checks if the value of the variable contains the string 'total'
         
         
        Parameters:
        envVar - The env var to verify
        operation - Operation
        value - The value to match against the condition
        Throws:
        Exception - Exception
      • saveInEnvironment

        @Given("^I save \'(.*)\' in variable \'(.*)\'$")
        public void saveInEnvironment​(String value,
                                      String envVar)
        Save value for future use.
        Parameters:
        value - value to be saved
        envVar - thread environment variable where to store the value
      • readFromCSV

        @When("^I read info from csv file \'(.*)\'$")
        public void readFromCSV​(String csvFile)
                         throws Exception
        Read csv file and store result in list of maps
        Parameters:
        csvFile - the csv file
        Throws:
        Exception - the exception
      • sortElements

        @When("^I sort elements in \'(.+?)\' by \'(.+?)\' criteria in \'(.+?)\' order$")
        public void sortElements​(String envVar,
                                 String criteria,
                                 String order)
        Sort elements in envVar by a criteria and order.
        Parameters:
        envVar - Environment variable to be sorted
        criteria - alphabetical,...
        order - ascending or descending
      • createFile

        @When("^I create file \'(.+?)\' based on \'(.+?)\' as \'(.+?)\' with:$")
        public void createFile​(String fileName,
                               String baseData,
                               String type,
                               io.cucumber.datatable.DataTable modifications)
                        throws Exception
        Create a file from seed.

        Creates a JSON file in the /target/test-classes directory of the project with the specified name. This file can later be referenced using $(pwd)/target/test-classes/fileName. This steps receives a datatable with a list of all modifications to be performed in the seed file (ADD, REPLACE, APPEND, ADDTO, etc)

        You can specify a seed file that uses the contents of another file to create a single merged file with ADDTO. For example

         
              Given I create file 'testCreateFilePlain.json' based on 'schemas/testCreateFile.json' as 'json' with:
                  | $.key2 | ADDTO | ${file:UTF-8:src/test/resources/schemas/testCreateFileReplacePlainText.json} | string |
         
         
        Will create a file with name testCreateFilePlain under /target/test-classes, using'schemas/testCreateFile.json' as template, changing the value $.key2 with the contents of schemas/testCreateFileReplacePlainText.json as string
        Parameters:
        fileName - name of the JSON file to be created
        baseData - path to file containing the schema to be used
        type - element to read from file (element should contain a json)
        modifications - DataTable containing the modifications to be done to the base schema element

        - Syntax will be: | <key path> | <type of modification> | <new value> | for DELETE/ADD/UPDATE/APPEND/PREPEND where: key path: path to the key to be modified type of modification: DELETE/ADD/UPDATE/APPEND/PREPEND new value: new value to be used

        - Or: | <key path> | <type of modification> | <new value> | <new value type> | for REPLACE where: key path: path to the key to be modified type of modification: REPLACE new value: new value to be used json value type: type of the json property (array|object|number|boolean|null|n/a (for string))

        For example:
        (1) If the element read is {"key1": "value1", "key2": {"key3": "value3"}} and we want to modify the value in "key3" with "new value3" the modification will be: | key2.key3 | UPDATE | "new value3" | being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}}
        (2) If the element read is {"key1": "value1", "key2": {"key3": "value3"}} and we want to replace the value in "key2" with {"key4": "value4"} the modification will be: | key2 | REPLACE | {"key4": "value4"} | object | being the result of the modification: {"key1": "value1", "key2": {"key4": "value4"}}

        Throws:
        Exception - Exception
      • readFileToVariable

        @When("^I read file \'(.+?)\' as \'(.+?)\' and save it in environment variable \'(.+?)\' with:$")
        public void readFileToVariable​(String baseData,
                                       String type,
                                       String envVar,
                                       io.cucumber.datatable.DataTable modifications)
                                throws Exception
        Saves file in variable with modifications.

        Read the file passed as parameter, perform the modifications specified and save the result in the environment variable passed as parameter.

        Using a json file and updating its contents

         
              Given I read file 'schemas/testCreateFile.json' as 'json' and save it in environment variable 'myjson' with:
                  | $.key1 | UPDATE | new_value     | n/a   |
                  | $.key2 | ADDTO  | ["new_value"] | array |
         
         
        Reading a plain text file and editin its contents
         
               Given I read file 'schemas/krb5.conf' as 'string' and save it in environment variable 'mystring' with:
                  | foo | REPLACE | bar | n/a |
         
         
        Parameters:
        baseData - file to read
        type - whether the info in the file is a 'json' or a simple 'string'
        envVar - name of the variable where to store the result
        modifications - modifications to perform in the content of the file
        Throws:
        Exception - Exception
      • readFileToVariableNoDataTable

        @When("^I read file \'(.+?)\' as \'(.+?)\' and save it in environment variable \'(.+?)\'$")
        public void readFileToVariableNoDataTable​(String baseData,
                                                  String type,
                                                  String envVar)
                                           throws Exception
        Saves file in variable.

        Read the file passed as parameter and save the result in the environment variable passed as parameter. Unlike the previous example, if no modifications are necessary in the file, there is no need to specify a datatable with modifications.

        Example

         
              Given I read file 'schemas/testCreateFile.json' as 'json' and save it in environment variable 'myjson'
         
         
        Parameters:
        baseData - file to read
        type - whether the info in the file is a 'json' or a simple 'string'
        envVar - name of the variable where to store the result
        Throws:
        Exception - Exception
      • assertExceptionNotThrown

        @Then("^an exception \'(.+?)\' thrown( with class \'(.+?)\'( and message like \'(.+?)\')?)?")
        public void assertExceptionNotThrown​(String exception,
                                             String foo,
                                             String clazz,
                                             String bar,
                                             String exceptionMsg)
                                      throws ClassNotFoundException
        Checks if an exception has been thrown.

        Checks if an exception is/is not thrown during the execution of the previous step. It can also check the exception class and the message of the exception

        Example: Checking if any exception is thrown

         
              When I execute a jdbc select 'SELECT count(*) FROM crossdataTables''
              Then an exception 'IS NOT' thrown
         
         
        Example: Checking if not exception is thrown
         
              Given I execute 'CREATE TABLE newCatalog.newTable'
              Then an exception 'IS' thrown
         
         
        Example: Checking if a particular exception is thrown
         
              When I delete the stream 'testStreamACK0'
              Then an exception 'IS' thrown with class 'PrivaliaEngineConnectionException' and message like 'Acknowledge timeout expired'
         
         
        Parameters:
        exception - : "IS NOT" | "IS"
        foo - parameter generated by cucumber because of the optional expression
        clazz - the clazz
        bar - parameter generated by cucumber because of the optional expression
        exceptionMsg - the exception msg
        Throws:
        ClassNotFoundException - the class not found exception
      • resultsMustBe

        @Then("^There are results found with:$")
        public void resultsMustBe​(io.cucumber.datatable.DataTable expectedResults)
                           throws Exception
        Checks the different results of a previous query
        Parameters:
        expectedResults - A DataTable Object with all data needed for check the results. The DataTable must contains at least 2 columns: a) A field column from the result b) Occurrences column (Integer type)

        Example: |latitude| longitude|place |occurrences| |12.5 |12.7 |Valencia |1 | |2.5 | 2.6 |Madrid |0 | |12.5 |13.7 |Sevilla |1 | IMPORTANT: There no should be no existing columns

        Throws:
        Exception - Exception
      • generateRandomNumberInRange

        @Given("^I generate a random number between \'(.*)\' and \'(.*)\' and save it in the variable \'(.*)\'$")
        public void generateRandomNumberInRange​(Integer lowerLimit,
                                                Integer upperLimit,
                                                String varName)
        Creates a random integer within range

        Creates a random number within the range provided and saves it in a variable for later use

         Example:
         
              Given I create a random number between '0' and '10' and save it in the variable 'RANDOM'
              And I wait '${RANDOM}' seconds
         
         
        Parameters:
        lowerLimit - lower limit in range
        upperLimit - upper limit in range
        varName - name of the variable to save the result
        See Also:
        generateRandomStrings(String, Integer, String)
      • generateRandomStrings

        @Given("^I generate a random \'(numeric|alphanumeric)\' string of length \'(.*)\' and save it in the variable \'(.*)\'$")
        public void generateRandomStrings​(String type,
                                          Integer length,
                                          String varName)
        Generate numeric or alphanumeric strings

        Generates a string that can be numeric ([0-9]) or alphanumeric ([0-9][A-Z][a-z]) of a given length and saves it in a variable for furute use

         Example: Generating a random numeric string of length 20
         
              Given I generate a random 'numeric' string of length '20' and save it in the variable 'NUMERIC'
         
         Example: Generating a random alphanumeric string of length 20
         
              Given I generate a random 'alphanumeric' string of length '20' and save it in the variable 'ALPHANUMERIC'
         
         
        Parameters:
        type - string type: numeric|alphanumeric
        length - string final length
        varName - name of the variable to save the result
        See Also:
        generateRandomNumberInRange(Integer, Integer, String)
      • ifStamenetBeginBlock

        @Given("^if \\((.*)\\) \\{$")
        public void ifStamenetBeginBlock​(String statement)
        Creates a conditional block of execution

        This allows the conditional execution of steps during runtime. All steps enclosed between this step and ifStamenetEndBlock() will be executed only if the given statement returns true, otherwise, the steps will be skipped. The statement can be any javascript expression that can return a true|false output. You can even use variables created during the scenario execution.

        Warning: use this functionality sparingly, or only in very concrete automation cases. We discourage the creation of tests that could return different results on different runs. Also, this functionality has not been tested on multi-threaded mode, so it may break when running tests in parallel

         
         Examples
        
         Scenario: Using if block to control execution
             * I save 'GingerSpec' in variable 'NAME'
             * if ('${NAME}'.contains('Ginger')) {
             * I run 'echo "This should be executed"' locally
             * }
             * if ('${NAME}'.contains('foo')) {
             * I run 'echo "This should NOT be executed"' locally
             * I run 'exit 1' locally
             * }
         
         
        Parameters:
        statement - Any javascript expression that could be resolved to true or false
        See Also:
        ifStamenetEndBlock()
      • ifStamenetEndBlock

        @Given("^\\}$")
        public void ifStamenetEndBlock()
        If statement end block

        Indicates the end of the if block

        See Also:
        ifStamenetBeginBlock(String)
      • sendMessageToSlackChannel

        @Given("I send a message to the slack channel(s) {string} with text")
        public void sendMessageToSlackChannel​(String slackChannel,
                                              io.cucumber.docstring.DocString message)
                                       throws com.slack.api.methods.SlackApiException,
                                              IOException
        Send a message to the given slack channel.

        Sends a message to the given channel (or group of channels separated by comma). The message is a DocString object and it can also contain other variables created during the execution of the scenario. you will need to provide the slack token either via src/test/resources/slack.properties file or via maven variables as Dslack.token=abcdefg123456. Check the attached link for more information.

         
         Examples
        
             Scenario: Sending message to a slack channel
                  Given I save 'GingerSpec' in variable 'FRAMEWORK'
                  Given I send a message to the slack channel '#qms-notifications' with text
                  """
                  :wave: Hello! You can send any type of text to a given slack channel.
                  You can even send variables created during your steps
        
                  Regards, ${FRAMEWORK} :slightly_smiling_face:
                  """
         
         
        Parameters:
        slackChannel - Name of the channel to send the notification to. It can also be a list of channels separated by comma (i.e #channel1,#channel2,#channel3)
        message - Message to send. It can contain variables created during the scenario
        Throws:
        com.slack.api.methods.SlackApiException - SlackApiException
        IOException - IOException
        See Also:
        @slack tag
      • thisIsADocString

        @Given("This is a DocString")
        public void thisIsADocString​(io.cucumber.docstring.DocString body)
        This step is for testing purposes of GingerSpec. Should NOT be used
        Parameters:
        body - Example DocString argument
      • thisIsADatatable

        @Given("this is a datatable:")
        public void thisIsADatatable​(io.cucumber.datatable.DataTable table)
        This step is for testing purposes of GingerSpec. Should NOT be used
        Parameters:
        table - Example DataTable argument
      • SeleniumPause

        @Then("^I pause$")
        public void SeleniumPause()
        Temporally stop the execution of the feature

        This step shows a dialog in the center of the screen and interrupts the execution of the rest of the steps in the feature until the "Ok" button in the dialog is pressed. This comes handy when debugging and the user needs to execute some manual actions before continuing

        
         Example:
        
         Scenario: Temporally stop the execution of the feature
             Given I go to 'http://demoqa.com/automation-practice-form'
             Then I pause
             Then I type 'Jose' on the element with 'id:firstName'
         
        See Also:
        idleWait(Integer)