github.com/neugram/ng@v0.0.0-20180309130942-d472ff93d872/ng_test.go (about) 1 // Copyright 2018 The Neugram 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 main_test 6 7 import ( 8 "bytes" 9 "fmt" 10 "os" 11 "os/exec" 12 "runtime" 13 "strings" 14 "testing" 15 ) 16 17 var exeSuffix string // set to ".exe" on GOOS=windows 18 var testng string // name of testng binary 19 20 func init() { 21 if runtime.GOOS == "windows" { 22 exeSuffix = ".exe" 23 } 24 testng = "./testng" + exeSuffix 25 } 26 27 // The TestMain function creates an ng command for testing purposes. 28 func TestMain(m *testing.M) { 29 out, err := exec.Command("go", "build", "-o", testng).CombinedOutput() 30 if err != nil { 31 fmt.Fprintf(os.Stderr, "building testng failed: %v\n%s", err, out) 32 os.Exit(2) 33 } 34 35 r := m.Run() 36 37 os.Remove(testng) 38 39 os.Exit(r) 40 } 41 42 func TestPrintf(t *testing.T) { 43 // The printf builtin should not return any values, unlike fmt.Printf. 44 out, err := exec.Command(testng, "-e", `printf("%x", 42)`).CombinedOutput() 45 if err != nil { 46 t.Errorf("testng failed: %v\n%s", err, out) 47 } 48 49 got := string(out) 50 want := "2a" 51 if got != want { 52 t.Errorf("printf returned %q, want %q", got, want) 53 } 54 } 55 56 func TestExitMsg(t *testing.T) { 57 out, err := exec.Command(testng, "-e", `exit`).CombinedOutput() 58 if err == nil { 59 t.Fatalf("testng failed: got a nil error. want 'Ctrl-D' exit") 60 } 61 if got := string(out); !strings.Contains(got, "Ctrl-D") { 62 t.Errorf("exit error does not mention Ctrl-D: %q", got) 63 } 64 switch e := err.(type) { 65 case *exec.ExitError: 66 default: 67 t.Errorf("testng should have failed with a non-zero exit code: %#v", e) 68 } 69 } 70 71 func TestGofmt(t *testing.T) { 72 exe, err := exec.LookPath("gofmt") 73 74 if err != nil { 75 t.Fatal(err) 76 } 77 78 cmd := exec.Command(exe, "-d", "-s", ".") 79 buf := new(bytes.Buffer) 80 cmd.Stdout = buf 81 cmd.Stderr = buf 82 83 err = cmd.Run() 84 if err != nil { 85 t.Fatalf("error running %s:\n%s\n%v", exe, string(buf.Bytes()), err) 86 } 87 88 if len(buf.Bytes()) != 0 { 89 t.Errorf("some files were not gofmt'ed:\n%s\n", string(buf.Bytes())) 90 } 91 }