github.com/google/cloudprober@v0.11.3/common/file/file_test.go (about) 1 // Copyright 2020 The Cloudprober Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package file 16 17 import ( 18 "io/ioutil" 19 "testing" 20 ) 21 22 func createTempFile(t *testing.T, b []byte) string { 23 tmpfile, err := ioutil.TempFile("", "") 24 if err != nil { 25 t.Fatal(err) 26 return "" 27 } 28 29 defer tmpfile.Close() 30 if _, err := tmpfile.Write(b); err != nil { 31 t.Fatal(err) 32 } 33 34 return tmpfile.Name() 35 } 36 37 func testReadFile(path string) ([]byte, error) { 38 return []byte("content-for-" + path), nil 39 } 40 41 func TestReadFile(t *testing.T) { 42 prefixToReadfunc["test://"] = testReadFile 43 44 // Virtual file 45 testPath := "test://test-file" 46 47 // Disk file 48 tempContent := "temp-content" 49 tempPath := createTempFile(t, []byte(tempContent)) 50 51 testData := map[string]string{ 52 testPath: "content-for-test-file", 53 tempPath: tempContent, 54 } 55 56 for path, expectedContent := range testData { 57 t.Run("ReadFile("+path+")", func(t *testing.T) { 58 b, err := ReadFile(path) 59 if err != nil { 60 t.Fatalf("Error while reading the file: %s", path) 61 } 62 63 if string(b) != expectedContent { 64 t.Errorf("ReadFile(%s) = %s, expected=%s", path, string(b), expectedContent) 65 } 66 }) 67 } 68 }