1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-07-17 01:12:45 +02:00

Fix Code.UnmarshalJSON to work with valid json only (#1276)

* Remove quotes from UnmarshalJSON

Signed-off-by: Daniil Rutskiy <dstdfx@gmail.com>

* Update CHANGELOG.md

Signed-off-by: Daniil Rutskiy <dstdfx@gmail.com>

* Fix issue number in CHANGELOG.md

* Fix 'Code.UnmarshalJSON' to work with valid json only

Signed-off-by: Daniil Rutskiy <dstdfx@gmail.com>

* Extend test data for TestCodeUnmarshalJSONErrorInvalidData

Signed-off-by: Daniil Rutskiy <dstdfx@gmail.com>

* Delete useless cond, extend test data

Signed-off-by: Daniil Rutskiy <dstdfx@gmail.com>
This commit is contained in:
Daniil Rutskiy
2020-10-28 01:30:49 +03:00
committed by GitHub
parent a6b31e0da1
commit d98ad1042c
3 changed files with 66 additions and 21 deletions

View File

@ -16,6 +16,7 @@ package codes
import (
"bytes"
"encoding/json"
"fmt"
"testing"
)
@ -61,17 +62,18 @@ func TestCodeUnmarshalJSON(t *testing.T) {
want Code
}{
{"0", Unset},
{"Unset", Unset},
{`"Unset"`, Unset},
{"1", Error},
{"Error", Error},
{`"Error"`, Error},
{"2", Ok},
{"Ok", Ok},
{`"Ok"`, Ok},
}
for _, test := range tests {
c := new(Code)
*c = Code(maxCode)
if err := c.UnmarshalJSON([]byte(test.input)); err != nil {
t.Fatalf("Code.UnmarshalJSON(%q) errored: %v", test.input, err)
if err := json.Unmarshal([]byte(test.input), c); err != nil {
t.Fatalf("json.Unmarshal(%q, Code) errored: %v", test.input, err)
}
if *c != test.want {
t.Errorf("failed to unmarshal %q as %v", test.input, test.want)
@ -83,11 +85,15 @@ func TestCodeUnmarshalJSONErrorInvalidData(t *testing.T) {
tests := []string{
fmt.Sprintf("%d", maxCode),
"Not a code",
"Unset",
"true",
`"Not existing"`,
"",
}
c := new(Code)
for _, test := range tests {
if err := c.UnmarshalJSON([]byte(test)); err == nil {
t.Fatalf("Code.UnmarshalJSON(%q) did not error", test)
if err := json.Unmarshal([]byte(test), c); err == nil {
t.Fatalf("json.Unmarshal(%q, Code) did not error", test)
}
}
}
@ -133,3 +139,30 @@ func TestCodeMarshalJSONErrorInvalid(t *testing.T) {
t.Fatal("Code(maxCode).MarshalJSON() returned non-nil value")
}
}
func TestRoundTripCodes(t *testing.T) {
tests := []struct {
input Code
}{
{Unset},
{Error},
{Ok},
}
for _, test := range tests {
c := test.input
out := new(Code)
b, err := c.MarshalJSON()
if err != nil {
t.Fatalf("Code(%s).MarshalJSON() errored: %v", test.input, err)
}
if err := out.UnmarshalJSON(b); err != nil {
t.Fatalf("Code.UnmarshalJSON(%q) errored: %v", c, err)
}
if *out != test.input {
t.Errorf("failed to round trip %q, output was %v", test.input, out)
}
}
}