Skip to content

Commit ccddf23

Browse files
committed
add unit tests
1 parent 0ee78f2 commit ccddf23

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package terraform
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"os"
7+
"path/filepath"
8+
"strings"
9+
"testing"
10+
11+
"github.com/stretchr/testify/require"
12+
)
13+
14+
func Test_getAbsoluteBinaryPath(t *testing.T) {
15+
t.Parallel()
16+
type args struct {
17+
ctx context.Context
18+
}
19+
tests := []struct {
20+
name string
21+
args args
22+
terraformVersion string
23+
expectedAbsoluteBinary string
24+
expectedOk bool
25+
}{
26+
{
27+
name: "TestCorrectVersion",
28+
args: args{ctx: context.Background()},
29+
terraformVersion: "1.1.9",
30+
expectedAbsoluteBinary: "",
31+
expectedOk: true,
32+
},
33+
{
34+
name: "TestOldVersion",
35+
args: args{ctx: context.Background()},
36+
terraformVersion: "1.0.9",
37+
expectedAbsoluteBinary: "",
38+
expectedOk: false,
39+
},
40+
{
41+
name: "TestNewVersion",
42+
args: args{ctx: context.Background()},
43+
terraformVersion: "1.2.9",
44+
expectedAbsoluteBinary: "",
45+
expectedOk: false,
46+
},
47+
{
48+
name: "TestMalformedVersion",
49+
args: args{ctx: context.Background()},
50+
terraformVersion: "version",
51+
expectedAbsoluteBinary: "",
52+
expectedOk: false,
53+
},
54+
}
55+
// nolint:paralleltest
56+
for _, tt := range tests {
57+
t.Run(tt.name, func(t *testing.T) {
58+
// Create a temp dir with the binary
59+
tempDir := t.TempDir()
60+
terraformBinaryOutput := fmt.Sprintf(`#!/bin/sh
61+
cat <<-EOF
62+
{
63+
"terraform_version": "%s",
64+
"platform": "linux_amd64",
65+
"provider_selections": {},
66+
"terraform_outdated": false
67+
}
68+
EOF`, tt.terraformVersion)
69+
70+
// #nosec
71+
err := os.WriteFile(
72+
filepath.Join(tempDir, "terraform"),
73+
[]byte(terraformBinaryOutput),
74+
0770,
75+
)
76+
require.NoError(t, err)
77+
78+
// Add the binary to PATH
79+
pathVariable := os.Getenv("PATH")
80+
t.Setenv("PATH", strings.Join([]string{tempDir, pathVariable}, ":"))
81+
82+
if tt.expectedOk {
83+
tt.expectedAbsoluteBinary = filepath.Join(tempDir, "terraform")
84+
}
85+
86+
actualAbsoluteBinary, actualOk := getAbsoluteBinaryPath(tt.args.ctx)
87+
if actualAbsoluteBinary != tt.expectedAbsoluteBinary {
88+
t.Errorf("getAbsoluteBinaryPath() absoluteBinaryPath, actual = %v, expected %v", actualAbsoluteBinary, tt.expectedAbsoluteBinary)
89+
}
90+
if actualOk != tt.expectedOk {
91+
t.Errorf("getAbsoluteBinaryPath() ok, actual = %v, expected %v", actualOk, tt.expectedOk)
92+
}
93+
})
94+
}
95+
}

0 commit comments

Comments
 (0)