Skip to content

Commit

Permalink
add test for editKloneFile function
Browse files Browse the repository at this point in the history
Signed-off-by: Tim Ramlot <42113979+inteon@users.noreply.github.com>
  • Loading branch information
inteon committed Jan 11, 2024
1 parent c9b4969 commit 24b0607
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions pkg/mod/index_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package mod

import (
"os"
"path"
"sort"
"testing"
)
Expand All @@ -26,3 +28,94 @@ func TestKloneItemSorting(t *testing.T) {
}
}
}

func Test_editKloneFile(t *testing.T) {
tests := []struct {
name string
initial string
modifyFn func(*kloneFile) error
expected string
expectErr bool
}{
{
name: "Preserve comments",
initial: `# Test comment1
# Test comment2
targets:
target1:
- folder_name: Folder A
repo_url: https://github.com/repo1
repo_ref: main
repo_hash: abc123
repo_path: path/to/repo1
`,
modifyFn: func(kf *kloneFile) error {
return nil
},
expected: `# Test comment1
# Test comment2
targets:
target1:
- folder_name: Folder A
repo_url: https://github.com/repo1
repo_ref: main
repo_hash: abc123
repo_path: path/to/repo1
`,
expectErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tempDirPath := t.TempDir()

// Create the file and write the initial contents
{
tempFile, err := os.Create(path.Join(tempDirPath, kloneFileName))
if err != nil {
t.Fatalf("Failed to create temporary file: %v", err)
}

// Write the initial content to the temporary file
_, err = tempFile.WriteString(tt.initial)
if err != nil {
t.Fatalf("Failed to write initial content to temporary file: %v", err)
}

// Close the temporary file
err = tempFile.Close()
if err != nil {
t.Fatalf("Failed to close temporary file: %v", err)
}
}

// Create a WorkDir instance with the path to the temporary file
workDir := WorkDir(tempDirPath)

// Call the editKloneFile function with the modifyFn
err := workDir.editKloneFile(tt.modifyFn)

// Check if an error is expected
if tt.expectErr && err == nil {
t.Errorf("Expected an error, but got nil")
} else if !tt.expectErr && err != nil {
t.Errorf("Expected no error, but got: %v", err)
}

// Read the new file contents and compare with the expected contents
{
// Read the content of the modified file
modifiedContent, err := os.ReadFile(path.Join(tempDirPath, kloneFileName))
if err != nil {
t.Fatalf("Failed to read modified content: %v", err)
}

// Compare the modified content with the expected content
if string(modifiedContent) != tt.expected {
t.Errorf("Expected modified content:\n%s\n\nBut got:\n%s", tt.expected, modifiedContent)
}
}
})
}
}

0 comments on commit 24b0607

Please sign in to comment.