Skip to content

Commit

Permalink
Merge pull request #303 from kittinunf/wm/better-tostring
Browse files Browse the repository at this point in the history
✨ Add response.guessContentType() and improve .toString()
  • Loading branch information
kindraywind authored Feb 1, 2018
2 parents 0001c44 + 49e534e commit f9bd365
Show file tree
Hide file tree
Showing 2 changed files with 188 additions and 8 deletions.
44 changes: 36 additions & 8 deletions fuel/src/main/kotlin/com/github/kittinunf/fuel/core/Response.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.net.URLConnection

class Response(
val url: URL,
Expand Down Expand Up @@ -33,14 +34,41 @@ class Response(
}
}

override fun toString(): String = buildString {
appendln("<-- $statusCode ($url)")
appendln("Response : $responseMessage")
appendln("Length : $contentLength")
appendln("Body : ${if (data.isNotEmpty()) String(data) else "(empty)"}")
appendln("Headers : (${headers.size})")
for ((key, value) in headers) {
appendln("$key : $value")
override fun toString(): String {
val contentType = guessContentType(headers)
val dataString = processBody(contentType, data)

return buildString {
appendln("<-- $statusCode ($url)")
appendln("Response : $responseMessage")
appendln("Length : $contentLength")
appendln("Body : ($dataString)")
appendln("Headers : (${headers.size})")
for ((key, value) in headers) {
appendln("$key : $value")
}
}
}

internal fun guessContentType(headers: Map<String, List<String>>): String {
val contentTypeFromHeaders = headers["Content-Type"]?.first()
if (contentTypeFromHeaders is String && !contentTypeFromHeaders.isNullOrEmpty()) {
return contentTypeFromHeaders
}

val contentTypeFromStream = URLConnection.guessContentTypeFromStream(ByteArrayInputStream(data))
return if (contentTypeFromStream.isNullOrEmpty()) "(unknown)" else contentTypeFromStream
}

internal fun processBody(contentType: String, bodyData: ByteArray): String {
return if (contentType.isNotEmpty() &&
(contentType.contains("image/") ||
contentType.contains("application/octet-stream"))) {
"$contentLength bytes of ${guessContentType(headers)}"
} else if (bodyData.isNotEmpty()) {
String(bodyData)
} else {
"(empty)"
}
}

Expand Down
152 changes: 152 additions & 0 deletions fuel/src/test/kotlin/com/github/kittinunf/fuel/RequestTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,32 @@ class RequestTest : BaseTestCase() {
}()
}

@Test
fun testResponseURLShouldSameWithRequestURL() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/get").response { req, res, result ->
request = req
response = res

val (d, err) = result
data = d
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())

assertThat(request?.url, notNullValue())
assertThat(response?.url, notNullValue())
assertThat(request?.url, isEqualTo(response?.url))
}

@Test
fun httpGetRequestWithDataResponse() {
var request: Request? = null
Expand Down Expand Up @@ -112,6 +138,131 @@ class RequestTest : BaseTestCase() {
assertThat(response?.statusCode, isEqualTo(statusCode))
}

@Test
fun httpGetRequestWithImageResponse() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/image/png").responseString { req, res, result ->
request = req
response = res

val (d, err) = result
data = d
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())

assertThat(response?.toString(), containsString("bytes of image/png"))

val statusCode = HttpURLConnection.HTTP_OK
assertThat(response?.statusCode, isEqualTo(statusCode))
}

@Test
fun httpGetRequestWithBytesResponse() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/bytes/555").responseString { req, res, result ->
request = req
response = res

val (d, err) = result
data = d
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())

assertThat(response?.toString(), containsString("Body : (555 bytes of application/octet-stream)"))

val statusCode = HttpURLConnection.HTTP_OK
assertThat(response?.statusCode, isEqualTo(statusCode))
}

@Test
fun testProcessBodyWithUnknownContentTypeAndNoData() {
var request: Request? = null
var response: Response? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/bytes/555").responseString { req, res, result ->
request = req
response = res

val (d, err) = result
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())

assertThat(response?.processBody("(unknown)", ByteArray(0)), isEqualTo("(empty)"))
}

@Test
fun testGuessContentTypeWithNoContentTypeInHeaders() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/bytes/555").responseString { req, res, result ->
request = req
response = res

val (d, err) = result
data = d
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())

val headers: Map<String, List<String>> = mapOf(Pair("Content-Type", listOf("")))
assertThat(response?.guessContentType(headers), isEqualTo("(unknown)"))
}

@Test
fun testGuessContentTypeWithNoHeaders() {
var request: Request? = null
var response: Response? = null
var data: Any? = null
var error: FuelError? = null

manager.request(Method.GET, "http://httpbin.org/image/png").responseString { req, res, result ->
request = req
response = res

val (d, err) = result
data = d
error = err
}

assertThat(request, notNullValue())
assertThat(response, notNullValue())
assertThat(error, nullValue())
assertThat(data, notNullValue())

val headers: Map<String, List<String>> = mapOf(Pair("Content-Type", listOf("")))
assertThat(response?.guessContentType(headers), isEqualTo("image/png"))
}

@Test
fun httpGetRequestWithParameters() {
var request: Request? = null
Expand Down Expand Up @@ -539,5 +690,6 @@ class RequestTest : BaseTestCase() {

assertThat(request.cUrlString(), isEqualTo("$ curl -i -X POST -H \"Authentication:Bearer xxx\" http://httpbin.org/post"))
}

}

0 comments on commit f9bd365

Please sign in to comment.