Skip to content

Instantly share code, notes, and snippets.

@Christian-Oette
Created October 17, 2023 10:33
Show Gist options
  • Save Christian-Oette/20da9723370dfca9d7e99221e9334df7 to your computer and use it in GitHub Desktop.
Save Christian-Oette/20da9723370dfca9d7e99221e9334df7 to your computer and use it in GitHub Desktop.
Programatically test the naming convention of OpenAPI in spring boot
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.models.OpenAPI;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
@SpringBootTest
@AutoConfigureMockMvc
class OpenApiNamingConventionTest {
@Autowired
private MockMvc mockMvc;
private static final Pattern ALLOWED_PATH_CHARS = Pattern.compile("[a-z/{}-]+");
@Test
public void thatOpenApiNamingConventionsAreCorrect() throws Exception {
// given
OpenAPI openAPI = loadOpenApi();
openAPI.getPaths().forEach((pathKey, pathItem) -> {
assertThat(pathKey).matches(ALLOWED_PATH_CHARS);
});
}
private OpenAPI loadOpenApi() throws Exception {
MvcResult result = mockMvc.perform(get("/v3/api-docs")) // Access the OpenAPI definition
.andExpect(status().isOk())
.andReturn();
String content = result.getResponse().getContentAsString();
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(content, OpenAPI.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment