github.com/wtrep/tgf@v1.18.8/config_test.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"math/rand"
     7  	"os"
     8  	"path"
     9  	"path/filepath"
    10  	"reflect"
    11  	"strings"
    12  	"testing"
    13  	"time"
    14  
    15  	"github.com/aws/aws-sdk-go/aws"
    16  	"github.com/aws/aws-sdk-go/aws/session"
    17  	"github.com/aws/aws-sdk-go/service/ssm"
    18  	"github.com/stretchr/testify/assert"
    19  )
    20  
    21  func TestCheckVersionRange(t *testing.T) {
    22  	t.Parallel()
    23  
    24  	type args struct {
    25  		version string
    26  		compare string
    27  	}
    28  	tests := []struct {
    29  		name    string
    30  		args    args
    31  		want    bool
    32  		wantErr bool
    33  	}{
    34  		{"Invalid version", args{"x", "y"}, false, true},
    35  		{"Valid", args{"1.20.0", ">=1.19.x"}, true, false},
    36  		{"Valid major minor", args{"1.19", ">=1.19.5"}, true, false},
    37  		{"Valid major minor 2", args{"1.19", ">=1.19.x"}, true, false},
    38  		{"Invalid major minor", args{"1.18", ">=1.19.x"}, false, false},
    39  		{"Out of range", args{"1.15.9-Beta.1", ">=1.19.x"}, false, false},
    40  		{"Same", args{"1.22.1", "=1.22.1"}, true, false},
    41  		{"Not same", args{"1.22.1", "=1.22.2"}, false, false},
    42  		{"Same minor", args{"1.22.1", "=1.22.x"}, true, false},
    43  		{"Same major", args{"1.22.1", "=1.x"}, true, false},
    44  		{"Not same major", args{"2.22.1", "=1.x"}, false, false},
    45  	}
    46  	for _, tt := range tests {
    47  		t.Run(tt.name, func(t *testing.T) {
    48  			got, err := CheckVersionRange(tt.args.version, tt.args.compare)
    49  			if (err != nil) != tt.wantErr {
    50  				t.Errorf("CheckVersionRange() error = %v, wantErr %v", err, tt.wantErr)
    51  				return
    52  			}
    53  			if got != tt.want {
    54  				t.Errorf("CheckVersionRange() = %v, want %v", got, tt.want)
    55  			}
    56  		})
    57  	}
    58  }
    59  
    60  func TestSetConfigDefaultValues(t *testing.T) {
    61  	tempDir, _ := filepath.EvalSymlinks(must(ioutil.TempDir("", "TestGetConfig")).(string))
    62  	currentDir, _ := os.Getwd()
    63  	os.Chdir(tempDir)
    64  	fmt.Println(tempDir)
    65  	defer func() {
    66  		os.Chdir(currentDir)
    67  		os.RemoveAll(tempDir)
    68  	}()
    69  
    70  	testTgfConfigFile := fmt.Sprintf("%s/.tgf.config", tempDir)
    71  	testTgfUserConfigFile := fmt.Sprintf("%s/tgf.user.config", tempDir)
    72  	testSSMParameterFolder := fmt.Sprintf("/test/tgf-%v", randInt())
    73  
    74  	writeSSMConfig(testSSMParameterFolder, "docker-image-build", "RUN ls test")
    75  	writeSSMConfig(testSSMParameterFolder, "docker-image-build-folder", "/abspath/my-folder")
    76  	writeSSMConfig(testSSMParameterFolder, "alias", `{"my-alias": "--arg value"}`)
    77  	defer deleteSSMConfig(testSSMParameterFolder, "docker-image-build")
    78  	defer deleteSSMConfig(testSSMParameterFolder, "docker-image-build-folder")
    79  	defer deleteSSMConfig(testSSMParameterFolder, "alias")
    80  
    81  	userTgfConfig := []byte(String(`
    82  		docker-image = "coveo/overwritten"
    83  		docker-image-tag = "test"
    84  	`).UnIndent().TrimSpace())
    85  	ioutil.WriteFile(testTgfUserConfigFile, userTgfConfig, 0644)
    86  
    87  	tgfConfig := []byte(String(`
    88  		docker-image: coveo/stuff
    89  		docker-image-build: RUN ls test2
    90  		docker-image-build-tag: hello
    91  		docker-image-build-folder: my-folder
    92  	`).UnIndent().TrimSpace())
    93  	ioutil.WriteFile(testTgfConfigFile, tgfConfig, 0644)
    94  
    95  	config := InitConfig()
    96  	config.setDefaultValues(testSSMParameterFolder)
    97  
    98  	assert.Len(t, config.imageBuildConfigs, 2)
    99  
   100  	assert.Equal(t, path.Join(tempDir, ".tgf.config"), config.imageBuildConfigs[0].source)
   101  	assert.Equal(t, "RUN ls test2", config.imageBuildConfigs[0].Instructions)
   102  	assert.Equal(t, "my-folder", config.imageBuildConfigs[0].Folder)
   103  	assert.Equal(t, path.Join(tempDir, "my-folder"), config.imageBuildConfigs[0].Dir())
   104  	assert.Equal(t, "hello", config.imageBuildConfigs[0].GetTag())
   105  
   106  	assert.Equal(t, "AWS/ParametersStore", config.imageBuildConfigs[1].source)
   107  	assert.Equal(t, "RUN ls test", config.imageBuildConfigs[1].Instructions)
   108  	assert.Equal(t, "/abspath/my-folder", config.imageBuildConfigs[1].Folder)
   109  	assert.Equal(t, "/abspath/my-folder", config.imageBuildConfigs[1].Dir())
   110  	assert.Equal(t, "AWS", config.imageBuildConfigs[1].GetTag())
   111  
   112  	assert.Equal(t, "coveo/stuff", config.Image)
   113  	assert.Equal(t, "test", *config.ImageTag)
   114  	assert.Equal(t, map[string]string{"my-alias": "--arg value"}, config.Aliases)
   115  	assert.Nil(t, config.ImageVersion)
   116  }
   117  
   118  func TestTwoLevelsOfTgfConfig(t *testing.T) {
   119  	tempDir, _ := filepath.EvalSymlinks(must(ioutil.TempDir("", "TestGetConfig")).(string))
   120  	subFolder := path.Join(tempDir, "sub-folder")
   121  	must(os.Mkdir(subFolder, os.ModePerm))
   122  	tempDir = subFolder
   123  	currentDir, _ := os.Getwd()
   124  	os.Chdir(tempDir)
   125  	fmt.Println(tempDir)
   126  	defer func() {
   127  		os.Chdir(currentDir)
   128  		os.RemoveAll(tempDir)
   129  	}()
   130  
   131  	testParentTgfConfigFile := fmt.Sprintf("%s/../.tgf.config", tempDir)
   132  	testTgfConfigFile := fmt.Sprintf("%s/.tgf.config", tempDir)
   133  	testSSMParameterFolder := fmt.Sprintf("/test/tgf-%v", randInt())
   134  
   135  	parentTgfConfig := []byte(String(`
   136  	docker-image: coveo/stuff
   137  	docker-image-version: 2.0.1
   138  	`).UnIndent().TrimSpace())
   139  	ioutil.WriteFile(testParentTgfConfigFile, parentTgfConfig, 0644)
   140  
   141  	// Current directory config overwrites parent directory config
   142  	tgfConfig := []byte(String(`docker-image-version: 2.0.2`))
   143  	ioutil.WriteFile(testTgfConfigFile, tgfConfig, 0644)
   144  
   145  	config := InitConfig()
   146  	config.setDefaultValues(testSSMParameterFolder)
   147  
   148  	assert.Equal(t, "coveo/stuff", config.Image)
   149  	assert.Equal(t, "2.0.2", *config.ImageVersion)
   150  }
   151  
   152  func TestWeirdDirName(t *testing.T) {
   153  	tempDir, _ := ioutil.TempDir("", "bad@(){}-good-_.1234567890ABC")
   154  	currentDir, _ := os.Getwd()
   155  	os.Chdir(tempDir)
   156  	fmt.Println(tempDir)
   157  	defer func() {
   158  		os.Chdir(currentDir)
   159  		os.RemoveAll(tempDir)
   160  	}()
   161  	testSSMParameterFolder := fmt.Sprintf("/test/tgf-%v", randInt())
   162  	testTgfConfigFile := fmt.Sprintf("%s/.tgf.config", tempDir)
   163  	tgfConfig := []byte(String(`
   164  		docker-image: coveo/stuff
   165  		docker-image-build: RUN ls test2
   166  		docker-image-build-folder: my-folder
   167  	`).UnIndent().TrimSpace())
   168  	ioutil.WriteFile(testTgfConfigFile, tgfConfig, 0644)
   169  
   170  	config := InitConfig()
   171  	config.setDefaultValues(testSSMParameterFolder)
   172  
   173  	assert.True(t, strings.HasPrefix(config.imageBuildConfigs[0].GetTag(), "bad-good-_.1234567890ABC"))
   174  }
   175  
   176  func TestParseAliases(t *testing.T) {
   177  	t.Parallel()
   178  
   179  	config := TGFConfig{
   180  		Aliases: map[string]string{
   181  			"to_replace": "one two three,four",
   182  			"other_arg1": "will not be replaced",
   183  			"with_quote": `quoted arg1 "arg 2" -D -it --rm`,
   184  		},
   185  	}
   186  
   187  	tests := []struct {
   188  		name   string
   189  		config TGFConfig
   190  		args   []string
   191  		want   []string
   192  	}{
   193  		{"Nil", config, nil, nil},
   194  		{"Empty", config, []string{}, nil},
   195  		{"Unchanged", config, strings.Split("whatever the args are", " "), nil},
   196  		{"Replaced", config, strings.Split("to_replace with some args", " "), []string{"one", "two", "three,four", "with", "some", "args"}},
   197  		{"Replaced 2", config, strings.Split("to_replace other_arg1", " "), []string{"one", "two", "three,four", "other_arg1"}},
   198  		{"Replaced with quote", config, strings.Split("with_quote 1 2 3", " "), []string{"quoted", "arg1", "arg 2", "-D", "-it", "--rm", "1", "2", "3"}},
   199  	}
   200  
   201  	for _, tt := range tests {
   202  		t.Run(tt.name, func(t *testing.T) {
   203  			if got := tt.config.ParseAliases(tt.args); !reflect.DeepEqual(got, tt.want) {
   204  				t.Errorf("TGFConfig.ParseAliases() = %v, want %v", got, tt.want)
   205  			}
   206  		})
   207  	}
   208  }
   209  
   210  func writeSSMConfig(parameterFolder, parameterKey, parameterValue string) {
   211  	fullParameterKey := fmt.Sprintf("%s/%s", parameterFolder, parameterKey)
   212  	client := getSSMClient()
   213  
   214  	putParameterInput := &ssm.PutParameterInput{
   215  		Name:      aws.String(fullParameterKey),
   216  		Value:     aws.String(parameterValue),
   217  		Overwrite: aws.Bool(true),
   218  		Type:      aws.String(ssm.ParameterTypeString),
   219  	}
   220  
   221  	if _, err := client.PutParameter(putParameterInput); err != nil {
   222  		panic(err)
   223  	}
   224  }
   225  
   226  func deleteSSMConfig(parameterFolder, parameterKey string) {
   227  	fullParameterKey := fmt.Sprintf("%s/%s", parameterFolder, parameterKey)
   228  	client := getSSMClient()
   229  
   230  	deleteParameterInput := &ssm.DeleteParameterInput{
   231  		Name: aws.String(fullParameterKey),
   232  	}
   233  
   234  	if _, err := client.DeleteParameter(deleteParameterInput); err != nil {
   235  		panic(err)
   236  	}
   237  }
   238  
   239  func getSSMClient() *ssm.SSM {
   240  	awsSession := session.Must(session.NewSessionWithOptions(session.Options{
   241  		SharedConfigState: session.SharedConfigEnable,
   242  	}))
   243  	return ssm.New(awsSession, &aws.Config{Region: aws.String("us-east-1")})
   244  }
   245  
   246  func randInt() int {
   247  	source := rand.NewSource(time.Now().UnixNano())
   248  	random := rand.New(source)
   249  	return random.Int()
   250  }