Better handling of NPE in parser when referencing invalid schema (#10882)

* try to catch NullPointerException and print error message

* handles invalid specifications when the spec file is invalid

* added comment

* added null pointer exception test
This commit is contained in:
Hong Zhuang
2021-11-20 19:31:11 -06:00
committed by GitHub
parent c69bff2871
commit 606db36c77
4 changed files with 44 additions and 2 deletions

View File

@@ -22,7 +22,9 @@ import org.apache.commons.lang3.ArrayUtils;
import org.mockito.MockSettings;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.Generator;
import org.openapitools.codegen.SpecValidationException;
import org.openapitools.codegen.config.CodegenConfigurator;
import org.testng.TestException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -430,4 +432,12 @@ public class GenerateTest {
verify(configurator).toContext();
verifyNoMoreInteractions(configurator);
}
/**
* This test ensures that when the
*/
@Test(expectedExceptions = SpecValidationException.class)
public void testNPEWithInvalidSpecFile() {
setupAndRunTest("-i", "src/test/resources/npe-test.yaml", "-g", "java", "-o", "src/main/java", false, null);
}
}

View File

@@ -0,0 +1,14 @@
test:
get:
responses:
'200':
description: test
content:
application/json:
schema:
type: object
properties:
prop1:
type: array
prop2:
type: date

View File

@@ -0,0 +1,8 @@
openapi: 3.0.0
info:
description: test
version: test
title: test
paths:
/test:
$ref: 'npe-test-spec-file.yaml#/test'

View File

@@ -534,8 +534,18 @@ public class CodegenConfigurator {
if (validationMessages.size() > 0) {
Set<String> warnings = new HashSet<>();
if (specification != null) {
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
// Wrap the getUnusedSchemas() in try catch block so it catches the NPE
// when the input spec file is not correct
try{
List<String> unusedModels = ModelUtils.getUnusedSchemas(specification);
if (unusedModels != null) {
unusedModels.forEach(name -> warnings.add("Unused model: " + name));
}
} catch (Exception e){
System.err.println("[error] There is an error with OpenAPI specification parsed from the input spec file: " + inputSpec);
System.err.println("[error] Please make sure the spec file has correct format and all required fields are populated with valid value.");
}
}
if (workflowSettings.isValidateSpec()) {