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

Swagger support #1236

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file modified build-local-docker-image.sh
100644 → 100755
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import io.specmatic.core.wsdl.parser.message.OPTIONAL_ATTRIBUTE_VALUE
import io.cucumber.messages.internal.com.fasterxml.jackson.databind.ObjectMapper
import io.cucumber.messages.types.Step
import io.ktor.util.reflect.*
import io.swagger.parser.OpenAPIParser
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.Operation
import io.swagger.v3.oas.models.PathItem
Expand All @@ -24,7 +25,6 @@ import io.swagger.v3.oas.models.parameters.*
import io.swagger.v3.oas.models.responses.ApiResponse
import io.swagger.v3.oas.models.responses.ApiResponses
import io.swagger.v3.oas.models.security.SecurityScheme
import io.swagger.v3.parser.OpenAPIV3Parser
import io.swagger.v3.parser.core.models.ParseOptions
import io.swagger.v3.parser.core.models.SwaggerParseResult
import java.io.File
Expand Down Expand Up @@ -83,11 +83,11 @@ class OpenApiSpecification(
}

fun getParsedOpenApi(openApiFilePath: String): OpenAPI {
return OpenAPIV3Parser().read(openApiFilePath, null, resolveExternalReferences())
return OpenAPIParser().readLocation(openApiFilePath, null, resolveExternalReferences()).openAPI
}

fun isParsable(openApiFilePath: String): Boolean {
return OpenAPIV3Parser().read(openApiFilePath, null, resolveExternalReferences()) != null
return OpenAPIParser().readLocation(openApiFilePath, null, resolveExternalReferences()) != null
}

fun fromYAML(
Expand All @@ -102,7 +102,7 @@ class OpenApiSpecification(
specmaticConfig: SpecmaticConfig = SpecmaticConfig()
): OpenApiSpecification {
val parseResult: SwaggerParseResult =
OpenAPIV3Parser().readContents(yamlContent, null, resolveExternalReferences(), openApiFilePath)
OpenAPIParser().readContents(yamlContent, null, resolveExternalReferences())
val parsedOpenApi: OpenAPI? = parseResult.openAPI

if (parsedOpenApi == null) {
Expand Down Expand Up @@ -1480,8 +1480,8 @@ class OpenApiSpecification(
emptyList()
else it.split("/")
}
val pathParamMap: Map<String, PathParameter> =
parameters.filterIsInstance<PathParameter>().associateBy {
val pathParamMap: Map<String, Parameter> =
parameters.filterIsInstance<Parameter>().filter { it.`in`?.lowercase() == "path" }.associateBy {
it.name
}

Expand Down
15 changes: 12 additions & 3 deletions core/src/main/kotlin/io/specmatic/stub/api.kt
Original file line number Diff line number Diff line change
Expand Up @@ -447,11 +447,20 @@ fun loadIfOpenAPISpecification(contractPathData: ContractPathData): Pair<String,
private fun recognizedExtensionButNotOpenAPI(contractPathData: ContractPathData) =
!hasOpenApiFileExtension(contractPathData.path) && File(contractPathData.path).extension in CONTRACT_EXTENSIONS

fun isOpenAPI(path: String): Boolean =
try {
fun isOpenAPI(path: String): Boolean {
val openAPI30 = try {
Yaml().load<MutableMap<String, Any?>>(File(path).reader()).contains("openapi")
} catch(e: Throwable) {
} catch (e: Throwable) {
logger.log(e, "Could not parse $path")
false
}

val swagger = try {
Yaml().load<MutableMap<String, Any?>>(File(path).reader()).contains("swagger")
} catch (e: Throwable) {
logger.log(e, "Could not parse $path")
false
}
return swagger || openAPI30
}

22 changes: 16 additions & 6 deletions core/src/test/kotlin/io/specmatic/conversions/OpenApiKtTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ Scenario: zero should return not found
Arguments.of("openapi/helloMultipartWithExamples.yaml", "input.txt"),
)
}

@JvmStatic
fun swaggerAndOpenAPI(): Stream<Arguments> {
return Stream.of(
Arguments.of("openapi"),
Arguments.of("swagger")
)
}
}

@Test
Expand Down Expand Up @@ -568,14 +576,15 @@ Background:
})
}

