Skip to content
Snippets Groups Projects
config_test.go 6.99 KiB
Newer Older
package runner_test
steeve.chailloux's avatar
steeve.chailloux committed
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
Florent Aide's avatar
Florent Aide committed
	"orus.io/orus-io/beaver/runner"
	"orus.io/orus-io/beaver/testutils"
	fixtures    = "fixtures/f1"
	shaFixtures = "fixtures/f2"
Florent Aide's avatar
Florent Aide committed
	config, err := runner.NewConfig(filepath.Join(fixtures, "base"))
	require.NoError(t, err)
	// first config.spec.variables entry name should be VAULT_KV in our test file
	assert.Equal(t, "VAULT_KV", config.Variables[0].Name)
	assert.Equal(t, "orus.io", config.Variables[0].Value)
	assert.Equal(t, "../vendor/helm/postgresql", config.Charts["postgres"].Path)
	assert.Equal(t, "../vendor/ytt/odoo", config.Charts["odoo"].Path)
func TestHydrate(t *testing.T) {
	rawVariables := []byte(`
#@data/values
---
foo: |
    a multi
    line string
bar:
Florent Aide's avatar
Florent Aide committed
    port: 5432
    simple: interface
    with:
        - some
        - content
baz: |
    only one line in multiline mode
boo: a simple joke line
Florent Aide's avatar
Florent Aide committed
voo: 33
`)
	variables := make(map[string]interface{})

	byteContent := bytes.NewReader(rawVariables)
	decoder := yaml.NewDecoder(byteContent)

	require.NoError(t, decoder.Decode(&variables))
	input := `
#@data/values
---
foo: <[foo]>
bar: <[bar]>
baz: <[baz]>
boo: <[boo]>
Florent Aide's avatar
Florent Aide committed
voo: <[voo]>
barport: <[bar.port]>
barwith: <[bar.with.1]>
`

	buf := bytes.NewBufferString("")
	require.NoError(t, runner.Hydrate([]byte(input), buf, variables))
	assert.Equal(
		t,
		`
#@data/values
---
foo: |
    a multi
    line string
bar:
    port: 5432
    simple: interface
    with:
        - some
        - content
baz: |
    only one line in multiline mode
boo: a simple joke line
voo: 33
barport: 5432
barwith: content
`,
		buf.String(),
	)
}

func TestHydrateSideEffect(t *testing.T) {
	rawVariables := []byte(`
---
foo: 33
`)
	variables := make(map[string]interface{})

	byteContent := bytes.NewReader(rawVariables)
	decoder := yaml.NewDecoder(byteContent)

	require.NoError(t, decoder.Decode(&variables))
	input := `
---
foo: <[foo]>
Florent Aide's avatar
Florent Aide committed
bar: |
  [section1]
  value1 = 1
  # ----------
  # some comment
  # ----------
  value2 = 2
replicas: 1
`
	expected := `
---
foo: 33
bar: |
Florent Aide's avatar
Florent Aide committed
    [section1]
    value1 = 1
    # ----------
    # some comment
    # ----------
    value2 = 2
replicas: 1
`

	buf := bytes.NewBufferString("")
	require.NoError(t, runner.Hydrate([]byte(input), buf, variables))
	assert.Equal(
		t,
		expected,
		buf.String(),
	)
}

