How to use Request.cUrlString method of com.github.kittinunf.fuel.core.extensions.Formatting class

Best Fuel code snippet using com.github.kittinunf.fuel.core.extensions.Formatting.Request.cUrlString

ADocTagAspect.kt

Source:ADocTagAspect.kt Github

copy

Full Screen

1package hal.spel.aspect2import com.fasterxml.jackson.databind.ObjectMapper3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.extensions.cUrlString6import com.github.kittinunf.fuel.core.requests.RepeatableBody7import hal.spel.Answer8import hal.spel.Link9import io.micronaut.http.HttpStatus10import java.io.PrintWriter11import kotlin.math.min12private val jackson = ObjectMapper()13private var counters = mutableMapOf<String, Int>()14private var relation: String? = null15/**16 * Reports the parts of the request and response as AsciiDoctor tags.17 *18 * Using this class the client application can produce the AsciiDoctor document containing19 * tags for all requests/responses application communicates with the server. Then that tags can be included20 * in a separate AsciiDoctor document built by AsciiDoctor plugin into final documentation including21 * "life" data.22 * Different instances of this class can report on different set of parts related to communication23 * with server. For example24 *25 * @param reporter -- the PrintWriter to print the text of the tag into. Could be File, Console or other Writer26 * @param parts -- the vararg of parts to include as tags27 * @param followed -- the AspectFormatter to link in the chain.28 * The Aspect generated by this Formatter will pass control to the aspect generated by this parameter29 */30class ADocTagFormatter(31 private val reporter: PrintWriter,32 vararg val parts: ReportPart,33 followed: AspectFormatter? = null34) : AspectFormatter(followed) {35 private val aDocTagFormatter = mutableMapOf<ReportPart, Pair<LinkFun?, AnswerFun?>>().also {36 ReportPart.values().forEach { part ->37 it[part] = Pair<LinkFun?, AnswerFun?>({38 preADocTagFormatter[part]?.invoke(this, reporter::println)39 this40 }, {41 postADocTagFormatter[part]?.invoke(it, reporter::println)42 })43 }44 }45 override fun makeAspect(aspect: Aspect?): Aspect {46 return makeReporterAspect(aDocTagFormatter, *parts, aspect = super.makeAspect(aspect))47 }48}49private fun <T> formatTag(tagName: String, obj: T?, reporter: (String) -> Unit) {50 reporter("""51 |#tag::$relation-$tagName-${counters[relation]}[]52 |${53 when (obj) {54 is Map<*, *> -> obj.filterValues {55 it != null56 }.map { (key, value) ->57 "$key:\t$value"58 }.joinToString("\n|\t", "\t")59 is Collection<*> -> obj.joinToString("\n|\t", "\t")60 else -> obj ?: ""61 }62 }63 |#end::$relation-$tagName-${counters[relation]}[]64 """.trimMargin()65 )66}67/**68 * AsciiDoc preRequest aspect definitions69 *70 * This Map defines the aspect making functions for different parts of [Link] object.71 *72 * The maker for [PRE_PARTS.REL] keeps track of similar requests and assigns unique number to make an AsciiDoc tag unique.73 * If this aspect won't be included in an aspect chain the [null] will be used instead of numbers and all segments74 * of AsciiDoc will have identical tags. It is recommended to always include [PRE_PARTS.REL] aspect even if the75 * corresponding segment won't be used in the final documentation.76 *77 *78 */79private val preADocTagFormatter = mapOf<ReportPart, (Link, (String) -> Unit) -> Link>(80 ReportPart.REL to { link, reporter ->81 // Assign next available number to make a unique AsciiDoc tag82 relation = link.rel?.apply {83 counters[this] = counters[this]?.let {84 it + 185 } ?: 186 }87 formatTag("ref", link.rel, reporter)88 link89 },90 ReportPart.LINK to { link, reporter ->91 formatTag("link", link.toMap(), reporter)92 link93 },94 ReportPart.URI to { link, reporter ->95 formatTag("URI", link.href, reporter)96 link97 },98 ReportPart.NAME to { link, reporter ->99 formatTag("name", link.name, reporter)100 link101 },102 ReportPart.TITLE to { link, reporter ->103 formatTag("title", link.title, reporter)104 link105 },106 ReportPart.TYPE to { link, reporter ->107 formatTag("type", link.type, reporter)108 link109 }110)111/**112 * AsciiDoc postRequest aspect definitions113 *114 * This Map defines the aspect making functions for different parts of [Answer] object.115 *116 */117private val postADocTagFormatter = mapOf<ReportPart, (Answer, (String) -> Unit) -> Unit>(118 ReportPart.URL to { answer, reporter ->119 formatTag("URL", answer.response.url.toString(), reporter)120 },121 ReportPart.CURL to { answer, reporter ->122 formatTag(123 "curl", answer.request.cUrlString()124 .replace(" -H", "\\\n -H")125 .replace(Regex(" (https?://.*)"), "\\\\\n \"$1\""), reporter126 )127 },128 ReportPart.HEADERS_OUT to { answer, reporter ->129 formatTag("headerOut", answer.request.headers, reporter)130 },131 ReportPart.COOKIES_OUT to { answer, reporter ->132 formatTag("cookieOut", answer.request["Set-Cookies"], reporter)133 },134 ReportPart.BODY_OUT to { answer, reporter ->135 if (answer.request.method in setOf(136 Method.POST,137 Method.PUT,138 Method.PATCH139 ) && !answer.request.body.isConsumed()140 ) {141 formatTag(142 "bodyOut",143 if (answer.request.body.isConsumed()) {144 "Length of the sent Body: ${answer.request.body.length}"145 } else {146 if (answer.request.header(Headers.CONTENT_TYPE).any { it.contains("json") }) {147 jackson.writerWithDefaultPrettyPrinter().writeValueAsString(answer.body?.invoke())148 } else {149 answer.request.body.asString(null)150 }151 }, reporter152 )153 } else {154 formatTag("bodyOut", "*** Cannot report body sent out ***", reporter)155 }156 },157 ReportPart.STATUS to { answer, reporter ->158 formatTag("status", "${answer.status.code} (${answer.status})", reporter)159 },160 ReportPart.HEADERS_IN to { answer, reporter ->161 formatTag("headersIn", answer.response.headers, reporter)162 },163 ReportPart.COOKIES_IN to { answer, reporter ->164 formatTag("cookiesIn", answer.response["Cookies"], reporter)165 },166 ReportPart.BODY_IN to { answer, reporter ->167 formatTag(168 "bodyIn",169 when (answer.status.code) {170 HttpStatus.FOUND.code -> "Redirection to: ${answer.response.header("Location").first()}"171 else ->172 if (answer.response.header(Headers.CONTENT_TYPE).any { it.contains("json") }) {173 jackson.writerWithDefaultPrettyPrinter().writeValueAsString(answer.body?.invoke())174 } else {175 val head = min(answer.response.contentLength, UNSTRUCTURED_HEAD_LENGTH)176 """ (length: ${answer.response.contentLength})177 |${String(answer.response.data).substring(0, head.toInt())}178 """.trimMargin()179 }180 }, reporter181 )182 }183)184/**185 * Factory function to create an aspect function to be called before sending HTTP request.186 *187 * The aspect created by this factory will call @reporter function for the string generated by the function in the map.188 * The function in the map formatting the corresponding part of the Link as an AsciiDocument tag and @reporter189 * will write that text into the stream, which may be associated with file or console.190 *191 * @param reporter -- function to record the formatted tag String192 * @param parts -- a vararg array of the parts to report on193 * @param aspect -- another aspect to chain to after executing this194 */195fun makePreADocTagAspect(reporter: (String) -> Unit, vararg parts: ReportPart, aspect: Aspect? = null): Aspect {196 return makePreReporterAspect(reporter, preADocTagFormatter, *parts, aspect = aspect)197}198/**199 * Factory function to create an aspect function to be called after sending HTTP request.200 *201 * The aspect created by this factory will call @reporter function for the string generated by the function in the map.202 * The function in the map formatting the corresponding part of the Answer as an AsciiDocument tag and @reporter203 * will write that text into the stream, which may be associated with file or console.204 *205 * @param reporter -- function to record the formatted tag String206 * @param parts -- a vararg array of the parts to report on207 * @param aspect -- another aspect to chain to after executing this208 */209fun makePostADocTagAspect(reporter: (String) -> Unit, vararg parts: ReportPart, aspect: Aspect? = null): Aspect {210 return makePostReporterAspect(reporter, postADocTagFormatter, *parts, aspect = aspect)211}...

Full Screen

Full Screen

LoggerAspect.kt

Source:LoggerAspect.kt Github

copy

Full Screen

1package hal.spel.aspect2import com.fasterxml.jackson.databind.ObjectMapper3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.core.Method5import com.github.kittinunf.fuel.core.extensions.cUrlString6import hal.spel.Answer7import hal.spel.Link8import io.micronaut.http.HttpStatus9import kotlin.math.min10const val UNSTRUCTURED_HEAD_LENGTH = 100L11private val jackson = ObjectMapper()12/**13 * Reports the parts of the request and response in the log.14 *15 * Using this class the client application can log all HTTP requests/responses.16 *17 * Different instances of this class can log at different level their own set of HTTP requests/responses parts.18 *19 * For example:20 * <code>21 * LoggerFormatter(logger::info, ReportPart.REL, ReportPart.status22 * , followed = LoggerFormatter(logger::debug, ReportPart.URL, ReportPart.HEADERS_OUT)23 * )24 * </code>25 *26 * @param reporter -- the simple function to log the logging message.27 * @param parts -- the vararg of parts to include as tags28 * @param followed -- the AspectFormatter to link in the chain.29 * The Aspect generated by this Formatter will pass control to the aspect generated by this parameter30 */31class LoggerFormatter(32 private val reporter: (String) -> Unit,33 vararg val parts: ReportPart,34 followed: AspectFormatter? = null35) : AspectFormatter(followed) {36 private val loggerFormatter: Map<ReportPart, Pair<LinkFun?, AnswerFun?>> =37 mutableMapOf<ReportPart, Pair<LinkFun?, AnswerFun?>>().also {38 ReportPart.values().forEach { part ->39 it[part] = Pair<LinkFun?, AnswerFun?>({40 preLoggerFormatter[part]?.invoke(this, reporter)41 this42 }, {43 postLoggerFormatter[part]?.invoke(it, reporter)44 })45 }46 }47 override fun makeAspect(aspect: Aspect?): Aspect {48 return makeReporterAspect(loggerFormatter, *parts, aspect = super.makeAspect(aspect))49 }50}51private val preLoggerFormatter = mapOf<ReportPart, (Link, (String) -> Unit) -> Link>(52 ReportPart.REL to { link, reporter ->53 reporter(">>> ${link.rel} <<<")54 link55 },56 ReportPart.LINK to { link, reporter ->57 reporter(58 if (link.name.isNullOrBlank()) {59 "Link href: ${link.href}"60 } else {61 "Link name: ${link.name} (${link.href})"62 }63 )64 link65 },66 ReportPart.URI to { link, reporter -> reporter("URL: ${link.href}"); link },67 ReportPart.NAME to { link, reporter -> reporter("Named: ${link.name}"); link },68 ReportPart.TITLE to { link, reporter -> reporter("Titled: ${link.title}"); link },69 ReportPart.TYPE to { link, reporter -> reporter("Accept: ${link.type}"); link }70)71private val postLoggerFormatter = mapOf<ReportPart, (Answer, (String) -> Unit) -> Unit>(72 ReportPart.URL to { answer, reporter -> reporter("Resource Location: ${answer.response.url}") },73 ReportPart.CURL to { answer, reporter ->74 if (!(answer.request.method in setOf(75 Method.POST,76 Method.PUT,77 Method.PATCH78 ) && answer.request.body.isConsumed())79 ) {80 reporter("$> ${answer.request.cUrlString()}")81 } else {82 reporter("*** Cannot report curl ***")83 }84 },85 ReportPart.HEADERS_OUT to { answer, reporter ->86 reporter(87 "Header sent: ${88 answer.request.headers.map { (key, value) ->89 "\t$key:\t${value.joinToString("\n\t\t")}"90 }.joinToString("\n", "\n")91 }"92 )93 },94 ReportPart.COOKIES_OUT to { answer, reporter ->95 reporter("Cookies sent: ${answer.request["Set-Cookies"].joinToString("\n\t", "\n\t")}")96 },97 ReportPart.BODY_OUT to { answer, reporter ->98 if (answer.request.method in setOf(99 Method.POST,100 Method.PUT,101 Method.PATCH102 ) && !answer.request.body.isConsumed()103 ) {104 reporter(105 if (answer.request.body.isConsumed()) {106 "Length of the sent Body: ${answer.request.body.length}"107 } else {108 "Body sent:\n${109 if (answer.request.header(Headers.CONTENT_TYPE).any { it.contains("json") }) {110 jackson.writerWithDefaultPrettyPrinter().writeValueAsString(answer.body?.invoke())111 } else {112 answer.request.body.asString(null)113 }114 }"115 }116 )117 } else {118 reporter("*** Cannot report body sent ***")119 }120 },121 ReportPart.STATUS to { answer, reporter -> reporter("Status: ${answer.status.code} (${answer.status})") },122 ReportPart.HEADERS_IN to { answer, reporter ->123 reporter(124 "Headers received: ${125 answer.response.headers.map { (key, value) ->126 "\t$key:\t${value.joinToString("\n\t\t")}"127 }.joinToString("\n", "\n")128 }"129 )130 },131 ReportPart.COOKIES_IN to { answer, reporter ->132 reporter("Cookies received: ${answer.response["Cookies"].joinToString("\n\t", "\n\t")}")133 },134 ReportPart.BODY_IN to { answer, reporter ->135 reporter(136 "Body received:${137 when (answer.status.code) {138 HttpStatus.FOUND.code -> "Redirection to: ${answer.response.header("Location").first()}"139 else ->140 if (answer.response.header(Headers.CONTENT_TYPE).any { it.contains("json") }) {141 "\n${jackson.writerWithDefaultPrettyPrinter().writeValueAsString(answer.body?.invoke())}"142 } else {143 val head = min(answer.response.contentLength, UNSTRUCTURED_HEAD_LENGTH)144 " (length: ${answer.response.contentLength})\n${145 String(answer.response.data).substring(146 0,147 head.toInt()148 )149 }"150 }151 }152 }"153 )154 }155)156/**157 * Factory function to create an aspect function to be called before sending HTTP request.158 *159 * The aspect created by this factory will call @reporter function for the string generated by the function in the map.160 * The function in the map formatting the corresponding part of the Link as an message for logger and @reporter161 * will call logger method with some level to log that message.162 *163 * @param reporter -- function to record the formatted tag String164 * @param parts -- a vararg array of the parts to report on165 * @param aspect -- another aspect to chain to after executing this166 */167fun makePreLoggerAspect(reporter: (String) -> Unit, vararg parts: ReportPart, aspect: Aspect? = null): Aspect {168 return makePreReporterAspect(reporter, preLoggerFormatter, *parts, aspect = aspect)169}170/**171 * Factory function to create an aspect function to be called after sending HTTP request.172 *173 * The aspect created by this factory will call @reporter function for the string generated by the function in the map.174 * The function in the map formatting the corresponding part of the Answer as an message for logger and @reporter175 * will call logger method with some level to log that message.176 *177 * @param reporter -- function to record the formatted tag String178 * @param parts -- a vararg array of the parts to report on179 * @param aspect -- another aspect to chain to after executing this180 */181fun makePostLoggerAspect(reporter: (String) -> Unit, vararg parts: ReportPart, aspect: Aspect? = null): Aspect {182 return makePostReporterAspect(reporter, postLoggerFormatter, *parts, aspect = aspect)183}...

Full Screen

Full Screen

FormattingTest.kt

Source:FormattingTest.kt Github

copy

Full Screen

1package com.github.kittinunf.fuel.core.extensions2import com.github.kittinunf.fuel.core.requests.DefaultRequest3import com.github.kittinunf.fuel.core.Headers4import com.github.kittinunf.fuel.core.Method5import org.hamcrest.CoreMatchers6import org.hamcrest.MatcherAssert7import org.junit.Test8import java.net.URL9class FormattingTest {10 @Test11 fun httpGetCurlString() {12 val request = DefaultRequest(13 method = Method.GET,14 url = URL("http://httpbin.org/get"),15 headers = Headers.from("Authentication" to "Bearer xxx"),16 parameters = listOf("foo" to "xxx")17 )18 MatcherAssert.assertThat(request.cUrlString(), CoreMatchers.equalTo("curl -i -H \"Authentication:Bearer xxx\" http://httpbin.org/get"))19 }20 @Test21 fun httpPostCurlString() {22 val request = DefaultRequest(23 method = Method.POST,24 url = URL("http://httpbin.org/post"),25 headers = Headers.from("Authentication" to "Bearer xxx"),26 parameters = listOf("foo" to "xxx")27 )28 MatcherAssert.assertThat(request.cUrlString(), CoreMatchers.equalTo("curl -i -X POST -H \"Authentication:Bearer xxx\" http://httpbin.org/post"))29 }30 @Test31 fun httpStringWithOutParams() {32 val request = DefaultRequest(33 Method.GET,34 url = URL("http://httpbin.org/post"),35 headers = Headers.from("Content-Type" to "text/html")36 )37 MatcherAssert.assertThat(request.httpString(), CoreMatchers.startsWith("GET http"))38 MatcherAssert.assertThat(request.httpString(), CoreMatchers.containsString("Content-Type"))39 }40 @Test41 fun httpStringWithParams() {42 val request = DefaultRequest(43 Method.POST,44 url = URL("http://httpbin.org/post"),45 headers = Headers.from("Content-Type" to "text/html"),46 parameters = listOf("foo" to "xxx")47 ).body("it's a body")48 MatcherAssert.assertThat(request.httpString(), CoreMatchers.startsWith("POST http"))49 MatcherAssert.assertThat(request.httpString(), CoreMatchers.containsString("Content-Type"))50 MatcherAssert.assertThat(request.httpString(), CoreMatchers.containsString("body"))51 }52}...

Full Screen

Full Screen

Request.cUrlString

Using AI Code Generation

copy

Full Screen

1val (data, error) = result2println(request.cUrlString())3}4val (data, error) = result5println(request.cUrlString())6}7val (data, error) = result8println(request.cUrlString())9}10val (data, error) = result11println(request.cUrlString())12}13val (data, error) = result14println(request.cUrlString())15}16val (data, error) = result17println(request.cUrlString())18}19val (data, error) = result20println(request.cUrlString())21}22val (data, error) = result23println(request.cUrlString())24}

