package utils import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" ) func TestModifyCommandValidate(t *testing.T) { tests := []struct { name string command ModifyCommand shouldError bool }{ { name: "Valid command", command: ModifyCommand{ Regex: "test pattern", Lua: "test expression", Files: []string{"file1", "file2"}, LogLevel: "INFO", }, shouldError: false, }, { name: "Missing pattern", command: ModifyCommand{ Regex: "", Lua: "test expression", Files: []string{"file1", "file2"}, LogLevel: "INFO", }, shouldError: true, }, { name: "Missing LuaExpr", command: ModifyCommand{ Regex: "test pattern", Lua: "", Files: []string{"file1", "file2"}, LogLevel: "INFO", }, shouldError: true, }, { name: "Missing files", command: ModifyCommand{ Regex: "test pattern", Lua: "test expression", Files: []string{}, LogLevel: "INFO", }, shouldError: true, }, { name: "Default log level", command: ModifyCommand{ Regex: "test pattern", Lua: "test expression", Files: []string{"file1", "file2"}, LogLevel: "", }, shouldError: false, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { err := tc.command.Validate() if tc.shouldError { if err == nil { t.Errorf("Expected an error for command %+v but got none", tc.command) } } else { if err != nil { t.Errorf("Unexpected error: %v", err) } // Check that default log level is set if tc.command.LogLevel == "" { t.Errorf("Default log level not set") } } }) } } func TestAssociateFilesWithCommands(t *testing.T) { // Create a temporary directory structure for testing tmpDir, err := os.MkdirTemp("", "associate-test") if err != nil { t.Fatalf("Failed to create temp dir: %v", err) } defer os.RemoveAll(tmpDir) // Create some test files testFiles := []string{ filepath.Join(tmpDir, "file1.xml"), filepath.Join(tmpDir, "file2.txt"), filepath.Join(tmpDir, "subdir", "file3.xml"), } // Create the directory structure err = os.MkdirAll(filepath.Join(tmpDir, "subdir"), 0755) if err != nil { t.Fatalf("Failed to create subdirectories: %v", err) } // Create the files for _, file := range testFiles { dir := filepath.Dir(file) if err := os.MkdirAll(dir, 0755); err != nil { t.Fatalf("Failed to create directory %s: %v", dir, err) } if err := os.WriteFile(file, []byte("test content"), 0644); err != nil { t.Fatalf("Failed to create file %s: %v", file, err) } } // Change to the temporary directory to use relative paths origDir, _ := os.Getwd() os.Chdir(tmpDir) defer os.Chdir(origDir) // Define commands with different globs commands := []ModifyCommand{ { Regex: "pattern1", Lua: "expr1", Files: []string{"*.xml"}, }, { Regex: "pattern2", Lua: "expr2", Files: []string{"*.txt"}, }, { Regex: "pattern3", Lua: "expr3", Files: []string{"subdir/*"}, }, } // Get files for testing relFiles := []string{ "file1.xml", "file2.txt", "subdir/file3.xml", } associations, err := AssociateFilesWithCommands(relFiles, commands) if err != nil { t.Fatalf("AssociateFilesWithCommands failed: %v", err) } // The associations expected depends on the implementation // Let's check the actual associations and verify they make sense for file, cmds := range associations { t.Logf("File %s is associated with %d commands", file, len(cmds)) for i, cmd := range cmds { t.Logf(" Command %d: Pattern=%s, Files=%v", i, cmd.Regex, cmd.Files) } // Specific validation based on our file types switch file { case "file1.xml": if len(cmds) < 1 { t.Errorf("Expected at least 1 command for file1.xml, got %d", len(cmds)) } // Verify at least one command with *.xml pattern hasXmlGlob := false for _, cmd := range cmds { for _, glob := range cmd.Files { if glob == "*.xml" { hasXmlGlob = true break } } if hasXmlGlob { break } } if !hasXmlGlob { t.Errorf("Expected command with *.xml glob for file1.xml") } case "file2.txt": if len(cmds) < 1 { t.Errorf("Expected at least 1 command for file2.txt, got %d", len(cmds)) } // Verify at least one command with *.txt pattern hasTxtGlob := false for _, cmd := range cmds { for _, glob := range cmd.Files { if glob == "*.txt" { hasTxtGlob = true break } } if hasTxtGlob { break } } if !hasTxtGlob { t.Errorf("Expected command with *.txt glob for file2.txt") } case "subdir/file3.xml": if len(cmds) < 1 { t.Errorf("Expected at least 1 command for subdir/file3.xml, got %d", len(cmds)) } // Should match both *.xml and subdir/* patterns matches := 0 for _, cmd := range cmds { for _, glob := range cmd.Files { if glob == "*.xml" || glob == "subdir/*" { matches++ break } } } if matches < 1 { t.Errorf("Expected subdir/file3.xml to match at least one pattern (*.xml or subdir/*)") } } } } func TestAggregateGlobs(t *testing.T) { commands := []ModifyCommand{ { Regex: "pattern1", Lua: "expr1", Files: []string{"*.xml", "*.txt"}, }, { Regex: "pattern2", Lua: "expr2", Files: []string{"*.xml", "*.json"}, }, { Regex: "pattern3", Lua: "expr3", Files: []string{"subdir/*.xml"}, }, } globs := AggregateGlobs(commands) expected := map[string]struct{}{ "*.xml": {}, "*.txt": {}, "*.json": {}, "subdir/*.xml": {}, } if len(globs) != len(expected) { t.Errorf("Expected %d unique globs, got %d: %v", len(expected), len(globs), globs) } for glob := range expected { if _, exists := globs[glob]; !exists { t.Errorf("Expected glob %s not found in result", glob) } } } func TestLoadCommandFromArgs(t *testing.T) { // Save original flags origGitFlag := *GitFlag origResetFlag := *ResetFlag origLogLevel := *LogLevel // Restore original flags after test defer func() { *GitFlag = origGitFlag *ResetFlag = origResetFlag *LogLevel = origLogLevel }() // Test cases tests := []struct { name string args []string gitFlag bool resetFlag bool logLevel string shouldError bool }{ { name: "Valid command", args: []string{"pattern", "expr", "file1", "file2"}, gitFlag: false, resetFlag: false, logLevel: "INFO", shouldError: false, }, { name: "Not enough args", args: []string{"pattern", "expr"}, gitFlag: false, resetFlag: false, logLevel: "INFO", shouldError: true, }, { name: "With git flag", args: []string{"pattern", "expr", "file1"}, gitFlag: true, resetFlag: false, logLevel: "INFO", shouldError: false, }, { name: "With reset flag (forces git flag)", args: []string{"pattern", "expr", "file1"}, gitFlag: false, resetFlag: true, logLevel: "INFO", shouldError: false, }, { name: "With custom log level", args: []string{"pattern", "expr", "file1"}, gitFlag: false, resetFlag: false, logLevel: "DEBUG", shouldError: false, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { // Set flags for this test case *GitFlag = tc.gitFlag *ResetFlag = tc.resetFlag *LogLevel = tc.logLevel commands, err := LoadCommandFromArgs(tc.args) if tc.shouldError { if err == nil { t.Errorf("Expected an error but got none") } return } if err != nil { t.Errorf("Unexpected error: %v", err) return } if len(commands) != 1 { t.Errorf("Expected 1 command, got %d", len(commands)) return } cmd := commands[0] // Check command properties if cmd.Regex != tc.args[0] { t.Errorf("Expected pattern %q, got %q", tc.args[0], cmd.Regex) } if cmd.Lua != tc.args[1] { t.Errorf("Expected LuaExpr %q, got %q", tc.args[1], cmd.Lua) } if len(cmd.Files) != len(tc.args)-2 { t.Errorf("Expected %d files, got %d", len(tc.args)-2, len(cmd.Files)) } // When reset is true, git should be true regardless of what was set expectedGit := tc.gitFlag || tc.resetFlag if cmd.Git != expectedGit { t.Errorf("Expected Git flag %v, got %v", expectedGit, cmd.Git) } if cmd.Reset != tc.resetFlag { t.Errorf("Expected Reset flag %v, got %v", tc.resetFlag, cmd.Reset) } if cmd.LogLevel != tc.logLevel { t.Errorf("Expected LogLevel %q, got %q", tc.logLevel, cmd.LogLevel) } }) } } // Successfully unmarshal valid YAML data into ModifyCommand slice func TestLoadCommandsFromCookFileSuccess(t *testing.T) { // Arrange yamlData := []byte(` - name: command1 pattern: "*.txt" lua: replace - name: command2 pattern: "*.go" lua: delete `) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Len(t, commands, 2) assert.Equal(t, "command1", commands[0].Name) assert.Equal(t, "*.txt", commands[0].Regex) assert.Equal(t, "replace", commands[0].Lua) assert.Equal(t, "command2", commands[1].Name) assert.Equal(t, "*.go", commands[1].Regex) assert.Equal(t, "delete", commands[1].Lua) } // Process YAML with comments or directives func TestLoadCommandsFromCookFileWithComments(t *testing.T) { // Arrange yamlData := []byte(` # This is a comment - name: command1 pattern: "*.txt" lua: replace # Another comment - name: command2 pattern: "*.go" lua: delete `) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Len(t, commands, 2) assert.Equal(t, "command1", commands[0].Name) assert.Equal(t, "*.txt", commands[0].Regex) assert.Equal(t, "replace", commands[0].Lua) assert.Equal(t, "command2", commands[1].Name) assert.Equal(t, "*.go", commands[1].Regex) assert.Equal(t, "delete", commands[1].Lua) } // Handle different YAML formatting styles (flow vs block) func TestLoadCommandsFromCookFileWithFlowStyle(t *testing.T) { // Arrange yamlData := []byte(`[ { name: command1, pattern: "*.txt", lua: replace }, { name: command2, pattern: "*.go", lua: delete } ]`) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Len(t, commands, 2) assert.Equal(t, "command1", commands[0].Name) assert.Equal(t, "*.txt", commands[0].Regex) assert.Equal(t, "replace", commands[0].Lua) assert.Equal(t, "command2", commands[1].Name) assert.Equal(t, "*.go", commands[1].Regex) assert.Equal(t, "delete", commands[1].Lua) } // Handle nil or empty cookFileData (should return error) func TestLoadCommandsFromCookFileNilOrEmptyData(t *testing.T) { // Arrange var nilData []byte emptyData := []byte{} // Act commandsNil, errNil := LoadCommandsFromCookFile(nilData) commandsEmpty, errEmpty := LoadCommandsFromCookFile(emptyData) // Assert assert.Nil(t, errNil) assert.Empty(t, commandsNil) assert.Nil(t, errEmpty) assert.Empty(t, commandsEmpty) } // Handle empty but valid YAML data (returning empty slice) func TestLoadCommandsFromCookFileEmptyData(t *testing.T) { // Arrange yamlData := []byte(``) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Empty(t, commands) } // Process YAML with multiple ModifyCommand entries correctly func TestLoadCommandsFromCookFileWithMultipleEntries(t *testing.T) { // Arrange yamlData := []byte(` - name: command1 pattern: "*.txt" lua: replace - name: command2 pattern: "*.go" lua: delete - name: command3 pattern: "*.md" lua: append `) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Len(t, commands, 3) assert.Equal(t, "command1", commands[0].Name) assert.Equal(t, "*.txt", commands[0].Regex) assert.Equal(t, "replace", commands[0].Lua) assert.Equal(t, "command2", commands[1].Name) assert.Equal(t, "*.go", commands[1].Regex) assert.Equal(t, "delete", commands[1].Lua) assert.Equal(t, "command3", commands[2].Name) assert.Equal(t, "*.md", commands[2].Regex) assert.Equal(t, "append", commands[2].Lua) } func TestLoadCommandsFromCookFileLegitExample(t *testing.T) { // Arrange yamlData := []byte(` - name: crewlayabout pattern: '!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)"!anydistance="(?!num)"!anySkillBonus!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)"!anyvalue="(?!num)' lua: | repairspeedpenalty=round(repairspeedpenalty/2, 2) skillpenalty=round(skillpenalty/2, 0) repairspeedbonus=round(repairspeedbonus*2, 2) skillbonus=round(skillbonus*2, 0) distance=round(distance*2, 0) skillpenaltyv=skillpenalty skillpenaltyv1=skillpenalty skillpenaltyv2=skillpenalty skillpenaltyv3=skillpenalty skillpenaltyv4=skillpenalty repairspeedpenaltyv=round(-repairspeedpenalty/100, 2) files: - '**/TalentsAssistant.xml' `) // Act commands, err := LoadCommandsFromCookFile(yamlData) // Assert assert.NoError(t, err) assert.Len(t, commands, 1) assert.Equal(t, "crewlayabout", commands[0].Name) } // Valid command with minimum 3 arguments returns a ModifyCommand slice with correct values func TestLoadCommandFromArgsWithValidArguments(t *testing.T) { // Setup oldGitFlag := GitFlag oldResetFlag := ResetFlag oldLogLevel := LogLevel gitValue := true resetValue := false logLevelValue := "info" GitFlag = &gitValue ResetFlag = &resetValue LogLevel = &logLevelValue defer func() { GitFlag = oldGitFlag ResetFlag = oldResetFlag LogLevel = oldLogLevel }() args := []string{"*.go", "return x", "file1.go", "file2.go"} // Execute commands, err := LoadCommandFromArgs(args) // Assert assert.NoError(t, err) assert.Len(t, commands, 1) assert.Equal(t, "*.go", commands[0].Regex) assert.Equal(t, "return x", commands[0].Lua) assert.Equal(t, []string{"file1.go", "file2.go"}, commands[0].Files) assert.Equal(t, true, commands[0].Git) assert.Equal(t, false, commands[0].Reset) assert.Equal(t, "info", commands[0].LogLevel) } // Less than 3 arguments returns an error with appropriate message func TestLoadCommandFromArgsWithInsufficientArguments(t *testing.T) { // Setup oldGitFlag := GitFlag oldResetFlag := ResetFlag oldLogLevel := LogLevel gitValue := false resetValue := false logLevelValue := "info" GitFlag = &gitValue ResetFlag = &resetValue LogLevel = &logLevelValue defer func() { GitFlag = oldGitFlag ResetFlag = oldResetFlag LogLevel = oldLogLevel }() testCases := []struct { name string args []string }{ {"empty args", []string{}}, {"one arg", []string{"*.go"}}, {"two args", []string{"*.go", "return x"}}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // Execute commands, err := LoadCommandFromArgs(tc.args) // Assert assert.Error(t, err) assert.Nil(t, commands) assert.Contains(t, err.Error(), "at least 3 arguments are required") }) } } // Pattern, Lua, and Files fields are correctly populated from args func TestLoadCommandFromArgsPopulatesFieldsCorrectly(t *testing.T) { // Setup oldGitFlag := GitFlag oldResetFlag := ResetFlag oldLogLevel := LogLevel gitValue := false resetValue := false logLevelValue := "debug" GitFlag = &gitValue ResetFlag = &resetValue LogLevel = &logLevelValue defer func() { GitFlag = oldGitFlag ResetFlag = oldResetFlag LogLevel = oldLogLevel }() args := []string{"*.txt", "print('Hello')", "file1.txt", "file2.txt"} // Execute commands, err := LoadCommandFromArgs(args) // Assert assert.NoError(t, err) assert.Len(t, commands, 1) assert.Equal(t, "*.txt", commands[0].Regex) assert.Equal(t, "print('Hello')", commands[0].Lua) assert.Equal(t, []string{"file1.txt", "file2.txt"}, commands[0].Files) assert.Equal(t, false, commands[0].Git) assert.Equal(t, false, commands[0].Reset) assert.Equal(t, "debug", commands[0].LogLevel) } // Git flag is set to true when ResetFlag is true func TestLoadCommandFromArgsSetsGitFlagWhenResetFlagIsTrue(t *testing.T) { // Setup oldGitFlag := GitFlag oldResetFlag := ResetFlag oldLogLevel := LogLevel gitValue := false resetValue := true logLevelValue := "info" GitFlag = &gitValue ResetFlag = &resetValue LogLevel = &logLevelValue defer func() { GitFlag = oldGitFlag ResetFlag = oldResetFlag LogLevel = oldLogLevel }() args := []string{"*.go", "return x", "file1.go", "file2.go"} // Execute commands, err := LoadCommandFromArgs(args) // Assert assert.NoError(t, err) assert.Len(t, commands, 1) assert.Equal(t, true, commands[0].Git) } // TODO: Figure out how to mock shit // Can't be asked doing that right now... // Successfully loads commands from multiple YAML files in the current directory // func TestLoadCommandsFromCookFilesSuccessfully(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // Create mock YAML files // yamlContent1 := []byte("commands:\n - name: command1\n type: test") // yamlContent2 := []byte("commands:\n - name: command2\n type: test") // err = os.WriteFile("test1.yaml", yamlContent1, 0644) // if err != nil { // t.Fatalf("Failed to write test1.yaml: %v", err) // } // err = os.WriteFile("test2.yaml", yamlContent2, 0644) // if err != nil { // t.Fatalf("Failed to write test2.yaml: %v", err) // } // // Mock LoadCommandsFromCookFile to return expected commands // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // var result []ModifyCommand // if string(data) == string(yamlContent1) { // result = []ModifyCommand{{Name: "command1", Type: "test"}} // } else if string(data) == string(yamlContent2) { // result = []ModifyCommand{{Name: "command2", Type: "test"}} // } // return result, nil // } // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // if len(commands) != 2 { // t.Errorf("Expected 2 commands, got: %d", len(commands)) // } // expectedNames := []string{"command1", "command2"} // for i, cmd := range commands { // if cmd.Name != expectedNames[i] { // t.Errorf("Expected command name %s, got: %s", expectedNames[i], cmd.Name) // } // } // } // No YAML files exist in the current directory func TestLoadCommandsFromCookFilesNoYamlFiles(t *testing.T) { // Setup empty test directory tempDir, err := os.MkdirTemp("", "cookfiles_empty_test") if err != nil { t.Fatalf("Failed to create temp directory: %v", err) } defer os.RemoveAll(tempDir) // Save current directory to restore later originalDir, err := os.Getwd() if err != nil { t.Fatalf("Failed to get current directory: %v", err) } // Change to temp directory err = os.Chdir(tempDir) if err != nil { t.Fatalf("Failed to change directory: %v", err) } defer os.Chdir(originalDir) // Create a non-yaml file to ensure it's not picked up err = os.WriteFile("test.txt", []byte("not a yaml file"), 0644) if err != nil { t.Fatalf("Failed to write test.txt: %v", err) } // Execute function commands, err := LoadCommandsFromCookFiles("") // Assertions if err != nil { t.Errorf("Expected no error, got: %v", err) } if len(commands) != 0 { t.Errorf("Expected 0 commands, got: %d", len(commands)) } // Verify the logger was used correctly (if applicable) // This would require mocking the logger, which isn't shown in the provided context } // Correctly appends commands from multiple cook files into a single slice // func TestLoadCommandsFromCookFilesAppendsCommands(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock YAML files // yamlContent1 := []byte("commands:\n - name: command1\n type: test") // yamlContent2 := []byte("commands:\n - name: command2\n type: test") // // err = os.WriteFile("test1.yaml", yamlContent1, 0644) // if err != nil { // t.Fatalf("Failed to write test1.yaml: %v", err) // } // // err = os.WriteFile("test2.yaml", yamlContent2, 0644) // if err != nil { // t.Fatalf("Failed to write test2.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return expected commands // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // var result []ModifyCommand // if string(data) == string(yamlContent1) { // result = []ModifyCommand{{Name: "command1", Type: "test"}} // } else if string(data) == string(yamlContent2) { // result = []ModifyCommand{{Name: "command2", Type: "test"}} // } // return result, nil // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // // if len(commands) != 2 { // t.Errorf("Expected 2 commands, got: %d", len(commands)) // } // // expectedNames := []string{"command1", "command2"} // for i, cmd := range commands { // if cmd.Name != expectedNames[i] { // t.Errorf("Expected command name %s, got: %s", expectedNames[i], cmd.Name) // } // } // } // Current working directory cannot be accessed // func TestLoadCommandsFromCookFilesCwdError(t *testing.T) { // // Mock os.Getwd to simulate an error // originalGetwd := os.Getwd // os.Getwd = func() (string, error) { // return "", fmt.Errorf("mock error: unable to access cwd") // } // defer func() { os.Getwd = originalGetwd }() // // // Execute function // _, err := LoadCommandsFromCookFiles("") // // // Assertions // if err == nil { // t.Errorf("Expected error, got nil") // } // // expectedErrorMsg := "failed to get current working directory: mock error: unable to access cwd" // if err.Error() != expectedErrorMsg { // t.Errorf("Expected error message '%s', got: '%s'", expectedErrorMsg, err.Error()) // } // } // Empty YAML files exist but contain no commands // func TestLoadCommandsFromEmptyCookFiles(t *testing.T) { // // Setup test directory with mock empty YAML file // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock empty YAML file // emptyYamlContent := []byte("") // // err = os.WriteFile("empty.yaml", emptyYamlContent, 0644) // if err != nil { // t.Fatalf("Failed to write empty.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return no commands for empty content // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // if len(data) == 0 { // return []ModifyCommand{}, nil // } // return nil, fmt.Errorf("unexpected data") // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // // if len(commands) != 0 { // t.Errorf("Expected 0 commands, got: %d", len(commands)) // } // } // LoadCommandsFromCookFile returns an error for a malformed YAML file // func TestLoadCommandsFromCookFilesMalformedYAML(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create a malformed YAML file // malformedYAMLContent := []byte("commands:\n - name: command1\n type") // // err = os.WriteFile("malformed.yaml", malformedYAMLContent, 0644) // if err != nil { // t.Fatalf("Failed to write malformed.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return an error for malformed YAML // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // return nil, fmt.Errorf("malformed YAML") // } // // // Execute function // _, err = LoadCommandsFromCookFiles("") // // // Assertions // if err == nil { // t.Errorf("Expected error for malformed YAML, got none") // } // } // Directory contains both valid and invalid YAML files // func TestLoadCommandsFromCookFilesWithInvalidYAML(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock YAML files // validYAMLContent := []byte("commands:\n - name: validCommand\n type: test") // invalidYAMLContent := []byte("invalid_yaml_content") // // err = os.WriteFile("valid.yaml", validYAMLContent, 0644) // if err != nil { // t.Fatalf("Failed to write valid.yaml: %v", err) // } // // err = os.WriteFile("invalid.yaml", invalidYAMLContent, 0644) // if err != nil { // t.Fatalf("Failed to write invalid.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return expected commands or error // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // if string(data) == string(validYAMLContent) { // return []ModifyCommand{{Name: "validCommand", Type: "test"}}, nil // } // return nil, fmt.Errorf("invalid YAML content") // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err == nil { // t.Errorf("Expected error due to invalid YAML, got none") // } // // if len(commands) != 1 { // t.Errorf("Expected 1 valid command, got: %d", len(commands)) // } // // if commands[0].Name != "validCommand" { // t.Errorf("Expected command name 'validCommand', got: %s", commands[0].Name) // } // } // Handles relative paths in the file system correctly // func TestLoadCommandsFromCookFilesWithRelativePaths(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock YAML files // yamlContent1 := []byte("commands:\n - name: command1\n type: test") // yamlContent2 := []byte("commands:\n - name: command2\n type: test") // // err = os.WriteFile("test1.yaml", yamlContent1, 0644) // if err != nil { // t.Fatalf("Failed to write test1.yaml: %v", err) // } // // err = os.WriteFile("test2.yaml", yamlContent2, 0644) // if err != nil { // t.Fatalf("Failed to write test2.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return expected commands // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // var result []ModifyCommand // if string(data) == string(yamlContent1) { // result = []ModifyCommand{{Name: "command1", Type: "test"}} // } else if string(data) == string(yamlContent2) { // result = []ModifyCommand{{Name: "command2", Type: "test"}} // } // return result, nil // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // // if len(commands) != 2 { // t.Errorf("Expected 2 commands, got: %d", len(commands)) // } // // expectedNames := []string{"command1", "command2"} // for i, cmd := range commands { // if cmd.Name != expectedNames[i] { // t.Errorf("Expected command name %s, got: %s", expectedNames[i], cmd.Name) // } // } // } // Maintains the order of commands as they appear in the files // func TestLoadCommandsFromCookFilesOrder(t *testing.T) { // // Setup test directory with mock YAML files // tempDir, err := os.MkdirTemp("", "cookfiles_order_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock YAML files // yamlContent1 := []byte("commands:\n - name: command1\n type: test") // yamlContent2 := []byte("commands:\n - name: command2\n type: test") // // err = os.WriteFile("test1.yaml", yamlContent1, 0644) // if err != nil { // t.Fatalf("Failed to write test1.yaml: %v", err) // } // // err = os.WriteFile("test2.yaml", yamlContent2, 0644) // if err != nil { // t.Fatalf("Failed to write test2.yaml: %v", err) // } // // // Mock LoadCommandsFromCookFile to return expected commands // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // var result []ModifyCommand // if string(data) == string(yamlContent1) { // result = []ModifyCommand{{Name: "command1", Type: "test"}} // } else if string(data) == string(yamlContent2) { // result = []ModifyCommand{{Name: "command2", Type: "test"}} // } // return result, nil // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // // if len(commands) != 2 { // t.Errorf("Expected 2 commands, got: %d", len(commands)) // } // // expectedNames := []string{"command1", "command2"} // for i, cmd := range commands { // if cmd.Name != expectedNames[i] { // t.Errorf("Expected command name %s, got: %s", expectedNames[i], cmd.Name) // } // } // } // Handles non-YAML files that might match the glob pattern // func TestLoadCommandsFromCookFilesIgnoresNonYamlFiles(t *testing.T) { // // Setup test directory with mock files // tempDir, err := os.MkdirTemp("", "cookfiles_test") // if err != nil { // t.Fatalf("Failed to create temp directory: %v", err) // } // defer os.RemoveAll(tempDir) // // // Save current directory to restore later // originalDir, err := os.Getwd() // if err != nil { // t.Fatalf("Failed to get current directory: %v", err) // } // // // Change to temp directory // err = os.Chdir(tempDir) // if err != nil { // t.Fatalf("Failed to change directory: %v", err) // } // defer os.Chdir(originalDir) // // // Create mock non-YAML file // nonYamlContent := []byte("This is not a YAML file") // // err = os.WriteFile("test.txt", nonYamlContent, 0644) // if err != nil { // t.Fatalf("Failed to write test.txt: %v", err) // } // // // Mock LoadCommandsFromCookFile to return no commands for non-YAML content // originalLoadFunc := LoadCommandsFromCookFile // defer func() { LoadCommandsFromCookFile = originalLoadFunc }() // // LoadCommandsFromCookFile = func(data []byte) ([]ModifyCommand, error) { // return nil, fmt.Errorf("not a YAML file") // } // // // Execute function // commands, err := LoadCommandsFromCookFiles("") // // // Assertions // if err != nil { // t.Errorf("Expected no error, got: %v", err) // } // // if len(commands) != 0 { // t.Errorf("Expected 0 commands, got: %d", len(commands)) // } // }