Skip to content

Commit

Permalink
add a CookieSpec literal class and some tests for cookie parsing end-…
Browse files Browse the repository at this point in the history
…to-end
  • Loading branch information
ryber committed Dec 8, 2020
1 parent 36e7480 commit eb8bac4
Show file tree
Hide file tree
Showing 9 changed files with 155 additions and 20 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* add a convenience method for setting the content type
* add a common reference to popular mime types
* cache methods on Config were not returning the config for the builder pattern.
* add a CookieSpecs const class for reference

## 3.11.05
* issue #383 some problems with relocated packages.
Expand Down
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@
<!-- Only a test dependency. Waiting on
https://github.com/perwendel/spark/pull/1201 -->
<exclude>2f9b8690-2b13-48ad-adc9-af1489d0a2f3</exclude>
<exclude>dbc80e9d-e821-4669-a4e1-6a537b6ad365</exclude>
</excludeVulnerabilityIds>
</banVulnerable>
</rules>
Expand Down
4 changes: 2 additions & 2 deletions unirest-mocks/src/test/java/kong/tests/AssertTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ void assertHeader() {
expect.assertHeader("monster", "grover");

assertException(() -> expect.assertHeader("monster", "oscar"),
"No invocation found with header [monster: oscar]\nFound:\nmonster: grover\n");
"No invocation found with header [monster: oscar]\nFound:\nmonster: grover");
}

@Test
Expand All @@ -92,7 +92,7 @@ void canSetHeaderExpectationOnExpects() {
assertException(() -> client.verifyAll(),
"A expectation was never invoked! GET http://basic\n" +
"Headers:\n" +
"monster: grover\n");
"monster: grover");

Unirest.get(path).header("monster", "grover").asEmpty();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ void canDifferenciateBetweenExpectations() {
"A expectation was never invoked! GET http://basic\n" +
"Headers:\n" +
"monster: oscar\n" +
"fruit: apple\n");
"fruit: apple");
}

@Test
Expand All @@ -64,7 +64,7 @@ void willPickTheBestMatchingExpectation() {
assertException(() -> client.verifyAll(),
"A expectation was never invoked! GET http://basic\n" +
"Headers:\n" +
"monster: grover\n");
"monster: grover");
}

@Test
Expand All @@ -87,7 +87,7 @@ void willPickTheBestMatchingQueryExpectation() {
assertException(() -> client.verifyAll(),
"A expectation was never invoked! GET http://basic\n" +
"Params:\n" +
"monster: grover\n");
"monster: grover");
}

@Test
Expand All @@ -110,6 +110,6 @@ void whenDuplicateExpectsExistUseTheLastOne() {
assertException(() -> client.verifyAll(),
"A expectation was never invoked! GET http://basic\n" +
"Params:\n" +
"monster: grover\n");
"monster: grover");
}
}
60 changes: 60 additions & 0 deletions unirest/src/main/java/kong/unirest/CookieSpecs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* The MIT License
*
* Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package kong.unirest;


/**
* Standard cookie specifications supported by Unirest.
*/
public final class CookieSpecs {

/**
* The default policy. This policy provides a higher degree of compatibility
* with common cookie management of popular HTTP agents for non-standard
* (Netscape style) cookies.
*/
public static final String DEFAULT = "default";

/**
* The Netscape cookie draft compliant policy.
*/
public static final String NETSCAPE = "netscape";

/**
* The RFC 6265 compliant policy (interoprability profile).
*/
public static final String STANDARD = "standard";

/**
* The RFC 6265 compliant policy (strict profile)
*/
public static final String STANDARD_STRICT = "standard-strict";

/**
* The policy that ignores cookies.
*/
public static final String IGNORE_COOKIES = "ignoreCookies";
}
14 changes: 8 additions & 6 deletions unirest/src/main/java/kong/unirest/Headers.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@

package kong.unirest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.function.Supplier;

import static java.util.stream.Collectors.toList;
Expand Down Expand Up @@ -164,8 +161,8 @@ void remove(String key, String value) {
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
headers.forEach(header -> sb.append(header.getName()).append(": ").append(header.getValue()).append(System.lineSeparator()));
final StringJoiner sb = new StringJoiner(System.lineSeparator());
headers.forEach(header -> sb.add(header.toString()));
return sb.toString();
}

Expand Down Expand Up @@ -228,5 +225,10 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(name, value.get());
}

@Override
public String toString() {
return String.format("%s: %s",getName(), getValue());
}
}
}
77 changes: 70 additions & 7 deletions unirest/src/test/java/BehaviorTests/CookieTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@
import org.apache.http.client.config.CookieSpecs;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

