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

feat(server): migrate limit number of subresources rule to context object to support openapi 3 #821

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package de.zalando.zally.rule.zalando

import com.typesafe.config.Config
import de.zalando.zally.rule.api.Check
import de.zalando.zally.rule.api.Context
import de.zalando.zally.rule.api.Rule
import de.zalando.zally.rule.api.Severity
import de.zalando.zally.rule.api.Violation
import de.zalando.zally.util.PatternUtil
import org.springframework.beans.factory.annotation.Autowired

@Rule(
ruleSet = ZalandoRuleSet::class,
id = "147",
severity = Severity.SHOULD,
title = "Limit number of Sub-resources level"
)
class LimitNumberOfSubResourcesRule(@Autowired rulesConfig: Config) {
private val subResourcesLimit = rulesConfig.getConfig(javaClass.simpleName).getInt("subresources_limit")
private val description = "Number of sub-resources should not exceed $subResourcesLimit"

@Check(severity = Severity.SHOULD)
fun checkNumberOfSubResources(context: Context): List<Violation> =
context.api.paths.orEmpty().entries
.map { (path, pathObj) -> Pair(path.split("/").filter { it.isNotEmpty() && !PatternUtil.isPathVariable(it) }.size - 1, pathObj) }
.filter { (numberOfSubResources, _) -> numberOfSubResources > subResourcesLimit }
.map { (_, pathObj) -> context.violation(description, pathObj) }
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class SuccessResponseAsJsonObjectRule {

@Check(severity = Severity.MUST)
fun checkJSONObjectIsUsedAsSuccessResponseType(context: Context): List<Violation> =
context.api.paths.values
context.api.paths.orEmpty().values
.flatMap {
it.readOperations().orEmpty()
.flatMap { it.responses.filter { (resCode, _) -> isSuccess(resCode) }.values }
Expand Down
2 changes: 1 addition & 1 deletion server/src/main/resources/rules-config.conf
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ LimitNumberOfResourcesRule {
resource_types_limit: 8
}

LimitNumberOfSubresourcesRule {
LimitNumberOfSubResourcesRule {
subresources_limit: 3
}

Expand Down
27 changes: 1 addition & 26 deletions server/src/test/java/de/zalando/zally/TestUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@ import de.zalando.zally.rule.ContentParseResult
import de.zalando.zally.rule.DefaultContext
import de.zalando.zally.rule.ObjectTreeReader
import de.zalando.zally.rule.api.Context
import io.swagger.models.ModelImpl
import io.swagger.models.Operation
import io.swagger.models.Path
import io.swagger.models.Response
import io.swagger.models.Swagger
import io.swagger.models.parameters.HeaderParameter
import io.swagger.models.properties.StringProperty
import io.swagger.parser.SwaggerParser
import io.swagger.parser.util.ClasspathHelper
import io.swagger.v3.oas.models.OpenAPI
Expand Down Expand Up @@ -65,7 +61,7 @@ fun getOpenApiContextFromContent(content: String): Context {
throw RuntimeException("Parsed with violations:$errors")
}
is ContentParseResult.NotApplicable -> {
throw RuntimeException("Missing the 'OpenAPI' property.")
throw RuntimeException("Missing the 'openapi' property.")
}
}
}
Expand Down Expand Up @@ -101,27 +97,6 @@ fun swaggerWithHeaderParams(vararg names: String) =
}.toMap()
}

fun swaggerWithDefinitions(vararg defs: Pair<String, List<String>>): Swagger =
Swagger().apply {
definitions = defs.map { def ->
def.first to ModelImpl().apply {
properties = def.second.map { prop -> prop to StringProperty() }.toMap()
}
}.toMap()
}

fun swaggerWithOperations(operations: Map<String, Iterable<String>>): Swagger =
Swagger().apply {
val path = Path()
operations.forEach { method, statuses ->
val operation = Operation().apply {
statuses.forEach { addResponse(it, Response()) }
}
path.set(method, operation)
}
paths = mapOf("/test" to path)
}

fun openApiWithOperations(operations: Map<String, Iterable<String>>): OpenAPI =
OpenAPI().apply {
val pathItem = PathItem()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package de.zalando.zally.rule.zalando

import de.zalando.zally.getOpenApiContextFromContent
import de.zalando.zally.testConfig
import org.assertj.core.api.Assertions.assertThat
import org.intellij.lang.annotations.Language
import org.junit.Test

class LimitNumberOfSubResourcesRuleTest {

private val rule = LimitNumberOfSubResourcesRule(testConfig)

@Test
fun `checkNumberOfSubResources should return violation if number of sub resources exceeds the limit`() {
@Language("YAML")
val spec = """
openapi: "3.0.0"
paths:
/worlds/{world-id}/countries/{country-id}/states/{state-id}/cities/{city-id}/streets/{street-id}: {}
""".trimIndent()
val context = getOpenApiContextFromContent(spec)

val violations = rule.checkNumberOfSubResources(context)

assertThat(violations).isNotEmpty
assertThat(violations[0].description).containsPattern("Number of sub-resources should not exceed")
assertThat(violations[0].pointer.toString()).isEqualTo("/paths/~1worlds~1{world-id}~1countries~1{country-id}~1states~1{state-id}~1cities~1{city-id}~1streets~1{street-id}")
}

@Test
fun `checkNumberOfSubResources should return no violation if number of sub resources doesn not exceed the limit`() {
@Language("YAML")
val spec = """
openapi: 3.0.1
paths:
/articles: {}
""".trimIndent()
val context = getOpenApiContextFromContent(spec)

val violations = rule.checkNumberOfSubResources(context)

assertThat(violations).isEmpty()
}
}

This file was deleted.

This file was deleted.

This file was deleted.