io.vertx.ext.web.api.validation.ValidationException Java Examples

The following examples show how to use io.vertx.ext.web.api.validation.ValidationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalPropertiesJson() throws Exception {
    Operation op = testSpec.getPaths().get("/additionalProperties")
            .getPost();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/additionalProperties", HttpMethod.POST, true,
            validationHandler, (routingContext) -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK")
                        .putHeader(HttpHeaders.CONTENT_TYPE,
                                "application/json")
                        .end(params.body().getJsonObject().encode());
            });

    JsonObject pet = new JsonObject();
    pet.put("id", 14612);
    pet.put("name", "Willy");
    pet.put("lazyness", "Highest");

    testRequestWithJSON(HttpMethod.POST, "/additionalProperties",
            pet.toBuffer(), 400,
            errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #2
Source File: SplitterCharContainerDeserializer.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> deserializeObject(String serialized) throws ValidationException {
  Map<String, String> result = new HashMap<>();
  String[] values = serialized.split(separator, -1);
  // Key value pairs -> odd length not allowed
  if (values.length % 2 != 0)
    throw ValidationException.ValidationExceptionFactory.generateDeserializationError("DeserializationError: Key "
      + "value pair Object must have odd fields");
  for (int i = 0; i < values.length; i += 2) {
    // empty key not allowed!
    if (values[i].length() == 0) {
      throw ValidationException.ValidationExceptionFactory.generateDeserializationError("DeserializationError: " +
        "Empty key not allowed");
    } else {
      result.put(values[i], this.nullateValue(values[i + 1]));
    }
  }
  return result;
}
 
Example #3
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Test: query_optional_form_explode_object
 * Expected parameters sent:
 * color: R=100&G=200&B=150&alpha=50
 * Expected response: Validation failure
 */
@Test
public void testQueryOptionalFormExplodeObjectFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/query/form/explode/object").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/query/form/explode/object", HttpMethod.GET, true, validationHandler, routingContext -> {
    RequestParameters params = routingContext.get("parsedParameters");

    RequestParameter colorQueryParam = params.queryParameter("color");
    assertNotNull(colorQueryParam);
    assertTrue(colorQueryParam.isObject());

    routingContext.response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader("content-type", "application/json")
      .end(((JsonObject)colorQueryParam.toJson()).encode());
  });

  String requestURI = "/query/form/explode/object?R=100&G=200&B=150&alpha=aaa";

  testRequest(HttpMethod.GET, requestURI, 400, errorMessage(ValidationException.ErrorType.NO_MATCH));

}
 
