...
1 package logrus
2
3 import (
4 "io/ioutil"
5 "log"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "testing"
12 "time"
13 )
14
15 func TestRegister(t *testing.T) {
16 current := len(handlers)
17 RegisterExitHandler(func() {})
18 if len(handlers) != current+1 {
19 t.Fatalf("expected %d handlers, got %d", current+1, len(handlers))
20 }
21 }
22
23 func TestHandler(t *testing.T) {
24 testprog := testprogleader
25 testprog = append(testprog, getPackage()...)
26 testprog = append(testprog, testprogtrailer...)
27 tempDir, err := ioutil.TempDir("", "test_handler")
28 if err != nil {
29 log.Fatalf("can't create temp dir. %q", err)
30 }
31 defer os.RemoveAll(tempDir)
32
33 gofile := filepath.Join(tempDir, "gofile.go")
34 if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
35 t.Fatalf("can't create go file. %q", err)
36 }
37
38 outfile := filepath.Join(tempDir, "outfile.out")
39 arg := time.Now().UTC().String()
40 err = exec.Command("go", "run", gofile, outfile, arg).Run()
41 if err == nil {
42 t.Fatalf("completed normally, should have failed")
43 }
44
45 data, err := ioutil.ReadFile(outfile)
46 if err != nil {
47 t.Fatalf("can't read output file %s. %q", outfile, err)
48 }
49
50 if string(data) != arg {
51 t.Fatalf("bad data. Expected %q, got %q", data, arg)
52 }
53 }
54
55
56
57 func getPackage() []byte {
58 pc, _, _, _ := runtime.Caller(0)
59 fullFuncName := runtime.FuncForPC(pc).Name()
60 idx := strings.LastIndex(fullFuncName, ".")
61 return []byte(fullFuncName[:idx])
62 }
63
64 var testprogleader = []byte(`
65 // Test program for atexit, gets output file and data as arguments and writes
66 // data to output file in atexit handler.
67 package main
68
69 import (
70 "`)
71 var testprogtrailer = []byte(
72 `"
73 "flag"
74 "fmt"
75 "io/ioutil"
76 )
77
78 var outfile = ""
79 var data = ""
80
81 func handler() {
82 ioutil.WriteFile(outfile, []byte(data), 0666)
83 }
84
85 func badHandler() {
86 n := 0
87 fmt.Println(1/n)
88 }
89
90 func main() {
91 flag.Parse()
92 outfile = flag.Arg(0)
93 data = flag.Arg(1)
94
95 logrus.RegisterExitHandler(handler)
96 logrus.RegisterExitHandler(badHandler)
97 logrus.Fatal("Bye bye")
98 }
99 `)
100
View as plain text