logger_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Copyright 2017 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package logger
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "os/exec"
  22. "path/filepath"
  23. "reflect"
  24. "sort"
  25. "syscall"
  26. "testing"
  27. )
  28. func TestCreateFileWithRotation(t *testing.T) {
  29. dir, err := ioutil.TempDir("", "test-rotation")
  30. if err != nil {
  31. t.Fatalf("Failed to get TempDir: %v", err)
  32. }
  33. defer os.RemoveAll(dir)
  34. file := filepath.Join(dir, "build.log")
  35. writeFile := func(name string, data string) {
  36. f, err := CreateFileWithRotation(name, 3)
  37. if err != nil {
  38. t.Fatalf("Failed to create file: %v", err)
  39. }
  40. if n, err := io.WriteString(f, data); err == nil && n < len(data) {
  41. t.Fatalf("Short write")
  42. } else if err != nil {
  43. t.Fatalf("Failed to write: %v", err)
  44. }
  45. if err := f.Close(); err != nil {
  46. t.Fatalf("Failed to close: %v", err)
  47. }
  48. }
  49. writeFile(file, "a")
  50. writeFile(file, "b")
  51. writeFile(file, "c")
  52. writeFile(file, "d")
  53. writeFile(file, "e")
  54. d, err := os.Open(dir)
  55. if err != nil {
  56. t.Fatalf("Failed to open dir: %v", err)
  57. }
  58. names, err := d.Readdirnames(0)
  59. if err != nil {
  60. t.Fatalf("Failed to read dir: %v", err)
  61. }
  62. sort.Strings(names)
  63. expected := []string{".lock_build.log", "build.1.log", "build.2.log", "build.3.log", "build.log"}
  64. if !reflect.DeepEqual(names, expected) {
  65. t.Errorf("File list does not match.")
  66. t.Errorf(" got: %v", names)
  67. t.Errorf("expected: %v", expected)
  68. t.FailNow()
  69. }
  70. expectFileContents := func(name, expected string) {
  71. data, err := ioutil.ReadFile(filepath.Join(dir, name))
  72. if err != nil {
  73. t.Errorf("Error reading file: %v", err)
  74. return
  75. }
  76. str := string(data)
  77. if str != expected {
  78. t.Errorf("Contents of %v does not match.", name)
  79. t.Errorf(" got: %v", data)
  80. t.Errorf("expected: %v", expected)
  81. }
  82. }
  83. expectFileContents("build.log", "e")
  84. expectFileContents("build.1.log", "d")
  85. expectFileContents("build.2.log", "c")
  86. expectFileContents("build.3.log", "b")
  87. }
  88. func TestPanic(t *testing.T) {
  89. if os.Getenv("ACTUALLY_PANIC") == "1" {
  90. panicValue := "foo"
  91. log := New(&bytes.Buffer{})
  92. defer func() {
  93. p := recover()
  94. if p == panicValue {
  95. os.Exit(42)
  96. } else {
  97. fmt.Fprintf(os.Stderr, "Expected %q, got %v\n", panicValue, p)
  98. os.Exit(3)
  99. }
  100. }()
  101. defer log.Cleanup()
  102. log.Panic(panicValue)
  103. os.Exit(2)
  104. return
  105. }
  106. // Run this in an external process so that we don't pollute stderr
  107. cmd := exec.Command(os.Args[0], "-test.run=TestPanic")
  108. cmd.Env = append(os.Environ(), "ACTUALLY_PANIC=1")
  109. err := cmd.Run()
  110. if e, ok := err.(*exec.ExitError); ok && e.Sys().(syscall.WaitStatus).ExitStatus() == 42 {
  111. return
  112. }
  113. t.Errorf("Expected process to exit with status 42, got %v", err)
  114. }
  115. func TestFatal(t *testing.T) {
  116. if os.Getenv("ACTUALLY_FATAL") == "1" {
  117. log := New(&bytes.Buffer{})
  118. defer func() {
  119. // Shouldn't get here
  120. os.Exit(3)
  121. }()
  122. defer log.Cleanup()
  123. log.Fatal("Test")
  124. os.Exit(0)
  125. return
  126. }
  127. cmd := exec.Command(os.Args[0], "-test.run=TestFatal")
  128. cmd.Env = append(os.Environ(), "ACTUALLY_FATAL=1")
  129. err := cmd.Run()
  130. if e, ok := err.(*exec.ExitError); ok && e.Sys().(syscall.WaitStatus).ExitStatus() == 1 {
  131. return
  132. }
  133. t.Errorf("Expected process to exit with status 1, got %v", err)
  134. }
  135. func TestNonFatal(t *testing.T) {
  136. if os.Getenv("ACTUAL_TEST") == "1" {
  137. log := New(&bytes.Buffer{})
  138. defer log.Cleanup()
  139. log.Println("Test")
  140. return
  141. }
  142. cmd := exec.Command(os.Args[0], "-test.run=TestNonFatal")
  143. cmd.Env = append(os.Environ(), "ACTUAL_TEST=1")
  144. err := cmd.Run()
  145. if e, ok := err.(*exec.ExitError); ok || (ok && !e.Success()) {
  146. t.Errorf("Expected process to exit cleanly, got %v", err)
  147. }
  148. }
  149. func TestRecoverFatal(t *testing.T) {
  150. log := New(&bytes.Buffer{})
  151. defer func() {
  152. if p := recover(); p != nil {
  153. t.Errorf("Unexpected panic: %#v", p)
  154. }
  155. }()
  156. defer Recover(func(err error) {
  157. if err.Error() != "Test" {
  158. t.Errorf("Expected %q, but got %q", "Test", err.Error())
  159. }
  160. })
  161. log.Fatal("Test")
  162. t.Errorf("Should not get here")
  163. }
  164. func TestRecoverNonFatal(t *testing.T) {
  165. log := New(&bytes.Buffer{})
  166. defer func() {
  167. if p := recover(); p == nil {
  168. t.Errorf("Panic not thrown")
  169. } else if p != "Test" {
  170. t.Errorf("Expected %q, but got %#v", "Test", p)
  171. }
  172. }()
  173. defer Recover(func(err error) {
  174. t.Errorf("Recover function should not be called")
  175. })
  176. log.Panic("Test")
  177. t.Errorf("Should not get here")
  178. }
  179. func TestRuntimePanic(t *testing.T) {
  180. defer func() {
  181. if p := recover(); p == nil {
  182. t.Errorf("Panic not thrown")
  183. }
  184. }()
  185. defer Recover(func(err error) {
  186. t.Errorf("Recover function should not be called")
  187. })
  188. var i *int
  189. *i = 0
  190. t.Errorf("Should not get here")
  191. }