Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category.

REST Response code

reactancexl
reactancexl Posts: 186

2024.2 --I have a REST call and I want to use the script on the misc tab of the rest url to check the response header code to pass the test or to fail it instead of hardcoding the code. I need conditions based off of environments. Does anyone have a simple script to do this?

Tagged:

Comments

  • benken_parasoft
    benken_parasoft Posts: 1,342 ✭✭✭
    edited April 30

    You can access environment variables using the getEnvironmentVariableValue method from com.parasoft.api.ScriptingContext. Groovy example:

    import com.parasoft.api.ScriptingContext
    
    String getExpectedStatus(ScriptingContext context) {
       return context.getEnvironmentVariableValue('EXPECTED_STATUS')
    }
    

    You can add your own conditional logic as required.

    In the above example I am just returning the value of an environment variable named "EXPECTED_STATUS". In this case I could also just set the value to Fixed (not Scripted) and reference the environment variable directly as ${EXPECTED_STATUS}.

  • reactancexl
    reactancexl Posts: 186

    thanks for the script, but I need to capture the actual response header HTTP code and based off of that then do the conditional logic. How do I get the actual response header code value?

  • benken_parasoft
    benken_parasoft Posts: 1,342 ✭✭✭
    edited May 1

    Just to confirm, are you asking about a REST Client in a SOAtest test suite?

    In your test suite, I recommend that you create different tests for positive vs negative cases. The configuration for a positive test vs a negative test is often going to be very different. For a negative test you would typically configure the request in a bad way such that you expect a specific status error to be returned that you know beforehand based on the input in the request. The response body for a negative test is also typically a lot different than a positive test which means validating the body in a generic way would be extremely difficult unless you intend to script the validation on the entire response body as well. I really don't recommend trying to create a single test to validate both positive and negative responses or different negative cases. They really should be separate tests.

    However, to do what you are now asking, it sounds like you would set "Valid HTTP Response Codes" to some very broad range that matches anything. Then you would chain an Extension Tool to the Response Traffic Header output. The first argument to the script contains the entire response header including the status code. Your script could probably just do a simple substring on the response header to extract the code.

Tagged