impr: modular sandbox configs

This commit is contained in:
Anton
2023-12-05 00:53:50 +05:00
parent 07b523cd4d
commit cfe8970ebf
9 changed files with 113 additions and 62 deletions

View File

@@ -2,6 +2,7 @@
package fileio
import (
"encoding/json"
"io"
"os"
"path/filepath"
@@ -37,3 +38,17 @@ func CopyFiles(pattern string, dstDir string) error {
return nil
}
// ReadJson reads the file and decodes it from JSON.
func ReadJson[T any](path string) (T, error) {
var obj T
data, err := os.ReadFile(path)
if err != nil {
return obj, err
}
err = json.Unmarshal(data, &obj)
if err != nil {
return obj, err
}
return obj, err
}

View File

@@ -3,6 +3,7 @@ package fileio
import (
"os"
"path/filepath"
"reflect"
"testing"
)
@@ -54,3 +55,30 @@ func TestCopyFiles(t *testing.T) {
t.Errorf("unexpected file content: got %q, want %q", data, expected)
}
}
func TestReadJson(t *testing.T) {
type Person struct{ Name string }
t.Run("valid", func(t *testing.T) {
got, err := ReadJson[Person](filepath.Join("testdata", "valid.json"))
if err != nil {
t.Fatalf("unexpected error %v", err)
}
want := Person{"alice"}
if !reflect.DeepEqual(got, want) {
t.Errorf("expected %v, got %v", want, got)
}
})
t.Run("invalid", func(t *testing.T) {
_, err := ReadJson[Person](filepath.Join("testdata", "invalid.json"))
if err == nil {
t.Fatal("expected error, got nil")
}
})
t.Run("does not exist", func(t *testing.T) {
_, err := ReadJson[Person](filepath.Join("testdata", "missing.json"))
if err == nil {
t.Fatal("expected error, got nil")
}
})
}

1
internal/fileio/testdata/invalid.json vendored Normal file
View File

@@ -0,0 +1 @@
name: alice

3
internal/fileio/testdata/valid.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"name": "alice"
}