Example #4
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testCookieExpandedObjectTestOnlyAdditionalPropertiesFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/cookieTests/objectTests/onlyAdditionalProperties").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/cookieTests/objectTests/onlyAdditionalProperties",
    HttpMethod.GET,
    true,
    validationHandler,
    (routingContext) -> {
      routingContext.response().setStatusCode(200).setStatusMessage("OK").end();
    }
  );

  QueryStringEncoder params = new QueryStringEncoder("/");
  params.addParam("param1", Integer.toString(5));
  params.addParam("param2", "a");
  params.addParam("wellKnownParam", "hello");

  testRequestWithCookies(HttpMethod.GET, "/cookieTests/objectTests/onlyAdditionalProperties", params.toUri().getRawQuery(), 400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #5
Source File: ObjectTypeValidator.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestParameter validate(Map<String, String> values) throws ValidationException {
  Map<String, RequestParameter> parsedParams = new HashMap<>();

  for (Map.Entry<String, ObjectField> field : fieldsMap.entrySet()) {
    if (!values.containsKey(field.getKey())) {
      if (field.getValue().required)
        throw ValidationException.ValidationExceptionFactory.generateObjectFieldNotFound(field.getKey());
      else if (field.getValue().validator.getDefault() != null)
        parsedParams.put(field.getKey(), RequestParameter.create(field.getKey(), field.getValue().validator
          .getDefault()));

    } else {
      RequestParameter param = field.getValue().validator.isValid(values.get(field.getKey()));
      param.setName(field.getKey());
      parsedParams.put(field.getKey(), param);
    }
  }

  return RequestParameter.create(parsedParams);
}
 
Example #6
Source File: OneOfTypeValidator.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public RequestParameter isValid(String value) throws ValidationException {
  RequestParameter resultParam = null;
  for (ParameterTypeValidator validator : validators) {
    try {
      RequestParameter validatedParam = validator.isValid(value);
      if (validatedParam != null) {
        if (resultParam == null) resultParam = validatedParam;
        else
          throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException(value + " match " +
            "" + "multiple schemas inside oneOf field");
      }
    } catch (ValidationException e) {
    }
  }
  if (resultParam != null) return resultParam;
  else
    throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException(value + " doesn't " +
      "match any of oneOf schemas");
}
 
Example #7
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdditionalPropertiesJson() throws Exception {
  Operation op = testSpec.getPaths().get("/additionalProperties").getPost();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/additionalProperties", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .end(params.body().getJsonObject().encode());
  });

  JsonObject pet = new JsonObject();
  pet.put("id", 14612);
  pet.put("name", "Willy");
  pet.put("lazyness",  "Highest");

  testRequestWithJSON(HttpMethod.POST, "/additionalProperties", pet.toBuffer(), 400, errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #8
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullJson() throws Exception {
  Operation op = testSpec.getPaths().get("/pets").getPost();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/pets", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .end(params.body().getJsonObject().encode());
  });

  // An empty body should be a non parsable json, not an empty object invalid
  testRequestWithJSON(HttpMethod.POST, "/pets", null, 400, errorMessage(ValidationException.ErrorType.JSON_INVALID));

  // An empty json object should be invalid, because some fields are required
  testRequestWithJSON(HttpMethod.POST, "/pets", new JsonObject().toBuffer(),400, errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #9
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParameterArrayDefaultStyleFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/arrayTests/default")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/arrayTests/default", HttpMethod.GET, true,
            validationHandler, (routingContext) -> routingContext.response()
                    .setStatusMessage("ok").end());
    List<String> values = new ArrayList<>();
    values.add("4");
    values.add("1"); // multipleOf: 2
    values.add("26");

    testRequest(HttpMethod.GET,
            "/queryTests/arrayTests/default?parameter="
                    + serializeInCSVStringArray(values),
            400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #10
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryExpandedObjectTestOnlyAdditionalPropertiesFailure()
        throws Exception {
    Operation op = testSpec.getPaths()
            .get("/queryTests/objectTests/onlyAdditionalProperties")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/objectTests/onlyAdditionalProperties",
            HttpMethod.GET, true, validationHandler, (routingContext) -> {
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK").end();
            });

    testRequest(HttpMethod.GET,
            "/queryTests/objectTests/onlyAdditionalProperties?param1=2&param2=a&wellKnownParam=a",
            400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #11
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonBodyFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/jsonBodyTest/sampleTest").getPost();
  if(op.getParameters()==null) op.setParameters(new ArrayList<>());
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/jsonBodyTest/sampleTest", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader("Content-Type", "application/json")
      .end(params.body().getJsonObject().encode());
  });

  JsonObject object = new JsonObject();
  object.put("id", "anId");

  List<String> valuesArray = new ArrayList<>();
  for (int i = 0; i < 4; i++)
    valuesArray.add(getSuccessSample(ParameterType.INT).getInteger().toString());
  valuesArray.add(2, getFailureSample(ParameterType.INT));
  object.put("values", valuesArray);

  testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest", object.toBuffer(), 400, errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #12
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormArrayParameterFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/formTests/arraytest").getPost();
  if(op.getParameters()==null) op.setParameters(new ArrayList<>());
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/formTests/arraytest", HttpMethod.POST, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());

  String id = "anId";

  List<String> valuesArray = new ArrayList<>();
  for (int i = 0; i < 4; i++)
    valuesArray.add(getSuccessSample(ParameterType.INT).getInteger().toString());
  valuesArray.add(getFailureSample(ParameterType.INT));
  String values = serializeInCSVStringArray(valuesArray);

  MultiMap form = MultiMap.caseInsensitiveMultiMap();
  form.add("id", id);
  form.add("values", values);

  testRequestWithForm(HttpMethod.POST, "/formTests/arraytest", FormType.FORM_URLENCODED, form, 400, errorMessage
    (ValidationException.ErrorType.NO_MATCH));
}
 
