github.com/petermattis/pebble@v0.0.0-20190905164901-ab51a2166067/tool/data_test.go (about) 1 // Copyright 2019 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 // of this source code is governed by a BSD-style license that can be found in 3 // the LICENSE file. 4 5 package tool 6 7 import ( 8 "bytes" 9 "os" 10 "path/filepath" 11 "strings" 12 "testing" 13 "time" 14 15 "github.com/petermattis/pebble/internal/base" 16 "github.com/petermattis/pebble/internal/datadriven" 17 "github.com/spf13/cobra" 18 ) 19 20 func runTests(t *testing.T, path string) { 21 paths, err := filepath.Glob(path) 22 if err != nil { 23 t.Fatal(err) 24 } 25 root := filepath.Dir(path) 26 for { 27 next := filepath.Dir(root) 28 if next == "." { 29 break 30 } 31 root = next 32 } 33 34 for _, path := range paths { 35 name, err := filepath.Rel(root, path) 36 if err != nil { 37 t.Fatal(err) 38 } 39 t.Run(name, func(t *testing.T) { 40 datadriven.RunTest(t, path, func(d *datadriven.TestData) string { 41 args := []string{d.Cmd} 42 for _, arg := range d.CmdArgs { 43 args = append(args, arg.String()) 44 } 45 args = append(args, strings.Fields(d.Input)...) 46 47 var buf bytes.Buffer 48 stdout = &buf 49 stderr = &buf 50 osExit = func(int) {} 51 52 var secs int64 53 timeNow = func() time.Time { secs++; return time.Unix(secs, 0) } 54 55 defer func() { 56 stdout = os.Stdout 57 stderr = os.Stderr 58 osExit = os.Exit 59 timeNow = time.Now 60 }() 61 62 tool := New() 63 // Register a test comparer and merger so that we can check the 64 // behavior of tools when the comparer and merger do not match. 65 tool.RegisterComparer(func() *Comparer { 66 var c Comparer 67 c = *base.DefaultComparer 68 c.Name = "test-comparer" 69 return &c 70 }()) 71 tool.RegisterMerger(func() *Merger { 72 var m Merger 73 m = *base.DefaultMerger 74 m.Name = "test-merger" 75 return &m 76 }()) 77 78 c := &cobra.Command{} 79 c.AddCommand(tool.Commands...) 80 c.SetArgs(args) 81 c.SetOutput(&buf) 82 if err := c.Execute(); err != nil { 83 return err.Error() 84 } 85 return buf.String() 86 }) 87 }) 88 } 89 }