github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/file/helper_test.go (about) 1 package file 2 3 import ( 4 "os" 5 "strings" 6 "testing" 7 ) 8 9 // Test cases for successful scenarios 10 func TestGetProjectDir_Success(t *testing.T) { 11 // Test case 1: Project name exists in the current working directory 12 // Replace 'projectName' with an existing project name on your system. 13 projectName := "go-kit" 14 actualPath, err := GetProjectDir(projectName) 15 if err != nil { 16 t.Errorf("Expected success, but got an error: %v", err) 17 } 18 if !strings.Contains(actualPath, projectName) { 19 t.Errorf("Expected containes: %s, but got: %s", projectName, actualPath) 20 } 21 22 // Test case 2: Empty project name (should return an error) 23 emptyProjectName := "not_found" 24 _, err = GetProjectDir(emptyProjectName) 25 if err == nil { 26 t.Error("Expected an error for an empty project name, but got nil") 27 } 28 } 29 30 // Test cases for error scenarios 31 func TestGetProjectDir_Errors(t *testing.T) { 32 // Test case 1: Project directory not found in the current working directory 33 projectName := "non_existent_project" 34 _, err := GetProjectDir(projectName) 35 if err != ErrProjectDirectoryNotFound { 36 t.Errorf("Expected error 'ErrProjectDirectoryNotFound', but got: %v", err) 37 } 38 39 // Test case 2: Getwd function error 40 // Temporarily change the current working directory to a non-existent path to simulate a Getwd error. 41 previousDir, _ := os.Getwd() 42 defer os.Chdir(previousDir) // Restore the previous directory. 43 os.Chdir("non_existent_path") 44 _, err = GetProjectDir(projectName) 45 if err == nil { 46 t.Error("Expected an error due to Getwd failure, but got nil") 47 } 48 } 49 50 func TestFirstIndexOfString(t *testing.T) { 51 tests := []struct { 52 source string 53 value string 54 expected int 55 }{ 56 {"abcdefgh", "def", 3}, 57 {"abcabcabc", "abc", 0}, 58 {"xyz", "abc", -1}, // Not found case 59 {"", "test", -1}, // Empty source case 60 {"test", "", 0}, // Empty value case 61 {"aaa", "aa", 0}, // Overlapping case 62 } 63 64 for _, test := range tests { 65 result := firstIndexOfString(test.source, test.value) 66 if result != test.expected { 67 t.Errorf("For source=%s, value=%s, expected %d but got %d", test.source, test.value, test.expected, result) 68 } 69 } 70 }