github.com/demonoid81/containerd@v1.3.4/pkg/testutil/helpers.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package testutil 18 19 import ( 20 "flag" 21 "fmt" 22 "io/ioutil" 23 "os" 24 "path/filepath" 25 "strconv" 26 "testing" 27 ) 28 29 var rootEnabled bool 30 31 func init() { 32 flag.BoolVar(&rootEnabled, "test.root", false, "enable tests that require root") 33 } 34 35 // DumpDir prints the contents of the directory to the testing logger. 36 // 37 // Use this in a defer statement from a test that may allocate and exercise a 38 // temporary directory. Immensely useful for sanity checking and debugging 39 // failing tests. 40 // 41 // One should still test that contents are as expected. This is only a visual 42 // tool to assist when things don't go your way. 43 func DumpDir(t *testing.T, root string) { 44 if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { 45 if err != nil { 46 return err 47 } 48 49 if fi.Mode()&os.ModeSymlink != 0 { 50 target, err := os.Readlink(path) 51 if err != nil { 52 return err 53 } 54 t.Log(fi.Mode(), fmt.Sprintf("%10s", ""), path, "->", target) 55 } else if fi.Mode().IsRegular() { 56 p, err := ioutil.ReadFile(path) 57 if err != nil { 58 t.Logf("error reading file: %v", err) 59 return nil 60 } 61 62 if len(p) > 64 { // just display a little bit. 63 p = p[:64] 64 } 65 t.Log(fi.Mode(), fmt.Sprintf("%10d", fi.Size()), path, "[", strconv.Quote(string(p)), "...]") 66 } else { 67 t.Log(fi.Mode(), fmt.Sprintf("%10d", fi.Size()), path) 68 } 69 70 return nil 71 }); err != nil { 72 t.Fatalf("error dumping directory: %v", err) 73 } 74 } 75 76 // DumpDirOnFailure prints the contents of the directory to the testing logger if 77 // the test has failed. 78 func DumpDirOnFailure(t *testing.T, root string) { 79 if t.Failed() { 80 DumpDir(t, root) 81 } 82 }