cancel
Showing results for 
Search instead for 
Did you mean: 

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

SOLVED
Highlighted
Community Manager

[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.

DifficultyStar_Gold.pngStar_Gold.pngStar_gray.png

 

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:

cookies.png

 

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!


Sonya Mihaljova
Community and Education Specialist

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
Tags (1)
2 ACCEPTED SOLUTIONS

Accepted Solutions
Highlighted
Community Hero

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();

 

 

 

 

 




---

Click the Accept as Solution button if my answer has helped, and remember to give kudos where appropriate too!

View solution in original post

Tags (1)
Highlighted
Community Hero

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
}

 

 



Regards,
Rao.

View solution in original post

Tags (1)
17 REPLIES 17
Highlighted
Community Leader

@sonya_m : It will be very helpful if you provide any dummy project 🙂


Click "Accept as Solution" if my answer has helped,
Remember to give "Kudos" 🙂 ↓↓↓↓↓



Thanks and Regards,
Himanshu Tayal
Highlighted
Community Manager

@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.

 

 


Sonya Mihaljova
Community and Education Specialist

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
Highlighted
Community Hero

Hahaha....difficulty level = easy.

Now this is more my speed!😉

Ta

Rich
if this helped answer the post, could you please mark it as 'solved'? Also if you consider whether the title of your post is relevant? Perhaps if the post is solved, it might make sense to update the Subject header field of the post to something more descriptive? This will help people when searching for problems. Ta
Highlighted
Community Manager

@richie don't be too humble regarding your skills 🙂


Sonya Mihaljova
Community and Education Specialist

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
Highlighted
Community Hero

This was set up to run as a script test step before "Login User 2". It could be set to run as a project level event, but wasn't sure what the intent was.

 

// Calling the request headers.
def request = context.testCase.testSteps["Login User 2"].testRequest
def headers = request.requestHeaders

// Get the iterateator of the map
Iterator<Map.Entry<String,Object>> iterate = headers.entrySet().iterator();

// Loop through the keys
while(iterate.hasNext()){
     Map.Entry<String,Object> entry = iterate.next();
     // Test each Key string to see if it matches the "COOKIE" string
     if (entry.key.toUpperCase().contains("COOKIE")) 
     {
     	// Remove key since it matched
     	iterate.remove();
     }
}

// Set request headers back to the parsed-down list.
request.requestHeaders = headers



---

Click the Accept as Solution button if my answer has helped, and remember to give kudos where appropriate too!
Highlighted
Community Leader

@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. 🙂

 


Click "Accept as Solution" if my answer has helped,
Remember to give "Kudos" 🙂 ↓↓↓↓↓



Thanks and Regards,
Himanshu Tayal
Community Manager

Thank you for creating the scripts! Our team took a look at them and here's a couple of ideas on how they can be improved.

 

@msiadak The script is run in Groovy TestStep that is created before the Login User 2 Step. Before Login TestStep is launched, the list of headers to be checked does not exist. The script should be launched with the RequestFilter.filterRequest event handler.

 

Also, the script works only for Headers that were added manually for the request, while it should work for Headers that ReadyAPI generates automatically.
Hint: the RequestFilter.filterRequest event should be used🙂

 

@HimanshuTayal We faced an error "No such property: testRequest for class: com.eviware.soapui.impl.wsdl.teststeps.DebuggableWsdlGroovyScriptTestStep" on this line - def request = testRunner.testCase.getTestStepAt(i).testRequest

This is something you might want to revise🙂 As for the method of getting Headers, I think it is similar to what msiadak is doing, so you can see my comment just above for that.

 

 


Sonya Mihaljova
Community and Education Specialist

Did my reply answer your question? Give Kudos or Accept it as a Solution to help others. ⬇️⬇️⬇️
Highlighted
Community Hero

Thanks for the insight @sonya_m. I was certain I was coming at this from the wrong angle and was expecting it needed to be an event. One of the problems I had though was I'm not actually sure what a "Cookie Header" looks like (short of the manual ones I used) to remove it.




---

Click the Accept as Solution button if my answer has helped, and remember to give kudos where appropriate too!
Highlighted
Community Hero

It makes sense to use Events, so that it can handle in any test step / test case / test suite, for this requirement instead of having extra groovy step.

SubmitListener.beforeSubmit event can be used as well to achieve the same. But user should pay attention to achieve this functionality by having conditional removal of required header for the required step.



Regards,
Rao.
New Here?
Join us and watch the welcome video:
Announcements
Top Kudoed Authors