logger_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package logger_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "net/http/httptest"
  8. "os"
  9. "strings"
  10. "testing"
  11. . "github.com/onsi/ginkgo"
  12. . "github.com/onsi/gomega"
  13. "github.com/vladimirok5959/golang-utils/utils/http/logger"
  14. )
  15. var _ = Describe("logger", func() {
  16. Context("LogInternalError", func() {
  17. original := logger.ErrorLogFile
  18. logger.ErrorLogFile = "/tmp/test-err-out.log"
  19. f, err := os.OpenFile(logger.ErrorLogFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  20. Expect(err).To(Succeed())
  21. _, err = fmt.Fprint(f, "")
  22. Expect(err).To(Succeed())
  23. Expect(f.Close()).To(Succeed())
  24. logger.LogInternalError(fmt.Errorf("MyError 1"))
  25. file, err := os.ReadFile(logger.ErrorLogFile)
  26. Expect(err).To(Succeed())
  27. content := string(file)
  28. Expect(strings.HasSuffix(content, "MyError 1\n")).To(Equal(true))
  29. logger.LogInternalError(fmt.Errorf("MyError 2"))
  30. file, err = os.ReadFile(logger.ErrorLogFile)
  31. Expect(err).To(Succeed())
  32. content = string(file)
  33. Expect(strings.HasSuffix(content, "MyError 2\n")).To(Equal(true))
  34. // Restore original value
  35. logger.ErrorLogFile = original
  36. })
  37. Context("LogRequests", func() {
  38. var srv *httptest.Server
  39. var client *http.Client
  40. var getTestHandler = func() http.HandlerFunc {
  41. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  42. if _, err := w.Write([]byte("Index")); err != nil {
  43. fmt.Printf("%s\n", err.Error())
  44. }
  45. })
  46. }
  47. BeforeEach(func() {
  48. srv = httptest.NewServer(logger.LogRequests(getTestHandler()))
  49. client = srv.Client()
  50. })
  51. AfterEach(func() {
  52. srv.Close()
  53. })
  54. It("log http requests", func() {
  55. buf := new(bytes.Buffer)
  56. log.SetOutput(buf)
  57. resp, err := client.Get(srv.URL + "/")
  58. Expect(err).To(Succeed())
  59. defer resp.Body.Close()
  60. Expect(resp.StatusCode).To(Equal(http.StatusOK))
  61. Expect(buf.String()).To(ContainSubstring(`"GET /" 200`))
  62. Expect(buf.String()).To(ContainSubstring(`Go-http-client`))
  63. })
  64. })
  65. })
  66. func TestSuite(t *testing.T) {
  67. RegisterFailHandler(Fail)
  68. RunSpecs(t, "logger")
  69. }