Example #13
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testCookieExpandedObjectTestOnlyAdditionalPropertiesFailure()
        throws Exception {
    Operation op = testSpec.getPaths()
            .get("/cookieTests/objectTests/onlyAdditionalProperties")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/cookieTests/objectTests/onlyAdditionalProperties",
            HttpMethod.GET, true, validationHandler, (routingContext) -> {
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK").end();
            });

    QueryStringEncoder params = new QueryStringEncoder("/");
    params.addParam("param1", Integer.toString(5));
    params.addParam("param2", "a");
    params.addParam("wellKnownParam", "hello");

    testRequestWithCookies(HttpMethod.GET,
            "/cookieTests/objectTests/onlyAdditionalProperties",
            params.toUri().getRawQuery(), 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #14
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllOfQueryParamFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/allOfTest")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/allOfTest", HttpMethod.GET, true,
            validationHandler, (routingContext) -> routingContext.response()
                    .setStatusMessage("ok").end());

    String a = "5";
    String b = "aString";

    String parameter = "parameter=a," + a + ",b," + b;

    testRequest(HttpMethod.GET, "/queryTests/allOfTest?" + parameter, 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #15
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormArrayParameterFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/formTests/arraytest")
            .getPost();
    if (op.getParameters() == null)
        op.setParameters(new ArrayList<>());
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/formTests/arraytest", HttpMethod.POST, true,
            validationHandler, (routingContext) -> routingContext.response()
                    .setStatusMessage("ok").end());

    String id = "anId";

    List<String> valuesArray = new ArrayList<>();
    for (int i = 0; i < 4; i++)
        valuesArray.add(getSuccessSample(ParameterType.INT).getInteger()
                .toString());
    valuesArray.add(getFailureSample(ParameterType.INT));
    String values = serializeInCSVStringArray(valuesArray);

    MultiMap form = MultiMap.caseInsensitiveMultiMap();
    form.add("id", id);
    form.add("values", values);

    testRequestWithForm(HttpMethod.POST, "/formTests/arraytest",
            FormType.FORM_URLENCODED, form, 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #16
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryParameterAnyOfFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/anyOfTest")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/queryTests/anyOfTest", HttpMethod.GET, true,
            validationHandler, (routingContext) -> routingContext.response()
                    .setStatusMessage("ok").end());

    testRequest(HttpMethod.GET, "/queryTests/anyOfTest?parameter=anyString",
            400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #17
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonBodyFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/jsonBodyTest/sampleTest")
            .getPost();
    if (op.getParameters() == null)
        op.setParameters(new ArrayList<>());
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/jsonBodyTest/sampleTest", HttpMethod.POST, true,
            validationHandler, (routingContext) -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK")
                        .putHeader("Content-Type", "application/json")
                        .end(params.body().getJsonObject().encode());
            });

    JsonObject object = new JsonObject();
    object.put("id", "anId");

    List<String> valuesArray = new ArrayList<>();
    for (int i = 0; i < 4; i++)
        valuesArray.add(getSuccessSample(ParameterType.INT).getInteger()
                .toString());
    valuesArray.add(2, getFailureSample(ParameterType.INT));
    object.put("values", valuesArray);

    testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest",
            object.toBuffer(), 400,
            errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #18
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
/**
 * Test: query_optional_form_explode_object Expected parameters sent: color:
 * R=100&G=200&B=150&alpha=50 Expected response: Validation failure
 */
