Best Hikaku code snippet using de.codecentric.hikaku.Hikaku
SpringConverter.kt
Source:SpringConverter.kt
1package de.codecentric.hikaku.converters.spring2import de.codecentric.hikaku.SupportedFeatures3import de.codecentric.hikaku.SupportedFeatures.Feature4import de.codecentric.hikaku.converters.AbstractEndpointConverter5import de.codecentric.hikaku.converters.spring.extensions.*6import de.codecentric.hikaku.endpoints.Endpoint7import de.codecentric.hikaku.endpoints.HttpMethod8import de.codecentric.hikaku.endpoints.HttpMethod.*9import org.springframework.context.ApplicationContext10import org.springframework.web.method.HandlerMethod11import org.springframework.web.servlet.mvc.method.RequestMappingInfo12import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping13/**14 * Extracts and converts [Endpoint]s from a spring [ApplicationContext].15 * @param applicationContext Spring application context16 */17class SpringConverter(private val applicationContext: ApplicationContext) : AbstractEndpointConverter() {18 override val supportedFeatures = SupportedFeatures(19 Feature.QueryParameters,20 Feature.PathParameters,21 Feature.HeaderParameters,22 Feature.MatrixParameters,23 Feature.Produces,24 Feature.Consumes,25 Feature.Deprecation26 )27 override fun convert(): Set<Endpoint> {28 return applicationContext.getBean(RequestMappingHandlerMapping::class.java)29 .handlerMethods30 .flatMap { mappingEntry ->31 mappingEntry.key.paths().flatMap { path ->32 createEndpoints(path, mappingEntry)33 }34 }35 .toSet()36 }37 private fun createEndpoints(path: String, mappingEntry: Map.Entry<RequestMappingInfo, HandlerMethod>): Set<Endpoint> {38 val httpMethods = extractAvailableHttpMethods(mappingEntry)39 val cleanedPath = removeRegex(path)40 val endpoints = httpMethods.map {41 Endpoint(42 path = cleanedPath,43 httpMethod = it,44 queryParameters = mappingEntry.value.hikakuQueryParameters(),45 pathParameters = mappingEntry.value.hikakuPathParameters(),46 headerParameters = mappingEntry.value.hikakuHeaderParameters(),47 matrixParameters = mappingEntry.value.hikakuMatrixParameters(),48 produces = mappingEntry.produces(),49 consumes = mappingEntry.consumes(),50 deprecated = mappingEntry.isEndpointDeprecated()51 )52 }53 .toMutableSet()54 // Spring always adds an OPTIONS http method if it does not exist, but without query and path parameter55 if (!httpMethods.contains(OPTIONS)) {56 endpoints.add(57 Endpoint(58 path = cleanedPath,59 httpMethod = OPTIONS,60 deprecated = mappingEntry.isEndpointDeprecated()61 )62 )63 }64 return endpoints65 }66 private fun removeRegex(path: String): String {67 return path.split('/').joinToString("/") { pathSegment ->68 pathSegment.let {69 when {70 it.contains(':') -> it.replace(Regex(":.*"), "}")71 else -> it72 }73 }74 }75 }76 private fun extractAvailableHttpMethods(mappingEntry: Map.Entry<RequestMappingInfo, HandlerMethod>): Set<HttpMethod> {77 val httpMethods = mappingEntry.key.hikakuHttpMethods()78 // Spring adds all http methods except for TRACE if no http method has been set explicitly79 // OPTIONS is a special case. If it's not added manually it has to be added without any path or query parameters80 return if (httpMethods.isEmpty()) {81 HttpMethod.values()82 .filterNot { it == TRACE }83 .filterNot { it == OPTIONS }84 .toSet()85 } else {86 // Spring always adds a HEAD http method87 httpMethods + HEAD88 }89 }90 companion object {91 @JvmField92 val IGNORE_ERROR_ENDPOINT: (Endpoint) -> Boolean = { endpoint -> endpoint.path == "/error" }93 }94}...
OpenApiConverter.kt
Source:OpenApiConverter.kt
1package de.codecentric.hikaku.converters.openapi2import de.codecentric.hikaku.SupportedFeatures3import de.codecentric.hikaku.SupportedFeatures.Feature4import de.codecentric.hikaku.converters.AbstractEndpointConverter5import de.codecentric.hikaku.converters.EndpointConverterException6import de.codecentric.hikaku.converters.openapi.extensions.httpMethods7import de.codecentric.hikaku.converters.openapi.extractors.*8import de.codecentric.hikaku.endpoints.Endpoint9import de.codecentric.hikaku.endpoints.HttpMethod10import de.codecentric.hikaku.extensions.checkFileValidity11import io.swagger.v3.oas.models.Operation12import io.swagger.v3.parser.OpenAPIV3Parser13import java.io.File14import java.nio.charset.Charset15import java.nio.charset.StandardCharsets.UTF_816import java.nio.file.Files.readAllLines17import java.nio.file.Path18/**19 * Extracts and converts [Endpoint]s from OpenAPI 3.0.X document. Either a *.yaml*, *.yml* or a *.json* file.20 */21class OpenApiConverter private constructor(private val specificationContent: String) : AbstractEndpointConverter() {22 @JvmOverloads23 constructor(openApiSpecification: File, charset: Charset = UTF_8): this(openApiSpecification.toPath(), charset)24 @JvmOverloads25 constructor(openApiSpecification: Path, charset: Charset = UTF_8): this(readFileContent(openApiSpecification, charset))26 override val supportedFeatures = SupportedFeatures(27 Feature.QueryParameters,28 Feature.PathParameters,29 Feature.HeaderParameters,30 Feature.Produces,31 Feature.Consumes,32 Feature.Deprecation33 )34 override fun convert(): Set<Endpoint> {35 try {36 return parseOpenApi()37 } catch (throwable: Throwable) {38 throw EndpointConverterException(throwable)39 }40 }41 private fun parseOpenApi(): Set<Endpoint> {42 val swaggerParseResult = OpenAPIV3Parser().readContents(specificationContent, null, null)43 val openApi = swaggerParseResult.openAPI ?: throw openApiParseException(swaggerParseResult.messages)44 val extractConsumesMediaTypes = ConsumesExtractor(openApi)45 val extractProduceMediaTypes = ProducesExtractor(openApi)46 val extractQueryParameters = QueryParameterExtractor(openApi)47 val extractHeaderParameters = HeaderParameterExtractor(openApi)48 val extractPathParameters = PathParameterExtractor(openApi)49 return openApi.paths.flatMap { (path, pathItem) ->50 val commonQueryParameters = extractQueryParameters(pathItem.parameters)51 val commonPathParameters = extractPathParameters(pathItem.parameters)52 val commonHeaderParameters = extractHeaderParameters(pathItem.parameters)53 pathItem.httpMethods().map { (httpMethod: HttpMethod, operation: Operation?) ->54 Endpoint(55 path = path,56 httpMethod = httpMethod,57 queryParameters = commonQueryParameters.union(extractQueryParameters(operation?.parameters)),58 pathParameters = commonPathParameters.union(extractPathParameters(operation?.parameters)),59 headerParameters = commonHeaderParameters.union(extractHeaderParameters(operation?.parameters)),60 consumes = extractConsumesMediaTypes(operation),61 produces = extractProduceMediaTypes(operation),62 deprecated = operation?.deprecated ?: false63 )64 }65 }66 .toSet()67 }68}69private fun readFileContent(openApiSpecification: Path, charset: Charset): String {70 try {71 openApiSpecification.checkFileValidity(".json", ".yaml", ".yml")72 } catch (throwable: Throwable) {73 throw EndpointConverterException(throwable)74 }75 val fileContent = readAllLines(openApiSpecification, charset).joinToString("\n")76 if (fileContent.isBlank()) {77 throw EndpointConverterException("Given OpenAPI file is blank.")78 }79 return fileContent80}81private fun openApiParseException(reasons: List<String>)82 = EndpointConverterException("Failed to parse OpenAPI spec. Reasons:\n${reasons.joinToString("\n")}")...
Hikaku.kt
Source:Hikaku.kt
...10 * @param specification An [EndpointConverter] which converts your specification for the equality check.11 * @param implementation An [EndpointConverter] which converts your implementation for the equality check.12 * @param config The configuration is optional. It lets you control the matching.13 */14class Hikaku(15 private val specification: EndpointConverter,16 private val implementation: EndpointConverter,17 var config: HikakuConfig = HikakuConfig()18) {19 private val supportedFeatures = SupportedFeatures(specification.supportedFeatures.intersect(implementation.supportedFeatures))20 private fun Set<Endpoint>.applyConfig(config: HikakuConfig): List<Endpoint> {21 val result = this.toMutableList()22 config.filters.forEach {23 result.removeAll(this.filter(it))24 }25 return result26 }27 private fun reportResult(matchResult: MatchResult) {28 config.reporters.forEach { it.report(matchResult) }29 }30 /**31 * Calling this method creates a [MatchResult]. It will be passed to the [Reporter] defined in the configuration and call [assert] with the end result.32 */33 fun match() {34 val specificationEndpoints = specification...
RamlConverter.kt
Source:RamlConverter.kt
1package de.codecentric.hikaku.converters.raml2import de.codecentric.hikaku.SupportedFeatures3import de.codecentric.hikaku.SupportedFeatures.Feature4import de.codecentric.hikaku.converters.AbstractEndpointConverter5import de.codecentric.hikaku.converters.EndpointConverterException6import de.codecentric.hikaku.converters.raml.extensions.*7import de.codecentric.hikaku.endpoints.Endpoint8import de.codecentric.hikaku.extensions.checkFileValidity9import org.raml.v2.api.RamlModelBuilder10import org.raml.v2.api.RamlModelResult11import org.raml.v2.api.model.v10.resources.Resource12import java.io.File13import java.nio.file.Path14class RamlConverter(private val ramlSpecification: File) : AbstractEndpointConverter() {15 constructor(ramlSpecification: Path) : this(ramlSpecification.toFile())16 override val supportedFeatures = SupportedFeatures(17 Feature.QueryParameters,18 Feature.PathParameters,19 Feature.HeaderParameters,20 Feature.Produces,21 Feature.Consumes,22 Feature.Deprecation23 )24 override fun convert(): Set<Endpoint> {25 val ramlParserResult: RamlModelResult?26 try {27 ramlSpecification.checkFileValidity(".raml")28 ramlParserResult = RamlModelBuilder().buildApi(ramlSpecification)29 } catch(throwable: Throwable) {30 throw EndpointConverterException(throwable)31 }32 if (ramlParserResult.isVersion08) {33 throw EndpointConverterException("Unsupported RAML version")34 }35 if (ramlParserResult.hasErrors()) {36 throw EndpointConverterException(ramlParserResult.validationResults.joinToString("\n"))37 }38 return ramlParserResult.apiV10?.resources()?.let { resourceList ->39 resourceList.flatMap { findEndpoints(it) }40 }41 .orEmpty()42 .toSet()43 }44 private fun findEndpoints(resource: Resource): List<Endpoint> {45 val endpoints = mutableListOf<Endpoint>()46 if (resource.resources().isNotEmpty()) {47 endpoints += resource.resources().flatMap {48 return@flatMap findEndpoints(it)49 }50 }51 if (resource.methods().isNotEmpty()) {52 endpoints += resource.methods().map {53 Endpoint(54 path = resource.resourcePath(),55 httpMethod = it.hikakuHttpMethod(),56 queryParameters = it.hikakuQueryParameters(),57 pathParameters = it.resource()?.hikakuPathParameters().orEmpty(),58 headerParameters = it?.hikakuHeaderParameters().orEmpty(),59 consumes = it.requestMediaTypes(),60 produces = it.responseMediaTypes(),61 deprecated = it.isEndpointDeprecated()62 )63 }64 }65 return endpoints66 }67}...
MethodExtensions.kt
Source:MethodExtensions.kt
1package de.codecentric.hikaku.converters.raml.extensions2import de.codecentric.hikaku.endpoints.HeaderParameter3import de.codecentric.hikaku.endpoints.HttpMethod4import de.codecentric.hikaku.endpoints.QueryParameter5import org.raml.v2.api.model.v10.methods.Method6internal fun Method.hikakuHttpMethod() = HttpMethod.valueOf(this.method().uppercase())7internal fun Method.hikakuQueryParameters(): Set<QueryParameter> {8 return this.queryParameters()9 .map {10 QueryParameter(it.name(), it.required())11 }12 .toSet()13}14internal fun Method.hikakuHeaderParameters(): Set<HeaderParameter> {15 return this.headers()16 .map {17 HeaderParameter(it.name(), it.required())18 }19 .toSet()20}21internal fun Method.requestMediaTypes(): Set<String> {22 return this.body().map {23 it.name()24 }25 .toSet()26}27internal fun Method.responseMediaTypes(): Set<String> {28 return this.responses().flatMap {response ->29 response.body().map { it.name() }30 }31 .toSet()32}33internal fun Method.isEndpointDeprecated() =34 this.annotations().any { i -> i.annotation().name() == "deprecated" }35 || checkNotNull(this.resource()).annotations().any { i -> i.annotation().name() == "deprecated" }...
PathItemExtensions.kt
Source:PathItemExtensions.kt
1package de.codecentric.hikaku.converters.openapi.extensions2import io.swagger.v3.oas.models.Operation3import io.swagger.v3.oas.models.PathItem4import de.codecentric.hikaku.endpoints.HttpMethod5import de.codecentric.hikaku.endpoints.HttpMethod.GET6import de.codecentric.hikaku.endpoints.HttpMethod.POST7import de.codecentric.hikaku.endpoints.HttpMethod.PATCH8import de.codecentric.hikaku.endpoints.HttpMethod.DELETE9import de.codecentric.hikaku.endpoints.HttpMethod.PUT10import de.codecentric.hikaku.endpoints.HttpMethod.OPTIONS11import de.codecentric.hikaku.endpoints.HttpMethod.HEAD12import de.codecentric.hikaku.endpoints.HttpMethod.TRACE13internal fun PathItem.httpMethods() = mapOf<HttpMethod, Operation?>(14 GET to get,15 POST to post,16 PATCH to patch,17 DELETE to delete,18 PUT to put,19 OPTIONS to options,20 HEAD to head,21 TRACE to trace22).filterValues { it != null }...
HikakuConfig.kt
Source:HikakuConfig.kt
...3import de.codecentric.hikaku.reporters.CommandLineReporter4import de.codecentric.hikaku.reporters.MatchResult5import de.codecentric.hikaku.reporters.Reporter6/**7 * Configuration for [Hikaku] class. It lets you partially control the matching process.8 * @param reporters The [MatchResult] will be passed to one or many [Reporter] before the test either fails or succeeds. Default is a [CommandLineReporter] that prints the results to [System.out].9 * @param filters Filtering rule: [Endpoint]s matching the predicate will be ignored.10 */11data class HikakuConfig12@JvmOverloads constructor(13 val reporters: List<Reporter> = listOf(CommandLineReporter()),14 val filters: List<(Endpoint) -> Boolean> = emptyList()15)...
EndpointConverter.kt
Source:EndpointConverter.kt
1package de.codecentric.hikaku.converters2import de.codecentric.hikaku.SupportedFeatures3import de.codecentric.hikaku.SupportedFeatures.Feature4import de.codecentric.hikaku.endpoints.Endpoint5/**6 * Converts either a specific type of specification or implementation into the internal hikaku format in order to be able to perform a matching on the extracted components.7 */8interface EndpointConverter {9 /** Result of the conversion containing all extracted [Endpoint]s. */10 val conversionResult: Set<Endpoint>11 /** List of [Feature]s that this [EndpointConverter]s supports. */12 val supportedFeatures: SupportedFeatures13}...
Hikaku
Using AI Code Generation
1+import de.codecentric.hikaku.converters.jaxrs.JaxRsConverter2+import de.codecentric.hikaku.endpoints.Endpoint3+import de.codecentric.hikaku.endpoints.Path4+import de.codecentric.hikaku.endpoints.QueryParameter5+import de.codecentric.hikaku.endpoints.http.*6+import de.codecentric.hikaku.converters.spring.data.SpringDataRestConverter7+import de.codecentric.hikaku.converters.spring.mvc.SpringMvcConverter8+import de.codecentric.hikaku.converters.spring.webflux.SpringWebFluxConverter9+import de.codecentric.hikaku.endpoints.PathParameter10+import de.codecentric.hikaku.endpoints.Produces11+import de.codecentric.hikaku.endpoints.RequestBody12+import de.codecentric.hikaku.endpoints.http.HttpMethod.*13+import de.codecentric.hikaku.endpoints.http.HttpStatus.*14+import de.codecentric.hikaku.endpoints.multipart.MultipartFile15+import de.codecentric.hikaku.endpoints.multipart.Part16+import de.codecentric.hikaku.endpoints.multipart.PartParameter17+import de.codecentric.hikaku.endpoints.multipart.PartType18+import de.codecentric.hikaku.endpoints.multipart.PartType.*19+import de.codecentric.hikaku.e
Hikaku
Using AI Code Generation
1@Hikaku(converter = OpenApiConverter::class)2class ContractTest {3 fun `check if api contract matches implementation`() {4 val specification = Specification(5 endpoints = listOf(6 Endpoint(7 path = "/api/v1/beer/{beerId}",8 response = Response(9 body = Body(10{11}12 val implementation = Implementation(13 endpoints = listOf(14 Endpoint(15 path = "/api/v1/beer/{beerId}",16 response = Response(17 body = Body(18{19}20 val result = specification.compare(implementation)21 assertTrue(result.contractsMatch())22 }23}
Hikaku
Using AI Code Generation
1 val converter = OpenApiConverter(OpenApiConverterConfig())2 val converted = converter.convert(specification)3 val hikaku = Hikaku(converted, converted)4 val result = hikaku.compare()5 println(result)6 }7}
Hikaku
Using AI Code Generation
1 Hikaku(2 ApiContract(3 Api(4 Endpoint(5 Headers(),6 ContentType("application/json"),7 Body(8 {9 }10 """.trimIndent()11 ).compareWith(12 ApiContract(13 Api(14 Endpoint(15 Headers(),16 ContentType("application/json"),17 Body(18 {19 }20 """.trimIndent()21 ).assertIsSatisfied()22 }23}
Hikaku
Using AI Code Generation
1 val hikaku = Hikaku(2 swaggerFile = Paths.get("swagger.json"),3 contract = Paths.get("contract.yaml")4 hikaku.execute()5 val report = hikaku.getReport()6 report.forEach { result ->7 println(result.httpMethod)8 println(result.path)9 println(result.statusCode)10 println(result.message)11 }12 }13}14plugins {15}16pluginManagement {17 repositories {18 mavenCentral()19 }20}21hikaku {22 swaggerFile = Paths.get("swagger.json")23 contract = Paths.get("contract.yaml")24}
Hikaku
Using AI Code Generation
1import de.codecentric.hikaku.converters.swagger.SwaggerConverter2import de.codecentric.hikaku.endpoints.Endpoint3import de.codecentric.hikaku.endpoints.PathParameter4import de.codecentric.hikaku.endpoints.QueryParameter5import de.codecentric.hikaku.endpoints.RequestBody6import de.codecentric.hikaku.endpoints.ResponseBody7import de.codecentric.hikaku.endpoints.mimeType8import de.codecentric.hikaku.endpoints.path9import de.codecentric.hikaku.endpoints.request10import de.codecentric.hikaku.endpoints.response11import de.codecentric.hikaku.endpoints.returns12import de.codecentric.hikaku.endpoints.version13import de.codecentric.hikaku.extensions.*14import de.codecentric.hikaku.transformers.*15import org.junit.jupiter.api.Test16import org.junit.jupiter.api.assertThrows17class BookApiTest {18 fun `compare specification`() {19 val specificationOne = setOf(20 Endpoint(21 path = path("/books"),22 request = request(23 produces = mimeType("application/json")24 response = response(25 body = ResponseBody(26 genericArguments = setOf(Book::class.java)27 Endpoint(28 path = path("/books"),29 request = request(30 consumes = mimeType("application/json"),31 produces = mimeType("application/json")32 response = response(33 body = ResponseBody(34 Endpoint(35 path = path("/books/{id}"),36 request = request(37 produces = mimeType("application/json"),38 parameters = setOf(PathParameter("id", "Long"))39 response = response(
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!