@Test
fun `should generate stub with non primitive open api data types`() {
@ParameterizedTest
@MethodSource("swaggerAndOpenAPI")
fun `should generate stub with non primitive open api data types`(specType: String) {
val feature = parseGherkinStringToFeature(
"""
Feature: Hello world

Background:
Given openapi openapi/petstore-expanded.yaml
Given openapi $specType/petstore-expanded.yaml
""".trimIndent(), sourceSpecPath
)

Expand Down Expand Up @@ -828,14 +837,15 @@ Background:
}
}

@Test
fun `should generate stub with http post and non primitive request and response data types`() {
@ParameterizedTest
@MethodSource("swaggerAndOpenAPI")
fun `should generate stub with http post and non primitive request and response data types`(specType: String) {
val feature = parseGherkinStringToFeature(
"""
Feature: Hello world

Background:
Given openapi openapi/petstore-expanded.yaml
Given openapi $specType/petstore-expanded.yaml
""".trimIndent(), sourceSpecPath
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8136,6 +8136,66 @@ components:
assertThat(results.success()).isTrue()
}

@Test
fun `parse Swagger 2 0`() {
val swaggerSpec = """
swagger: '2.0'
info:
version: '1.0.0'
title: Employee API
produces:
- application/json
paths:
/employee/{id}:
get:
summary: Get Employee by ID
parameters:
- name: id
in: path
required: true
type: integer
responses:
200:
description: Employee data
schema:
type: object
properties:
id:
type: integer
name:
type: string
department:
type: integer
404:
description: Employee not found
""".trimIndent()

val feature = OpenApiSpecification.fromYAML(swaggerSpec, "").toFeature()

val results = feature.executeTests(object : TestExecutor {
override fun execute(request: HttpRequest): HttpResponse {
val path = request.path!!
path.split("/").last().toInt()

return HttpResponse(200, body = parsedJSONObject("""{"id": 10, "name": "Jack", "department": 123}"""))
}

})

assertThat(results.success()).withFailMessage(results.report()).isTrue()

HttpStub(feature).use { stub ->
val request = HttpRequest("GET", "/employee/10")
val response = stub.client.execute(request)

assertThat(response.status).isEqualTo(200)
val jsonObjectValue = response.body as JSONObjectValue
assertThat(jsonObjectValue.findFirstChildByPath("id")).isInstanceOf(NumberValue::class.java)
assertThat(jsonObjectValue.findFirstChildByPath("name")).isInstanceOf(StringValue::class.java)
assertThat(jsonObjectValue.findFirstChildByPath("department")).isInstanceOf(NumberValue::class.java)
}
}

private fun ignoreButLogException(function: () -> OpenApiSpecification) {
try {
function()
Expand Down
142 changes: 142 additions & 0 deletions core/src/test/resources/swagger/petstore-expanded.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
swagger: "2.0"
info:
version: 1.0.0
title: Swagger Petstore
description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
termsOfService: http://swagger.io/terms/
contact:
name: Swagger API Team
email: [email protected]
url: http://swagger.io
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
host: petstore.swagger.io
basePath: /api
schemes:
- http
consumes:
- application/json
produces:
- application/json
paths:
/pets:
get:
description: |
Returns all pets from the system that the user has access to
operationId: findPets
parameters:
- name: tags
in: query
description: tags to filter by
required: false
type: array
collectionFormat: csv
items:
type: string
- name: limit
in: query
description: maximum number of results to return
required: false
type: integer
format: int32
responses:
"200":
description: pet response
schema:
type: array
items:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
post:
description: Creates a new pet in the store. Duplicates are allowed
operationId: addPet
parameters:
- name: pet
in: body
description: Pet to add to the store
required: true
schema:
$ref: '#/definitions/NewPet'
responses:
"200":
description: pet response
schema:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
/pets/{id}:
get:
description: Returns a user based on a single ID, if the user does not have access to the pet
operationId: find pet by id
parameters:
- name: id
in: path
description: ID of pet to fetch
required: true
type: integer
format: int64
responses:
"200":
description: pet response
schema:
$ref: '#/definitions/Pet'
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
delete:
description: deletes a single pet based on the ID supplied
operationId: deletePet
parameters:
- name: id
in: path
description: ID of pet to delete
required: true
type: integer
format: int64
responses:
"204":
description: pet deleted
default:
description: unexpected error
schema:
$ref: '#/definitions/Error'
definitions:
Pet:
allOf:
- $ref: '#/definitions/NewPet'
- required:
- id
type: "object"
properties:
id:
type: integer
format: int64

NewPet:
type: "object"
required:
- name
properties:
name:
type: string
tag:
type: string

Error:
type: "object"
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string