oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Zero value in nullable and required field

Open ShouheiNishi opened this issue 2 years ago • 4 comments

The field of the go structure corresponding to the nullable and required OpenAPI property has zero value. In this case, if there is no 'nullable-type' option, the field is encoded as JSON null. But, if 'nullable-type' option is exist, the field is encoded with the zero value of the type parameter of the Nullable generics. Is this difference in behavior intentional?

Test code is https://github.com/ShouheiNishi/oapi-codegen/tree/43adbaa45458d20038d0af271a47802d8c4b5578/internal/test/issues/nullable-zero-value.

$ git status
HEAD detached at 43adbaa
nothing to commit, working tree clean
$ (cd internal/test ; go generate ./issues/nullable-zero-value/... ; go test ./issues/nullable-zero-value/...)
?       github.com/deepmap/oapi-codegen/v2/internal/test/issues/nullable-zero-value/new-nullable        [no test files]
?       github.com/deepmap/oapi-codegen/v2/internal/test/issues/nullable-zero-value/old-nullable        [no test files]
--- FAIL: TestIssue1236 (0.00s)
    issue_test.go:22:
                Error Trace:    /home/nishi/free5gc-deb/free5gc/lib/oapi-codegen/internal/test/issues/nullable-zero-value/issue_test.go:22
                Error:          Not equal:
                                expected: map[string]interface {}{"NullableRequired":interface {}(nil)}
                                actual  : map[string]interface {}{"NullableRequired":0}

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -1,3 +1,3 @@
                                 (map[string]interface {}) (len=1) {
                                - (string) (len=16) "NullableRequired": (interface {}) <nil>
                                + (string) (len=16) "NullableRequired": (float64) 0
                                 }
                Test:           TestIssue1236
FAIL
FAIL    github.com/deepmap/oapi-codegen/v2/internal/test/issues/nullable-zero-value     0.007s
FAIL
$

ShouheiNishi avatar Jan 25 '24 01:01 ShouheiNishi

Hey, so this is something @sonasingh46 and I looked at while introducing the https://github.com/oapi-codegen/nullable type - a required field should always be present, so the correct zero value is the zero value of the type, rather than it being a null

jamietanna avatar Jan 25 '24 10:01 jamietanna

Presumably, in the case of nullable and required properties, JSON null is more likely to satisfy the schema than zero value. Therefore, wouldn't it be better if JSON null was output?

ShouheiNishi avatar Jan 29 '24 04:01 ShouheiNishi

cc @sonasingh46 thoughts?

jamietanna avatar Jan 29 '24 13:01 jamietanna