github.com/tompao/docker@v1.9.1/builder/dockerfile/parser/parser_test.go (about) 1 package parser 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "testing" 9 ) 10 11 const testDir = "testfiles" 12 const negativeTestDir = "testfiles-negative" 13 14 func getDirs(t *testing.T, dir string) []string { 15 f, err := os.Open(dir) 16 if err != nil { 17 t.Fatal(err) 18 } 19 20 defer f.Close() 21 22 dirs, err := f.Readdirnames(0) 23 if err != nil { 24 t.Fatal(err) 25 } 26 27 return dirs 28 } 29 30 func TestTestNegative(t *testing.T) { 31 for _, dir := range getDirs(t, negativeTestDir) { 32 dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile") 33 34 df, err := os.Open(dockerfile) 35 if err != nil { 36 t.Fatalf("Dockerfile missing for %s: %v", dir, err) 37 } 38 39 _, err = Parse(df) 40 if err == nil { 41 t.Fatalf("No error parsing broken dockerfile for %s", dir) 42 } 43 44 df.Close() 45 } 46 } 47 48 func TestTestData(t *testing.T) { 49 for _, dir := range getDirs(t, testDir) { 50 dockerfile := filepath.Join(testDir, dir, "Dockerfile") 51 resultfile := filepath.Join(testDir, dir, "result") 52 53 df, err := os.Open(dockerfile) 54 if err != nil { 55 t.Fatalf("Dockerfile missing for %s: %v", dir, err) 56 } 57 defer df.Close() 58 59 ast, err := Parse(df) 60 if err != nil { 61 t.Fatalf("Error parsing %s's dockerfile: %v", dir, err) 62 } 63 64 content, err := ioutil.ReadFile(resultfile) 65 if err != nil { 66 t.Fatalf("Error reading %s's result file: %v", dir, err) 67 } 68 69 if ast.Dump()+"\n" != string(content) { 70 fmt.Fprintln(os.Stderr, "Result:\n"+ast.Dump()) 71 fmt.Fprintln(os.Stderr, "Expected:\n"+string(content)) 72 t.Fatalf("%s: AST dump of dockerfile does not match result", dir) 73 } 74 } 75 } 76 77 func TestParseWords(t *testing.T) { 78 tests := []map[string][]string{ 79 { 80 "input": {"foo"}, 81 "expect": {"foo"}, 82 }, 83 { 84 "input": {"foo bar"}, 85 "expect": {"foo", "bar"}, 86 }, 87 { 88 "input": {"foo=bar"}, 89 "expect": {"foo=bar"}, 90 }, 91 { 92 "input": {"foo bar 'abc xyz'"}, 93 "expect": {"foo", "bar", "'abc xyz'"}, 94 }, 95 { 96 "input": {`foo bar "abc xyz"`}, 97 "expect": {"foo", "bar", `"abc xyz"`}, 98 }, 99 } 100 101 for _, test := range tests { 102 words := parseWords(test["input"][0]) 103 if len(words) != len(test["expect"]) { 104 t.Fatalf("length check failed. input: %v, expect: %v, output: %v", test["input"][0], test["expect"], words) 105 } 106 for i, word := range words { 107 if word != test["expect"][i] { 108 t.Fatalf("word check failed for word: %q. input: %v, expect: %v, output: %v", word, test["input"][0], test["expect"], words) 109 } 110 } 111 } 112 }