import static java.time.LocalDateTime.of;
import static org.junit.jupiter.api.Assertions.*;

class CookieTest extends BddTest {
Expand Down Expand Up @@ -114,13 +120,7 @@ void canGetValuesWithBadCharacters() {

@Test
void complicatedCookies(){
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("color", "blue");
cookie.setDomain("localhost");
cookie.setPath("/get");
cookie.setHttpOnly(true);
cookie.setSecure(false);
cookie.setMaxAge(42);
MockServer.expectCookie(cookie);
expectCoookie(42);

HttpResponse response = Unirest.get(MockServer.GET).asEmpty();

Expand All @@ -131,7 +131,34 @@ void complicatedCookies(){
assertTrue(back.isHttpOnly());
assertFalse(back.isSecure());
assertEquals(42, back.getMaxAge());
}

@Test
void cookieLifeCycle() {
expectCoookie(42);
HttpResponse r1 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
assertNotNull(r1.getCookies().getNamed("color"));

MockServer.clearCookies();
expectCoookie(0);

HttpResponse<RequestCapture> r2 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
assertNotNull(r1.getCookies().getNamed("color"));
r2.getBody().assertCookie("color", "blue");

MockServer.clearCookies();
HttpResponse<RequestCapture> r3 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
r3.getBody().assertNoCookie("color");
}

private void expectCoookie(int expiry) {
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("color", "blue");
cookie.setDomain("localhost");
cookie.setPath("/get");
cookie.setHttpOnly(true);
cookie.setSecure(false);
cookie.setMaxAge(expiry);
MockServer.expectCookie(cookie);
}

@Test
Expand Down Expand Up @@ -197,4 +224,40 @@ void canSetDefaultCookieAsFullCookieObj() {
.assertCookie("flavor", "snickerdoodle")
.assertCookie("size", "large");
}

@Test
void stringCookieParsing() {
MockServer.addResponseHeader("Set-Cookie", getCookieValue(of(2140, Month.APRIL, 2, 4, 20, 0).atZone(ZoneId.of("UTC"))));

HttpResponse r1 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
assertNotNull(r1.getCookies().getNamed("color"));

MockServer.clearHeaders();
MockServer.addResponseHeader("Set-Cookie", getCookieValue(of(1985, Month.APRIL, 2, 4, 20, 0).atZone(ZoneId.of("UTC"))));


HttpResponse<RequestCapture> r2 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
assertNotNull(r1.getCookies().getNamed("color"));
r2.getBody().assertCookie("color", "blue");

MockServer.clearHeaders();
HttpResponse<RequestCapture> r3 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
r3.getBody().assertNoCookie("color");
}

@Test
void newAgeCookies() {
Unirest.config().cookieSpec("standard");
MockServer.addResponseHeader("Set-Cookie", "cookie_name=blah;Max-Age=86400;Expires=Wed, 9 Dec 2220 20:26:05 GMT;Path=/;Domain=localhost;HTTPOnly");
HttpResponse response = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
assertNotNull(response.getCookies().getNamed("cookie_name"));
HttpResponse<RequestCapture> r2 = Unirest.get(MockServer.GET).asObject(RequestCapture.class);
r2.getBody().assertCookie("cookie_name","blah");

}

private String getCookieValue(ZonedDateTime dt) {
String date = dt.format(DateTimeFormatter.ofPattern("EEE, dd-MMM-yyyy HH:mm:ss zzz"));
return String.format("color=blue; Path=/get; Domain=localhost; Expires=%s; HttpOnly", date);
}
}
8 changes: 8 additions & 0 deletions unirest/src/test/java/BehaviorTests/MockServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -257,11 +257,19 @@ public static void expectedPages(int expected) {
pages = expected;
}

public static void clearCookies(){
cookies.clear();
}

public static void expectCookie(String name, String value) {
cookies.add(new Cookie(name, UrlEncoded.encodeString(value)));
}

public static void expectCookie(Cookie cookie) {
cookies.add(cookie);
}

public static void clearHeaders() {
responseHeaders.clear();
}
}
2 changes: 1 addition & 1 deletion unirest/src/test/java/kong/unirest/HeadersTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void toStringOverride() {
String toString = h.toString();
assertEquals("a: 1" + ls +
"c: 3" + ls +
"d: null" + ls, toString);
"d: null", toString);
}

@Test
Expand Down

0 comments on commit eb8bac4

Please sign in to comment.