From 3eafcb1801b769e4c44fa5697d64b46348b090a4 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Thu, 10 Aug 2023 15:07:40 +0200 Subject: [PATCH 1/9] remove const testing, no need to validate constants --- constants_test.go | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 constants_test.go diff --git a/constants_test.go b/constants_test.go deleted file mode 100644 index dc5457f..0000000 --- a/constants_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package coralogix - -import "testing" - -func TestNormalSendSpeedInterval(t *testing.T) { - if NormalSendSpeedInterval <= 0 { - t.Error("Bulk send interval in normal mode should be greater than 0!") - } -} - -func TestNormalFastSendSpeedInterval(t *testing.T) { - if FastSendSpeedInterval <= 0 { - t.Error("Bulk send interval in fast mode should be greater than 0!") - } -} From e1e182c10976bb8e1499f0ac6908c3a51608e838 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Fri, 11 Aug 2023 18:58:38 +0200 Subject: [PATCH 2/9] added testify to depts --- go.mod | 5 ++++- go.sum | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index c381988..a2e888b 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,7 @@ module github.com/coralogix/go-coralogix-sdk go 1.14 -require github.com/sirupsen/logrus v1.6.0 +require ( + github.com/sirupsen/logrus v1.6.0 + github.com/stretchr/testify v1.2.2 +) diff --git a/go.sum b/go.sum index b078084..f42da32 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,12 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= From bef94eaf6c1c2e86b1a8c804aba6b2674899635e Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Fri, 11 Aug 2023 18:58:54 +0200 Subject: [PATCH 3/9] updated tests --- logger_test.go | 264 ++++++++++++++++++++++++++----------------------- 1 file changed, 141 insertions(+), 123 deletions(-) diff --git a/logger_test.go b/logger_test.go index e0f2a85..1bb5eb5 100644 --- a/logger_test.go +++ b/logger_test.go @@ -1,23 +1,62 @@ package coralogix import ( + "encoding/json" + "log" + "net/http" + "net/http/httptest" + "os" "reflect" + "strings" "testing" + + "github.com/stretchr/testify/assert" +) + +const ( + testPrivateKey = "7569303a-6269-4d2c-bf14-1aec9b1786a4" ) +// testRequestChan = a channel used to pass requests +// that have been sent to the mockHTTPServer +var testRequestChan chan *Bulk + +// mockHTTPServer - stores all requests received in a map +// for validation +func mockHTTPServer(w http.ResponseWriter, r *http.Request) { + var bulk Bulk + if err := json.NewDecoder(r.Body).Decode(&bulk); err != nil { + log.Fatalf("unable to unmarshal test message: %s", err) + } + + testRequestChan <- &bulk + defer r.Body.Close() + sc := http.StatusOK + w.WriteHeader(sc) +} + +func TestMain(m *testing.M) { + server := httptest.NewServer(http.HandlerFunc(mockHTTPServer)) + testRequestChan = make(chan *Bulk, 1) + LogURL = server.URL + code := m.Run() + server.Close() + os.Exit(code) +} + func TestNewLogger(t *testing.T) { NewLoggerTestInstance := NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", ) defer NewLoggerTestInstance.Destroy() - if reflect.TypeOf(NewLoggerTestInstance) != reflect.TypeOf(&CoralogixLogger{}) { - t.Error("CoralogixLogger creation failed!") - } + assert.Equal(t, + reflect.TypeOf(NewLoggerTestInstance), + reflect.TypeOf(&CoralogixLogger{})) } func TestNewLoggerWithoutPrivateKey(t *testing.T) { @@ -27,39 +66,33 @@ func TestNewLoggerWithoutPrivateKey(t *testing.T) { "test", ) defer NewLoggerTestInstance.Destroy() - if NewLoggerTestInstance.LoggerManager.PrivateKey != FailedPrivateKey { - t.Error("Invalid default value for incorrect private key!") - } + assert.Equal(t, FailedPrivateKey, NewLoggerTestInstance.LoggerManager.PrivateKey) } func TestNewLoggerWithoutApplicationName(t *testing.T) { NewLoggerTestInstance := NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "", "test", ) defer NewLoggerTestInstance.Destroy() - if NewLoggerTestInstance.LoggerManager.ApplicationName != NoAppName { - t.Error("Invalid default value for empty application name!") - } + assert.Equal(t, NoAppName, NewLoggerTestInstance.LoggerManager.ApplicationName) } func TestNewLoggerWithoutSubsystemName(t *testing.T) { NewLoggerTestInstance := NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "", ) defer NewLoggerTestInstance.Destroy() - if NewLoggerTestInstance.LoggerManager.SubsystemName != NoSubSystem { - t.Error("Invalid default value for empty subsystem name!") - } + assert.Equal(t, NoSubSystem, NewLoggerTestInstance.LoggerManager.SubsystemName) } func TestNewLoggerWithCategory(t *testing.T) { @@ -67,39 +100,35 @@ func TestNewLoggerWithCategory(t *testing.T) { NewLoggerTestInstance := NewCoralogixLoggerWithCategory( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", TestCategory, ) defer NewLoggerTestInstance.Destroy() - if NewLoggerTestInstance.Category != TestCategory { - t.Error("Invalid logger category!") - } + assert.Equal(t, TestCategory, NewLoggerTestInstance.Category) } func TestNewLoggerWithEmptyCategory(t *testing.T) { NewLoggerTestInstance := NewCoralogixLoggerWithCategory( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", "", ) defer NewLoggerTestInstance.Destroy() - if NewLoggerTestInstance.Category != LogCategory { - t.Error("Category checking is not working!") - } + assert.Equal(t, LogCategory, NewLoggerTestInstance.Category) } func TestLogger_Destroy(t *testing.T) { NewLoggerTestInstance := NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", @@ -108,16 +137,16 @@ func TestLogger_Destroy(t *testing.T) { } func TestLogger_Log(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( + clogger := NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.Log( + defer clogger.Destroy() + clogger.Log( Level.DEBUG, "Test message", LogCategory, @@ -125,115 +154,104 @@ func TestLogger_Log(t *testing.T) { "", "", ) - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 { - t.Error("New log message add failed!") - } -} -func TestLogger_Debug(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Debug("Test debug message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.DEBUG { - t.Error("Debug log message add failed!") - } -} + clogger.LoggerManager.Flush() + bulk := <-testRequestChan -func TestLogger_Verbose(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Verbose("Test verbose message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.VERBOSE { - t.Error("Verbose log message add failed!") + var msg bool + for _, entry := range bulk.LogEntries { + msg = entry.Text == "Test message" } + assert.True(t, msg, "no matching message found") } -func TestLogger_Info(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( +func TestLoggerSeverity(t *testing.T) { + var cxlogger = NewCoralogixLogger( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Info("Test info message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.INFO { - t.Error("Info log message add failed!") - } -} -func TestLogger_Warning(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Warning("Test warning message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.WARNING { - t.Error("Warning log message add failed!") - } -} + defer cxlogger.Destroy() -func TestLogger_Error(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Error("Test error message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.ERROR { - t.Error("Error log message add failed!") + testcases := []struct { + name string + clogger *CoralogixLogger + match string + logfn func(*CoralogixLogger) + severity uint + }{ + { + name: "debug", + match: "debug", + logfn: func(logger *CoralogixLogger) { + logger.Debug("Test message DEBUG") + }, + severity: Level.DEBUG, + }, + { + name: "verbose", + match: "verbose", + // clogger: newtestCoralogixLoggerFn(), + logfn: func(logger *CoralogixLogger) { + logger.Verbose("Test message VERBOSE") + }, + severity: Level.VERBOSE, + }, + { + name: "info", + // clogger: newtestCoralogixLoggerFn(), + match: "info", + logfn: func(logger *CoralogixLogger) { + logger.Info("Test message INFO") + }, + severity: Level.INFO, + }, + { + name: "warning", + match: "warning", + logfn: func(logger *CoralogixLogger) { + logger.Warning("Test message WARNING") + }, + severity: Level.WARNING, + }, + { + name: "error", + match: "error", + logfn: func(logger *CoralogixLogger) { + logger.Error("Test message ERROR") + }, + severity: Level.ERROR, + }, + { + name: "critical", + match: "critical", + // clogger: newtestCoralogixLoggerFn(), + logfn: func(logger *CoralogixLogger) { + logger.Critical("Test message CRITICAL") + }, + severity: Level.CRITICAL, + }, } -} -func TestLogger_Critical(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer NewLoggerTestInstance.Destroy() - NewLoggerTestInstance.LoggerManager.Stop() - NewLoggerTestInstance.Critical("Test critical message") - if NewLoggerTestInstance.LoggerManager.LogsBuffer.Len() < 1 || - NewLoggerTestInstance.LoggerManager.LogsBuffer.Slice(1)[0].Severity != Level.CRITICAL { - t.Error("Critical log message add failed!") + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + tc.logfn(cxlogger) + cxlogger.LoggerManager.Flush() + bulkReq := <-testRequestChan + + var msg = true + for _, entry := range bulkReq.LogEntries { + // fmt.Println(i, entry.Text) + if msg = strings.Contains(strings.ToLower(entry.Text), tc.name); msg { + assert.Equal(t, tc.severity, entry.Severity) + } + } + + assert.True(t, msg, "no matching message found") + }) } } From 5029c1bef8e5b441f1fd576739d792669d393479 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Fri, 11 Aug 2023 18:59:18 +0200 Subject: [PATCH 4/9] removed unnecessary comparison --- debug.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debug.go b/debug.go index f45b347..70b209e 100644 --- a/debug.go +++ b/debug.go @@ -11,7 +11,7 @@ var DebugLogger = log.New(ioutil.Discard, "CORALOGIX: ", log.Ldate|log.Ltime) // SetDebug enable/disable internal logger func SetDebug(Status bool) { - if Status == true { + if Status { DebugLogger.SetOutput(os.Stdout) } else { DebugLogger.SetOutput(ioutil.Discard) From 5e4fc1e3dbb7ce1a2f4362c000e5f80437e68d64 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Fri, 11 Aug 2023 19:15:20 +0200 Subject: [PATCH 5/9] adjusted print statemnt --- manager.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manager.go b/manager.go index 95bf0cf..74dd095 100644 --- a/manager.go +++ b/manager.go @@ -150,7 +150,7 @@ func (manager *LoggerManager) Run() { } } - DebugLogger.Printf("Next buffer check is scheduled in %.1f seconds\n", NextSendInterval) + DebugLogger.Printf("Next buffer check is scheduled in %.1f seconds\n", NextSendInterval.Seconds()) time.Sleep(NextSendInterval) } } From 6444ff6c5070bef165ad463fbd6241324faeb24c Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Fri, 11 Aug 2023 19:18:40 +0200 Subject: [PATCH 6/9] add channel close to testResponseChan --- logger_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/logger_test.go b/logger_test.go index 1bb5eb5..be1d910 100644 --- a/logger_test.go +++ b/logger_test.go @@ -41,6 +41,7 @@ func TestMain(m *testing.M) { LogURL = server.URL code := m.Run() server.Close() + close(testRequestChan) os.Exit(code) } From 19cc1536ef3cac8307a9ddc47e4e26aec4364b39 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Tue, 15 Aug 2023 01:05:12 +0100 Subject: [PATCH 7/9] upadted and refactored tests --- bulk_test.go | 22 +++----- hook_test.go | 144 ++++++++++++++++++++++++++++++++--------------- http_test.go | 6 +- logger_test.go | 115 ++++++++++++++++--------------------- severity_test.go | 42 +++++--------- 5 files changed, 177 insertions(+), 152 deletions(-) diff --git a/bulk_test.go b/bulk_test.go index 237c4e6..f298659 100644 --- a/bulk_test.go +++ b/bulk_test.go @@ -1,15 +1,14 @@ package coralogix import ( - "reflect" "testing" "time" + + "github.com/stretchr/testify/assert" ) func TestNewBulk(t *testing.T) { - if reflect.TypeOf(CreateBulk()) != reflect.TypeOf(&Bulk{}) { - t.Error("Bulk creation failed!") - } + assert.IsType(t, &Bulk{}, CreateBulk(), "Bulk creation failed!") } func TestBulk_AddRecord(t *testing.T) { @@ -24,24 +23,21 @@ func TestBulk_AddRecord(t *testing.T) { "", 0, }) - if len(RecordsBulk.LogEntries) < 1 { - t.Error("Adding new record to bulk failed!") - } + + assert.True(t, len(RecordsBulk.LogEntries) >= 1, "Adding new record to bulk failed!") } func TestBulk_ToJSON(t *testing.T) { RecordsBulkJSON := CreateBulk().ToJSON() - if RecordsBulkJSON == nil || reflect.TypeOf(RecordsBulkJSON) != reflect.TypeOf([]byte{}) { - t.Error("Error while converting bulk to JSON!") - } + assert.NotNil(t, RecordsBulkJSON) + assert.IsType(t, []byte(""), RecordsBulkJSON, "Error while converting bulk to JSON!") + } func TestBulk_ToJSONFail(t *testing.T) { RecordsBulk := CreateBulk() RecordsBulk.AddRecord(*InvalidLogMessage()) - if RecordsBulk.ToJSON() != nil { - t.Error("Error while catching JSON converting error!") - } + assert.Nil(t, RecordsBulk.ToJSON(), "Error while catching JSON converting error!") } func CreateBulk() *Bulk { diff --git a/hook_test.go b/hook_test.go index 8719a31..6ed2eae 100644 --- a/hook_test.go +++ b/hook_test.go @@ -1,15 +1,20 @@ package coralogix import ( - "github.com/sirupsen/logrus" + "fmt" + "strings" "testing" + "time" + + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" ) func TestHook_Send(t *testing.T) { CoralogixHook := NewCoralogixHook( GetEnv( "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", + testPrivateKey, ), "sdk-go", "test", @@ -18,54 +23,105 @@ func TestHook_Send(t *testing.T) { defer CoralogixHook.Close() log := logrus.New() - log.SetLevel(logrus.TraceLevel) + log.SetLevel(logrus.TraceLevel) log.AddHook(CoralogixHook) + fields := logrus.Fields{ + "Category": "MyCategory", + "ThreadId": "MyThreadId", + "extra": "additional", + } - log.WithFields(logrus.Fields{ - "Category": "MyCategory", - "ClassName": "MyClassName", - "MethodName": "MyMethodName", - "ThreadId": "MyThreadId", - "extra": "additional", - }).Debug("Test message!") + testcases := []struct { + name string + logfn func(args ...interface{}) + severity uint + }{ + { + name: "test trace", + severity: Level.TRACE, + logfn: func(args ...interface{}) { + log.WithFields(fields).Trace(args...) + }, + }, + { + name: "test debug", + severity: Level.DEBUG, + logfn: func(args ...interface{}) { + log.WithFields(fields).Debug(args...) + }, + }, + { + name: "test error", + severity: Level.ERROR, + logfn: func(args ...interface{}) { + log.WithFields(fields).Error(args...) + }, + }, + { + name: "test info", + severity: Level.ERROR, + logfn: func(args ...interface{}) { + log.WithFields(fields).Error(args...) + }, + }, + { + name: "test warn", + severity: Level.WARNING, + logfn: func(args ...interface{}) { + log.WithFields(fields).Warn(args...) + }, + }, + } - log.Trace("Test trace message!") - log.Debug("Test debug message!") - log.Info("Test info message!") - log.Warn("Test warn message!") - log.Error("Test error message!") - log.Panic("Test panic message!") -} + for _, tc := range testcases { + t.Run(tc.name, func(t *testing.T) { + msg := fmt.Sprintf("%s (%s)", tc.name, t.Name()) + tc.logfn(msg) + time.Sleep(time.Duration(1) * time.Second) + bulk, ok := mockHTTPServerMap[t.Name()] + assert.True(t, ok, "%s key not found in mockHTTPServerMap", t.Name()) -func TestHook_SendWithCaller(t *testing.T) { - CoralogixHook := NewCoralogixHook( - GetEnv( - "PRIVATE_KEY", - "7569303a-6269-4d2c-bf14-1aec9b1786a4", - ), - "sdk-go", - "test", - ) - defer func() { recover() }() - defer CoralogixHook.Close() + var msgExists bool + for _, entry := range bulk.LogEntries { + if msgExists = strings.Contains(entry.Text, tc.name); msgExists { + assert.Equal(t, tc.severity, entry.Severity) + assert.Equal(t, fields["Category"], entry.Category) + assert.Equal(t, fields["ThreadId"], entry.ThreadID, + "expected %v, got %v", fields["MyThreadId"], entry.ThreadID) + assert.True(t, strings.Contains(entry.Text, fields["extra"].(string)), + "entry Text does not contain extra field", entry.Text, fields["extra"]) + break + } + } + assert.True(t, msgExists, "no matching message found", string(bulk.ToJSON())) + }) + } - log := logrus.New() + // test with caller\ log.SetReportCaller(true) - log.SetLevel(logrus.TraceLevel) - - log.AddHook(CoralogixHook) - - log.WithFields(logrus.Fields{ - "Category": "MyCategory", - "ThreadId": "MyThreadId", - "extra": "additional", - }).Debug("Test message!") + for _, tc := range testcases { + tc.name = fmt.Sprintf("%s_withReportCaller", tc.name) + t.Run(tc.name, func(t *testing.T) { + msg := fmt.Sprintf("%s (%s)", tc.name, t.Name()) + tc.logfn(msg) + time.Sleep(time.Duration(1) * time.Second) + bulk, ok := mockHTTPServerMap[t.Name()] + assert.True(t, ok, "%s key not found in mockHTTPServerMap", t.Name()) - log.Trace("Test trace message with caller!") - log.Debug("Test debug message with caller!") - log.Info("Test info message with caller!") - log.Warn("Test warn message with caller!") - log.Error("Test error message with caller!") - log.Panic("Test panic message with caller!") + var msgExists bool + for _, entry := range bulk.LogEntries { + if msgExists = strings.Contains(entry.Text, tc.name); msgExists { + assert.Equal(t, tc.severity, entry.Severity) + assert.Equal(t, fields["Category"], entry.Category) + assert.Equal(t, fields["ThreadId"], entry.ThreadID, + "expected %v, got %v", fields["MyThreadId"], entry.ThreadID) + assert.True(t, strings.Contains(entry.Text, fields["extra"].(string)), + "entry Text does not contain extra field", entry.Text, fields["extra"]) + break + } + } + assert.True(t, msgExists, "no matching message found", string(bulk.ToJSON())) + }) + } } diff --git a/http_test.go b/http_test.go index dc1a335..40b5edd 100644 --- a/http_test.go +++ b/http_test.go @@ -25,6 +25,8 @@ func TestSendRequestSuccess(t *testing.T) { } func TestSendRequestPostFail(t *testing.T) { + // TODO: update SendRequest for better error handling, and redo this test + t.Skip("Skipping test, the SendRequest can and will only return 0, therefore this test is invalid") SetDebug(true) BulkToSend := CreateBulk() BulkToSend.AddRecord(*InvalidLogMessage()) @@ -35,6 +37,8 @@ func TestSendRequestPostFail(t *testing.T) { } func TestSendRequestErrorResponseStatus(t *testing.T) { + // TODO: update SendRequest for better error handling, and redo this test + t.Skip("Skipping test, the SendRequest can and will only return 0, therefore this test is invalid") BulkToSend := CreateBulk() BulkToSend.AddRecord(Log{ 1, @@ -47,7 +51,7 @@ func TestSendRequestErrorResponseStatus(t *testing.T) { 0, }) HTTPStatus := SendRequest(BulkToSend) - if HTTPStatus == 200 { + if HTTPStatus == 0 { t.Error("Logs bulk was successful!") } } diff --git a/logger_test.go b/logger_test.go index be1d910..1402108 100644 --- a/logger_test.go +++ b/logger_test.go @@ -2,11 +2,13 @@ package coralogix import ( "encoding/json" + "fmt" "log" "net/http" "net/http/httptest" "os" "reflect" + "regexp" "strings" "testing" @@ -15,33 +17,63 @@ import ( const ( testPrivateKey = "7569303a-6269-4d2c-bf14-1aec9b1786a4" + startupMessage = "The Application Name sdk-go and Subsystem Name test from the Go SDK, version 1.0.2 has started to send data" ) // testRequestChan = a channel used to pass requests // that have been sent to the mockHTTPServer -var testRequestChan chan *Bulk +var ( + cxlogger *CoralogixLogger + // mockHTTPServerMap - store Bulk requests sent to mock + // endpoint + mockHTTPServerMap map[string]*Bulk + mockKeyRegex = regexp.MustCompile(`\((.*)\)`) +) // mockHTTPServer - stores all requests received in a map // for validation func mockHTTPServer(w http.ResponseWriter, r *http.Request) { var bulk Bulk if err := json.NewDecoder(r.Body).Decode(&bulk); err != nil { - log.Fatalf("unable to unmarshal test message: %s", err) + log.Println("unable to unmarshal test message:", err) + w.WriteHeader(http.StatusBadRequest) + return + } + if len(bulk.LogEntries) == 1 && bulk.LogEntries[0].Text == startupMessage { + w.WriteHeader(http.StatusOK) + return + } + + for _, entry := range bulk.LogEntries { + if matches := mockKeyRegex.FindStringSubmatch(entry.Text); len(matches) == 2 { + k := matches[1] + mockHTTPServerMap[k] = &bulk + } } - testRequestChan <- &bulk defer r.Body.Close() sc := http.StatusOK + w.WriteHeader(sc) } func TestMain(m *testing.M) { + mockHTTPServerMap = make(map[string]*Bulk) server := httptest.NewServer(http.HandlerFunc(mockHTTPServer)) - testRequestChan = make(chan *Bulk, 1) LogURL = server.URL + cxlogger = NewCoralogixLogger( + GetEnv( + "PRIVATE_KEY", + testPrivateKey, + ), + "sdk-go", + "test", + ) + code := m.Run() + + cxlogger.Destroy() server.Close() - close(testRequestChan) os.Exit(code) } @@ -125,59 +157,7 @@ func TestNewLoggerWithEmptyCategory(t *testing.T) { assert.Equal(t, LogCategory, NewLoggerTestInstance.Category) } -func TestLogger_Destroy(t *testing.T) { - NewLoggerTestInstance := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - testPrivateKey, - ), - "sdk-go", - "test", - ) - NewLoggerTestInstance.Destroy() -} - -func TestLogger_Log(t *testing.T) { - clogger := NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - testPrivateKey, - ), - "sdk-go", - "test", - ) - defer clogger.Destroy() - clogger.Log( - Level.DEBUG, - "Test message", - LogCategory, - "", - "", - "", - ) - - clogger.LoggerManager.Flush() - bulk := <-testRequestChan - - var msg bool - for _, entry := range bulk.LogEntries { - msg = entry.Text == "Test message" - } - assert.True(t, msg, "no matching message found") -} - func TestLoggerSeverity(t *testing.T) { - var cxlogger = NewCoralogixLogger( - GetEnv( - "PRIVATE_KEY", - testPrivateKey, - ), - "sdk-go", - "test", - ) - - defer cxlogger.Destroy() - testcases := []struct { name string clogger *CoralogixLogger @@ -189,7 +169,7 @@ func TestLoggerSeverity(t *testing.T) { name: "debug", match: "debug", logfn: func(logger *CoralogixLogger) { - logger.Debug("Test message DEBUG") + logger.Debug(fmt.Sprintf("test message debug (%s/debug)", t.Name())) }, severity: Level.DEBUG, }, @@ -198,7 +178,7 @@ func TestLoggerSeverity(t *testing.T) { match: "verbose", // clogger: newtestCoralogixLoggerFn(), logfn: func(logger *CoralogixLogger) { - logger.Verbose("Test message VERBOSE") + logger.Verbose(fmt.Sprintf("test message verbose (%s/verbose)", t.Name())) }, severity: Level.VERBOSE, }, @@ -207,7 +187,7 @@ func TestLoggerSeverity(t *testing.T) { // clogger: newtestCoralogixLoggerFn(), match: "info", logfn: func(logger *CoralogixLogger) { - logger.Info("Test message INFO") + logger.Info(fmt.Sprintf("test message info (%s/info)", t.Name())) }, severity: Level.INFO, }, @@ -215,7 +195,7 @@ func TestLoggerSeverity(t *testing.T) { name: "warning", match: "warning", logfn: func(logger *CoralogixLogger) { - logger.Warning("Test message WARNING") + logger.Warning(fmt.Sprintf("test message warning (%s/warning)", t.Name())) }, severity: Level.WARNING, }, @@ -223,7 +203,7 @@ func TestLoggerSeverity(t *testing.T) { name: "error", match: "error", logfn: func(logger *CoralogixLogger) { - logger.Error("Test message ERROR") + logger.Error(fmt.Sprintf("test message error (%s/error)", t.Name())) }, severity: Level.ERROR, }, @@ -232,7 +212,7 @@ func TestLoggerSeverity(t *testing.T) { match: "critical", // clogger: newtestCoralogixLoggerFn(), logfn: func(logger *CoralogixLogger) { - logger.Critical("Test message CRITICAL") + logger.Critical(fmt.Sprintf("test message debug (%s/critical)", t.Name())) }, severity: Level.CRITICAL, }, @@ -241,14 +221,17 @@ func TestLoggerSeverity(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { tc.logfn(cxlogger) + // time.Sleep(time.Second * 1) cxlogger.LoggerManager.Flush() - bulkReq := <-testRequestChan + + bulk, ok := mockHTTPServerMap[t.Name()] + assert.True(t, ok, "%s key not found in mockHTTPServerMap", t.Name()) var msg = true - for _, entry := range bulkReq.LogEntries { - // fmt.Println(i, entry.Text) + for _, entry := range bulk.LogEntries { if msg = strings.Contains(strings.ToLower(entry.Text), tc.name); msg { assert.Equal(t, tc.severity, entry.Severity) + break } } diff --git a/severity_test.go b/severity_test.go index 04efd15..ca99973 100644 --- a/severity_test.go +++ b/severity_test.go @@ -1,33 +1,19 @@ package coralogix -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestSeveritiesList(t *testing.T) { - if Level.TRACE != 1 { - t.Error("TRACE level should equals to 1!") - } - if Level.DEBUG != 1 { - t.Error("DEBUG level should equals to 1!") - } - if Level.VERBOSE != 2 { - t.Error("VERBOSE level should equals to 2!") - } - if Level.INFO != 3 { - t.Error("INFO level should equals to 3!") - } - if Level.WARNING != 4 { - t.Error("WARNING level should equals to 4!") - } - if Level.ERROR != 5 { - t.Error("ERROR level should equals to 5!") - } - if Level.CRITICAL != 6 { - t.Error("CRITICAL level should equals to 6!") - } - if Level.FATAL != 6 { - t.Error("FATAL level should equals to 6!") - } - if Level.PANIC != 6 { - t.Error("PANIC level should equals to 6!") - } + assert.Equal(t, uint(1), Level.TRACE, "TRACE level should equals to 1!") + assert.Equal(t, uint(1), Level.DEBUG, "DEBUG level should equals to 1!") + assert.Equal(t, uint(2), Level.VERBOSE, "VERBOSE level should equals to 2!") + assert.Equal(t, uint(3), Level.INFO, "INFO level should equals to 3!") + assert.Equal(t, uint(4), Level.WARNING, "WARNING level should equals to 4!") + assert.Equal(t, uint(5), Level.ERROR, "ERROR level should equals to 5!") + assert.Equal(t, uint(6), Level.CRITICAL, "CRITICAL level should equals to 6!") + assert.Equal(t, uint(6), Level.FATAL, "FATAL level should equals to 6!") + assert.Equal(t, uint(6), Level.PANIC, "PANIC level should equals to 6!") } From df92e979a237a577cad189da45b47564694c2ad1 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Wed, 16 Aug 2023 14:37:17 +0100 Subject: [PATCH 8/9] updated go version 1.19 --- go.mod | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index a2e888b..4f61f85 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,15 @@ module github.com/coralogix/go-coralogix-sdk -go 1.14 +go 1.19 require ( github.com/sirupsen/logrus v1.6.0 github.com/stretchr/testify v1.2.2 ) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/sys v0.0.0-20190422165155-953cdadca894 // indirect +) From 57f0a5f3630d135be56e5d723ad458d8146babb0 Mon Sep 17 00:00:00 2001 From: Shaun Remekie Date: Wed, 16 Aug 2023 14:37:37 +0100 Subject: [PATCH 9/9] updated github workflow --- .github/workflows/release.yaml | 43 ++++++++++++++++++++++++++++++++++ .github/workflows/tests.yaml | 26 ++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 .github/workflows/release.yaml create mode 100644 .github/workflows/tests.yaml diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..0caed2d --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,43 @@ +name: Create Release with SemVer + +on: + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' # e.g., v1.2.3 + workflow_dispatch: + inputs: + version: + description: 'Semantic Version (e.g., v1.2.3)' + required: true + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Determine Version + run: | + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "VERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV + else + echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV + fi + + - name: Validate Semantic Versioning + run: | + if ! [[ $VERSION =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Error: Version does not follow semantic versioning" + exit 1 + fi + + - name: Create GitHub Release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ env.VERSION }} + release_name: Release ${{ env.VERSION }} + draft: false + prerelease: false diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml new file mode 100644 index 0000000..9c17f40 --- /dev/null +++ b/.github/workflows/tests.yaml @@ -0,0 +1,26 @@ +name: Go Tests + +on: + pull_request: + branches: + - master + +jobs: + build: + name: Run Go tests + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: ^1.17 + + - name: Install dependencies + run: go mod download + + - name: Run tests + run: go test ./...