func TestYttBuildArgs(t *testing.T) {
	tl := testutils.NewTestLogger(t)
Florent Aide's avatar
Florent Aide committed
	testNS := "environments/ns1"
	absConfigDir, err := filepath.Abs(fixtures)
	require.NoError(t, err)
steeve.chailloux's avatar
steeve.chailloux committed
	c := runner.NewCmdConfig(tl.Logger(), absConfigDir, testNS, false, "")
	tmpDir, err := os.MkdirTemp(os.TempDir(), "beaver-")
	require.NoError(t, err)
Florent Aide's avatar
Florent Aide committed
	defer func() {
		assert.NoError(t, os.RemoveAll(tmpDir))
	}()
	require.NoError(t, c.Initialize(tmpDir))
	args := c.BuildYttArgs(c.Spec.Ytt, []string{"/tmp/postgres.1234.yaml", "/tmp/odoo.5678.yaml"})
steeve.chailloux's avatar
steeve.chailloux committed
	require.NoError(t, err)
steeve.chailloux's avatar
steeve.chailloux committed
		// []string{
		// 	"-f", "/tmp/postgres.1234.yaml", "--file-mark=postgres.1234.yaml:type=yaml-plain",
		// 	"-f", "/tmp/odoo.5678.yaml", "--file-mark=odoo.5678.yaml:type=yaml-plain",
		// 	"-f", filepath.Join(fixtures, "base/ytt"),
		// 	"-f", filepath.Join(fixtures, "base/ytt.yml"),
		// 	"-f", filepath.Join(fixtures, "environments/ns1/ytt"),
		// 	"-f", filepath.Join(fixtures, "environments/ns1/ytt.yaml"),
		// },
		14,
		len(args),
func TestInheritVariables(t *testing.T) {
	tl := testutils.NewTestLogger(t)
	testNS := "environments/ns1"
	absConfigDir, err := filepath.Abs(fixtures)
	require.NoError(t, err)
	c := runner.NewCmdConfig(tl.Logger(), absConfigDir, testNS, false, "")
	tmpDir, err := os.MkdirTemp(os.TempDir(), "beaver-")
	require.NoError(t, err)
	defer func() {
		assert.NoError(t, os.RemoveAll(tmpDir))
	}()
	require.NoError(t, c.Initialize(tmpDir))
	assert.Equal(t, "another value", c.Spec.Variables.GetD("test-nested.nested-value1", nil))
	assert.Equal(t, "Value2", c.Spec.Variables.GetD("test-nested.nested-value2", nil))
}

func TestCreateConfig(t *testing.T) {
	tl := testutils.NewTestLogger(t)
Florent Aide's avatar
Florent Aide committed
	testNS := "environments/ns1"
	absConfigDir, err := filepath.Abs(fixtures)
	require.NoError(t, err)
steeve.chailloux's avatar
steeve.chailloux committed
	c := runner.NewCmdConfig(tl.Logger(), absConfigDir, testNS, false, "")
	tmpDir, err := os.MkdirTemp(os.TempDir(), "beaver-")
	require.NoError(t, err)
	defer func() {
		assert.NoError(t, os.RemoveAll(tmpDir))
	}()
	require.NoError(t, c.Initialize(tmpDir))
	require.Equal(t, 1, len(c.Spec.Creates))

	assert.True(t, filepath.IsAbs(c.Spec.Charts["postgres"].Path))
	crKey := runner.CmdCreateKey{
		Type: "configmap",
		Name: "xbus-pipelines",
	}
	cr, ok := c.Spec.Creates[crKey]
	assert.True(t, ok)
	require.Equal(t, 1, len(cr.Args))

	for k, create := range c.Spec.Creates {
		args := k.BuildArgs(c.Namespace, create.Args)
		assert.Equal(
			t,
			[]string{
				"-n", c.Namespace,
				"create",
				"configmap", "xbus-pipelines",
				"--dry-run=client", "-o", "yaml",
steeve.chailloux's avatar
steeve.chailloux committed
				"--from-file", "pipelines",
Christophe de Vienne's avatar
Christophe de Vienne committed
	shaValue := "2145bea9e32804c65d960e6d4af1c87f95ccc39fad7df5eec2f3925a193112ab"
steeve.chailloux's avatar
steeve.chailloux committed
	buildDir := filepath.Join(shaFixtures, "build", "example")
	defer func() {
		require.NoError(t, runner.CleanDir(buildDir))
	}()

	tl := testutils.NewTestLogger(t)
	absConfigDir, err := filepath.Abs(shaFixtures)
	require.NoError(t, err)
	c := runner.NewCmdConfig(tl.Logger(), absConfigDir, "base", false, "")
	tmpDir, err := os.MkdirTemp(os.TempDir(), "beaver-")
	require.NoError(t, err)
	defer func() {
		assert.NoError(t, os.RemoveAll(tmpDir))
	}()
	require.NoError(t, c.Initialize(tmpDir))
	r := runner.NewRunner(c)
	require.NoError(t, r.Build(tmpDir))

	configMap := filepath.Join(buildDir, "ConfigMap.v1.demo.yaml")
	cm, err := parseFile(configMap)
steeve.chailloux's avatar
steeve.chailloux committed
	require.NoError(t, err)
	sha, err := getLabel(cm, "mysha")
	require.NoError(t, err)
	require.Equal(t, shaValue, sha)

	deployment := filepath.Join(buildDir, "Deployment.apps_v1.nginx.yaml")
steeve.chailloux's avatar
steeve.chailloux committed
	deploy, err := parseFile(deployment)
	require.NoError(t, err)
	sha, err = getLabel(deploy, "config.sha")
	require.NoError(t, err)
	require.Equal(t, shaValue, sha)
steeve.chailloux's avatar
steeve.chailloux committed
func getLabel(resource map[string]interface{}, label string) (string, error) {
	metadata, ok := resource["metadata"].(map[string]interface{})
steeve.chailloux's avatar
steeve.chailloux committed
	if !ok {
		return "", fmt.Errorf("fail to get label: metadata on %+v", resource["metadata"])
steeve.chailloux's avatar
steeve.chailloux committed
	}
	labels, ok := metadata["labels"].(map[string]interface{})
steeve.chailloux's avatar
steeve.chailloux committed
	if !ok {
		return "", fmt.Errorf("fail to get label: labels on %+v", metadata["labels"])
steeve.chailloux's avatar
steeve.chailloux committed
	}
	result, ok := labels[label].(string)
steeve.chailloux's avatar
steeve.chailloux committed
	if !ok {
steeve.chailloux's avatar
steeve.chailloux committed
		return "", fmt.Errorf("fail to get label: result")
steeve.chailloux's avatar
steeve.chailloux committed
	}
	return result, nil
steeve.chailloux's avatar
steeve.chailloux committed
func parseFile(input string) (map[string]interface{}, error) {
	resource := make(map[string]interface{})

	content, err := os.ReadFile(input)
steeve.chailloux's avatar
steeve.chailloux committed
	if err != nil {
		return nil, fmt.Errorf("fail to parse: %w", err)
	}

	byteContent := bytes.NewReader(content)
	decoder := yaml.NewDecoder(byteContent)

	err = decoder.Decode(&resource)
steeve.chailloux's avatar
steeve.chailloux committed
	if err != nil {
		return nil, fmt.Errorf("fail to parse: %w", err)
	}
steeve.chailloux's avatar
steeve.chailloux committed
	return resource, nil