okhttp

Форк
0
201 строка · 5.9 Кб
1
/*
2
 * Copyright (C) 2024 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
 */
16
package okhttp3.containers
17

18
import assertk.assertThat
19
import assertk.assertions.contains
20
import assertk.assertions.isEqualTo
21
import java.net.HttpURLConnection
22
import java.net.Proxy
23
import java.net.URI
24
import javax.net.ssl.HttpsURLConnection
25
import okhttp3.HttpUrl.Companion.toHttpUrl
26
import okhttp3.OkHttpClient
27
import okhttp3.Protocol
28
import okhttp3.Request
29
import okhttp3.containers.BasicMockServerTest.Companion.MOCKSERVER_IMAGE
30
import okhttp3.containers.BasicMockServerTest.Companion.trustMockServer
31
import okio.buffer
32
import okio.source
33
import org.junit.jupiter.api.Test
34
import org.mockserver.client.MockServerClient
35
import org.mockserver.configuration.Configuration
36
import org.mockserver.logging.MockServerLogger
37
import org.mockserver.model.HttpRequest.request
38
import org.mockserver.model.HttpResponse.response
39
import org.mockserver.proxyconfiguration.ProxyConfiguration
40
import org.mockserver.socket.tls.KeyStoreFactory
41
import org.testcontainers.containers.MockServerContainer
42
import org.testcontainers.junit.jupiter.Container
43
import org.testcontainers.junit.jupiter.Testcontainers
44

45
@Testcontainers
46
class BasicProxyTest {
47
  @Container
48
  val mockServer: MockServerContainer =
49
    MockServerContainer(MOCKSERVER_IMAGE)
50
      .withNetworkAliases("mockserver")
51

52
  @Test
53
  fun testOkHttpDirect() {
54
    testRequest {
55
      val client = OkHttpClient()
56

57
      val response =
58
        client.newCall(
59
          Request((mockServer.endpoint + "/person?name=peter").toHttpUrl()),
60
        ).execute()
61

62
      assertThat(response.body.string()).contains("Peter the person")
63
      assertThat(response.protocol).isEqualTo(Protocol.HTTP_1_1)
64
    }
65
  }
66

67
  @Test
68
  fun testOkHttpProxied() {
69
    testRequest {
70
      it.withProxyConfiguration(ProxyConfiguration.proxyConfiguration(ProxyConfiguration.Type.HTTP, it.remoteAddress()))
71

72
      val client =
73
        OkHttpClient.Builder()
74
          .proxy(Proxy(Proxy.Type.HTTP, it.remoteAddress()))
75
          .build()
76

77
      val response =
78
        client.newCall(
79
          Request((mockServer.endpoint + "/person?name=peter").toHttpUrl()),
80
        ).execute()
81

82
      assertThat(response.body.string()).contains("Peter the person")
83
    }
84
  }
85

86
  @Test
87
  fun testOkHttpSecureDirect() {
88
    testRequest {
89
      val client =
90
        OkHttpClient.Builder()
91
          .trustMockServer()
92
          .build()
93

94
      val response =
95
        client.newCall(
96
          Request((mockServer.secureEndpoint + "/person?name=peter").toHttpUrl()),
97
        ).execute()
98

99
      assertThat(response.body.string()).contains("Peter the person")
100
      assertThat(response.protocol).isEqualTo(Protocol.HTTP_2)
101
    }
102
  }
103

104
  @Test
105
  fun testOkHttpSecureProxiedHttp1() {
106
    testRequest {
107
      val client =
108
        OkHttpClient.Builder()
109
          .trustMockServer()
110
          .proxy(Proxy(Proxy.Type.HTTP, it.remoteAddress()))
111
          .protocols(listOf(Protocol.HTTP_1_1))
112
          .build()
113

114
      val response =
115
        client.newCall(
116
          Request((mockServer.secureEndpoint + "/person?name=peter").toHttpUrl()),
117
        ).execute()
118

119
      assertThat(response.body.string()).contains("Peter the person")
120
      assertThat(response.protocol).isEqualTo(Protocol.HTTP_1_1)
121
    }
122
  }
123

124
  @Test
125
  fun testUrlConnectionDirect() {
126
    testRequest {
127
      val url = URI(mockServer.endpoint + "/person?name=peter").toURL()
128

129
      val connection = url.openConnection() as HttpURLConnection
130

131
      assertThat(connection.inputStream.source().buffer().readUtf8()).contains("Peter the person")
132
    }
133
  }
134

135
  @Test
136
  fun testUrlConnectionPlaintextProxied() {
137
    testRequest {
138
      val proxy =
139
        Proxy(
140
          Proxy.Type.HTTP,
141
          it.remoteAddress(),
142
        )
143

144
      val url = URI(mockServer.endpoint + "/person?name=peter").toURL()
145

146
      val connection = url.openConnection(proxy) as HttpURLConnection
147

148
      assertThat(connection.inputStream.source().buffer().readUtf8()).contains("Peter the person")
149
    }
150
  }
151

152
  @Test
153
  fun testUrlConnectionSecureDirect() {
154
    val keyStoreFactory = KeyStoreFactory(Configuration.configuration(), MockServerLogger())
155
    HttpsURLConnection.setDefaultSSLSocketFactory(keyStoreFactory.sslContext().socketFactory)
156

157
    testRequest {
158
      val url = URI(mockServer.secureEndpoint + "/person?name=peter").toURL()
159

160
      val connection = url.openConnection() as HttpURLConnection
161

162
      assertThat(connection.inputStream.source().buffer().readUtf8()).contains("Peter the person")
163
    }
164
  }
165

166
  @Test
167
  fun testUrlConnectionSecureProxied() {
168
    val keyStoreFactory = KeyStoreFactory(Configuration.configuration(), MockServerLogger())
169
    HttpsURLConnection.setDefaultSSLSocketFactory(keyStoreFactory.sslContext().socketFactory)
170

171
    testRequest {
172
      val proxy =
173
        Proxy(
174
          Proxy.Type.HTTP,
175
          it.remoteAddress(),
176
        )
177

178
      val url = URI(mockServer.secureEndpoint + "/person?name=peter").toURL()
179

180
      val connection = url.openConnection(proxy) as HttpURLConnection
181

182
      assertThat(connection.inputStream.source().buffer().readUtf8()).contains("Peter the person")
183
    }
184
  }
185

186
  private fun testRequest(function: (MockServerClient) -> Unit) {
187
    MockServerClient(mockServer.host, mockServer.serverPort).use { mockServerClient ->
188
      val request =
189
        request().withPath("/person")
190
          .withQueryStringParameter("name", "peter")
191

192
      mockServerClient
193
        .`when`(
194
          request,
195
        )
196
        .respond(response().withBody("Peter the person!"))
197

198
      function(mockServerClient)
199
    }
200
  }
201
}
202

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.