1
0
mirror of https://github.com/square/okhttp.git synced 2025-11-23 06:42:24 +03:00

Run okhttp-android unit tests (#7865)

This commit is contained in:
Yuri Schimke
2023-05-27 19:24:38 +01:00
committed by GitHub
parent 736aaba99a
commit b14b129a3f
4 changed files with 37 additions and 40 deletions

View File

@@ -389,7 +389,6 @@ jobs:
timeout-minutes: 30 timeout-minutes: 30
if: github.ref == 'refs/heads/master' || contains(github.event.pull_request.labels.*.name, 'android') || contains(github.event.pull_request.labels.*.name, 'renovate') if: github.ref == 'refs/heads/master' || contains(github.event.pull_request.labels.*.name, 'android') || contains(github.event.pull_request.labels.*.name, 'renovate')
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -411,6 +410,8 @@ jobs:
- name: Gradle cache - name: Gradle cache
uses: gradle/gradle-build-action@v2 uses: gradle/gradle-build-action@v2
with:
arguments: -PandroidBuild=true :okhttp-android:test
- name: AVD cache - name: AVD cache
uses: actions/cache@v3 uses: actions/cache@v3

View File

@@ -3,29 +3,30 @@ import com.vanniktech.maven.publish.JavadocJar
plugins { plugins {
id("com.android.library") id("com.android.library")
kotlin("android") kotlin("android")
id("de.mannodermaus.android-junit5")
id("org.jetbrains.dokka") id("org.jetbrains.dokka")
id("com.vanniktech.maven.publish.base") id("com.vanniktech.maven.publish.base")
id("binary-compatibility-validator") id("binary-compatibility-validator")
} }
android { android {
compileSdk = 31 compileSdk = 33
defaultConfig { defaultConfig {
minSdk = 21 minSdk = 21
targetSdk = 31 targetSdk = 33
// Make sure to use the AndroidJUnitRunner (or a sub-class) in order to hook in the JUnit 5 Test Builder // Make sure to use the AndroidJUnitRunner (or a sub-class) in order to hook in the JUnit 5 Test Builder
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunnerArguments += mapOf(
"runnerBuilder" to "de.mannodermaus.junit5.AndroidJUnit5Builder",
"notPackage" to "org.bouncycastle"
)
buildFeatures { buildFeatures {
buildConfig = false buildConfig = false
} }
testOptions {
unitTests {
isIncludeAndroidResources = true
}
}
} }
compileOptions { compileOptions {
@@ -55,14 +56,12 @@ dependencies {
testImplementation(libs.androidx.test.runner) testImplementation(libs.androidx.test.runner)
testImplementation(libs.robolectric) testImplementation(libs.robolectric)
testImplementation(libs.androidx.espresso.core) testImplementation(libs.androidx.espresso.core)
testImplementation(libs.squareup.okio.fakefilesystem)
androidTestImplementation(projects.okhttpTls) androidTestImplementation(projects.okhttpTls)
androidTestImplementation(libs.assertj.core) androidTestImplementation(libs.assertj.core)
androidTestImplementation(projects.mockwebserver3Junit5) androidTestImplementation(projects.mockwebserver3Junit4)
androidTestImplementation(libs.androidx.test.runner) androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.junit.jupiter.api)
androidTestImplementation(libs.junit5android.core)
androidTestRuntimeOnly(libs.junit5android.runner)
} }
mavenPublishing { mavenPublishing {

View File

@@ -24,7 +24,7 @@ import java.net.UnknownHostException
import java.util.concurrent.CountDownLatch import java.util.concurrent.CountDownLatch
import mockwebserver3.MockResponse import mockwebserver3.MockResponse
import mockwebserver3.MockWebServer import mockwebserver3.MockWebServer
import mockwebserver3.junit5.internal.MockWebServerExtension import mockwebserver3.junit4.MockWebServerRule
import okhttp3.AsyncDns import okhttp3.AsyncDns
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
@@ -34,17 +34,17 @@ import okhttp3.tls.HeldCertificate
import okio.IOException import okio.IOException
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail import org.assertj.core.api.Assertions.fail
import org.junit.jupiter.api.BeforeEach import org.junit.AssumptionViolatedException
import org.junit.jupiter.api.Disabled import org.junit.Before
import org.junit.jupiter.api.Test import org.junit.Ignore
import org.junit.jupiter.api.extension.ExtendWith import org.junit.Rule
import org.opentest4j.TestAbortedException import org.junit.Test
/** /**
* Run with "./gradlew :android-test:connectedCheck -PandroidBuild=true" and make sure ANDROID_SDK_ROOT is set. * Run with "./gradlew :android-test:connectedCheck -PandroidBuild=true" and make sure ANDROID_SDK_ROOT is set.
*/ */
@ExtendWith(MockWebServerExtension::class)
class AndroidAsyncDnsTest { class AndroidAsyncDnsTest {
@JvmField @Rule val serverRule = MockWebServerRule()
private val localhost: HandshakeCertificates by lazy { private val localhost: HandshakeCertificates by lazy {
// Generate a self-signed cert for the server to serve and the client to trust. // Generate a self-signed cert for the server to serve and the client to trust.
@@ -63,20 +63,17 @@ class AndroidAsyncDnsTest {
.sslSocketFactory(localhost.sslSocketFactory(), localhost.trustManager) .sslSocketFactory(localhost.sslSocketFactory(), localhost.trustManager)
.build() .build()
private lateinit var server: MockWebServer @Before
fun init() {
@BeforeEach serverRule.server.useHttps(localhost.sslSocketFactory())
fun init(server: MockWebServer) {
this.server = server
server.useHttps(localhost.sslSocketFactory())
} }
@Test @Test
@Disabled("java.net.UnknownHostException: No results for localhost, in CI.") @Ignore("java.net.UnknownHostException: No results for localhost, in CI.")
fun testRequest() { fun testRequest() {
server.enqueue(MockResponse()) serverRule.server.enqueue(MockResponse())
val call = client.newCall(Request(server.url("/"))) val call = client.newCall(Request(serverRule.server.url("/")))
call.execute().use { response -> call.execute().use { response ->
assertThat(response.code).isEqualTo(200) assertThat(response.code).isEqualTo(200)
@@ -107,7 +104,7 @@ class AndroidAsyncDnsTest {
} }
@Test @Test
@Disabled("No results on CI for localhost") @Ignore("No results on CI for localhost")
fun testDnsRequest() { fun testDnsRequest() {
val (allAddresses, exception) = dnsQuery("localhost") val (allAddresses, exception) = dnsQuery("localhost")
@@ -165,7 +162,7 @@ class AndroidAsyncDnsTest {
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = val network =
connectivityManager.activeNetwork ?: throw TestAbortedException("No active network") connectivityManager.activeNetwork ?: throw AssumptionViolatedException("No active network")
val client = OkHttpClient.Builder() val client = OkHttpClient.Builder()
.dns(AsyncDns.toDns(AndroidAsyncDns.IPv4, AndroidAsyncDns.IPv6)) .dns(AsyncDns.toDns(AndroidAsyncDns.IPv4, AndroidAsyncDns.IPv6))
@@ -184,7 +181,7 @@ class AndroidAsyncDnsTest {
try { try {
InetAddress.getByName("www.google.com") InetAddress.getByName("www.google.com")
} catch (uhe: UnknownHostException) { } catch (uhe: UnknownHostException) {
throw TestAbortedException(uhe.message, uhe) throw AssumptionViolatedException(uhe.message, uhe)
} }
} }
} }

View File

@@ -23,7 +23,6 @@ import okhttp3.CacheControl
import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import okhttp3.android.OkHttpClientContext.okHttpClient
import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThat
import org.junit.AssumptionViolatedException import org.junit.AssumptionViolatedException
import org.junit.Before import org.junit.Before
@@ -31,17 +30,17 @@ import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.net.InetAddress import java.net.InetAddress
import java.net.UnknownHostException import java.net.UnknownHostException
import okhttp3.Cache
import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem
@RunWith(RobolectricTestRunner::class) @RunWith(RobolectricTestRunner::class)
@Config( @Config(
sdk = [30], sdk = [30],
qualifiers = "w221dp-h221dp-small-notlong-round-watch-xhdpi-keyshidden-nonav"
) )
@GraphicsMode(GraphicsMode.Mode.NATIVE) class RobolectricOkHttpClientTest {
class RobolectricClientBuilderTest {
private lateinit var context: Context private lateinit var context: Context
private lateinit var client: OkHttpClient private lateinit var client: OkHttpClient
@@ -49,7 +48,9 @@ class RobolectricClientBuilderTest {
@Before @Before
fun setUp() { fun setUp() {
context = ApplicationProvider.getApplicationContext<Application>() context = ApplicationProvider.getApplicationContext<Application>()
client = context.okHttpClient client = OkHttpClient.Builder()
.cache(Cache("/cache".toPath(), 10_000_000, FakeFileSystem()))
.build()
} }
@Test @Test
@@ -59,21 +60,20 @@ class RobolectricClientBuilderTest {
val request = Request("https://www.google.com/robots.txt".toHttpUrl()) val request = Request("https://www.google.com/robots.txt".toHttpUrl())
val networkRequest = request.newBuilder() val networkRequest = request.newBuilder()
.cacheControl(CacheControl.FORCE_NETWORK)
.build() .build()
val call = client.newCall(networkRequest) val call = client.newCall(networkRequest)
call.execute().use { response -> call.execute().use { response ->
assertThat(response.code).isEqualTo(200) assertThat(response.code).isEqualTo(200)
assertThat(response.networkResponse).isNull() assertThat(response.cacheResponse).isNull()
} }
val cachedCall = client.newCall(request) val cachedCall = client.newCall(request)
cachedCall.execute().use { response -> cachedCall.execute().use { response ->
assertThat(response.code).isEqualTo(200) assertThat(response.code).isEqualTo(200)
assertThat(response.networkResponse).isNotNull() assertThat(response.cacheResponse).isNotNull()
} }
} }