Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[mockserver] Allow to set the content-type of String responses #5489

Merged
merged 8 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion gradle/libraries.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ kotlinx-datetime = "0.5.0"
kotlinx-serialization-runtime = "1.6.2"
ksp = "2.0.0-Beta1-1.0.14"
okio = "3.6.0"
ktor = "2.3.5"
ktor = "2.3.7"
okhttp = "4.11.0"
rx-android = "2.0.1"
rx-java2 = "2.2.21"
Expand Down
9 changes: 7 additions & 2 deletions libraries/apollo-mockserver/api/apollo-mockserver.api
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ public abstract interface class com/apollographql/apollo3/mockserver/MockRequest
public abstract fun getVersion ()Ljava/lang/String;
}

public final class com/apollographql/apollo3/mockserver/MockRequestBaseKt {
public static final fun headerValueOf (Ljava/util/Map;Ljava/lang/String;)Ljava/lang/String;
}

public final class com/apollographql/apollo3/mockserver/MockResponse {
public fun <init> ()V
public fun <init> (ILkotlinx/coroutines/flow/Flow;Ljava/util/Map;J)V
Expand Down Expand Up @@ -75,9 +79,10 @@ public final class com/apollographql/apollo3/mockserver/MockServerKt {
public static synthetic fun awaitRequest-8Mi8wO0$default (Lcom/apollographql/apollo3/mockserver/MockServer;JLkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object;
public static final fun enqueue (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JI)V
public static synthetic fun enqueue$default (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JIILjava/lang/Object;)V
public static final fun enqueueGraphQLString (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;)V
public static final fun enqueueMultipart (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/util/List;)Ljava/lang/Void;
public static final fun enqueueString (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JI)V
public static synthetic fun enqueueString$default (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JIILjava/lang/Object;)V
public static final fun enqueueString (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JILjava/lang/String;)V
public static synthetic fun enqueueString$default (Lcom/apollographql/apollo3/mockserver/MockServer;Ljava/lang/String;JILjava/lang/String;ILjava/lang/Object;)V
}

public final class com/apollographql/apollo3/mockserver/TcpServer_concurrentKt {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,23 @@ interface MockRequestBase {
val method: String
val path: String
val version: String

/**
* The request headers
*
* Names are copied as-is from the wire. Since headers are case-insensitive, use [headerValueOf] to retrieve values.
* Values are trimmed.
*/
val headers: Map<String, String>
}

/**
* Retrieves the value of the given key, using a case-insensitive matching
*/
fun Map<String, String>.headerValueOf(name: String): String? {
return entries.firstOrNull { it.key.compareTo(name, ignoreCase = true) == 0 }?.value
}

class MockRequest(
override val method: String,
override val path: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,13 @@ constructor(
fun delayMillis(delayMillis: Long) = apply { this.delayMillis = delayMillis }

fun build(): MockResponse {
val headersWithContentLength = if (contentLength == null) headers else headers + mapOf("Content-Length" to contentLength.toString())
val headersWithContentLength = buildMap {
putAll(headers)
if (contentLength != null) {
put("Content-Length", contentLength.toString())
}
}

// https://youtrack.jetbrains.com/issue/KT-34480
@Suppress("DEPRECATION_ERROR")
return MockResponse(statusCode = statusCode, body = body, headers = headersWithContentLength, delayMillis = delayMillis)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,14 +267,23 @@ fun MockServer(handler: MockServerHandler): MockServer =
@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v4_0_0)
fun MockServer.enqueue(string: String = "", delayMs: Long = 0, statusCode: Int = 200) = enqueueString(string, delayMs, statusCode)

fun MockServer.enqueueString(string: String = "", delayMs: Long = 0, statusCode: Int = 200) {
fun MockServer.enqueueString(string: String = "", delayMs: Long = 0, statusCode: Int = 200, contentType: String = "text/plain") {
enqueue(MockResponse.Builder()
.statusCode(statusCode)
.body(string)
.addHeader("Content-Type", contentType)
.delayMillis(delayMs)
.build())
}

fun MockServer.enqueueGraphQLString(string: String) {
enqueue(MockResponse.Builder()
.statusCode(200)
.addHeader("content-type", "application/graphql-response+json")
.body(string)
.build())
}

@ApolloExperimental
interface MultipartBody {
fun enqueuePart(bytes: ByteString, isLast: Boolean)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.apollographql.apollo3.mockserver

import okio.Buffer
import okio.IOException

internal interface Reader {
val buffer: Buffer
Expand Down Expand Up @@ -35,7 +34,7 @@ private fun parseRequestLine(line: String): Triple<String, String, String> {
return Triple(method, match.groupValues[2], match.groupValues[3])
}

internal class ConnectionClosed(cause: Throwable?): Exception("client closed the connection", cause)
internal class ConnectionClosed(cause: Throwable?) : Exception("client closed the connection", cause)

internal suspend fun readRequest(reader: Reader): MockRequestBase {
suspend fun nextLine(): String {
Expand All @@ -62,23 +61,21 @@ internal suspend fun readRequest(reader: Reader): MockRequestBase {
return buffer2
}

/**
* Check if the client closed the connection
*/
if (reader.buffer.size == 0L) {
try {
reader.fillBuffer()
} catch (e: IOException) {
throw ConnectionClosed(e)
}
var line = try {
nextLine()
} catch (e: Exception) {
/**
* XXX: if the connection is closed in the middle of the first request line, this is detected
* as a normal connection close.
*/
throw ConnectionClosed(e)
}

var line = nextLine()

val (method, path, version) = parseRequestLine(line.trimEol())
//println("Line: ${line.trimEol()}")

val headers = mutableMapOf<String, String>()

/**
* Read headers
*/
Expand All @@ -93,8 +90,8 @@ internal suspend fun readRequest(reader: Reader): MockRequestBase {
headers.put(key, value)
}

val contentLength = headers["Content-Length"]?.toLongOrNull() ?: 0
val transferEncoding = headers["Transfer-Encoding"]?.lowercase()
val contentLength = headers.headerValueOf("content-length")?.toLongOrNull() ?: 0
val transferEncoding = headers.headerValueOf("transfer-encoding")?.lowercase()
check(transferEncoding == null || transferEncoding == "identity" || transferEncoding == "chunked") {
"Transfer-Encoding $transferEncoding is not supported"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ actual class DefaultHttpEngine constructor(private val connectTimeoutMillis: Lon
}
val responseByteArray: ByteArray = response.body()
val responseBufferedSource = Buffer().write(responseByteArray)

return HttpResponse.Builder(statusCode = response.status.value)
.body(responseBufferedSource)
.addHeaders(response.headers.flattenEntries().map { HttpHeader(it.first, it.second) })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ class LoggingInterceptorTest {
private lateinit var mockServer: MockServer
private lateinit var logger: Logger

private suspend fun setUp() {
private fun setUp() {
mockServer = MockServer()
logger = Logger()
}

private suspend fun tearDown() {
private fun tearDown() {
mockServer.close()
}

Expand All @@ -41,10 +41,49 @@ class LoggingInterceptorTest {
}

fun assertLog(expected: String) {
assertEquals(expected.trimIndent().lowercase(), fullLog.toString().lowercase().trim())
val actual = fullLog.toString().lowercase().trim()
if (expected == "") {
assertEquals("", actual)
return
}

/**
* This is more involved than expected because the response headers order is not preserved on JS.
* The order of HTTP headers is not important unless there are multiple headers with the same name.
* It would be a nice property to keep the HTTP headers order albeit it is currently not the case.
*
* See https://youtrack.jetbrains.com/issue/KTOR-6582/
*/
expected
.lowercase()
.toStream()
.assertEquals(actual.toStream())
}

private fun String.toStream(): Stream {
val responseIndex = indexOf("http: ")
check(responseIndex > 0)

val request = substring(0, responseIndex)
val responseLines = substring(responseIndex).split("\n")
val endOfHeaders = responseLines.indexOfFirst { it == "[end of headers]" }
return if (endOfHeaders > 0) {
Stream(request, responseLines.subList(1, endOfHeaders), responseLines.subList(0, 1) + responseLines.subList(endOfHeaders, responseLines.size))
} else {
Stream(request, emptyList(), responseLines)
}
}

private class Stream(val request: String, val responseHeaders: List<String>, val otherResponseLines: List<String>) {
fun assertEquals(other: Stream) {
assertEquals(request, other.request)
assertEquals(responseHeaders.sorted(), other.responseHeaders.sorted())
assertEquals(otherResponseLines, other.otherResponseLines)
}
}
}


@Test
fun levelNone() = runTest(before = { setUp() }, after = { tearDown() }) {
val client = ApolloClient.Builder()
Expand All @@ -68,7 +107,7 @@ class LoggingInterceptorTest {
Post http://0.0.0.0/

HTTP: 200
""")
""".trimIndent())
}

@Test
Expand All @@ -87,9 +126,10 @@ class LoggingInterceptorTest {
[end of headers]

HTTP: 200
Content-Type: text/plain
Content-Length: 322
[end of headers]
""")
""".trimIndent())
}

@Test
Expand All @@ -109,6 +149,7 @@ class LoggingInterceptorTest {
{"operationName":"HeroName","variables":{},"query":"query HeroName { hero { name } }"}

HTTP: 200
Content-Type: text/plain
Content-Length: 322
[end of headers]
{
Expand All @@ -130,7 +171,7 @@ class LoggingInterceptorTest {
}
}
}
""")
""".trimIndent())
}

@Test
Expand All @@ -140,6 +181,7 @@ class LoggingInterceptorTest {
.addHttpInterceptor(LoggingInterceptor(level = Level.BODY, log = logger::log))
.build()
mockServer.enqueueString(testFixtureToUtf8("HeroNameResponse.json").replace("\n", ""))

client.query(HeroNameQuery()).execute()
logger.assertLog("""
Post http://0.0.0.0/
Expand All @@ -150,10 +192,11 @@ class LoggingInterceptorTest {
{"operationName":"HeroName","variables":{},"query":"query HeroName { hero { name } }"}

HTTP: 200
Content-Type: text/plain
Content-Length: 303
[end of headers]
{ "data": { "hero": { "__typename": "Droid", "name": "R2-D2" } }, "extensions": { "cost": { "requestedQueryCost": 3, "actualQueryCost": 3, "throttleStatus": { "maximumAvailable": 1000, "currentlyAvailable": 997, "restoreRate": 50 } } }}
""")
""".trimIndent())
}

@Test
Expand Down