diff --git a/okhttp-tests/src/test/java/okhttp3/CookieTest.java b/okhttp-tests/src/test/java/okhttp3/CookieTest.java index bffa4c7be..9ab211780 100644 --- a/okhttp-tests/src/test/java/okhttp3/CookieTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CookieTest.java @@ -17,8 +17,10 @@ package okhttp3; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.Date; import java.util.List; +import java.util.Objects; import okhttp3.internal.Util; import okhttp3.internal.http.HttpDate; import org.junit.Test; @@ -459,6 +461,32 @@ public final class CookieTest { assertEquals(true, cookie.httpOnly()); } + @Test public void equalsAndHashCode() throws Exception { + List cookieStrings = Arrays.asList( + "a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly", + "a= ; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly", + "a=b; Domain=example.com; Max-Age=5; Secure; HttpOnly", + "a=b; Path=/c; Max-Age=5; Secure; HttpOnly", + "a=b; Path=/c; Domain=example.com; Secure; HttpOnly", + "a=b; Path=/c; Domain=example.com; Max-Age=5; HttpOnly", + "a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; " + ); + for (String stringA : cookieStrings) { + Cookie cookieA = Cookie.parse(0, url, stringA); + for (String stringB : cookieStrings) { + Cookie cookieB = Cookie.parse(0, url, stringB); + if (Objects.equals(stringA, stringB)) { + assertEquals(cookieA.hashCode(), cookieB.hashCode()); + assertEquals(cookieA, cookieB); + } else { + assertFalse(cookieA.hashCode() == cookieB.hashCode()); + assertFalse(cookieA.equals(cookieB)); + } + } + assertFalse(cookieA.equals(null)); + } + } + private Date date(String s) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); format.setTimeZone(Util.UTC); diff --git a/okhttp/src/main/java/okhttp3/Cookie.java b/okhttp/src/main/java/okhttp3/Cookie.java index 12c4584b1..74e341de4 100644 --- a/okhttp/src/main/java/okhttp3/Cookie.java +++ b/okhttp/src/main/java/okhttp3/Cookie.java @@ -559,4 +559,32 @@ public final class Cookie { return result.toString(); } + + @Override public boolean equals(Object other) { + if (!(other instanceof Cookie)) return false; + Cookie that = (Cookie) other; + return that.name.equals(name) + && that.value.equals(value) + && that.domain.equals(domain) + && that.path.equals(path) + && that.expiresAt == expiresAt + && that.secure == secure + && that.httpOnly == httpOnly + && that.persistent == persistent + && that.hostOnly == hostOnly; + } + + @Override public int hashCode() { + int hash = 17; + hash = 31 * hash + name.hashCode(); + hash = 31 * hash + value.hashCode(); + hash = 31 * hash + domain.hashCode(); + hash = 31 * hash + path.hashCode(); + hash = 31 * hash + (int) (expiresAt ^ (expiresAt >>> 32)); + hash = 31 * hash + (secure ? 0 : 1); + hash = 31 * hash + (httpOnly ? 0 : 1); + hash = 31 * hash + (persistent ? 0 : 1); + hash = 31 * hash + (hostOnly ? 0 : 1); + return hash; + } }