forked from orijtech/otils
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix decoding null for NullableString
While at it, also fix golangci-lint errors, and add tests to make sure the NullableTime are able to decode null time, too.
- Loading branch information
Showing
3 changed files
with
74 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package otils | ||
|
||
import ( | ||
"encoding/json" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func TestNullableString(t *testing.T) { | ||
type testNullableString struct { | ||
S NullableString | ||
} | ||
tests := []struct { | ||
name string | ||
s string | ||
expected NullableString | ||
}{ | ||
{"normal", `{"s": "foo"}`, NullableString("foo")}, | ||
{"null", `{"s": null}`, NullableString("")}, | ||
} | ||
|
||
for _, tc := range tests { | ||
tc := tc | ||
t.Run(tc.name, func(t *testing.T) { | ||
t.Parallel() | ||
tn := testNullableString{S: "init"} | ||
if err := json.Unmarshal([]byte(tc.s), &tn); err != nil { | ||
t.Error(err) | ||
} | ||
if tn.S != tc.expected { | ||
t.Errorf("unexpected result, want: %q, got: %q", tc.expected, tn.S) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
func TestNullableTime(t *testing.T) { | ||
type testNullableTime struct { | ||
T *NullableTime | ||
} | ||
now := NullableTime(time.Now()) | ||
tests := []struct { | ||
name string | ||
s string | ||
isNull bool | ||
expected NullableTime | ||
}{ | ||
{"null", `{"T": null}`, true, NullableTime(now)}, | ||
} | ||
for _, tc := range tests { | ||
tc := tc | ||
t.Run(tc.name, func(t *testing.T) { | ||
t.Parallel() | ||
tn := testNullableTime{T: &now} | ||
if err := json.Unmarshal([]byte(tc.s), &tn); err != nil { | ||
t.Error(err) | ||
} | ||
if tc.isNull && tn.T != nil { | ||
t.Errorf("expected nil, got non-nil") | ||
} | ||
if !tc.isNull && time.Time(*tn.T).UnixNano() != time.Time(tc.expected).UnixNano() { | ||
t.Errorf("unexpected result, want: %v, got: %v", tc.expected, *tn.T) | ||
} | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters