pkg: add new manifesttest package with test helpers

This commit adds a new `manifesttest` that helps sharing code
when testing generated osbuild manifests.
This commit is contained in:
Michael Vogt 2024-12-02 12:16:37 +01:00 committed by Simon de Vlieger
parent 8ae5b98d9d
commit 5a6ee5c1ca
2 changed files with 62 additions and 0 deletions

View file

@ -0,0 +1,27 @@
package manifesttest
import (
"encoding/json"
"fmt"
)
// PipelineNamesFrom will return all pipeline names from an osbuild
// json manifest. It will error on missing pipelines.
//
// TODO: move to images:pkg/manifesttest
func PipelineNamesFrom(osbuildManifest []byte) ([]string, error) {
var manifest map[string]interface{}
if err := json.Unmarshal(osbuildManifest, &manifest); err != nil {
return nil, fmt.Errorf("cannot unmarshal manifest: %w", err)
}
if manifest["pipelines"] == nil {
return nil, fmt.Errorf("cannot find any pipelines in %v", manifest)
}
pipelines := manifest["pipelines"].([]interface{})
pipelineNames := make([]string, len(pipelines))
for idx, pi := range pipelines {
pipelineNames[idx] = pi.(map[string]interface{})["name"].(string)
}
return pipelineNames, nil
}

View file

@ -0,0 +1,35 @@
package manifesttest_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/osbuild/image-builder-cli/internal/manifesttest"
)
var fakeOsbuildManifest = `{
"version": "2",
"pipelines": [
{
"name": "noop"
},
{
"name": "noop2"
}
]
}`
func TestPipelineNamesFrom(t *testing.T) {
names, err := manifesttest.PipelineNamesFrom([]byte(fakeOsbuildManifest))
assert.NoError(t, err)
assert.Equal(t, []string{"noop", "noop2"}, names)
}
func TestPipelineNamesFromSad(t *testing.T) {
_, err := manifesttest.PipelineNamesFrom([]byte("bad-json"))
assert.ErrorContains(t, err, "cannot unmarshal manifest: invalid char")
_, err = manifesttest.PipelineNamesFrom([]byte("{}"))
assert.ErrorContains(t, err, "cannot find any pipelines in map[]")
}