Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cds-74] Test Refactoring and Automate release lifecycle #15

Merged
merged 9 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -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 ./...
22 changes: 9 additions & 13 deletions bulk_test.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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 {
Expand Down
15 changes: 0 additions & 15 deletions constants_test.go

This file was deleted.

2 changes: 1 addition & 1 deletion debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 12 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
module github.com/coralogix/go-coralogix-sdk

go 1.14
go 1.19

require github.com/sirupsen/logrus v1.6.0
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
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
144 changes: 100 additions & 44 deletions hook_test.go
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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()))
})
}
}
6 changes: 5 additions & 1 deletion http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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,
Expand All @@ -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!")
}
}
Expand Down
Loading
Loading