github.com/quickfeed/quickfeed@v0.0.0-20240507093252-ed8ca812a09c/internal/env/path_test.go (about) 1 package env 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 8 "github.com/go-git/go-git/v5" 9 ) 10 11 func TestRoot(t *testing.T) { 12 // make sure quickfeedRoot is set 13 wantRoot := Root() 14 gotRoot := Root() 15 if gotRoot != wantRoot { 16 t.Errorf("Root() = %s, want %s", gotRoot, wantRoot) 17 } 18 19 // reset quickfeedRoot to empty string; to circumvent the init() function 20 quickfeedRoot = "" 21 22 // get current dir; to change back to after test 23 wd, err := os.Getwd() 24 if err != nil { 25 t.Fatal(err) 26 } 27 defer func() { _ = os.Chdir(wd) }() 28 29 // change to other directory inside the quickfeed repository 30 if err = os.Chdir(filepath.Join(wantRoot, "internal", "env")); err != nil { 31 t.Fatal(err) 32 } 33 34 gotRoot = Root() 35 if gotRoot != wantRoot { 36 t.Errorf("Root() = %s, want %s", gotRoot, wantRoot) 37 } 38 } 39 40 func TestSetRoot(t *testing.T) { 41 // assume working directory is within the quickfeed repository 42 defer func() { 43 if r := recover(); r != nil { 44 t.Errorf("Unexpected panic: %v", r) 45 } 46 }() 47 setRoot() 48 } 49 50 func TestSetRootWorkingDirOutside(t *testing.T) { 51 // reset quickfeedRoot to empty string; to circumvent the init() function 52 quickfeedRoot = "" 53 54 // set working directory to be outside the quickfeed repository 55 wd, err := os.Getwd() 56 if err != nil { 57 t.Fatal(err) 58 } 59 err = os.Chdir("/") 60 if err != nil { 61 t.Fatal(err) 62 } 63 defer func() { _ = os.Chdir(wd) }() 64 65 // setRoot() is expected to panic; this test will fail if it does not panic 66 defer func() { 67 if r := recover(); r == nil { 68 t.Errorf("Expected setRoot() to panic") 69 } 70 }() 71 setRoot() 72 } 73 74 func TestSetRootWrongGitRepo(t *testing.T) { 75 // reset quickfeedRoot to empty string; to circumvent the init() function 76 quickfeedRoot = "" 77 78 // set working directory to be inside a git repository that is not the quickfeed repository 79 wd, err := os.Getwd() 80 if err != nil { 81 t.Fatal(err) 82 } 83 gitRepo := t.TempDir() 84 err = os.Chdir(gitRepo) 85 if err != nil { 86 t.Fatal(err) 87 } 88 defer func() { _ = os.Chdir(wd) }() 89 90 // create a git repository 91 _, err = git.PlainInit(gitRepo, false) 92 if err != nil { 93 t.Fatal(err) 94 } 95 96 // create go.mod file with a different module name than the quickfeed module 97 modFile := filepath.Join(gitRepo, "go.mod") 98 f, err := os.Create(modFile) 99 if err != nil { 100 t.Fatal(err) 101 } 102 defer func() { _ = f.Close() }() 103 if _, err := f.WriteString("module github.com/wrong/module\n"); err != nil { 104 t.Fatal(err) 105 } 106 107 // setRoot() is expected to panic; this test will fail if it does not panic 108 defer func() { 109 if r := recover(); r == nil { 110 t.Errorf("Expected setRoot() to panic") 111 } 112 }() 113 setRoot() 114 }