utils_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package utils
  2. import (
  3. "net/http/httptest"
  4. "os"
  5. "testing"
  6. "time"
  7. )
  8. func TestSendTextResponse(t *testing.T) {
  9. w := httptest.NewRecorder()
  10. SendTextResponse(w, "Hello, World!")
  11. if w.Body.String() != "Hello, World!" {
  12. t.Errorf("Expected: 'Hello, World!', Got: '%s'", w.Body.String())
  13. }
  14. }
  15. func TestSendJSONResponse(t *testing.T) {
  16. w := httptest.NewRecorder()
  17. SendJSONResponse(w, `{"key": "value"}`)
  18. expectedBody := `{"key": "value"}`
  19. if w.Body.String() != expectedBody {
  20. t.Errorf("Expected: '%s', Got: '%s'", expectedBody, w.Body.String())
  21. }
  22. if w.Header().Get("Content-Type") != "application/json" {
  23. t.Error("Content-Type header should be set to 'application/json'")
  24. }
  25. }
  26. func TestSendErrorResponse(t *testing.T) {
  27. w := httptest.NewRecorder()
  28. SendErrorResponse(w, "Something went wrong")
  29. expectedBody := `{"error":"Something went wrong"}`
  30. if w.Body.String() != expectedBody {
  31. t.Errorf("Expected: '%s', Got: '%s'", expectedBody, w.Body.String())
  32. }
  33. if w.Header().Get("Content-Type") != "application/json" {
  34. t.Error("Content-Type header should be set to 'application/json'")
  35. }
  36. }
  37. func TestSendOK(t *testing.T) {
  38. w := httptest.NewRecorder()
  39. SendOK(w)
  40. expectedBody := `"OK"`
  41. if w.Body.String() != expectedBody {
  42. t.Errorf("Expected: '%s', Got: '%s'", expectedBody, w.Body.String())
  43. }
  44. if w.Header().Get("Content-Type") != "application/json" {
  45. t.Error("Content-Type header should be set to 'application/json'")
  46. }
  47. }
  48. func TestTimeToString(t *testing.T) {
  49. testTime := time.Date(2022, 2, 3, 12, 30, 0, 0, time.UTC)
  50. result := TimeToString(testTime)
  51. expectedResult := "2022-02-03 12:30:00"
  52. if result != expectedResult {
  53. t.Errorf("Expected: '%s', Got: '%s'", expectedResult, result)
  54. }
  55. }
  56. func TestFileExists(t *testing.T) {
  57. // Create a temporary file for testing
  58. tempFile, err := os.CreateTemp("", "testfile.txt")
  59. tempFile.Close()
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. defer os.Remove(tempFile.Name())
  64. t.Log(tempFile.Name())
  65. // Test case 1: Existing file
  66. exists := FileExists(tempFile.Name())
  67. if !exists {
  68. t.Errorf("Test case 1 failed. Expected: true, Got: false")
  69. }
  70. // Test case 2: Non-existing file
  71. err = os.Remove(tempFile.Name())
  72. if err != nil {
  73. t.Errorf("OS Remove failed %v", err.Error())
  74. }
  75. exists = FileExists(tempFile.Name())
  76. if exists {
  77. t.Errorf("Test case 2 failed. Expected: false, Got: true")
  78. }
  79. }