Skip to content
Snippets Groups Projects
flags_test.go 2.57 KiB
// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0

package configuration

import (
	"flag"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

// Example for README
// Print are commented out because they are only for demonstration
func TestReadmeExample3(t *testing.T) {
	config := struct {
		Host string `flag:"host"`
	}{
		Host: "localhost",
	}

	// Set value
	flag.String("host", "www.example.com", "help message for flagname")
	flag.Parse()

	s := New(config)
	s.InitFromFlagSet(flag.CommandLine)

	//fmt.Println(s.Config().Host) // www.example.com
	assert.Equal(t, s.Config().Host, "www.example.com")

}

func TestSettingFromFlagWithDefault(t *testing.T) {
	config := ConfigStruct6{}

	s := New(config)
	assert.Equal(t, s.Config().IB, "yes")

	cmd := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	cmd.String("config", "", "help message for flagname")

	tmp, err := os.CreateTemp("", "config")
	if err != nil {
		t.Error(err)
		return
	}
	defer os.Remove(tmp.Name())

	tmp.WriteString("IB: i-am-b")
	cmd.Parse([]string{"--config", tmp.Name()})
	s.AddFileFromFlagSet(cmd, "config", Yaml)

	s.Import()

	assert.Equal(t, s.Config().IB, "i-am-b")

}

func TestSettingFromFlag2(t *testing.T) {

	config := ConfigStruct6{
		IA: 1234,
		IB: "no",
		IC: false,
		ID: true,
	}

	s := New(config)

	cmd := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	cmd.Int("value-ia", 1234, "help message for flagname")
	cmd.String("value-ib", "no", "help message for flagname")
	cmd.Bool("value-ic", false, "help message for flagname")
	cmd.Bool("value-id", true, "help message for flagname")

	cmd.Parse([]string{"--value-ia=1423"})

	s.InitFromFlagSet(cmd)

	if s.Config().IA != 1423 {
		t.Errorf("Expected 1423, got %d", s.Config().IA)
	}

}

func TestSettingFromFlag(t *testing.T) {
	config := ConfigStruct6{
		IA: 34567,
		ID: true,
	}

	s := New(config)

	cmd := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	cmd.Int("value-ia", 1234, "help message for flagname")
	cmd.String("value-ib", "no", "help message for flagname")
	cmd.Bool("value-ic", false, "help message for flagname")
	cmd.Bool("value-id", true, "help message for flagname")

	cmd.Parse([]string{"--value-ia=8900",
		"--value-ib=i-am-b",
		"--value-ic=true",
		"--value-id=false"})

	s.InitFromFlagSet(cmd)

	if s.Config().IA != 8900 {
		t.Errorf("Expected 8900, got %d", s.Config().IA)
	}

	if s.Config().IB != "i-am-b" {
		t.Errorf("Expected i-am-b, got %s", s.Config().IB)
	}

	if s.Config().IC != true {
		t.Errorf("Expected true, got %t", s.Config().IC)
	}

	if s.Config().ID != false {
		t.Errorf("Expected false, got %t", s.Config().ID)
	}

}