You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.6 KiB

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