initial commit
[govpp.git] / vendor / github.com / Sirupsen / logrus / alt_exit_test.go
1 package logrus
2
3 import (
4         "io/ioutil"
5         "os/exec"
6         "testing"
7         "time"
8 )
9
10 func TestRegister(t *testing.T) {
11         current := len(handlers)
12         RegisterExitHandler(func() {})
13         if len(handlers) != current+1 {
14                 t.Fatalf("can't add handler")
15         }
16 }
17
18 func TestHandler(t *testing.T) {
19         gofile := "/tmp/testprog.go"
20         if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
21                 t.Fatalf("can't create go file")
22         }
23
24         outfile := "/tmp/testprog.out"
25         arg := time.Now().UTC().String()
26         err := exec.Command("go", "run", gofile, outfile, arg).Run()
27         if err == nil {
28                 t.Fatalf("completed normally, should have failed")
29         }
30
31         data, err := ioutil.ReadFile(outfile)
32         if err != nil {
33                 t.Fatalf("can't read output file %s", outfile)
34         }
35
36         if string(data) != arg {
37                 t.Fatalf("bad data")
38         }
39 }
40
41 var testprog = []byte(`
42 // Test program for atexit, gets output file and data as arguments and writes
43 // data to output file in atexit handler.
44 package main
45
46 import (
47         "github.com/Sirupsen/logrus"
48         "flag"
49         "fmt"
50         "io/ioutil"
51 )
52
53 var outfile = ""
54 var data = ""
55
56 func handler() {
57         ioutil.WriteFile(outfile, []byte(data), 0666)
58 }
59
60 func badHandler() {
61         n := 0
62         fmt.Println(1/n)
63 }
64
65 func main() {
66         flag.Parse()
67         outfile = flag.Arg(0)
68         data = flag.Arg(1)
69
70         logrus.RegisterExitHandler(handler)
71         logrus.RegisterExitHandler(badHandler)
72         logrus.Fatal("Bye bye")
73 }
74 `)