@Test
public void testQueryOptionalFormExplodeObjectFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/query/form/explode/object")
            .getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/query/form/explode/object", HttpMethod.GET, true,
            validationHandler, routingContext -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");

                RequestParameter colorQueryParam = params
                        .queryParameter("color");
                assertNotNull(colorQueryParam);
                assertTrue(colorQueryParam.isObject());

                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK")
                        .putHeader("content-type", "application/json")
                        .end(((JsonObject) colorQueryParam.toJson())
                                .encode());
            });

    String requestURI = "/query/form/explode/object?R=100&G=200&B=150&alpha=aaa";

    testRequest(HttpMethod.GET, requestURI, 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));

}
 
Example #19
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathParameterFailure() throws Exception {
    Operation op = testSpec.getPaths().get("/pets/{petId}").getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/pets/:petId", HttpMethod.GET, true, validationHandler,
            (routingContext) -> routingContext.response()
                    .setStatusMessage("ok").end());
    testRequest(HttpMethod.GET, "/pets/three", 400,
            errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #20
Source File: BooleanTypeValidator.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public RequestParameter isValidSingleParam(String value) {
  if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("t") || value.equalsIgnoreCase("1"))
    return RequestParameter.create(true);
  else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("f") || value.equalsIgnoreCase("0"))
    return RequestParameter.create(false);
  else
    throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException(null);
}
 
Example #21
Source File: OpenAPI3MultipleFilesValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullJson() throws Exception {
    Operation op = testSpec.getPaths().get("/pets").getPost();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(
            op, op.getParameters(), testSpec, refsCache);
    loadHandlers("/pets", HttpMethod.POST, true, validationHandler,
            (routingContext) -> {
                RequestParameters params = routingContext
                        .get("parsedParameters");
                routingContext.response().setStatusCode(200)
                        .setStatusMessage("OK")
                        .putHeader(HttpHeaders.CONTENT_TYPE,
                                "application/json")
                        .end(params.body().getJsonObject().encode());
            });

    // An empty body should be a non parsable json, not an empty object
    // invalid
    testRequestWithJSON(HttpMethod.POST, "/pets", null, 400,
            errorMessage(ValidationException.ErrorType.JSON_INVALID));

    // An empty json object should be invalid, because some fields are
    // required
    testRequestWithJSON(HttpMethod.POST, "/pets",
            new JsonObject().toBuffer(), 400,
            errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example #22
Source File: FailureHandler.java    From vertx-in-production with MIT License 5 votes vote down vote up
public void handle(RoutingContext context) {

        Throwable thrown = context.failure();
        String userId = context.request().getHeader("Authorization");
        recordError(userId, thrown);

        if(thrown instanceof ValidationException) {
            context.response().setStatusCode(400).end(thrown.getMessage());
        } else {
            context.response().setStatusCode(500).end(thrown.getMessage());
        }
    }
 
Example #23
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathParameterFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/pets/{petId}").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/pets/:petId", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());
  testRequest(HttpMethod.GET, "/pets/three", 400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #24
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryParameterArrayDefaultStyleFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/arrayTests/default").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/arrayTests/default", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());
  List<String> values = new ArrayList<>();
  values.add("4");
  values.add("1"); // multipleOf: 2
  values.add("26");

  testRequest(HttpMethod.GET, "/queryTests/arrayTests/default?parameter=" + serializeInCSVStringArray(values), 400,
    errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #25
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllOfQueryParamFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/allOfTest").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/allOfTest", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());

  String a = "5";
  String b = "aString";

  String parameter = "parameter=a," + a + ",b," + b;

  testRequest(HttpMethod.GET, "/queryTests/allOfTest?" + parameter, 400, errorMessage(ValidationException.ErrorType
    .NO_MATCH));
}
 
