Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ plugins {
id("pl.allegro.tech.build.axion-release") version "1.9.2"
jacoco
`maven-publish`
id("org.jmailen.kotlinter") version "1.25.2" apply false
id("org.jmailen.kotlinter") version "3.3.0" apply false
id("com.github.kt3k.coveralls") version "2.8.2"
id("com.jfrog.bintray") version "1.8.4" apply false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ open class PostmanExtension(project: Project) : ApiSpecExtension(project) {
companion object {
const val name = "postman"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ open class PostmanTask : ApiSpecTask() {

override fun generateSpecification(resourceModels: List<ResourceModel>): String =
jacksonObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(
PostmanCollectionGenerator.generate(
resources = resourceModels,
title = title,
version = apiVersion,
baseUrl = baseUrl
)
PostmanCollectionGenerator.generate(
resources = resourceModels,
title = title,
version = apiVersion,
baseUrl = baseUrl
)
)

fun applyExtension(extension: PostmanExtension) {
Expand All @@ -39,4 +39,4 @@ open class PostmanTask : ApiSpecTask() {
apiVersion = extension.version
baseUrl = extension.baseUrl
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,33 +63,33 @@ abstract class ApiSpecTaskTest {
private fun Path.initializeGradleProperties() {
// jacoco agent configuration
resolve("gradle.properties").toFile()
.writeText(File("build/testkit/testkit-gradle.properties").readText())
.writeText(File("build/testkit/testkit-gradle.properties").readText())
}

protected fun whenPluginExecuted() {
result = GradleRunner.create()
.withProjectDir(testProjectDir.toFile())
.withArguments("--info", "--stacktrace", taskName)
.withPluginClasspath()
.withDebug(true)
.build()
.withProjectDir(testProjectDir.toFile())
.withArguments("--info", "--stacktrace", taskName)
.withPluginClasspath()
.withDebug(true)
.build()
}

protected fun outputFileContext(): DocumentContext =
JsonPath.parse(outputFolder.resolve("$outputFileNamePrefix.$format").readText().also { println(it) })
JsonPath.parse(outputFolder.resolve("$outputFileNamePrefix.$format").readText().also { println(it) })

fun baseBuildFile() = """
plugins {
id 'java'
id 'com.epages.restdocs-api-spec'
}

""".trimIndent()
""".trimIndent()

protected fun givenResourceSnippet() {
val operationDir = File(snippetsFolder, "some-operation").apply { mkdir() }
File(operationDir, "resource.json").writeText(
"""
"""
{
"operationId" : "product-get",
"summary" : null,
Expand Down Expand Up @@ -125,7 +125,7 @@ abstract class ApiSpecTaskTest {
protected fun givenPrivateResourceSnippet() {
val operationDir = File(snippetsFolder, "some-private-operation").apply { mkdir() }
File(operationDir, "resource.json").writeText(
"""
"""
{
"operationId" : "product-get-some",
"summary" : null,
Expand Down Expand Up @@ -176,13 +176,15 @@ abstract class ApiSpecTaskTest {

protected fun thenExpectedFileFound(expectedFile: String) {
BDDAssertions.then(outputFolder.resolve(expectedFile))
.describedAs("Output file not found '$expectedFile' - output dir contains ${Files.list(outputFolder.toPath()).map {
.describedAs(
"Output file not found '$expectedFile' - output dir contains ${Files.list(outputFolder.toPath()).map {
it.toFile().path
}.toList()}")
.exists()
}.toList()}"
)
.exists()
}

protected fun givenBuildFileWithoutApiSpecClosure() {
buildFile.writeText(baseBuildFile())
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,16 @@ class PostmanTaskTest : ApiSpecTaskTest() {
}

private fun givenBuildFileWithPostmanClosure() {
buildFile.writeText(baseBuildFile() + """
buildFile.writeText(
baseBuildFile() + """
postman {
title = '$title'
version = '$version'
baseUrl = '$baseUrl'
separatePublicApi = $separatePublicApi
outputFileNamePrefix = '$outputFileNamePrefix'
}
""".trimIndent())
""".trimIndent()
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ class RestdocsOpenApi3TaskTest : RestdocsOpenApiTaskTestBase() {
}

override fun givenBuildFileWithOpenApiClosure() {
givenBuildFileWithOpenApiClosure("servers",
givenBuildFileWithOpenApiClosure(
"servers",
"""[ {
url = 'http://some.api/api/{id}'
variables = [
Expand All @@ -87,11 +88,13 @@ class RestdocsOpenApi3TaskTest : RestdocsOpenApiTaskTestBase() {
]
]
}
]""".trimMargin())
]""".trimMargin()
)
}

private fun givenBuildFileWithOpenApiClosure(serverConfigurationFieldName: String, serversSection: String) {
buildFile.writeText(baseBuildFile() + """
buildFile.writeText(
baseBuildFile() + """
openapi3 {
$serverConfigurationFieldName = $serversSection
title = '$title'
Expand All @@ -100,11 +103,13 @@ class RestdocsOpenApi3TaskTest : RestdocsOpenApiTaskTestBase() {
separatePublicApi = $separatePublicApi
outputFileNamePrefix = '$outputFileNamePrefix'
}
""".trimIndent())
""".trimIndent()
)
}

override fun givenBuildFileWithOpenApiClosureAndSecurityDefinitions() {
buildFile.writeText(baseBuildFile() + """
buildFile.writeText(
baseBuildFile() + """
openapi3 {
servers = [ { url = "http://some.api" } ]
title = '$title'
Expand All @@ -121,7 +126,8 @@ class RestdocsOpenApi3TaskTest : RestdocsOpenApiTaskTestBase() {
scopeDescriptionsPropertiesFile = "scopeDescriptions.yaml"
}
}
""".trimIndent())
""".trimIndent()
)
}

override fun thenSecurityDefinitionsFoundInOutputFile() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ class RestdocsOpenApiTaskTest : RestdocsOpenApiTaskTestBase() {
override val taskName = "openapi"

override fun givenBuildFileWithOpenApiClosure() {
buildFile.writeText(baseBuildFile() + """
buildFile.writeText(
baseBuildFile() + """
openapi {
host = '$host'
basePath = '$basePath'
Expand All @@ -24,11 +25,13 @@ class RestdocsOpenApiTaskTest : RestdocsOpenApiTaskTestBase() {
separatePublicApi = $separatePublicApi
outputFileNamePrefix = '$outputFileNamePrefix'
}
""".trimIndent())
""".trimIndent()
)
}

override fun givenBuildFileWithOpenApiClosureAndSecurityDefinitions() {
buildFile.writeText(baseBuildFile() + """
buildFile.writeText(
baseBuildFile() + """
openapi {
host = '$host'
basePath = '$basePath'
Expand All @@ -45,7 +48,8 @@ class RestdocsOpenApiTaskTest : RestdocsOpenApiTaskTestBase() {
scopeDescriptionsPropertiesFile = "scopeDescriptions.yaml"
}
}
""".trimIndent())
""".trimIndent()
)
}

override fun thenSecurityDefinitionsFoundInOutputFile() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,17 @@ abstract class RestdocsOpenApiTaskTestBase : ApiSpecTaskTest() {

private fun givenScopeTextFile() {
testProjectDir.resolve("scopeDescriptions.yaml").toFile().writeText(
"""
"""
"prod:r": "Some text"
""".trimIndent()
)
""".trimIndent()
)
}
private fun givenTagsTextFile() {
testProjectDir.resolve("tagDescriptions.yaml").toFile().writeText(
"""
"""
"tag1": "tag1 description"
"tag2": "tag2 description"
""".trimIndent()
""".trimIndent()
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ internal object ConstraintResolver {
internal fun minLengthString(fieldDescriptor: FieldDescriptor): Int? {
return findConstraints(fieldDescriptor)
.firstOrNull { constraint ->
(NOT_EMPTY_CONSTRAINTS.contains(constraint.name) ||
NOT_BLANK_CONSTRAINTS.contains(constraint.name) ||
LENGTH_CONSTRAINT == constraint.name)
(
NOT_EMPTY_CONSTRAINTS.contains(constraint.name) ||
NOT_BLANK_CONSTRAINTS.contains(constraint.name) ||
LENGTH_CONSTRAINT == constraint.name
)
}
?.let { constraint -> if (LENGTH_CONSTRAINT == constraint.name) constraint.configuration["min"] as Int else 1 }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import org.everit.json.schema.ArraySchema
import org.everit.json.schema.BooleanSchema
import org.everit.json.schema.CombinedSchema
import org.everit.json.schema.EmptySchema
import org.everit.json.schema.EnumSchema
import org.everit.json.schema.NullSchema
import org.everit.json.schema.NumberSchema
import org.everit.json.schema.ObjectSchema
import org.everit.json.schema.EnumSchema
import org.everit.json.schema.Schema
import org.everit.json.schema.StringSchema
import org.everit.json.schema.internal.JSONPrinter
Expand Down Expand Up @@ -46,11 +46,12 @@ class JsonSchemaFromFieldDescriptorsGenerator {
it
)
}
.foldRight(listOf()) { fieldDescriptor, groups -> groups
.firstOrNull { it.equalsOnPathAndType(fieldDescriptor) }
?.let { groups } // omit the descriptor it is considered equal and can be omitted
?: groups.firstOrNull { it.path == fieldDescriptor.path }
?.let { groups - it + it.merge(fieldDescriptor) } // merge the type with the descriptor with the same name
.foldRight(listOf()) { fieldDescriptor, groups ->
groups
.firstOrNull { it.equalsOnPathAndType(fieldDescriptor) }
?.let { groups } // omit the descriptor it is considered equal and can be omitted
?: groups.firstOrNull { it.path == fieldDescriptor.path }
?.let { groups - it + it.merge(fieldDescriptor) } // merge the type with the descriptor with the same name
?: groups + fieldDescriptor // it is new just add it
}
}
Expand Down Expand Up @@ -140,7 +141,8 @@ class JsonSchemaFromFieldDescriptorsGenerator {
) {
traversedSegments.add(remainingSegments[0])
builder.addPropertySchema(
propertyName, ArraySchema.builder()
propertyName,
ArraySchema.builder()
.allItemSchema(traverse(traversedSegments, fields, ObjectSchema.builder()))
.description(propertyField?.fieldDescriptor?.description)
.build()
Expand All @@ -150,8 +152,10 @@ class JsonSchemaFromFieldDescriptorsGenerator {
builder.addRequiredProperty(propertyName)
}
builder.addPropertySchema(
propertyName, traverse(
traversedSegments, fields, ObjectSchema.builder()
propertyName,
traverse(
traversedSegments, fields,
ObjectSchema.builder()
.description(propertyField?.fieldDescriptor?.description) as ObjectSchema.Builder
)
)
Expand All @@ -167,8 +171,10 @@ class JsonSchemaFromFieldDescriptorsGenerator {
builder.addRequiredProperty(propertyName)
}
if (propertyName == "[]") {
builder.addPropertySchema(propertyName,
createSchemaWithArrayContent(ObjectSchema.builder().build(), depthOfArrayPath(fieldDescriptor.path)))
builder.addPropertySchema(
propertyName,
createSchemaWithArrayContent(ObjectSchema.builder().build(), depthOfArrayPath(fieldDescriptor.path))
)
} else {
builder.addPropertySchema(propertyName, fieldDescriptor.jsonSchemaType())
}
Expand Down Expand Up @@ -233,30 +239,35 @@ class JsonSchemaFromFieldDescriptorsGenerator {
"null" -> NullSchema.builder()
"empty" -> EmptySchema.builder()
"object" -> ObjectSchema.builder()
"array" -> ArraySchema.builder().allItemSchema(CombinedSchema.oneOf(
"array" -> ArraySchema.builder().allItemSchema(
CombinedSchema.oneOf(
listOf(
ObjectSchema.builder().build(),
BooleanSchema.builder().build(),
StringSchema.builder().build(),
NumberSchema.builder().build()
ObjectSchema.builder().build(),
BooleanSchema.builder().build(),
StringSchema.builder().build(),
NumberSchema.builder().build()
)
).build())
).build()
)
"boolean" -> BooleanSchema.builder()
"number" -> NumberSchema.builder()
"string" -> StringSchema.builder()
.minLength(minLengthString(this))
.maxLength(maxLengthString(this))
"enum" -> CombinedSchema.oneOf(
listOf(
StringSchema.builder().build(),
EnumSchema.builder().possibleValues(this.attributes.enumValues).build())
).isSynthetic(true)
listOf(
StringSchema.builder().build(),
EnumSchema.builder().possibleValues(this.attributes.enumValues).build()
)
).isSynthetic(true)
else -> throw IllegalArgumentException("unknown field type $type")
}

fun equalsOnPathAndType(f: FieldDescriptorWithSchemaType): Boolean =
(this.path == f.path &&
this.type == f.type)
(
this.path == f.path &&
this.type == f.type
)

companion object {
fun fromFieldDescriptor(fieldDescriptor: FieldDescriptor) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ class JsonFieldPathTest {

@Test
fun should_get_remaining_segments() {
with(compile(
JsonSchemaFromFieldDescriptorsGenerator.FieldDescriptorWithSchemaType(
"a.b.c", "", "", false, false,
Attributes()
with(
compile(
JsonSchemaFromFieldDescriptorsGenerator.FieldDescriptorWithSchemaType(
"a.b.c", "", "", false, false,
Attributes()
)
)
)) {
) {
then(remainingSegments(listOf("a"))).contains("b", "c")
then(remainingSegments(listOf("a", "b"))).contains("c")
then(remainingSegments(listOf("a", "b", "c"))).isEmpty()
Expand Down
Loading