Skip to content

Commit

Permalink
fix(docker): errors when creating images with no name or id
Browse files Browse the repository at this point in the history
vitorfhc committed Mar 28, 2022
1 parent 440f7d6 commit bf2f8f3
Showing 3 changed files with 30 additions and 5 deletions.
14 changes: 14 additions & 0 deletions pkg/docker/image.go
Original file line number Diff line number Diff line change
@@ -61,6 +61,20 @@ func NewImage(m map[string]interface{}) (*Image, error) {
v.Set(key, val)
}

fieldsNoEmpty := []string{"id", "name"}
invalidFields := []string{}
for _, field := range fieldsNoEmpty {
value := v.GetString(field)
if value == "" {
invalidFields = append(invalidFields, field)
}
}
if len(invalidFields) > 0 {
errMsg := fmt.Sprintf("Invalid fields: %s", strings.Join(invalidFields, ", "))
errMsg += ". All these fields are required."
return nil, errors.New(errMsg)
}

err := v.Unmarshal(&img.Config)
if err != nil {
return nil, err
15 changes: 13 additions & 2 deletions pkg/docker/image_test.go
Original file line number Diff line number Diff line change
@@ -109,11 +109,12 @@ func TestNewImage(t *testing.T) {
{
name: "image with defaults",
fields: map[string]interface{}{
"id": "test-id", // avoids random id
"id": "test-id", // avoids random id
"name": "test-image",
},
want: map[string]interface{}{
"id": "test-id",
"name": "",
"name": "test-image",
"tags": []string{"latest"},
"context": ".",
"dockerfile": "Dockerfile",
@@ -149,6 +150,13 @@ func TestNewImage(t *testing.T) {
"registry": "duckuhub",
},
},
{
name: "image with no name",
fields: map[string]interface{}{
"id": "test-id",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -157,6 +165,9 @@ func TestNewImage(t *testing.T) {
t.Errorf("NewImage() error = %v, wantErr %v", err, tt.wantErr)
t.FailNow()
}
if err != nil {
return
}
got := map[string]interface{}{
"id": img.Config.ID,
"name": img.Config.Name,
6 changes: 3 additions & 3 deletions pkg/docker/imagesset_test.go
Original file line number Diff line number Diff line change
@@ -13,17 +13,17 @@ func TestImagesSet_AddImages(t *testing.T) {
name: "adds images without error",
imagesAdded: []map[string]interface{}{},
imagesToAdd: []map[string]interface{}{
{"id": "1"},
{"id": "1", "name": "test-image"},
},
wantErr: false,
},
{
name: "adds duplicated images",
imagesAdded: []map[string]interface{}{
{"id": "1"},
{"id": "1", "name": "test-image"},
},
imagesToAdd: []map[string]interface{}{
{"id": "1"},
{"id": "1", "name": "another-image"},
},
wantErr: true,
},

0 comments on commit bf2f8f3

Please sign in to comment.