Skip to content

Commit

Permalink
Add new constructor to create documents
Browse files Browse the repository at this point in the history
The change would allow to build a document object from bytes

Change-Id: I15c13a960b4e989cffa4525c85b8f32f2a51a0e1
Relates-To: #238
Relates-To: #279
Closes: #279
  • Loading branch information
teoyaomiqui committed Jun 17, 2020
1 parent 6a89670 commit 36facd3
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pkg/document/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const (
SecretKind = "Secret"
BareMetalHostKind = "BareMetalHost"

ConfigMapKind = "ConfigMap"
ConfigMapVersion = "v1"

ClusterctlMetadataKind = "Metadata"
ClusterctlMetadataVersion = "v1alpha3"
ClusterctlMetadataGroup = "clusterctl.cluster.x-k8s.io"
Expand Down
12 changes: 12 additions & 0 deletions pkg/document/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package document

import (
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/yaml"
)
Expand Down Expand Up @@ -198,3 +199,14 @@ func NewDocument(r *resource.Resource) (Document, error) {
err := doc.SetKustomizeResource(r)
return doc, err
}

// NewDocumentFromBytes constructs document from bytes
func NewDocumentFromBytes(b []byte) (Document, error) {
res, err := resource.NewFactory(kunstruct.NewKunstructuredFactoryImpl()).FromBytes(b)
if err != nil {
return nil, err
}
doc := &Factory{}
err = doc.SetKustomizeResource(res)
return doc, err
}
43 changes: 43 additions & 0 deletions pkg/document/document_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,46 @@ func TestDocument(t *testing.T) {
}
})
}

func TestNewDocumentFromBytes(t *testing.T) {
tests := []struct {
name string
stringData string
expectErr bool
expectedDocName string
}{
{
name: "ConfigMap",
stringData: `apiVersion: v1
kind: Secret
metadata:
name: control-0-bmc
namespace: metal3
type: Opaque
stringData:
username: username
password: password`,
expectErr: false,
expectedDocName: "control-0-bmc",
},
{
name: "Manformed Bytes",
stringData: `
broken:fas -<
fasd`,
expectErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
doc, err := document.NewDocumentFromBytes([]byte(tt.stringData))
if tt.expectErr {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, doc.GetName(), tt.expectedDocName)
}
})
}
}

0 comments on commit 36facd3

Please sign in to comment.