omissis / go-jsonschema

A tool to generate Go data types from JSON Schema definitions.
MIT License
582 stars 93 forks source link

Only perform minItems validation when field is provided #122

Closed nick-jones closed 1 year ago

nick-jones commented 1 year ago

As reported in #86, minItems validation is being applied even when a non-required field is omitted from the input json.

A json schema like

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "https://example.com/array",
  "type": "object",
  "properties": {
    "myArray": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "minItems": 1,
      "maxItems": 3
    },
  }
}

should pass against an empty object input

{}

(can be tested at https://www.jsonschemavalidator.net/)

Instead the generated code will result in an error during unmarshal. The proposed solution is to just add a nil check - non-required slices use omitempty, which means they end up nil if not supplied. If the field is required, the earlier field presence check will catch these - but also they'll never be nil because omitempty is not used under such circumstances. So overall this additional constraint seems safe to add. Happy to take direction on other approaches.

codecov[bot] commented 1 year ago

Codecov Report

All modified lines are covered by tests :white_check_mark:

Comparison is base (0f951fd) 78.14% compared to head (5f48a22) 78.14%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #122 +/- ## ======================================= Coverage 78.14% 78.14% ======================================= Files 10 10 Lines 1446 1446 ======================================= Hits 1130 1130 Misses 244 244 Partials 72 72 ``` | [Files](https://app.codecov.io/gh/omissis/go-jsonschema/pull/122?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Claudio+Beatrice) | Coverage Δ | | |---|---|---| | [pkg/generator/validator.go](https://app.codecov.io/gh/omissis/go-jsonschema/pull/122?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=Claudio+Beatrice#diff-cGtnL2dlbmVyYXRvci92YWxpZGF0b3IuZ28=) | `95.23% <100.00%> (ø)` | |

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.