okhttp

Форк
0
116 строк · 3.7 Кб
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.isEmpty
21
import assertk.assertions.isNotEmpty
22
import java.io.ByteArrayOutputStream
23
import java.io.PrintStream
24
import java.util.concurrent.ExecutorService
25
import java.util.concurrent.Executors
26
import okhttp3.Dispatcher
27
import okhttp3.HttpUrl.Companion.toHttpUrl
28
import okhttp3.OkHttpClient
29
import okhttp3.Request
30
import okhttp3.containers.BasicMockServerTest.Companion.MOCKSERVER_IMAGE
31
import okhttp3.containers.BasicMockServerTest.Companion.trustMockServer
32
import okhttp3.testing.PlatformRule
33
import org.junit.jupiter.api.AfterEach
34
import org.junit.jupiter.api.BeforeEach
35
import org.junit.jupiter.api.Test
36
import org.junit.jupiter.api.extension.RegisterExtension
37
import org.junit.jupiter.api.parallel.Isolated
38
import org.mockserver.client.MockServerClient
39
import org.mockserver.model.HttpRequest.request
40
import org.mockserver.model.HttpResponse.response
41
import org.testcontainers.containers.MockServerContainer
42
import org.testcontainers.junit.jupiter.Container
43
import org.testcontainers.junit.jupiter.Testcontainers
44

45
@Testcontainers
46
@Isolated
47
class BasicLoomTest {
48
  @JvmField
49
  @RegisterExtension
50
  val platform = PlatformRule()
51

52
  // Use mock server so we are strictly testing OkHttp client only in this test.
53
  // We should test MockWebServer later.
54
  @Container
55
  val mockServer: MockServerContainer = MockServerContainer(MOCKSERVER_IMAGE)
56

57
  val capturedOut = ByteArrayOutputStream()
58

59
  private lateinit var executor: ExecutorService
60

61
  private lateinit var client: OkHttpClient
62

63
  @BeforeEach
64
  fun setUp() {
65
    platform.assumeLoom()
66
    assertThat(System.getProperty("jdk.tracePinnedThreads")).isNotEmpty()
67

68
    client =
69
      OkHttpClient.Builder()
70
        .trustMockServer()
71
        .dispatcher(Dispatcher(newVirtualThreadPerTaskExecutor()))
72
        .build()
73

74
    executor = newVirtualThreadPerTaskExecutor()
75

76
    // Capture non-deterministic but probable sysout warnings of pinned threads
77
    // https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html
78
    System.setOut(PrintStream(capturedOut))
79
  }
80

81
  @AfterEach
82
  fun checkForPinning() {
83
    assertThat(capturedOut.toString()).isEmpty()
84
  }
85

86
  private fun newVirtualThreadPerTaskExecutor(): ExecutorService {
87
    return Executors::class.java.getMethod("newVirtualThreadPerTaskExecutor").invoke(null) as ExecutorService
88
  }
89

90
  @Test
91
  fun testHttpsRequest() {
92
    MockServerClient(mockServer.host, mockServer.serverPort).use { mockServerClient ->
93
      mockServerClient
94
        .`when`(
95
          request().withPath("/person")
96
            .withQueryStringParameter("name", "peter"),
97
        )
98
        .respond(response().withBody("Peter the person!"))
99

100
      val results =
101
        (1..20).map {
102
          executor.submit {
103
            val response =
104
              client.newCall(Request((mockServer.secureEndpoint + "/person?name=peter").toHttpUrl())).execute()
105

106
            val body = response.body.string()
107
            assertThat(body).contains("Peter the person")
108
          }
109
        }
110

111
      results.forEach {
112
        it.get()
113
      }
114
    }
115
  }
116
}
117

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

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

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

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