2

I am currently using a Swagger schema which defines enums for several values. I would like to know how I can assert my response against my swagger document. I would like to make sure that the response values that come back are only one of the values specified in the schema (think enum in Swagger). If anything else is returned in the response which is not defined in the array within the schema, then the test should fail.

How can I achieve this using the following:

Schema.json

{
    "itemType":{
        "hardware":[
            "VIDEO CARD",
            "SOLID STATE DRIVE",
            "HARD DRIVE"
        ] 
    }
}

All values are optional and will respond with a string value.

Response:

{
    "itemType": {
        "hardware": "HARD DRIVE"
    }
}

My guess is that it may be something along the lines of * match response.itemType.hardware == "##string? _ == 'VIDEO CARD' || _ == 'SOLID STATE DRIVE' || _ == 'HARD DRIVE'" but I may have my syntax incorrect.

zwanchi101
  • 181
  • 3
  • 14

3 Answers3

2

You can try this:

* def schema = 
"""
{
    "itemType":{
        "hardware":[
            "VIDEO CARD",
            "SOLID STATE DRIVE",
            "HARD DRIVE"
        ] 
    }
}
"""
* def response = 
"""
{
    "itemType": {
        "hardware": "HARD DRIVE"
    }
}
"""
* match response == { itemType: { hardware: '#? schema.itemType.hardware.contains(_)' } }
* def isValidHardware = function(x){ return schema.itemType.hardware.contains(x) }
* match response == { itemType: { hardware: '#? isValidHardware(_)' } }
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
2

I find this more readable:

      * match schema.itemType.hardware contains response.itemType.hardware

Having response on the right side may be a bit unusual.

Peter
  • 4,752
  • 2
  • 20
  • 32
1

Another way yo validate that is using matchers. With a JSON path you can get all things inside of an element and with the help of comparison operators like contains, contains only and !contains to check if inside a list of Strings exists certain elements. For example, in you case:

Scenario:
  Given path '/something'
  When method GET
  Then status 200
  And print response
  And match response.itemType.hardware[*] contains only ["value1", "value2"]

Is more clearly write your tests in this manner. Is more readable.

NOTE: take into consideration that the contains operators works only with a List, so you need to get a list. In the previous example we do that using * symbol.

lozanotux
  • 115
  • 1
  • 9