Skip to content

Commit

Permalink
Merge pull request #303 from pstibrany/marshalling-url-wrapper-with-nil
Browse files Browse the repository at this point in the history
Fix marshalling of URL wrapper with nil value.
  • Loading branch information
roidelapluie authored Jun 3, 2021
2 parents 6a45412 + 558a787 commit 401cd58
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
2 changes: 1 addition & 1 deletion config/http_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func (u URL) MarshalJSON() ([]byte, error) {
if u.URL != nil {
return json.Marshal(u.URL.String())
}
return nil, nil
return []byte("null"), nil
}

// OAuth2 is the oauth2 client configuration.
Expand Down
77 changes: 77 additions & 0 deletions config/http_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1302,6 +1302,83 @@ func TestMarshalURL(t *testing.T) {
}
}

func TestMarshalURLWrapperWithNilValue(t *testing.T) {
u := &URL{}

c, err := json.Marshal(u)
if err != nil {
t.Fatal(err)
}
if string(c) != "null" {
t.Fatalf("URL with nil value not properly marshaled into JSON, got %q", c)
}

c, err = yaml.Marshal(u)
if err != nil {
t.Fatal(err)
}
if string(c) != "null\n" {
t.Fatalf("URL with nil value not properly marshaled into JSON, got %q", c)
}
}

func TestUnmarshalNullURL(t *testing.T) {
b := []byte(`null`)

{
var u URL
err := json.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if !isEmptyNonNilURL(u.URL) {
t.Fatalf("`null` literal not properly unmarshaled from JSON as URL, got %#v", u.URL)
}
}

{
var u URL
err := yaml.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if u.URL != nil { // UnmarshalYAML is not called when parsing null literal.
t.Fatalf("`null` literal not properly unmarshaled from YAML as URL, got %#v", u.URL)
}
}
}

func TestUnmarshalEmptyURL(t *testing.T) {
b := []byte(`""`)

{
var u URL
err := json.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if !isEmptyNonNilURL(u.URL) {
t.Fatalf("empty string not properly unmarshaled from JSON as URL, got %#v", u.URL)
}
}

{
var u URL
err := yaml.Unmarshal(b, &u)
if err != nil {
t.Fatal(err)
}
if !isEmptyNonNilURL(u.URL) {
t.Fatalf("empty string not properly unmarshaled from YAML as URL, got %#v", u.URL)
}
}
}

// checks if u equals to &url.URL{}
func isEmptyNonNilURL(u *url.URL) bool {
return u != nil && *u == url.URL{}
}

func TestUnmarshalURL(t *testing.T) {
b := []byte(`"http://example.com/a b"`)
var u URL
Expand Down

0 comments on commit 401cd58

Please sign in to comment.