github.com/jchengjr77/canaveral@v1.0.1-0.20200715160102-ea9245d1a2fb/lib/errcheck_test.go (about) 1 package lib 2 3 import ( 4 "errors" 5 "os" 6 "os/user" 7 "testing" 8 ) 9 10 const testFile = "canaveral_test_file" 11 12 func checkPanic(t *testing.T, f func()) { 13 defer func() bool { 14 if r := recover(); r == nil { 15 t.Log("The code did not panic") 16 return false 17 } 18 t.Log("The code panicked") 19 return true 20 }() 21 f() 22 } 23 24 func TestCheck(t *testing.T) { 25 var err1 error = nil 26 t.Log("Following check should not panic") 27 checkPanic(t, func() { 28 Check(err1) 29 }) 30 31 var err2 error = errors.New("Test Error") 32 t.Log("Following check should panic") 33 checkPanic(t, func() { 34 Check(err2) 35 }) 36 } 37 38 func TestFileExists(t *testing.T) { 39 tempusr, err := user.Current() 40 Check(err) 41 tempHome := tempusr.HomeDir 42 newPath := tempHome + "/canaveral_test_dir/" 43 if FileExists(newPath+testFile) == true { 44 t.Errorf("function FileExists() found a non-existent file at: %s", 45 tempHome+testFile) 46 t.Errorf("Check that no file exists there already.") 47 } 48 49 err = os.MkdirAll(newPath, os.ModePerm) 50 Check(err) 51 f, err := os.Create(newPath + testFile) 52 Check(err) 53 defer os.RemoveAll(newPath) 54 defer f.Close() 55 if FileExists(newPath+testFile) == false { 56 t.Errorf("function FileExists() failed to recognize file at: %s", 57 tempHome+testFile) 58 } 59 60 } 61 62 func TestDirExists(t *testing.T) { 63 tempusr, err := user.Current() 64 Check(err) 65 tempHome := tempusr.HomeDir 66 newPath := tempHome + "/canaveral_test_dir/" 67 if DirExists(newPath) == true { 68 t.Errorf("function DirExists() found a non-existent dir at: %s", 69 newPath) 70 t.Errorf("Check that no dir exists there already.") 71 } 72 73 err = os.MkdirAll(newPath, os.ModePerm) 74 Check(err) 75 defer os.RemoveAll(newPath) 76 if DirExists(newPath) == false { 77 t.Errorf("function DirExists() failed to recognize dir at: %s", 78 newPath) 79 } 80 } 81 82 func TestCheckToolExists(t *testing.T) { 83 actual := CheckToolExists("") 84 expect := false 85 if expect != actual { 86 t.Errorf("func CheckToolExists() did not fail given empty toolname") 87 } 88 actual = CheckToolExists("shouldnotexist") 89 expect = false 90 if expect != actual { 91 t.Errorf("func CheckToolExists() did not fail given fake toolname") 92 } 93 actual = CheckToolExists("--passingAnOption") 94 expect = false 95 if expect != actual { 96 t.Fatalf("func CheckToolExists() did not fail given bad parameter") 97 } 98 actual = CheckToolExists("which") // runs 'which which' 99 expect = true 100 if expect != actual { 101 t.Errorf("func CheckToolExists() did not find built-in command 'which'") 102 } 103 }