Forum Discussion

sonya_m's avatar
sonya_m
SmartBear Alumni (Retired)
5 years ago

[TechCorner Challenge #8] How to Clear Cookies in API Request

Hello Community!

 

I am back with another interesting task for you.

 

Here is the task: create a Groovy script that will clear the cookies that are sent with the request.

Difficulty

 

Assume that you have a TestCase in ReadyAPI with several test steps and for some of them, you need to maintain the HTTP session, i.e. to send the Cookie HTTP header.

 

You can achieve this task by using the Maintain HTTP session option of the TestCase. But, for other requests in your Test Case, cookies cause failure. In this case, you may need a script that will remove the Cookie header for these test steps.

 

For example, you have the following configuration of your ReadyAPI test:

 

You need to write a script that will remove the cookies only for the “Login Server 2” and “Get Info Server 2” test steps. Note that there could be several or zero Cookie headers in the requests.
 
Expected Task Results: the implementation of this task requires a Groovy script to be created.
 

Tip: Working With Headers

 

Good luck!

  • Task: create a Groovy script that will clear the cookies that are sent with the request.

     

    This is a solution created for [TechCorner Challenge #8]

     

    Thank you, sonya_m. Those articles provided context that I did not have / understand, and from there I was able to make this work. This script needs to be set as an event script for "RequestFilter.filterRequest" and the target needs to be set as the steps that need to be filtered. Per the original request, an event would need to be created whose target is one of the test steps that needs the cookies cleared. Once that is in place, this script will clear the cookies.

     

     

     

     

     

    import org.apache.http.protocol.HttpContext
    import com.eviware.soapui.model.iface.SubmitContext
    import org.apache.http.impl.client.BasicCookieStore
    import org.apache.http.client.protocol.HttpClientContext
    
    HttpContext httpContext = context.getProperty(SubmitContext.HTTP_STATE_PROPERTY);
    BasicCookieStore cookieStore = httpContext.getAttribute(HttpClientContext.COOKIE_STORE)
    
    cookieStore.clear();

     

     

     

     

     

  • nmrao's avatar
    nmrao
    5 years ago

    Task: create a Groovy script that will clear the cookies that are sent with the request.

     

    This is a solution created for [TechCorner Challenge #8]

     

    sonya_m Thanks for the feedback.

     

    Completely ignored about automatic Cookie's earlier.

     

    Here is updated one which covers both automatic and manual set cookies

     

    This the script for SubmitListener.beforeSubmit

     

    To make the script more dynamic, using project level custom properties to avoid hard coded header and test step names in the script. i.e., user can add the comma separated values to each custom property.

     

    For example,

    1. add REMOVE_COOKIE_FOR_STEPS property and values as requested, Login Server 2, Get Info Server 2

    2. add HEADERS_TO_REMOVE property and value as requested COOKIE

     

    UPDATE: made few changes

     

     

     

    //Closure to get the project property value
    def getProjectProperty = { context.testCase.testSuite.project.getPropertyValue(it) ?: '' }
     
    //Get the test step names for which defined headers to be removed
    def names = getProjectProperty('REMOVE_COOKIE_FOR_STEPS')?.split(',')*.trim()
    
    //Actual business logic
    if ( context.getProperty('wsdlRequest').testStep.name in names) {
        //Removes automatic Cookie's
        context.'#HTTP_STATE'.getAttribute('http.cookie-store').clear()
    
        //Removes manual COOKIE
        def eHeaders = submit.request.requestHeaders
        getProjectProperty('HEADERS_TO_REMOVE')?.split(',')*.trim().each {
            eHeaders.remove(it)
        }
        submit.request.requestHeaders = eHeaders
    }

     

     

    NOTE: the same is having issues with Pro for SubmitListener.beforeSubmit event.

    Works in free edition (tested in 5.4v)with soapUIExtensions

     

    Script for RequestFilter.filterRequest

     

     

    //Closure to get the project property value
    def getProjectProperty = { context.testCase.testSuite.project.getPropertyValue(it) ?: '' }
     
    //Get the test step names for which defined headers to be removed
    def names = getProjectProperty('REMOVE_COOKIE_FOR_STEPS')?.split(',')*.trim()
    
    //Actual business logic
    if ((context.getProperty('wsdlRequest').testStep.name in names)) {
        
        //Removes automatic Cookie's
        context.'#HTTP_STATE'.getAttribute('http.cookie-store').clear()
    
        def eHeaders = request.requestHeaders
        getProjectProperty('HEADERS_TO_REMOVE')?.split(',')*.trim().each {
            eHeaders.remove(it)
        }
        request.requestHeaders = eHeaders
    }

     

     

    • sonya_m's avatar
      sonya_m
      SmartBear Alumni (Retired)

      HimanshuTayal the sample you are looking for can be found here under Working with headers sample🙂

       

      Edit: I've also attached a sample project to this comment that we created. You can download it as an alternative to the above sample.

       

      There’s a virtual service in the project, with the following behavior:
      1.     If the login request has no cookies – cookies with the login specified in the query returns.
      2.     If the login request has cookies, code 409 and the message to log out returns.
      3.     If any other request has no cookies, code 401 and the message to log in returns.
      4.     If any other request has cookies – everything’s OK.
      So, the first three steps are successful in the project, but step 4 gets code 409 from the server. To avoid this, we need to clear cookies at step 4.

       

       

      • HimanshuTayal's avatar
        HimanshuTayal
        Community Hero

        sonya_m :

         

        Thanks for sharing the info, below code will remove cookies from the request if it found in more than 1 test step. Below is the code:

         

         

        //Getting Test Step Count
        testStepCount = testRunner.testCase.getTestStepCount()
        int flag = 0
        //Iterating over all Test Steps excepting 1st(which is the step in which this code is written) and skipping last step which is data sink
        for(int i = 1 ; i < testStepCount-1 ; i++){
        //Getting Request from each Test Step
        	def request = testRunner.testCase.getTestStepAt(i).testRequest
        //Getting Header from each Test Step
        	def headers = request.requestHeaders
        //iterating on all Headers present in request
        	Iterator<Map.Entry<String,Object>> header__iterator = headers.entrySet().iterator();
        	while(header__iterator.hasNext()){
        		Map.Entry<String,Object> header__map = header__iterator.next();
        //checking whether "COOKIE" Text is available in Request Header or not
        		if (header__map.key.toUpperCase().contains("COOKIE"))
        			flag++
        //Removing Header for 2nd Occurance Onwards.
        		if(flag > 1)
        			header__iterator.remove();
        	}
        	request.requestHeaders = headers
        }

         

         

         

        Let me know if it meets the requirement or not. 🙂