Skip to content

Commit

Permalink
Use testify for all tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MacroPower committed Dec 31, 2024
1 parent c7f94fc commit b4168fa
Show file tree
Hide file tree
Showing 8 changed files with 149 additions and 245 deletions.
22 changes: 0 additions & 22 deletions pkg/helm/helm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,6 @@ import (
"github.com/MacroPower/kclx/pkg/jsonschema"
)

// func TestGetHelmValuesSchema(t *testing.T) {
// t.Parallel()

// yamls, err := helm.DefaultHelm.GetValuesSchemas(&helm.TemplateOpts{
// ChartName: "podinfo",
// TargetRevision: "6.7.1",
// RepoURL: "https://stefanprodan.github.io/podinfo",
// })
// if err != nil {
// t.Fatal(err)
// }

// _, okDefault := yamls["values.yaml"]
// if !okDefault {
// t.Fatalf("values.yaml not found")
// }
// _, okProd := yamls["values-prod.yaml"]
// if !okProd {
// t.Fatalf("values-prod.yaml not found")
// }
// }

func TestGetHelmValuesJsonSchema(t *testing.T) {
t.Parallel()

Expand Down
26 changes: 8 additions & 18 deletions pkg/helmutil/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"testing"

"github.com/stretchr/testify/require"
"kcl-lang.io/cli/pkg/options"
"kcl-lang.io/kcl-go"

Expand All @@ -26,9 +27,8 @@ func TestHelmChartAdd(t *testing.T) {

ca := helmutil.NewChartPkg(chartPath)

if err := ca.Init(); err != nil {
t.Fatal(err)
}
err := ca.Init()
require.NoError(t, err)

tcs := map[string]struct {
chart *helmchart.ChartConfig
Expand Down Expand Up @@ -61,28 +61,20 @@ func TestHelmChartAdd(t *testing.T) {

err := ca.Add(tc.chart.Chart, tc.chart.RepoURL, tc.chart.TargetRevision,
tc.chart.SchemaPath, tc.chart.SchemaGenerator)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

depsOpt, err := options.LoadDepsFrom(chartPath, true)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
results, err := kcl.Test(
&kcl.TestOptions{
PkgList: []string{chartPath},
FailFast: true,
},
*depsOpt,
)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

if len(results.Info) != 0 {
t.Fatalf("expected no errors, got %d: %#v", len(results.Info), results)
}
require.Emptyf(t, results.Info, "expected no errors, got %d: %#v", len(results.Info), results)
})
}
}
Expand Down Expand Up @@ -131,9 +123,7 @@ func TestDefaultReplacement(t *testing.T) {
t.Run(name, func(t *testing.T) {
t.Parallel()
got := tc.re.ReplaceAllString(tc.input, tc.repl)
if got != tc.want {
t.Fatalf("expected %q, got %q", tc.want, got)
}
require.Equalf(t, tc.want, got, "expected %q, got %q", tc.want, got)
})
}
}
17 changes: 7 additions & 10 deletions pkg/helmutil/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"path"
"testing"

"github.com/stretchr/testify/require"

"github.com/MacroPower/kclx/pkg/helmutil"
"github.com/MacroPower/kclx/pkg/jsonschema"
)
Expand All @@ -21,18 +23,13 @@ func TestHelmChartUpdate(t *testing.T) {

chartPkg := helmutil.NewChartPkg(chartPath)

if err := chartPkg.Init(); err != nil {
t.Fatal(err)
}
err := chartPkg.Init()
require.NoError(t, err)

err := chartPkg.Add("podinfo", "https://stefanprodan.github.io/podinfo", "6.7.1", "", jsonschema.AutoGeneratorType)
if err != nil {
t.Fatal(err)
}
err = chartPkg.Add("podinfo", "https://stefanprodan.github.io/podinfo", "6.7.1", "", jsonschema.AutoGeneratorType)
require.NoError(t, err)
os.RemoveAll(path.Join(chartPath, "podinfo"))

err = chartPkg.Update()
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
}
217 changes: 48 additions & 169 deletions pkg/plugin/helm/plugin_test.go
Original file line number Diff line number Diff line change
@@ -1,200 +1,83 @@
package helm_test

import (
"encoding/json"
"regexp"
"os"
"path/filepath"
"runtime"
"testing"

argocli "github.com/argoproj/argo-cd/v2/util/cli"
"github.com/stretchr/testify/require"
"kcl-lang.io/kcl-go/pkg/spec/gpyrpc"
"kcl-lang.io/lib/go/native"

_ "github.com/MacroPower/kclx/pkg/plugin/helm"
)

var testDataDir string

func init() {
argocli.SetLogLevel("warn")

//nolint:dogsled
_, filename, _, _ := runtime.Caller(0)
dir := filepath.Dir(filename)
testDataDir = filepath.Join(dir, "testdata")
}

