github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/utils/accesslogutils_test.go (about) 1 package utils 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 "testing" 8 "time" 9 10 "github.com/siglens/siglens/pkg/common/dtypeutils" 11 ) 12 13 func TestAddAccessLogEntry(t *testing.T) { 14 // Create a temporary test access.log file 15 tempLogFile, err := os.CreateTemp("", "test_access.log") 16 if err != nil { 17 t.Fatal(err) 18 } 19 defer os.Remove(tempLogFile.Name()) 20 21 // Example data 22 data := dtypeutils.AccessLogData{ 23 TimeStamp: time.Now().Format(time.RFC3339), 24 UserName: "test_user", 25 URI: "/example", 26 RequestBody: "test_body", 27 StatusCode: 200, 28 Duration: int64(time.Second * 2), 29 } 30 31 // Call the function with the temporary logFile 32 allowWebsocket := false 33 fileName := tempLogFile.Name() 34 AddAccessLogEntry(data, allowWebsocket, fileName) 35 36 // Read the content of the temporary file 37 content, err := os.ReadFile(fileName) 38 if err != nil { 39 t.Fatal(err) 40 } 41 42 // Validate the content of the file 43 expectedLogEntry := fmt.Sprintf("%s %s %s %s %d %d\n", 44 data.TimeStamp, 45 data.UserName, 46 data.URI, 47 data.RequestBody, 48 data.StatusCode, 49 int(data.Duration)) 50 51 if !strings.Contains(string(content), expectedLogEntry) { 52 t.Errorf("Expected log entry not found in the file. Expected:\n%s\nGot:\n%s", expectedLogEntry, string(content)) 53 } 54 } 55 56 func Test_AddLogEntryValidations(t *testing.T) { 57 cases := []struct { 58 input dtypeutils.AccessLogData 59 }{ 60 { // case#1 61 dtypeutils.AccessLogData{ 62 TimeStamp: "", 63 UserName: "", 64 URI: "http:///", 65 RequestBody: "{\n \"indexName\":\"traces\"\n}", 66 StatusCode: 0, 67 Duration: 0, 68 }, 69 }, 70 { //case 2 71 dtypeutils.AccessLogData{ 72 StatusCode: 101, 73 }, 74 }, 75 } 76 77 for _, test := range cases { 78 // Create a temporary test access.log file 79 tempLogFile, err := os.CreateTemp("", "test_access.log") 80 if err != nil { 81 t.Fatal(err) 82 } 83 defer os.Remove(tempLogFile.Name()) 84 85 // Call the function with the temporary logFile 86 allowWebsocket := false 87 fileName := tempLogFile.Name() 88 AddAccessLogEntry(test.input, allowWebsocket, fileName) 89 90 // Read the content of the temporary file 91 content, err := os.ReadFile(fileName) 92 if err != nil { 93 t.Fatal(err) 94 } 95 96 if len(content) != 0 { 97 t.Errorf("Expected log entry not found in the file. Expected:\n%s\nGot:\n%s", "", string(content)) 98 } 99 100 } 101 102 }