Verified Commit 8a1370bb authored by José M. Requena Plens's avatar José M. Requena Plens Committed by GitLab
Browse files

fix(issues): avoid panic unmarshalling an Issue with no id

Changelog: Improvements
parent fc4b4cca
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -167,7 +167,7 @@ func (i *Issue) UnmarshalJSON(data []byte) error {
		return err
	}

	if reflect.TypeOf(raw["id"]).Kind() == reflect.String {
	if _, ok := raw["id"].(string); ok {
		raw["external_id"] = raw["id"]
		delete(raw, "id")
	}
+53 −0
Original line number Diff line number Diff line
@@ -17,6 +17,7 @@
package gitlab

import (
	"encoding/json"
	"fmt"
	"net/http"
	"testing"
@@ -996,3 +997,55 @@ func TestGetIssueWithServiceDesk(t *testing.T) {

	assert.Equal(t, want, issue)
}

func TestIssueUnmarshalJSON(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name           string
		body           string
		wantID         int64
		wantExternalID string
	}{
		{
			name:   "numeric id is preserved",
			body:   `{"id":1,"title":"test"}`,
			wantID: 1,
		},
		{
			name:           "string id is moved to external_id",
			body:           `{"id":"PROJECT-123","title":"test"}`,
			wantExternalID: "PROJECT-123",
		},
		{
			name: "object without an id",
			body: `{"title":"test"}`,
		},
		{
			name: "explicit null id",
			body: `{"id":null,"title":"test"}`,
		},
		{
			name: "empty object",
			body: `{}`,
		},
		{
			name: "null document",
			body: `null`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			var issue Issue
			require.NotPanics(t, func() {
				require.NoError(t, json.Unmarshal([]byte(tt.body), &issue))
			})

			assert.Equal(t, tt.wantID, issue.ID)
			assert.Equal(t, tt.wantExternalID, issue.ExternalID)
		})
	}
}