github.com/brownsys/tracing-framework-go@v0.0.0-20161210174012-0542a62412fe/go/darwin_amd64/misc/tour/content/content_test.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package content 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "io/ioutil" 12 "os" 13 "os/exec" 14 "path/filepath" 15 "strings" 16 "testing" 17 ) 18 19 // Test that all the .go files inside the content file build 20 // and execute (without checking for output correctness). 21 // Files that contain the string "// +build no-build" are not built. 22 // Files that contain the string "// +build no-run" are not executed. 23 func TestContent(t *testing.T) { 24 scratch, err := ioutil.TempDir("", "tour-content-test") 25 if err != nil { 26 t.Fatal(err) 27 } 28 defer os.RemoveAll(scratch) 29 30 err = filepath.Walk(".", func(path string, fi os.FileInfo, err error) error { 31 if filepath.Ext(path) != ".go" { 32 return nil 33 } 34 if filepath.Base(path) == "content_test.go" { 35 return nil 36 } 37 if err := testSnippet(t, path, scratch); err != nil { 38 t.Errorf("%v: %v", path, err) 39 } 40 return nil 41 }) 42 if err != nil { 43 t.Error(err) 44 } 45 } 46 47 func testSnippet(t *testing.T, path, scratch string) error { 48 b, err := ioutil.ReadFile(path) 49 if err != nil { 50 return err 51 } 52 53 build := string(bytes.SplitN(b, []byte{'\n'}, 2)[0]) 54 if !strings.HasPrefix(build, "// +build ") { 55 return errors.New("first line is not a +build comment") 56 } 57 if !strings.Contains(build, "OMIT") { 58 return errors.New(`+build comment does not contain "OMIT"`) 59 } 60 61 if strings.Contains(build, "no-build") { 62 return nil 63 } 64 bin := filepath.Join(scratch, filepath.Base(path)+".exe") 65 out, err := exec.Command("go", "build", "-o", bin, path).CombinedOutput() 66 if err != nil { 67 return fmt.Errorf("build error: %v\noutput:\n%s", err, out) 68 } 69 defer os.Remove(bin) 70 71 if strings.Contains(build, "no-run") { 72 return nil 73 } 74 out, err = exec.Command(bin).CombinedOutput() 75 if err != nil { 76 return fmt.Errorf("%v\nOutput:\n%s", err, out) 77 } 78 return nil 79 }