Skip to content

Commit

Permalink
refactor: better use of test helpers
Browse files Browse the repository at this point in the history
Signed-off-by: Anders Eknert <[email protected]>
  • Loading branch information
anderseknert committed Jan 23, 2025
1 parent 2b25493 commit 41b5de6
Show file tree
Hide file tree
Showing 21 changed files with 194 additions and 388 deletions.
Empty file added .clj-kondo/.cache/v1/lock
Empty file.
1 change: 1 addition & 0 deletions .lsp/.cache/db.transit.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
["^ ","~:classpath",["~#set",[]],"~:project-hash","","~:project-root","/Users/anderseknert/git/styra/regal","~:kondo-config-hash","e98a28fd523b559ab8f61e74e2bf5f40a28efd98f0faf95735b82e5adb0607ab","~:dependency-scheme","jar","~:analysis",null,"~:analysis-checksums",["^ "],"~:project-analysis-type","~:project-and-full-dependencies","~:version",12,"~:stubs-generation-namespaces",["^1",[]]]
1 change: 0 additions & 1 deletion cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,6 @@ func scaffoldBuiltinRule(params newRuleCommandParams) error {

func createBuiltinDocs(params newRuleCommandParams) error {
docsDir := filepath.Join(params.output, "docs", "rules", params.category)

docTmpl := template.New("builtin.md.tpl")

docTmpl = docTmpl.Funcs(template.FuncMap{
Expand Down
45 changes: 8 additions & 37 deletions e2e/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,10 @@ func readProvidedConfig(t *testing.T) config.Config {
t.Helper()

cwd := testutil.Must(os.Getwd())(t)

configPath := filepath.Join(cwd, "..", "bundle", "regal", "config", "provided", "data.yaml")
bs, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("failed to read config from %q: %v", configPath, err)
}
bs := testutil.MustReadFile(t, filepath.Join(cwd, "..", "bundle", "regal", "config", "provided", "data.yaml"))

var cfg config.Config
if err = yaml.Unmarshal(bs, &cfg); err != nil {
if err := yaml.Unmarshal(bs, &cfg); err != nil {
t.Fatalf("failed to unmarshal config: %v", err)
}

Expand Down Expand Up @@ -855,7 +850,6 @@ func TestFix(t *testing.T) {
t.Parallel()

stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
td := t.TempDir()

initialState := map[string]string{
".regal/config.yaml": `
Expand Down Expand Up @@ -909,9 +903,7 @@ allow if { true }
"unrelated.txt": `foobar`,
}

for file, content := range initialState {
mustWriteToFile(t, filepath.Join(td, file), content)
}
td := testutil.TempDirectoryOf(t, initialState)

// --force is required to make the changes when there is no git repo
err := regal(&stdout, &stderr)(
Expand Down Expand Up @@ -1026,7 +1018,6 @@ func TestFixWithConflicts(t *testing.T) {

stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
td := t.TempDir()

initialState := map[string]string{
".regal/config.yaml": "", // needed to find the root in the right place
Expand Down Expand Up @@ -1055,9 +1046,7 @@ import rego.v1
`,
}

for file, content := range initialState {
mustWriteToFile(t, filepath.Join(td, file), content)
}
td := testutil.TempDirectoryOf(t, initialState)

// --force is required to make the changes when there is no git repo
err := regal(&stdout, &stderr)("fix", "--force", td)
Expand All @@ -1083,7 +1072,7 @@ Cannot move multiple files to: bar/bar.rego
}

for file, expectedContent := range initialState {
bs := testutil.Must(os.ReadFile(filepath.Join(td, file)))(t)
bs := testutil.MustReadFile(t, filepath.Join(td, file))

if act := string(bs); expectedContent != act {
t.Errorf("expected %s contents:\n%s\ngot\n%s", file, expectedContent, act)
Expand All @@ -1096,7 +1085,6 @@ func TestFixWithConflictRenaming(t *testing.T) {

stdout := bytes.Buffer{}
stderr := bytes.Buffer{}
td := t.TempDir()

initialState := map[string]string{
".regal/config.yaml": "", // needed to find the root in the right place
Expand Down Expand Up @@ -1127,9 +1115,7 @@ import rego.v1
`,
}

for file, content := range initialState {
mustWriteToFile(t, filepath.Join(td, file), content)
}
td := testutil.TempDirectoryOf(t, initialState)

// --force is required to make the changes when there is no git repo
// --conflict=rename will rename inbound files when there is a conflict
Expand Down Expand Up @@ -1205,7 +1191,6 @@ func TestFixSingleFileNested(t *testing.T) {
t.Parallel()

stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
td := t.TempDir()

initialState := map[string]string{
".regal/config.yaml": `
Expand All @@ -1223,15 +1208,13 @@ rules:
"foo/foo.rego": `package wow`,
}

for file, content := range initialState {
mustWriteToFile(t, filepath.Join(td, file), content)
}
td := testutil.TempDirectoryOf(t, initialState)

// --force is required to make the changes when there is no git repo
err := regal(&stdout, &stderr)(
"fix",
"--force",
filepath.Join(td, "foo/foo.rego"),
filepath.Join(td, "foo", "foo.rego"),
)

// 0 exit status is expected as all violations should have been fixed
Expand Down Expand Up @@ -1369,15 +1352,3 @@ func expectExitCode(t *testing.T, err error, exp int, stdout *bytes.Buffer, stde
exp, act, stdout.String(), stderr.String())
}
}

func mustWriteToFile(t *testing.T, path string, content string) {
t.Helper()

if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("failed to create directory %s: %v", filepath.Dir(path), err)
}

if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("failed to write to %s: %v", path, err)
}
}
19 changes: 3 additions & 16 deletions internal/lsp/bundles/bundles_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package bundles

import (
"os"
"path/filepath"
"reflect"
"testing"

"github.com/styrainc/regal/internal/testutil"
)

func TestLoadDataBundle(t *testing.T) {
Expand Down Expand Up @@ -67,21 +68,7 @@ func TestLoadDataBundle(t *testing.T) {
t.Run(testCase, func(t *testing.T) {
t.Parallel()

workspacePath := t.TempDir()

// create the workspace state
for file, contents := range testData.files {
filePath := filepath.Join(workspacePath, file)

dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("failed to create directory %s: %v", dir, err)
}

if err := os.WriteFile(filePath, []byte(contents), 0o600); err != nil {
t.Fatalf("failed to write file %s: %v", filePath, err)
}
}
workspacePath := testutil.TempDirectoryOf(t, testData.files)

b, err := LoadDataBundle(filepath.Join(workspacePath, testData.path))
if err != nil {
Expand Down
47 changes: 9 additions & 38 deletions internal/lsp/bundles/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,17 @@ import (
"reflect"
"slices"
"testing"

"github.com/styrainc/regal/internal/testutil"
)

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

workspacePath := t.TempDir()

// create the initial filesystem state
files := map[string]string{
workspacePath := testutil.TempDirectoryOf(t, map[string]string{
"foo/.manifest": `{"roots":["foo"]}`,
"foo/data.json": `{"foo": "bar"}`,
}

writeFiles := func(files map[string]string) {
for file, contents := range files {
filePath := filepath.Join(workspacePath, file)

dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("failed to create directory %s: %v", dir, err)
}

if err := os.WriteFile(filePath, []byte(contents), 0o600); err != nil {
t.Fatalf("failed to write file %s: %v", filePath, err)
}
}
}

writeFiles(files)
})

c := NewCache(&CacheOptions{WorkspacePath: workspacePath})

Expand Down Expand Up @@ -80,11 +62,7 @@ func TestRefresh(t *testing.T) {
}

// add a new unrelated file
writeFiles(
map[string]string{
"foo/foo.rego": `package wow`,
},
)
testutil.MustWriteFile(t, filepath.Join(workspacePath, "foo", "foo.rego"), []byte(`package wow`))

// perform the third load of the bundles, after adding a new unrelated file
refreshedBundles, err = c.Refresh()
Expand All @@ -97,11 +75,7 @@ func TestRefresh(t *testing.T) {
}

// update the data in the bundle
writeFiles(
map[string]string{
"foo/data.json": `{"foo": "baz"}`,
},
)
testutil.MustWriteFile(t, filepath.Join(workspacePath, "foo", "data.json"), []byte(`{"foo": "baz"}`))

refreshedBundles, err = c.Refresh()
if err != nil {
Expand All @@ -122,12 +96,9 @@ func TestRefresh(t *testing.T) {
}

// create a new bundle
writeFiles(
map[string]string{
"bar/.manifest": `{"roots":["bar"]}`,
"bar/data.json": `{"bar": true}`,
},
)
testutil.MustMkdirAll(t, workspacePath, "bar")
testutil.MustWriteFile(t, filepath.Join(workspacePath, "bar", ".manifest"), []byte(`{"roots":["bar"]}`))
testutil.MustWriteFile(t, filepath.Join(workspacePath, "bar", "data.json"), []byte(`{"bar": true}`))

refreshedBundles, err = c.Refresh()
if err != nil {
Expand Down
23 changes: 9 additions & 14 deletions internal/lsp/config/watcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,22 @@ package config
import (
"context"
"os"
"path/filepath"
"testing"
"time"

"github.com/styrainc/regal/internal/lsp/log"
"github.com/styrainc/regal/internal/testutil"
)

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

tempDir := t.TempDir()

configFilePath := tempDir + "/config.yaml"

configFileContents := `---
tempDir := testutil.TempDirectoryOf(t, map[string]string{
"config.yaml": `---
foo: bar
`

if err := os.WriteFile(configFilePath, []byte(configFileContents), 0o600); err != nil {
t.Fatal(err)
}
`,
})

watcher := NewWatcher(&WatcherOpts{LogFunc: func(l log.Level, s string, a ...any) {
t.Logf(l.String()+": "+s, a...)
Expand All @@ -37,6 +33,8 @@ foo: bar
}
}()

configFilePath := filepath.Join(tempDir, "config.yaml")

watcher.Watch(configFilePath)

select {
Expand All @@ -48,10 +46,7 @@ foo: bar
newConfigFileContents := `---
foo: baz
`

if err := os.WriteFile(configFilePath, []byte(newConfigFileContents), 0o600); err != nil {
t.Fatal(err)
}
testutil.MustWriteFile(t, configFilePath, []byte(newConfigFileContents))

select {
case <-watcher.Reload:
Expand Down
22 changes: 8 additions & 14 deletions internal/lsp/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import (
"context"
"maps"
"os"
"path/filepath"
"slices"
"testing"

rio "github.com/styrainc/regal/internal/io"
"github.com/styrainc/regal/internal/lsp/log"
"github.com/styrainc/regal/internal/parse"
"github.com/styrainc/regal/internal/testutil"
)

func TestEvalWorkspacePath(t *testing.T) {
Expand Down Expand Up @@ -115,12 +117,10 @@ func TestFindInput(t *testing.T) {

tmpDir := t.TempDir()

workspacePath := tmpDir + "/workspace"
file := tmpDir + "/workspace/foo/bar/baz.rego"
workspacePath := filepath.Join(tmpDir, "workspace")
file := filepath.Join(tmpDir, "workspace", "foo", "bar", "baz.rego")

if err := os.MkdirAll(workspacePath+"/foo/bar", 0o755); err != nil {
t.Fatal(err)
}
testutil.MustMkdirAll(t, workspacePath, "foo", "bar")

path, content := rio.FindInput(file, workspacePath)
if path != "" || content != nil {
Expand All @@ -134,9 +134,7 @@ func TestFindInput(t *testing.T) {
t.Errorf(`expected input {"x": true} at, got %s`, content)
}

if err := os.Remove(tmpDir + "/workspace/foo/bar/input." + tc.fileType); err != nil {
t.Fatal(err)
}
testutil.MustRemove(t, tmpDir+"/workspace/foo/bar/input."+tc.fileType)

createWithContent(t, tmpDir+"/workspace/input."+tc.fileType, tc.fileContent)

Expand All @@ -151,14 +149,10 @@ func TestFindInput(t *testing.T) {
func createWithContent(t *testing.T, path string, content string) {
t.Helper()

f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}

f := testutil.Must(os.Create(path))(t)
defer f.Close()

if _, err = f.WriteString(content); err != nil {
if _, err := f.WriteString(content); err != nil {
t.Fatal(err)
}
}
9 changes: 3 additions & 6 deletions internal/lsp/hover/hover_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package hover

import (
"os"
"testing"

"github.com/open-policy-agent/opa/v1/ast"
"github.com/open-policy-agent/opa/v1/types"

"github.com/styrainc/regal/internal/testutil"
)

func TestCreateHoverContent(t *testing.T) {
Expand Down Expand Up @@ -45,11 +46,7 @@ func TestCreateHoverContent(t *testing.T) {
}

for _, c := range cases {
file, err := os.ReadFile(c.testdata)
if err != nil {
t.Fatal(err)
}

file := testutil.MustReadFile(t, c.testdata)
hoverContent := CreateHoverContent(c.builtin)

if string(file) != hoverContent {
Expand Down
Loading

0 comments on commit 41b5de6

Please sign in to comment.