func TestPluginHelmTemplate(t *testing.T) {
t.Parallel()

code := `
import kcl_plugin.helm
_chart = helm.template(
chart="wakatime-exporter",
repo_url="https://jacobcolvin.com/helm-charts",
target_revision="0.1.0",
values={service.main.enabled = False},
)
{result = _chart}
`

client := native.NewNativeServiceClient()
result, err := client.ExecProgram(&gpyrpc.ExecProgram_Args{
KFilenameList: []string{"main.k"},
KCodeList: []string{code},
Args: []*gpyrpc.Argument{},
})
if err != nil {
t.Fatal(err)
}
if result.GetErrMessage() != "" {
t.Fatal(result.GetErrMessage())
tcs := map[string]struct {
kclFile string
resultsFile string
}{
"Simple": {
kclFile: "input/simple.k",
resultsFile: "output/simple.json",
},
}
for name, tc := range tcs {
t.Run(name, func(t *testing.T) {
t.Parallel()

wantJSON := `{"result":
[
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"labels": {
"app.kubernetes.io/instance": "wakatime-exporter",
"app.kubernetes.io/managed-by": "Helm",
"app.kubernetes.io/name": "wakatime-exporter",
"app.kubernetes.io/version": "0.1.0",
"helm.sh/chart": "wakatime-exporter-0.1.0"
},
"name": "wakatime-exporter"
},
"spec": {
"replicas": 1,
"revisionHistoryLimit": 3,
"selector": {
"matchLabels": {
"app.kubernetes.io/instance": "wakatime-exporter",
"app.kubernetes.io/name": "wakatime-exporter"
}
},
"strategy": { "type": "Recreate" },
"template": {
"metadata": {
"labels": {
"app.kubernetes.io/instance": "wakatime-exporter",
"app.kubernetes.io/name": "wakatime-exporter"
}
},
"spec": {
"automountServiceAccountToken": true,
"containers": [
{
"env": [
{
"name": "WAKA_API_KEY",
"valueFrom": {
"secretKeyRef": {
"key": "api-key",
"name": "wakatime-credentials"
}
}
}
],
"image": "macropower/wakatime_exporter:0.1.0",
"imagePullPolicy": "IfNotPresent",
"name": "wakatime-exporter"
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"serviceAccountName": "default"
}
}
}
}
]}
`

re := regexp.MustCompile(`\s+`)
if re.ReplaceAllString(result.GetJsonResult(), "") != re.ReplaceAllString(wantJSON, "") {
t.Fatal(result.GetJsonResult())
}
}

func TestExecProgramWithPlugin(t *testing.T) {
t.Parallel()
inputKCLFile := filepath.Join(testDataDir, tc.kclFile)
wantResultsFile := filepath.Join(testDataDir, tc.resultsFile)

code := `
import kcl_plugin.helm
inputKCL, err := os.ReadFile(inputKCLFile)
require.NoError(t, err)

_chart = helm.template(
chart="wakatime-exporter",
repo_url="https://jacobcolvin.com/helm-charts",
target_revision="0.1.0",
)
patch = lambda resource: {str:} -> {str:} {
if resource.kind == "Service":
resource.metadata.annotations = {
added = "by kcl"
}
resource.metadata.labels = {}
resource
}
want, err := os.ReadFile(wantResultsFile)
require.NoError(t, err)

{"resources": [patch(r) for r in _chart]}
`
client := native.NewNativeServiceClient()
result, err := client.ExecProgram(&gpyrpc.ExecProgram_Args{
KFilenameList: []string{"main.k"},
KCodeList: []string{string(inputKCL)},
Args: []*gpyrpc.Argument{},
})
require.NoError(t, err)
require.Empty(t, result.GetErrMessage())

client := native.NewNativeServiceClient()
result, err := client.ExecProgram(&gpyrpc.ExecProgram_Args{
KFilenameList: []string{"main.k"},
KCodeList: []string{code},
Args: []*gpyrpc.Argument{},
})
if err != nil {
t.Fatal(err)
}
if result.GetErrMessage() != "" {
t.Fatalf("error message must be empty, got: %s", result.GetErrMessage())
}
got := result.GetJsonResult()

resultMap := map[string]any{}
if err := json.Unmarshal([]byte(result.GetJsonResult()), &resultMap); err != nil {
t.Fatal(err)
}
resultChart, ok := resultMap["resources"].([]interface{})
if !ok {
t.Fatalf("unexpected type in object: %v", resultMap)
}
obj0, ok := resultChart[0].(map[string]interface{})
if !ok {
t.Fatalf("unexpected type in object: %v", resultChart)
}
obj0md, err := json.Marshal(obj0["metadata"])
if err != nil {
t.Fatal(err)
}
if string(obj0md) != `{"annotations":{"added":"by kcl"},"labels":{},"name":"wakatime-exporter"}` {
t.Fatalf("result is not correct, %s", string(obj0md))
require.JSONEq(t, string(want), got)
})
}
}

func BenchmarkPluginHelmTemplate(b *testing.B) {
code := `
import kcl_plugin.helm
_chart = helm.template(
chart="wakatime-exporter",
repo_url="https://jacobcolvin.com/helm-charts",
target_revision="0.1.0",
values={service.main.enabled = False},
)
{result = _chart}
`
inputKCLFile := filepath.Join(testDataDir, "input/simple.k")
inputKCL, err := os.ReadFile(inputKCLFile)
require.NoError(b, err)

client := native.NewNativeServiceClient()
_, err := client.ExecProgram(&gpyrpc.ExecProgram_Args{
_, err = client.ExecProgram(&gpyrpc.ExecProgram_Args{
KFilenameList: []string{"main.k"},
KCodeList: []string{code},
KCodeList: []string{string(inputKCL)},
Args: []*gpyrpc.Argument{},
})
if err != nil {
b.Fatal(err)
}
require.NoError(b, err)

b.ResetTimer()

Expand All @@ -203,15 +86,11 @@ _chart = helm.template(
client := native.NewNativeServiceClient()
result, err := client.ExecProgram(&gpyrpc.ExecProgram_Args{
KFilenameList: []string{"main.k"},
KCodeList: []string{code},
KCodeList: []string{string(inputKCL)},
Args: []*gpyrpc.Argument{},
})
if err != nil {
b.Fatal(err)
}
if result.GetErrMessage() != "" {
b.Fatal(result.GetErrMessage())
}
require.NoError(b, err)
require.Empty(b, result.GetErrMessage())
}
})
}
Loading

0 comments on commit b4168fa

Please sign in to comment.