421775 CookiePatternRule only sets cookie if not set already

This commit is contained in:
Greg Wilkins 2013-11-25 11:47:15 +11:00
parent e37a369ca6
commit ffddaeceec
3 changed files with 30 additions and 27 deletions

View File

@ -73,6 +73,18 @@ public class CookiePatternRule extends PatternRule
@Override
public String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Check that cookie is not already set
Cookie[] cookies = request.getCookies();
if (cookies!=null)
{
for (Cookie cookie:cookies)
{
if (_name.equals(cookie.getName()) && _value.equals(cookie.getValue()))
return target;
}
}
// set it
response.addCookie(new Cookie(_name, _value));
return target;
}

View File

@ -85,7 +85,7 @@ public abstract class AbstractRuleTestCase
_server.start();
_latch=new CountDownLatch(1);
_connector.executeRequest("GET / HTTP/1.0\n\n");
_connector.executeRequest("GET / HTTP/1.0\nCookie: set=already\n\n");
while (_response==null)
Thread.sleep(1);
@ -98,7 +98,7 @@ public abstract class AbstractRuleTestCase
_request = null;
_response = null;
_latch=new CountDownLatch(1);
_connector.executeRequest("GET / HTTP/1.0\n\n");
_connector.executeRequest("GET / HTTP/1.0\nCookie: set=already\n\n");
while (_response==null)
Thread.yield();

View File

@ -39,51 +39,42 @@ public class CookiePatternRuleTest extends AbstractRuleTestCase
@Test
public void testSingleCookie() throws IOException
{
String[][] cookie = {
{"cookie", "value"}
};
assertCookies(cookie);
String[] cookie = {"cookie", "value"};
assertCookies(cookie,true);
}
@Test
public void testMultipleCookies() throws IOException
public void testSetAlready() throws IOException
{
String[][] cookies = {
{"cookie", "value"},
{"name", "wolfgangpuck"},
{"age", "28"}
};
assertCookies(cookies);
String[] cookie = {"set", "already"};
assertCookies(cookie,false);
}
private void assertCookies(String[][] cookies) throws IOException
private void assertCookies(String[] cookie,boolean setExpected) throws IOException
{
for (String[] cookie : cookies)
{
// set cookie pattern
CookiePatternRule rule = new CookiePatternRule();
rule.setPattern("*");
rule.setName(cookie[0]);
rule.setValue(cookie[1]);
System.out.println(rule.toString());
// System.out.println(rule.toString());
// apply cookie pattern
rule.apply(_request.getRequestURI(), _request, _response);
// verify
HttpFields httpFields = _response.getHttpFields();
Enumeration e = httpFields.getValues(HttpHeader.SET_COOKIE.asString());
int index = 0;
Enumeration<String> e = httpFields.getValues(HttpHeader.SET_COOKIE.asString());
boolean set = false;
while (e.hasMoreElements())
{
String[] result = ((String)e.nextElement()).split("=");
assertEquals(cookies[index][0], result[0]);
assertEquals(cookies[index][1], result[1]);
// +1 cookies index
index++;
String[] result = (e.nextElement()).split("=");
assertEquals(cookie[0], result[0]);
assertEquals(cookie[1], result[1]);
set=true;
}
}
assertEquals(setExpected,set);
}
}