Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/utils/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import (
"gopkg.in/yaml.v2"
)

// ToMap accepts any object and will return at as a map using json marshal and
// unmarshal. This fuction will return an error if if fails to marshal or
// unmarshal the input object.
func ToMap(in any, out any) error {
b, err := json.Marshal(in)
if err != nil {
Expand All @@ -23,6 +26,8 @@ func ToMap(in any, out any) error {
// will first attempt to unmarshal the byte array as JSON. If that fails, it
// will attempt to unmarshal the data as YAML.
func UnmarshalData(data []byte, ptr any) {
// FIXME (privateip) This function should be refactored to return an error
// instead of simply logging a fatal error.
if err := json.Unmarshal(data, ptr); err != nil {
logger.Error(err, "failed to unmarshal json data")
if err = yaml.Unmarshal(data, ptr); err != nil {
Expand Down
63 changes: 63 additions & 0 deletions internal/utils/encoding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright 2024 Itential Inc. All Rights Reserved
// Unauthorized copying of this file, via any medium is strictly prohibited
// Proprietary and confidential

package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

// SampleStruct is a sample data structure for testing.
type SampleStruct struct {
Name string `json:"name" yaml:"name"`
Value int `json:"value" yaml:"value"`
}

// TestToMapSuccess tests the successful conversion of a struct to a map.
func TestToMapSuccess(t *testing.T) {
input := SampleStruct{
Name: "test",
Value: 42,
}

var output map[string]interface{}
err := ToMap(input, &output)

assert.NoError(t, err)
assert.Equal(t, "test", output["name"])
assert.Equal(t, float64(42), output["value"]) // JSON unmarshals numbers into float64
}

// TestToMapInvalidInput tests ToMap with an invalid input (channel can't be marshaled).
func TestToMapInvalidInput(t *testing.T) {
ch := make(chan int)
var output map[string]interface{}
err := ToMap(ch, &output)

assert.Error(t, err)
}

// TestUnmarshalDataJSON tests successful JSON unmarshalling.
func TestUnmarshalDataJSON(t *testing.T) {
data := []byte(`{"name": "json", "value": 123}`)
var obj SampleStruct

UnmarshalData(data, &obj)

assert.Equal(t, "json", obj.Name)
assert.Equal(t, 123, obj.Value)
}

// TestUnmarshalDataYAML tests fallback to YAML unmarshalling.
func TestUnmarshalDataYAML(t *testing.T) {
data := []byte("name: yaml\nvalue: 456")
var obj SampleStruct

UnmarshalData(data, &obj)

assert.Equal(t, "yaml", obj.Name)
assert.Equal(t, 456, obj.Value)
}
19 changes: 19 additions & 0 deletions internal/utils/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright 2024 Itential Inc. All Rights Reserved
// Unauthorized copying of this file, via any medium is strictly prohibited
// Proprietary and confidential

package utils

import (
"os"
"testing"

"github.com/rs/zerolog"
)

func TestMain(m *testing.M) {
zerolog.SetGlobalLevel(zerolog.Disabled)
zerolog.GlobalLevel()
code := m.Run()
os.Exit(code)
}
2 changes: 2 additions & 0 deletions internal/utils/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ func WriteJsonToDisk(o any, fn, fp string) error {
return WriteBytesToDisk(b, dst, true)
}

// WRiteYamlToDisck will accept an object, marshal it to yaml encoding and
// write it to disk.
func WriteYamlToDisk(o any, fn, fp string) error {
logger.Trace()

Expand Down
146 changes: 146 additions & 0 deletions internal/utils/path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright 2024 Itential Inc. All Rights Reserved
// Unauthorized copying of this file, via any medium is strictly prohibited
// Proprietary and confidential

package utils

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

"github.com/stretchr/testify/assert"
)

type sampleStruct struct {
Name string `json:"name" yaml:"name"`
Age int `json:"age" yaml:"age"`
}

func TestPathExists(t *testing.T) {
tmpFile, _ := os.CreateTemp("", "testfile")
defer os.Remove(tmpFile.Name())

assert.True(t, PathExists(tmpFile.Name()))
assert.False(t, PathExists("/some/nonexistent/path"))
}

func TestLoadObject(t *testing.T) {
input := map[string]interface{}{"name": "John", "age": 30}
var output sampleStruct

LoadObject(input, &output)

assert.Equal(t, "John", output.Name)
assert.Equal(t, 30, output.Age)
}

func TestNormalizeFilename(t *testing.T) {
fn := "my/test/file.json"
fp := "/tmp/test"

result, err := NormalizeFilename(fn, fp)

assert.NoError(t, err)
assert.Contains(t, result, "my_test_file.json")
assert.Contains(t, result, "/tmp/test")
}

func TestWriteAndReadBytesToDisk(t *testing.T) {
tmpDir := t.TempDir()
dst := filepath.Join(tmpDir, "output.txt")

err := WriteBytesToDisk([]byte("hello"), dst, false)
assert.NoError(t, err)

data, err := os.ReadFile(dst)
assert.NoError(t, err)
assert.Equal(t, "hello", string(data))
}

func TestWriteBytesToDisk_Overwrite(t *testing.T) {
tmpDir := t.TempDir()
dst := filepath.Join(tmpDir, "file.txt")

// Write once
err := WriteBytesToDisk([]byte("original"), dst, false)
assert.NoError(t, err)

// Overwrite
err = WriteBytesToDisk([]byte("updated"), dst, true)
assert.NoError(t, err)

data, _ := os.ReadFile(dst)
assert.Equal(t, "updated", string(data))
}

func TestWriteJsonToDisk(t *testing.T) {
tmpDir := t.TempDir()
obj := sampleStruct{"Alice", 25}

err := WriteJsonToDisk(obj, "data.json", tmpDir)
assert.NoError(t, err)

content, _ := os.ReadFile(filepath.Join(tmpDir, "data.json"))
assert.Contains(t, string(content), "Alice")
assert.Contains(t, string(content), "25")
}

func TestWriteYamlToDisk(t *testing.T) {
tmpDir := t.TempDir()
obj := sampleStruct{"Bob", 40}

err := WriteYamlToDisk(obj, "data.yaml", tmpDir)
assert.NoError(t, err)

content, _ := os.ReadFile(filepath.Join(tmpDir, "data.yaml"))
assert.Contains(t, string(content), "Bob")
assert.Contains(t, string(content), "40")
}

func TestWrite(t *testing.T) {
tmpDir := t.TempDir()
obj := sampleStruct{"Test", 10}

err := Write(obj, "file.json", tmpDir, "json")
assert.NoError(t, err)

err = Write(obj, "file.yaml", tmpDir, "yaml")
assert.NoError(t, err)

jsonData, _ := os.ReadFile(filepath.Join(tmpDir, "file.json"))
yamlData, _ := os.ReadFile(filepath.Join(tmpDir, "file.yaml"))

assert.Contains(t, string(jsonData), "Test")
assert.Contains(t, string(yamlData), "Test")
}

func TestReadStringFromFile(t *testing.T) {
tmpFile := filepath.Join(t.TempDir(), "file.txt")
os.WriteFile(tmpFile, []byte("hello world"), 0644)

data, err := ReadStringFromFile(tmpFile)
assert.NoError(t, err)
assert.Equal(t, "hello world", data)
}

func TestEnsurePathExists(t *testing.T) {
tmpDir := filepath.Join(t.TempDir(), "newdir")

err := EnsurePathExists(tmpDir)
assert.NoError(t, err)
assert.True(t, PathExists(tmpDir))
}

func TestReadObjectFromDisk_JSON(t *testing.T) {
tmpDir := t.TempDir()
obj := sampleStruct{"Test", 99}
_ = WriteJsonToDisk(obj, "readme.json", tmpDir)

var output sampleStruct
err := ReadObjectFromDisk(filepath.Join(tmpDir, "readme.json"), &output)

assert.NoError(t, err)
assert.Equal(t, "Test", output.Name)
assert.Equal(t, 99, output.Age)
}
31 changes: 0 additions & 31 deletions internal/utils/strings.go

This file was deleted.