Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created August 1, 2016 17:55
Show Gist options
  • Save swankjesse/29e4c343a785e586a6657022636d294e to your computer and use it in GitHub Desktop.
Save swankjesse/29e4c343a785e586a6657022636d294e to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertEquals;
public final class CacheTest {
@Rule public MockWebServer server = new MockWebServer();
@Rule public TemporaryFolder temp = new TemporaryFolder();
@Test public void conditionalMissUpdatesCache2() throws Exception {
Cache cache = new Cache(temp.getRoot(), Integer.MAX_VALUE);
OkHttpClient client = new OkHttpClient.Builder()
.cache(cache)
.build();
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(0, TimeUnit.SECONDS))
.addHeader("Cache-Control: max-age=0")
.setBody("A"));
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=30")
.setBody("B"));
// Cache miss seeds the cache.
Response response1 = get(client, server.url("/a"));
assertEquals("A", response1.body().string());
assertEquals(null, response1.header("Allow"));
// Cache miss updates the cache.
Response response2 = get(client, server.url("/a"));
assertEquals(HttpURLConnection.HTTP_OK, response2.code());
assertEquals("B", response2.body().string());
// Full cache hit returns data from the cache.
Response response3 = get(client, server.url("/a"));
assertEquals("B", response3.body().string());
assertEquals(2, server.getRequestCount());
}
private Response get(OkHttpClient client, HttpUrl url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
return client.newCall(request).execute();
}
private String formatDate(long delta, TimeUnit timeUnit) {
return formatDate(new Date(System.currentTimeMillis() + timeUnit.toMillis(delta)));
}
private String formatDate(Date date) {
DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
rfc1123.setTimeZone(TimeZone.getTimeZone("GMT"));
return rfc1123.format(date);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment