1/*
2 * Copyright (C) 2014 Square, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.squareup.okhttp;
17
18import com.squareup.okhttp.internal.RecordingAuthenticator;
19import com.squareup.okhttp.internal.http.AuthenticatorAdapter;
20import com.squareup.okhttp.internal.http.RecordingProxySelector;
21import com.squareup.okhttp.internal.tls.OkHostnameVerifier;
22import java.io.IOException;
23import java.net.Authenticator;
24import java.net.CacheRequest;
25import java.net.CacheResponse;
26import java.net.CookieHandler;
27import java.net.CookieManager;
28import java.net.ProxySelector;
29import java.net.ResponseCache;
30import java.net.URI;
31import java.net.URLConnection;
32import java.util.Arrays;
33import java.util.List;
34import java.util.Map;
35import java.util.concurrent.TimeUnit;
36import javax.net.SocketFactory;
37import org.junit.After;
38import org.junit.Test;
39
40import static org.junit.Assert.assertEquals;
41import static org.junit.Assert.assertNotNull;
42import static org.junit.Assert.assertNull;
43import static org.junit.Assert.assertSame;
44import static org.junit.Assert.assertTrue;
45import static org.junit.Assert.fail;
46
47public final class OkHttpClientTest {
48  private static final ProxySelector DEFAULT_PROXY_SELECTOR = ProxySelector.getDefault();
49  private static final CookieHandler DEFAULT_COOKIE_HANDLER = CookieManager.getDefault();
50  private static final ResponseCache DEFAULT_RESPONSE_CACHE = ResponseCache.getDefault();
51  private static final Authenticator DEFAULT_AUTHENTICATOR = null; // No Authenticator.getDefault().
52
53  @After public void tearDown() throws Exception {
54    ProxySelector.setDefault(DEFAULT_PROXY_SELECTOR);
55    CookieManager.setDefault(DEFAULT_COOKIE_HANDLER);
56    ResponseCache.setDefault(DEFAULT_RESPONSE_CACHE);
57    Authenticator.setDefault(DEFAULT_AUTHENTICATOR);
58  }
59
60  @Test public void timeoutDefaults() {
61    OkHttpClient client = new OkHttpClient();
62    assertEquals(10_000, client.getConnectTimeout());
63    assertEquals(10_000, client.getReadTimeout());
64    assertEquals(10_000, client.getWriteTimeout());
65  }
66
67  @Test public void timeoutValidRange() {
68    OkHttpClient client = new OkHttpClient();
69    try {
70      client.setConnectTimeout(1, TimeUnit.NANOSECONDS);
71    } catch (IllegalArgumentException ignored) {
72    }
73    try {
74      client.setWriteTimeout(1, TimeUnit.NANOSECONDS);
75    } catch (IllegalArgumentException ignored) {
76    }
77    try {
78      client.setReadTimeout(1, TimeUnit.NANOSECONDS);
79    } catch (IllegalArgumentException ignored) {
80    }
81    try {
82      client.setConnectTimeout(365, TimeUnit.DAYS);
83    } catch (IllegalArgumentException ignored) {
84    }
85    try {
86      client.setWriteTimeout(365, TimeUnit.DAYS);
87    } catch (IllegalArgumentException ignored) {
88    }
89    try {
90      client.setReadTimeout(365, TimeUnit.DAYS);
91    } catch (IllegalArgumentException ignored) {
92    }
93  }
94
95  /** Confirm that {@code copyWithDefaults} gets expected constant values. */
96  @Test public void copyWithDefaultsWhenDefaultIsAConstant() throws Exception {
97    OkHttpClient client = new OkHttpClient().copyWithDefaults();
98    assertNull(client.internalCache());
99    assertEquals(10_000, client.getConnectTimeout());
100    assertEquals(10_000, client.getReadTimeout());
101    assertEquals(10_000, client.getWriteTimeout());
102    assertTrue(client.getFollowSslRedirects());
103    assertNull(client.getProxy());
104    assertEquals(Arrays.asList(Protocol.HTTP_2, Protocol.SPDY_3, Protocol.HTTP_1_1),
105        client.getProtocols());
106  }
107
108  /**
109   * Confirm that {@code copyWithDefaults} gets some default implementations
110   * from the core library.
111   */
112  @Test public void copyWithDefaultsWhenDefaultIsGlobal() throws Exception {
113    ProxySelector proxySelector = new RecordingProxySelector();
114    CookieManager cookieManager = new CookieManager();
115    Authenticator authenticator = new RecordingAuthenticator();
116    SocketFactory socketFactory = SocketFactory.getDefault(); // Global isn't configurable.
117    OkHostnameVerifier hostnameVerifier = OkHostnameVerifier.INSTANCE; // Global isn't configurable.
118    CertificatePinner certificatePinner = CertificatePinner.DEFAULT; // Global isn't configurable.
119
120    CookieManager.setDefault(cookieManager);
121    ProxySelector.setDefault(proxySelector);
122    Authenticator.setDefault(authenticator);
123
124    OkHttpClient client = new OkHttpClient().copyWithDefaults();
125
126    assertSame(proxySelector, client.getProxySelector());
127    assertSame(cookieManager, client.getCookieHandler());
128    assertSame(AuthenticatorAdapter.INSTANCE, client.getAuthenticator());
129    assertSame(socketFactory, client.getSocketFactory());
130    assertSame(hostnameVerifier, client.getHostnameVerifier());
131    assertSame(certificatePinner, client.getCertificatePinner());
132  }
133
134  /** There is no default cache. */
135  @Test public void copyWithDefaultsCacheIsNull() throws Exception {
136    OkHttpClient client = new OkHttpClient().copyWithDefaults();
137    assertNull(client.getCache());
138  }
139
140  @Test public void copyWithDefaultsDoesNotHonorGlobalResponseCache() {
141    ResponseCache.setDefault(new ResponseCache() {
142      @Override public CacheResponse get(URI uri, String requestMethod,
143          Map<String, List<String>> requestHeaders) throws IOException {
144        throw new AssertionError();
145      }
146
147      @Override public CacheRequest put(URI uri, URLConnection connection) {
148        throw new AssertionError();
149      }
150    });
151
152    OkHttpClient client = new OkHttpClient().copyWithDefaults();
153    assertNull(client.internalCache());
154  }
155
156  @Test public void clonedInterceptorsListsAreIndependent() throws Exception {
157    OkHttpClient original = new OkHttpClient();
158    OkHttpClient clone = original.clone();
159    clone.interceptors().add(null);
160    clone.networkInterceptors().add(null);
161    assertEquals(0, original.interceptors().size());
162    assertEquals(0, original.networkInterceptors().size());
163  }
164
165  /**
166   * When copying the client, stateful things like the connection pool are
167   * shared across all clients.
168   */
169  @Test public void cloneSharesStatefulInstances() throws Exception {
170    OkHttpClient client = new OkHttpClient();
171
172    // Values should be non-null.
173    OkHttpClient a = client.clone().copyWithDefaults();
174    assertNotNull(a.routeDatabase());
175    assertNotNull(a.getDispatcher());
176    assertNotNull(a.getConnectionPool());
177    assertNotNull(a.getSslSocketFactory());
178
179    // Multiple clients share the instances.
180    OkHttpClient b = client.clone().copyWithDefaults();
181    assertSame(a.routeDatabase(), b.routeDatabase());
182    assertSame(a.getDispatcher(), b.getDispatcher());
183    assertSame(a.getConnectionPool(), b.getConnectionPool());
184    assertSame(a.getSslSocketFactory(), b.getSslSocketFactory());
185  }
186
187  @Test public void setProtocolsRejectsHttp10() throws Exception {
188    OkHttpClient client = new OkHttpClient();
189    try {
190      client.setProtocols(Arrays.asList(Protocol.HTTP_1_0, Protocol.HTTP_1_1));
191      fail();
192    } catch (IllegalArgumentException expected) {
193    }
194  }
195}
196