fix: Handle null paths in OpenAPI to prevent NPE

Signed-off-by: Haotian Zhang <928016560@qq.com>
pull/1803/head
Haotian Zhang 2 months ago
parent 2433d3aa41
commit ef9cad9259

@ -114,7 +114,7 @@ public class PolarisContractReporter implements ApplicationListener<ApplicationR
request.setVersion(polarisDiscoveryProperties.getVersion());
List<InterfaceDescriptor> interfaceDescriptorList = getInterfaceDescriptorFromSwagger(openAPI);
request.setInterfaceDescriptors(interfaceDescriptorList);
if (StringUtils.isNotBlank(contextPath)) {
if (StringUtils.isNotBlank(contextPath) && openAPI.getPaths() != null) {
Paths newPaths = new Paths();
for (Map.Entry<String, PathItem> entry : openAPI.getPaths().entrySet()) {
newPaths.addPathItem(contextPath + entry.getKey(), entry.getValue());
@ -154,6 +154,9 @@ public class PolarisContractReporter implements ApplicationListener<ApplicationR
private List<InterfaceDescriptor> getInterfaceDescriptorFromSwagger(OpenAPI openAPI) {
List<InterfaceDescriptor> interfaceDescriptorList = new ArrayList<>();
Paths paths = openAPI.getPaths();
if (paths == null) {
return interfaceDescriptorList;
}
for (Map.Entry<String, PathItem> p : paths.entrySet()) {
PathItem path = p.getValue();
Map<String, Operation> operationMap = getOperationMapFromPath(path);
@ -162,7 +165,12 @@ public class PolarisContractReporter implements ApplicationListener<ApplicationR
}
for (Map.Entry<String, Operation> o : operationMap.entrySet()) {
InterfaceDescriptor interfaceDescriptor = new InterfaceDescriptor();
interfaceDescriptor.setPath(contextPath + p.getKey());
if (StringUtils.isNotBlank(contextPath)) {
interfaceDescriptor.setPath(contextPath + p.getKey());
}
else {
interfaceDescriptor.setPath(p.getKey());
}
interfaceDescriptor.setMethod(o.getKey());
try {
String jsonValue;

@ -161,4 +161,26 @@ class PolarisContractReporterTest {
.extracting(InterfaceDescriptor::getPath)
.allMatch(path -> path.startsWith("/api/"));
}
/**
* Test that null paths in OpenAPI returns an empty descriptor list without NPE.
* When OpenAPI.getPaths() returns null, the method should gracefully return
* an empty list instead of throwing NullPointerException.
*/
@DisplayName("null paths in OpenAPI returns empty descriptor list")
@Test
void testNullPathsReturnsEmptyList() throws Exception {
// Arrange
PolarisContractReporter reporter = new PolarisContractReporter(
null, null, polarisContractProperties, providerAPI,
polarisDiscoveryProperties, springdocObjectMapperProvider, "/context");
OpenAPI openAPI = new OpenAPI();
// Do not call openAPI.setPaths(), so getPaths() returns null
// Act
List<InterfaceDescriptor> descriptors = invokeGetInterfaceDescriptorFromSwagger(reporter, openAPI);
// Assert
assertThat(descriptors).isNotNull().isEmpty();
}
}

Loading…
Cancel
Save