OSDN Git Service

Hulk did something
[bytom/vapor.git] / vendor / github.com / spf13 / cobra / cobra / cmd / golden_test.go
1 package cmd
2
3 import (
4         "bytes"
5         "errors"
6         "flag"
7         "fmt"
8         "io/ioutil"
9         "os/exec"
10 )
11
12 var update = flag.Bool("update", false, "update .golden files")
13
14 func init() {
15         // Mute commands.
16         addCmd.SetOutput(new(bytes.Buffer))
17         initCmd.SetOutput(new(bytes.Buffer))
18 }
19
20 // compareFiles compares the content of files with pathA and pathB.
21 // If contents are equal, it returns nil.
22 // If not, it returns which files are not equal
23 // and diff (if system has diff command) between these files.
24 func compareFiles(pathA, pathB string) error {
25         contentA, err := ioutil.ReadFile(pathA)
26         if err != nil {
27                 return err
28         }
29         contentB, err := ioutil.ReadFile(pathB)
30         if err != nil {
31                 return err
32         }
33         if !bytes.Equal(contentA, contentB) {
34                 output := new(bytes.Buffer)
35                 output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB))
36
37                 diffPath, err := exec.LookPath("diff")
38                 if err != nil {
39                         // Don't execute diff if it can't be found.
40                         return nil
41                 }
42                 diffCmd := exec.Command(diffPath, "-u", pathA, pathB)
43                 diffCmd.Stdout = output
44                 diffCmd.Stderr = output
45
46                 output.WriteString("$ diff -u " + pathA + " " + pathB + "\n")
47                 if err := diffCmd.Run(); err != nil {
48                         output.WriteString("\n" + err.Error())
49                 }
50                 return errors.New(output.String())
51         }
52         return nil
53 }
54
55 // checkLackFiles checks if all elements of expected are in got.
56 func checkLackFiles(expected, got []string) error {
57         lacks := make([]string, 0, len(expected))
58         for _, ev := range expected {
59                 if !stringInStringSlice(ev, got) {
60                         lacks = append(lacks, ev)
61                 }
62         }
63         if len(lacks) > 0 {
64                 return fmt.Errorf("Lack %v file(s): %v", len(lacks), lacks)
65         }
66         return nil
67 }
68
69 // stringInStringSlice checks if s is an element of slice.
70 func stringInStringSlice(s string, slice []string) bool {
71         for _, v := range slice {
72                 if s == v {
73                         return true
74                 }
75         }
76         return false
77 }