Example #26
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryParameterAnyOfFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/anyOfTest").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/anyOfTest", HttpMethod.GET, true, validationHandler, (routingContext) -> routingContext.response().setStatusMessage("ok").end());

  testRequest(HttpMethod.GET, "/queryTests/anyOfTest?parameter=anyString", 400, errorMessage(ValidationException
    .ErrorType.NO_MATCH));
}
 
Example #27
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonBodyFailureErrorMessage() throws Exception {
  Operation op = testSpec.getPaths().get("/jsonBodyTest/sampleTest").getPost();
  if(op.getParameters()==null) op.setParameters(new ArrayList<>());
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/jsonBodyTest/sampleTest", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader("Content-Type", "application/json")
      .end(params.body().getJsonObject().encode());
  }, routingContext -> {
    ValidationException e = (ValidationException) routingContext.failure();
    routingContext
      .response()
      .setStatusCode(400)
      .setStatusMessage(errorMessage(ValidationException.ErrorType.JSON_INVALID))
      .putHeader("Content-Type", "application/json")
      .end(new JsonObject().put("field", e.parameterName()).toBuffer());
  });

  JsonObject object = new JsonObject();
  object.put("id", "anId");

  List<String> valuesArray = new ArrayList<>();
  for (int i = 0; i < 4; i++)
    valuesArray.add(getSuccessSample(ParameterType.INT).getInteger().toString());
  valuesArray.add(0, getFailureSample(ParameterType.INT));
  object.put("values", valuesArray);

  testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest", object.toBuffer(), 400,
    errorMessage(ValidationException.ErrorType.JSON_INVALID),
    new JsonObject().put("field", "body.values[0]").toBuffer());

  testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest", new JsonArray().toBuffer(), 400,
    errorMessage(ValidationException.ErrorType.JSON_INVALID),
    new JsonObject().put("field", "body").toBuffer());
}
 
Example #28
Source File: OpenAPI3ValidationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryExpandedObjectTestOnlyAdditionalPropertiesFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/queryTests/objectTests/onlyAdditionalProperties").getGet();
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/queryTests/objectTests/onlyAdditionalProperties",
    HttpMethod.GET,
    true,
    validationHandler,
    (routingContext) -> {
      routingContext.response().setStatusCode(200).setStatusMessage("OK").end();
    }
  );

  testRequest(HttpMethod.GET, "/queryTests/objectTests/onlyAdditionalProperties?param1=2&param2=a&wellKnownParam=a", 400, errorMessage(ValidationException.ErrorType.NO_MATCH));
}
 
Example #29
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Handler<RoutingContext> generateFailureHandler(boolean expected) {
  return routingContext -> {
    Throwable failure = routingContext.failure();
    if (failure instanceof ValidationException) {
      if (!expected) {
        failure.printStackTrace();
      }
      routingContext.response().setStatusCode(400).setStatusMessage("failure:" + ((ValidationException) failure)
        .type().name()).end();
    } else {
      failure.printStackTrace();
      routingContext.response().setStatusCode(500).setStatusMessage("unknownfailure:" + failure.toString()).end();
    }
  };
}
 
Example #30
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void notMountValidationFailureHandler() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(
        new RouterFactoryOptions()
          .setRequireSecurityHandlers(false)
          .setMountValidationFailureHandler(false)
      );

      routerFactory.addHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode(200)
        .setStatusMessage(((RequestParameters) routingContext.get("parsedParameters")).queryParameter("limit").toString())
        .end());

      routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> routingContext
        .response()
        .setStatusCode((routingContext.failure() instanceof ValidationException) ? 400 : 500)
        .setStatusMessage((routingContext.failure() instanceof ValidationException) ? "Very very Bad Request" : "Error")
        .end());

      latch.countDown();
    });
  awaitLatch(latch);

  startServer();

  testRequest(HttpMethod.GET, "/pets?limit=hello", 400, "Very very Bad Request");
  testRequest(HttpMethod.GET, "/pets?limit=10", 200, "10");
}