logger_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2014 Jakob Borg. All rights reserved. Use of this source code
  2. // is governed by an MIT-style license that can be found in the LICENSE file.
  3. package logger
  4. import (
  5. "strings"
  6. "testing"
  7. )
  8. func TestAPI(t *testing.T) {
  9. l := New()
  10. l.SetFlags(0)
  11. l.SetPrefix("testing")
  12. debug := 0
  13. l.AddHandler(LevelDebug, checkFunc(t, LevelDebug, "test 0", &debug))
  14. info := 0
  15. l.AddHandler(LevelInfo, checkFunc(t, LevelInfo, "test 1", &info))
  16. warn := 0
  17. l.AddHandler(LevelWarn, checkFunc(t, LevelWarn, "test 2", &warn))
  18. ok := 0
  19. l.AddHandler(LevelOK, checkFunc(t, LevelOK, "test 3", &ok))
  20. l.Debugf("test %d", 0)
  21. l.Debugln("test", 0)
  22. l.Infof("test %d", 1)
  23. l.Infoln("test", 1)
  24. l.Warnf("test %d", 2)
  25. l.Warnln("test", 2)
  26. l.Okf("test %d", 3)
  27. l.Okln("test", 3)
  28. if debug != 2 {
  29. t.Errorf("Debug handler called %d != 2 times", debug)
  30. }
  31. if info != 2 {
  32. t.Errorf("Info handler called %d != 2 times", info)
  33. }
  34. if warn != 2 {
  35. t.Errorf("Warn handler called %d != 2 times", warn)
  36. }
  37. if ok != 2 {
  38. t.Errorf("Ok handler called %d != 2 times", ok)
  39. }
  40. }
  41. func checkFunc(t *testing.T, expectl LogLevel, expectmsg string, counter *int) func(LogLevel, string) {
  42. return func(l LogLevel, msg string) {
  43. *counter++
  44. if l != expectl {
  45. t.Errorf("Incorrect message level %d != %d", l, expectl)
  46. }
  47. if !strings.HasSuffix(msg, expectmsg) {
  48. t.Errorf("%q does not end with %q", msg, expectmsg)
  49. }
  50. }
  51. }
  52. func TestFacilityDebugging(t *testing.T) {
  53. l := New()
  54. l.SetFlags(0)
  55. msgs := 0
  56. l.AddHandler(LevelDebug, func(l LogLevel, msg string) {
  57. msgs++
  58. if strings.Contains(msg, "f1") {
  59. t.Fatal("Should not get message for facility f1")
  60. }
  61. })
  62. l.SetDebug("f0", true)
  63. l.SetDebug("f1", false)
  64. f0 := l.NewFacility("f0")
  65. f1 := l.NewFacility("f1")
  66. f0.Debugln("Debug line from f0")
  67. f1.Debugln("Debug line from f1")
  68. if msgs != 1 {
  69. t.Fatalf("Incorrent number of messages, %d != 1", msgs)
  70. }
  71. }