Vanish Kota
Vanish Kota

Reputation: 85

Use conditional logic in karate API

In below test case we want to print get[0] response.Languages if condition fulfills

Scenario: languages
  Given path 'admin/rest/core/languages/'
  When method get
  Then status 200
  * def resp = response
  * print resp
  * def lang = get[0] response.Languages
  * if ( response.Languages.IsDefault == '1' );
  Then print lang

Response of API is as below

Languages": [
    {
      "FullName": "English",
      "ShortName": "en",
      "ID": "1",
      "ParentID": "0",
      "IsFolder": "1",
      "Icon": {
        "URL": "/admin/images/flags/en.gif",
        "Timestamp": "2019-08-19 13:19:07"
      },
      "DateFormat": "American24",
      "NumberFormat": "####.##",
      "IsDefault": "0",
      "IsAvailable": "1",
      "LCID": "2057",
      "Self": "admin/rest/core.json/colors/1"
    },

another condition is if IsDefault is 1 then only related language response should get printed

Upvotes: 1

Views: 423

Answers (1)

Neodawn
Neodawn

Reputation: 1096

Sample Code:

Feature: Validation

    Scenario:

        * def resp =
            """
            {
                        "Languages": [
                    {
                        "FullName": "English1",
                        "ShortName": "en",
                        "ID": "1",
                        "ParentID": "0",
                        "IsFolder": "1",
                        "Icon": {
                            "URL": "/admin/images/flags/en.gif",
                            "Timestamp": "2019-08-19 13:19:07"
                        },
                        "DateFormat": "American24",
                        "NumberFormat": "####.##",
                        "IsDefault": "0",
                        "IsAvailable": "1",
                        "LCID": "2057",
                        "Self": "admin/rest/core.json/colors/1"
                    },
                    {
                        "FullName": "English2",
                        "ShortName": "en",
                        "ID": "1",
                        "ParentID": "0",
                        "IsFolder": "1",
                        "Icon": {
                            "URL": "/admin/images/flags/en.gif",
                            "Timestamp": "2019-08-19 13:19:07"
                        },
                        "DateFormat": "American24",
                        "NumberFormat": "####.##",
                        "IsDefault": "1",
                        "IsAvailable": "1",
                        "LCID": "2057",
                        "Self": "admin/rest/core.json/colors/1"
                    }
                ]
            }            
            """
            * def fun = function(x){ return x.IsDefault == 1 }
            * def a = get resp.Languages[*]
            * def res = karate.filter(a, fun)
            * print res

Upvotes: 2

Related Questions