Full Screen

Full Screen

Request.cUrlString

Using AI Code Generation

copy

Full Screen

1val (data, error) = result2when (result) {3is Result.Success -> {4println(data)5}6is Result.Failure -> {7println(error)8}9}10}11val (data, error) = result12when (result) {13is Result.Success -> {14println(data)15}16is Result.Failure -> {17println(error)18}19}20}21val (data, error) = result22when (result) {23is Result.Success -> {24println(data)25}26is Result.Failure -> {27println(error)28}29}30}31val (data, error) = result32when (result) {33is Result.Success -> {34println(data)35}36is Result.Failure -> {37println(error)38}39}40}41val (data, error) = result42when (result) {43is Result.Success -> {44println(data)45}46is Result.Failure -> {47println(error)48}49}50}51val (data, error) = result52when (result) {53is Result.Success -> {54println(data)55}56is Result.Failure -> {57println(error)58}59}60}61val (data, error) = result

Full Screen

Full Screen

Request.cUrlString

Using AI Code Generation

copy

Full Screen

1val (request, response, result) = url.httpGet().responseString()2val curlString = request.cUrlString()3println(curlString)4val (request, response, result) = url.httpGet().responseString()5val curlString = request.cUrlString()6println(curlString)7val (request, response, result) = url.httpGet().responseString()8val curlString = request.cUrlString()9println(curlString)10val (request, response, result) = url.httpGet().responseString()11val curlString = request.cUrlString()12println(curlString)13val (request, response, result) = url.httpGet().responseString()14val curlString = request.cUrlString()15println(curlString)

Full Screen

Full Screen

Request.cUrlString

Using AI Code Generation

copy

Full Screen

1request.cUrlString()2request.cUrlString()3request.cUrlString()4request.cUrlString()5request.cUrlString()6request.cUrlString()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Fuel automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Formatting

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful