Skip to content

Commit

Permalink
[fix] add nil checks to avoid panic when creating an OIR without a su…
Browse files Browse the repository at this point in the history
…bscription (#1039)
  • Loading branch information
Shastick authored May 24, 2024
1 parent 2c0ff28 commit c2cecc0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
3 changes: 3 additions & 0 deletions pkg/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ const (
// PgUUID converts an ID to a pgtype.UUID.
// If the ID this is called on is nil, nil will be returned
func (id *ID) PgUUID() (*pgtype.UUID, error) {
if id == nil {
return nil, nil
}
pgUUID := pgtype.UUID{}
err := (&pgUUID).Scan(id.String())
if err != nil {
Expand Down
57 changes: 56 additions & 1 deletion pkg/models/models_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package models

import "testing"
import (
"reflect"
"testing"

"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
)

func TestIDFromString(t *testing.T) {
type args struct {
Expand Down Expand Up @@ -82,3 +88,52 @@ func TestIDFromString(t *testing.T) {
})
}
}

func scanIntoUUID(t *testing.T, id ID) *pgtype.UUID {
uuid := pgtype.UUID{}
err := uuid.Scan(id.String())
assert.Nil(t, err)
return &uuid
}

func TestID_PgUUID(t *testing.T) {
someID := ID("00000179-e36d-40be-838b-eca6ca350000")
badID := ID("00000179-e36d-40be-838b-eca6ca35")
tests := []struct {
name string
id *ID
want *pgtype.UUID
wantErr bool
}{
{
name: "Ok",
id: &someID,
want: scanIntoUUID(t, someID),
wantErr: false,
},
{
name: "Nil ID",
id: nil,
want: nil,
wantErr: false,
},
{
name: "Bad UUID",
id: &badID,
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.id.PgUUID()
if (err != nil) != tt.wantErr {
t.Errorf("PgUUID() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("PgUUID() got = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit c2cecc0

Please sign in to comment.