From bda2dc28c8872230e0f452e637e6155b9fffe86d Mon Sep 17 00:00:00 2001 From: microup <46453591+microup@users.noreply.github.com> Date: Sat, 2 Dec 2023 19:58:44 +0300 Subject: [PATCH] feat: improve tests (#48) --- .golangci.yml | 194 ++++++++++++------------- go.mod | 7 + go.sum | 8 + internal/core/archiv.go | 2 +- internal/core/archiv_test.go | 47 +++--- internal/core/converts.go | 8 +- internal/core/converts_test.go | 32 ++-- internal/core/date_time.go | 2 +- internal/core/date_time_test.go | 16 +- internal/core/text.go | 2 +- internal/core/text_test.go | 18 +-- internal/proxy/peer/peer.go | 4 +- internal/proxy/proxy_test.go | 108 +++++++------- internal/proxy/response/response.go | 11 +- internal/proxy/rules/blacklist.go | 8 +- internal/proxy/rules/blacklist_test.go | 36 +++-- internal/types/consts.go | 10 +- internal/types/types_codes_test.go | 26 ++-- internal/vlog/log_data_types.go | 4 +- internal/vlog/log_data_types_test.go | 23 ++- internal/vlog/log_file.go | 1 - internal/vlog/log_files.go | 2 +- internal/vlog/log_test.go | 20 +-- internal/vlog/vlog.go | 10 +- mocks/mock_logger.go | 2 +- mocks/mock_net_conn.go | 6 +- mocks/mock_peer.go | 21 +-- 27 files changed, 308 insertions(+), 320 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7d758b8..bafe811 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,115 +16,115 @@ linters-settings: linters: enable: - - asasalint - - asciicheck - - bidichk - - bodyclose - - containedctx - - contextcheck - - cyclop - - decorder - - depguard - - dogsled - - dupl + - asasalint + - asciicheck + - bidichk + - bodyclose + - containedctx + - contextcheck + - cyclop + - decorder + - dogsled + - dupl - dupword - - durationcheck - - errcheck - - errchkjson - - errname - - errorlint - - execinquery - - exhaustive - - exhaustruct - - exportloopref - - forbidigo - - forcetypeassert - - funlen + - durationcheck + - errcheck + - errchkjson + - errname + - errorlint + - execinquery + - exhaustive + - exhaustruct + - exportloopref + - forbidigo + - forcetypeassert + - funlen - - gochecknoglobals - - gochecknoinits - - gocognit + - gochecknoglobals + - gochecknoinits + - gocognit - - gocognit - - goconst - - gocritic - - gomnd + - gocognit + - goconst + - gocritic + - gomnd - - gomoddirectives - - gomodguard - - goprintffuncname - - gosec - - gosimple - - govet - - grouper - - importas - - ineffassign - - interfacebloat - - ireturn - - lll - - loggercheck - - maintidx - - makezero - - misspell + - gomoddirectives + - gomodguard + - goprintffuncname + - gosec + - gosimple + - govet + - grouper + - importas + - ineffassign + - interfacebloat + - ireturn + - lll + - loggercheck + - maintidx + - makezero + - misspell - nakedret - nestif - - nilerr - - nilnil - - nlreturn - - noctx - - nolintlint - - nonamedreturns - - nosprintfhostport - - paralleltest - - prealloc - - predeclared - - promlinter - - reassign - - revive - - staticcheck - - stylecheck - - tagliatelle - - tenv - - testableexamples - - testpackage - - thelper - - tparallel - - typecheck - - unconvert - - unparam - - unused - - usestdlibvars - - varnamelen - - whitespace - - wrapcheck - - wsl + - nilerr + - nilnil + - nlreturn + - noctx + - nolintlint + - nonamedreturns + - nosprintfhostport + - paralleltest + - prealloc + - predeclared + - promlinter + - reassign + - revive + - staticcheck + - stylecheck + - tagliatelle + - tenv + - testableexamples + - testpackage + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - usestdlibvars + - varnamelen + - whitespace + - wrapcheck + - wsl - - gochecknoglobals - - gochecknoinits - - gocritic - - gocyclo - - godot - - godox - - goerr113 + - gochecknoglobals + - gochecknoinits + - gocritic + - gocyclo + - godot + - godox + - goerr113 - - goconst - - gocyclo - - godot - - godox - - goerr113 + - goconst + - gocyclo + - godot + - godox + - goerr113 - golint - deadcode - - nosnakecase - - varcheck - - scopelint - - maligned + - nosnakecase + - varcheck + - scopelint + - maligned - interfacer - exhaustivestruct unsused: - - ifshort - - gofumpt - - wastedassign + - depguard + - ifshort + - gofumpt + - wastedassign - rowserrcheck - - structcheck - - sqlclosecheck \ No newline at end of file + - structcheck + - sqlclosecheck \ No newline at end of file diff --git a/go.mod b/go.mod index 04db45d..7b8c57d 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,14 @@ require ( gopkg.in/yaml.v2 v2.4.0 ) +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + require ( github.com/microup/vcache v0.0.0-20230809073841-0dd87922568e + github.com/stretchr/testify v1.8.4 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect ) diff --git a/go.sum b/go.sum index a5c90b8..e02a64b 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +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/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= @@ -7,6 +9,10 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/microup/vcache v0.0.0-20230809073841-0dd87922568e h1:K7vMoZfAeVbhsqt+0Fz5yczYwkXEtveyRzbEopvYGOg= github.com/microup/vcache v0.0.0-20230809073841-0dd87922568e/go.mod h1:GeOzwOgxTozs3eOlL2qFy/fm1ro4CmeAXy7nhP+O/yc= +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/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -35,3 +41,5 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/core/archiv.go b/internal/core/archiv.go index cc4e178..162069c 100644 --- a/internal/core/archiv.go +++ b/internal/core/archiv.go @@ -10,7 +10,7 @@ import ( "strings" ) -// ArchiveFile function for archive file. +// ArchiveFile function for archive file. func ArchiveFile(fileName string, extension string) error { file := filepath.Base(fileName) // + ".zip" file = strings.TrimSuffix(file, filepath.Ext(file)) + extension // ".zip" diff --git a/internal/core/archiv_test.go b/internal/core/archiv_test.go index bb11f1e..7f88c18 100644 --- a/internal/core/archiv_test.go +++ b/internal/core/archiv_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" "vbalancer/internal/core" + + "github.com/stretchr/testify/assert" ) // TestArchive this is a test function for `archive()`. @@ -16,7 +18,6 @@ func TestArchiveFile(t *testing.T) { helperArchiveFile(t) } -//nolint:funlen,cyclop func helperArchiveFile(t *testing.T) { t.Helper() @@ -28,58 +29,50 @@ func helperArchiveFile(t *testing.T) { extension := ".zip" testFile, err := os.Create(fileName) - if err != nil { - t.Fatalf("Failed to create test file: %v", err) - } + + assert.Nil(t, err, "failed to create test file") defer os.Remove(fileName) _, err = testFile.Write([]byte("test data")) - if err != nil { - t.Fatalf("Failed to write data to test file: %v", err) - } + + assert.Nil(t, err, "failed to write data to test file") err = testFile.Close() - if err != nil { - t.Fatalf("Failed to close test file: %v", err) - } + + assert.Nil(t, err, "failed to close test file") err = core.ArchiveFile(fileName, extension) - if err != nil { - t.Fatalf("Archiving failed: %v", err) - } + + assert.Nil(t, err, "archiving failed") archivedFile := strings.TrimSuffix(fileName, filepath.Ext(fileName)) + extension if _, err = os.Stat(archivedFile); os.IsNotExist(err) { - t.Fatalf("Archived file does not exist: %v", err) + assert.FailNow(t, "archived file does not exist", err) } + assert.Nil(t, err, "archiving failed") + defer os.Remove(archivedFile) zipFile, err := zip.OpenReader(archivedFile) if err != nil { - t.Fatalf("Failed to open archived file: %v", err) + assert.FailNow(t, "failed to open archived file: %v", err) } defer zipFile.Close() - if len(zipFile.File) != 1 { - t.Fatalf("Unexpected number of files in archived file: %d", len(zipFile.File)) - } + assert.Equal(t, 1, len(zipFile.File), "unexpected number of files in archived file") fileInArchive := zipFile.File[0] zipFileContent, err := fileInArchive.Open() - if err != nil { - t.Fatalf("Failed to open file in archive: %v", err) - } + assert.Nil(t, err, "failed to open file in archive") + defer zipFileContent.Close() data, err := io.ReadAll(zipFileContent) - if err != nil { - t.Fatalf("Failed to read data from file in archive: %v", err) - } - if string(data) != "test data" { - t.Fatalf("Unexpected data in archived file: %s", string(data)) - } + assert.Nil(t, err, "failed to read data from file in archive") + + assert.Equal(t, "test data", string(data), "unexpected data in archived file") } diff --git a/internal/core/converts.go b/internal/core/converts.go index 0a43154..3c0e33b 100644 --- a/internal/core/converts.go +++ b/internal/core/converts.go @@ -7,8 +7,8 @@ import ( ) const ( - place = 2 - prec = -1 + place = 2 + prec = -1 ) // HumanFileSize returns a human-readable file size. @@ -33,8 +33,8 @@ func HumanFileSize(size float64) string { } // Round rounds a float to a given number of decimal places. -func Round(val float64, roundOn float64, places int) float64 { +func Round(val float64, _ float64, places int) float64 { pow := math.Pow(types.PowX, float64(places)) - + return math.Round(val*pow) / pow } diff --git a/internal/core/converts_test.go b/internal/core/converts_test.go index f57071d..0640328 100644 --- a/internal/core/converts_test.go +++ b/internal/core/converts_test.go @@ -1,12 +1,15 @@ package core_test import ( + "fmt" "math" "testing" "vbalancer/internal/core" + + "github.com/stretchr/testify/assert" ) -// TestHumanFileSize tests the HumanFileSize function. +// TestHumanFileSize tests the HumanFileSize function. func TestHumanFileSize(t *testing.T) { t.Parallel() @@ -24,11 +27,10 @@ func TestHumanFileSize(t *testing.T) { {1099511627776, "1 TB"}, } - for _, tc := range testCases { - got := core.HumanFileSize(tc.size) - if got != tc.want { - t.Errorf("HumanFileSize(%f) = %s; want %s", tc.size, got, tc.want) - } + for _, test := range testCases { + got := core.HumanFileSize(test.size) + + assert.Equalf(t, test.want, got, fmt.Sprintf("size %f want %s", test.size, test.want)) } } @@ -42,18 +44,24 @@ func TestRound(t *testing.T) { places int expected float64 }{ - {3.1415, 0.5, 2, 3.14}, + {3.1415, 0.4, 2, 3.14}, {1.2345, 0.5, 3, 1.235}, {2.6666, 0.5, 2, 2.67}, {0.0, 0.5, 2, 0.0}, {-1.234, 0.5, 2, -1.23}, } - for _, tc := range testCases { - actual := core.Round(tc.val, tc.roundOn, tc.places) - if math.Abs(actual-tc.expected) > 0.0001 { - t.Errorf("For val %v, roundOn %v and places %v, expected %v but got %v", - tc.val, tc.roundOn, tc.places, tc.expected, actual) + for _, testCase := range testCases { + actual := core.Round(testCase.val, testCase.roundOn, testCase.places) + if math.Abs(actual-testCase.expected) > 0.0001 { + assert.InDelta( + t, + testCase.expected, + actual, + 0.0001, + "for val %v, roundOn %v and places %v, expected %v but got %v", + testCase.val, testCase.roundOn, testCase.places, actual, testCase.expected, + ) } } } diff --git a/internal/core/date_time.go b/internal/core/date_time.go index bbe55fd..5bc034b 100644 --- a/internal/core/date_time.go +++ b/internal/core/date_time.go @@ -5,7 +5,7 @@ import "time" // GetDateTimeStr returns the date and time string in the format of YYYY-MM-DD HH:MM:SS. func GetDateTimeStr(recordTime time.Time) (string, string) { var dateStr = recordTime.Format("2006-01-02") - + var timeStr = recordTime.Format("15:04:05") return dateStr, timeStr diff --git a/internal/core/date_time_test.go b/internal/core/date_time_test.go index 75e40be..cbe6e4a 100644 --- a/internal/core/date_time_test.go +++ b/internal/core/date_time_test.go @@ -1,9 +1,12 @@ package core_test import ( + "fmt" "testing" "time" "vbalancer/internal/core" + + "github.com/stretchr/testify/assert" ) // TestGetDateTimeStr tests the GetDateTimeStr function. @@ -20,11 +23,12 @@ func TestGetDateTimeStr(t *testing.T) { {time.Date(2022, time.December, 31, 23, 59, 59, 0, time.UTC), "2022-12-31", "23:59:59"}, } - for _, tc := range testCases { - dateStr, timeStr := core.GetDateTimeStr(tc.recordTime) - if dateStr != tc.expectedDateStr || timeStr != tc.expectedTimeStr { - t.Errorf("GetDateTimeStr(%v) = (%v, %v), want (%v, %v)", tc.recordTime, - dateStr, timeStr, tc.expectedDateStr, tc.expectedTimeStr) - } + for _, test := range testCases { + dateStr, timeStr := core.GetDateTimeStr(test.recordTime) + assert.Equal(t, test.expectedDateStr, dateStr, "unexpected date string for recordTime: %v", test.recordTime) + + assert.Equal(t, fmt.Sprintf("%s %s", test.expectedDateStr, test.expectedTimeStr), + fmt.Sprintf("%s %s", dateStr, timeStr), + "unexpected combined date and time string for recordTime: %v", test.recordTime) } } diff --git a/internal/core/text.go b/internal/core/text.go index 2c6286a..766ab2b 100644 --- a/internal/core/text.go +++ b/internal/core/text.go @@ -14,7 +14,7 @@ func TrimLastChar(value string) string { if size == len(value) { return "" } - + return value[:len(value)-size] } diff --git a/internal/core/text_test.go b/internal/core/text_test.go index 4333ff4..ddc4e52 100644 --- a/internal/core/text_test.go +++ b/internal/core/text_test.go @@ -3,6 +3,8 @@ package core_test import ( "testing" "vbalancer/internal/core" + + "github.com/stretchr/testify/assert" ) // TestTrimLastChar tests the TrimLastChar function. @@ -24,9 +26,8 @@ func TestTrimLastChar(t *testing.T) { } for _, tc := range testCases { got := core.TrimLastChar(tc.input) - if got != tc.want { - t.Errorf("TrimLastChar(%q) = %q, want %q", tc.input, got, tc.want) - } + + assert.Equal(t, got, tc.want) } } @@ -35,9 +36,9 @@ func TestFmtStringWithDelimiter(t *testing.T) { t.Parallel() delimiter := "," - tests := []struct { + testCases := []struct { values []interface{} - result string + want string isError bool }{ {[]interface{}{"a", "b", "c"}, "a,b,c", false}, @@ -50,10 +51,9 @@ func TestFmtStringWithDelimiter(t *testing.T) { {[]interface{}{1, 2, "c", []int{}}, "1,2,c", false}, } - for _, test := range tests { + for _, test := range testCases { result := core.FmtStringWithDelimiter(delimiter, test.values...) - if result != test.result { - t.Errorf("Expected %s, but got %s", test.result, result) - } + + assert.Equal(t, result, test.want) } } diff --git a/internal/proxy/peer/peer.go b/internal/proxy/peer/peer.go index 934d5f4..052e6f7 100644 --- a/internal/proxy/peer/peer.go +++ b/internal/proxy/peer/peer.go @@ -15,8 +15,8 @@ type IPeer interface { // Peer this is the struct that implements the IPeer interface. type Peer struct { - Name string `yaml:"name"` - URI string `yaml:"uri"` + Name string `yaml:"name"` + URI string `yaml:"uri"` } // Dial dials a connection to a peer. diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index 334bfd2..5c7a3c7 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -12,6 +12,8 @@ import ( "vbalancer/internal/proxy/peers" "vbalancer/internal/types" "vbalancer/mocks" + + "github.com/stretchr/testify/assert" ) // TestProxyServer - this is the `TestProxyServer` function of the proxy server. @@ -19,9 +21,9 @@ func TestCheckNewConnection(t *testing.T) { t.Parallel() proxySrv, err := net.Listen("tcp", "127.0.0.1:18880") - if err != nil { - t.Fatalf("Error creating listener: %v", err) - } + + assert.Nil(t, err, "error creating listener") + defer proxySrv.Close() logger := &mocks.MockLogger{} @@ -35,26 +37,23 @@ func TestCheckNewConnection(t *testing.T) { //nolint:exhaustivestruct,exhaustruct testProxy := &Proxy{ - Logger: logger, - Port: "18880", - ClientDeadLineTime: 10, - PeerConnectionTimeout: 10, - PeerHostDeadLine: 10, - MaxCountConnection: 100, + Logger: logger, + Port: "18880", + ClientDeadLineTime: 10, + PeerConnectionTimeout: 10, + PeerHostDeadLine: 10, + MaxCountConnection: 100, } resultCode := testProxy.updatePort() - if resultCode != types.ResultOK { - t.Fatalf("can't update proxy port: %d", resultCode) - } + assert.Equal(t, resultCode, types.ResultOK, "name: `%s`") //nolint:exhaustivestruct,exhaustruct testProxy.Peers = &peers.Peers{} err = testProxy.Peers.Init(context.Background(), listPeer) - if err != nil { - t.Fatalf("can't init peers: %v", err) - } + + assert.Nil(t, err, "can't init peers") ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -62,9 +61,8 @@ func TestCheckNewConnection(t *testing.T) { go testProxy.AcceptConnections(ctx, proxySrv) conn, err := net.Dial("tcp", proxySrv.Addr().String()) - if err != nil { - t.Fatalf("dialing to proxy server: %v", err) - } + + assert.Nil(t, err, "dialing to proxy server") defer conn.Close() } @@ -72,69 +70,65 @@ func TestCheckNewConnection(t *testing.T) { // TestGetProxyPort tests the UpdatePort function. // It validates UpdatePort handles invalid environment variable values, // default values, and valid custom environment variable values correctly. -// -//nolint:funlen func TestGetProxyPort(t *testing.T) { t.Parallel() - tests := []struct { - port string - name string - envVar string - expected types.ResultCode - checkValue string + testCases := []struct { + port string + name string + envVar string + want types.ResultCode + wantValue string }{ { - name: "set port `1234`", - port: "1234", - envVar: ":", - expected: types.ResultOK, - checkValue: ":1234", + name: "set port `1234`", + port: "1234", + envVar: ":", + want: types.ResultOK, + wantValue: ":1234", }, { - name: "empty env var, got DefaultPort", - envVar: "", - expected: types.ResultOK, - checkValue: fmt.Sprintf(":%s", types.DefaultProxyPort), + name: "empty env var, got DefaultPort", + port: "", + envVar: "", + want: types.ResultOK, + wantValue: fmt.Sprintf(":%s", types.DefaultProxyPort), }, { - name: "valid proxy port from env var", - envVar: "8080", - expected: types.ResultOK, - checkValue: ":8080", + name: "valid proxy port from env var", + port: "", + envVar: "8080", + want: types.ResultOK, + wantValue: ":8080", }, { - name: "empty proxy port from default value", - envVar: " ", - expected: types.ErrEmptyValue, - checkValue: ":", - port: ":", + name: "empty proxy port from default value", + envVar: " ", + want: types.ErrEmptyValue, + wantValue: ":", + port: ":", }, { - name: "empty proxy port from default value", - envVar: " ", - expected: types.ErrEmptyValue, - checkValue: ":", - port: ":", + name: "empty proxy port from default value", + envVar: " ", + want: types.ErrEmptyValue, + wantValue: ":", + port: ":", }, } - //nolint:exhaustivestruct,exhaustruct prx := &Proxy{} - for _, test := range tests { + for _, test := range testCases { prx.Port = test.port os.Clearenv() os.Setenv("ProxyPort", test.envVar) result := prx.updatePort() - if result != test.expected { - t.Fatalf("name: %s, expected result %v, got %v", test.name, test.expected, result) - } - if prx.Port != test.checkValue { - t.Fatalf("name: %s, expected value %s, got %s", test.name, test.checkValue, prx.Port) - } + assert.Equalf(t, result, test.want, "name: `%s`", test.name) + + assert.Equalf(t, prx.Port, test.wantValue, "name: `%s`", test.name) } } diff --git a/internal/proxy/response/response.go b/internal/proxy/response/response.go index 076e045..519bb49 100644 --- a/internal/proxy/response/response.go +++ b/internal/proxy/response/response.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" "net" - + "vbalancer/internal/types" ) @@ -36,15 +36,14 @@ func (r *Response) SentResponseToClient(client net.Conn, err error) error { responseBody := fmt.Sprintf( "HTTP/1.1 200 OK\r\nConnection: close\r\n"+ - "Content-Type: application/json\r\n"+ - "Content-Length: %d\r\n\r\n"+ - "%s", responseLen, responseJSON) + "Content-Type: application/json\r\n"+ + "Content-Length: %d\r\n\r\n"+ + "%s", responseLen, responseJSON) _, err = client.Write([]byte(responseBody)) if err != nil { - return fmt.Errorf("%w", err ) + return fmt.Errorf("%w", err) } return nil } - diff --git a/internal/proxy/rules/blacklist.go b/internal/proxy/rules/blacklist.go index 36ac3da..7820c0e 100644 --- a/internal/proxy/rules/blacklist.go +++ b/internal/proxy/rules/blacklist.go @@ -11,15 +11,15 @@ import ( // Blacklist defines the blacklist configuration. type Blacklist struct { - Cache *cache.VCache + Cache *cache.VCache CacheDurationToEvict time.Duration `yaml:"cacheDurationToEvict"` - RemoteIP []string `yaml:"remoteIp"` + RemoteIP []string `yaml:"remoteIp"` } // Init initializes the blacklist. func (b *Blacklist) Init(ctx context.Context) error { b.Cache = cache.New(time.Second, b.CacheDurationToEvict) - + err := b.Cache.StartEvict(ctx) if err != nil { return fmt.Errorf("%w", err) @@ -36,7 +36,7 @@ func (b *Blacklist) IsBlacklistIP(checkIP string) bool { if ok { return b } - } + } host, _, err := net.SplitHostPort(checkIP) if err != nil { diff --git a/internal/proxy/rules/blacklist_test.go b/internal/proxy/rules/blacklist_test.go index c517e1d..a189160 100644 --- a/internal/proxy/rules/blacklist_test.go +++ b/internal/proxy/rules/blacklist_test.go @@ -7,6 +7,7 @@ import ( "vbalancer/internal/proxy/rules" cache "github.com/microup/vcache" + "github.com/stretchr/testify/assert" ) const CachedDurationToEvict = 5 * time.Second @@ -15,7 +16,7 @@ const CachedDurationToEvict = 5 * time.Second func TestBlacklist_CheckIpBlacklist(t *testing.T) { t.Parallel() - cases := []struct { + testCases := []struct { name string b *rules.Blacklist checkedIP string @@ -25,8 +26,8 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { name: "empty blacklisted", b: &rules.Blacklist{ CacheDurationToEvict: CachedDurationToEvict, - Cache: cache.New(time.Second, CachedDurationToEvict), - RemoteIP: []string{""}, + Cache: cache.New(time.Second, CachedDurationToEvict), + RemoteIP: []string{""}, }, checkedIP: "89.207.132.170", want: false, @@ -35,8 +36,8 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { name: "ip is blacklisted", b: &rules.Blacklist{ CacheDurationToEvict: CachedDurationToEvict, - Cache: cache.New(time.Second, CachedDurationToEvict), - RemoteIP: []string{"89.207.132.170", "89.207.132.172"}, + Cache: cache.New(time.Second, CachedDurationToEvict), + RemoteIP: []string{"89.207.132.170", "89.207.132.172"}, }, checkedIP: "89.207.132.170", want: true, @@ -46,8 +47,8 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { b: &rules.Blacklist{ CacheDurationToEvict: CachedDurationToEvict, - Cache: cache.New(time.Second, CachedDurationToEvict), - RemoteIP: []string{"89.207.132.170", "89.207.132.172"}, + Cache: cache.New(time.Second, CachedDurationToEvict), + RemoteIP: []string{"89.207.132.170", "89.207.132.172"}, }, checkedIP: "89.207.132.170:1234", want: true, @@ -57,8 +58,8 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { b: &rules.Blacklist{ CacheDurationToEvict: CachedDurationToEvict, - Cache: cache.New(time.Second, CachedDurationToEvict), - RemoteIP: []string{"89.207.132.170", "89.207.132.175"}, + Cache: cache.New(time.Second, CachedDurationToEvict), + RemoteIP: []string{"89.207.132.170", "89.207.132.175"}, }, checkedIP: "89.207.132.171", want: false, @@ -67,8 +68,8 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { name: "ip is not blacklisted with port", b: &rules.Blacklist{ CacheDurationToEvict: CachedDurationToEvict, - Cache: cache.New(time.Second, CachedDurationToEvict), - RemoteIP: []string{"89.207.132.170", "89.207.132.175"}, + Cache: cache.New(time.Second, CachedDurationToEvict), + RemoteIP: []string{"89.207.132.170", "89.207.132.175"}, }, checkedIP: "89.207.132.171:1234", want: false, @@ -76,15 +77,12 @@ func TestBlacklist_CheckIpBlacklist(t *testing.T) { } ctx := context.Background() - - for _, test := range cases { + + for _, test := range testCases { err := test.b.Init(ctx) - if err != nil { - t.Errorf("name: `%s` goe err: %v", test.name, err) - } - if got := test.b.IsBlacklistIP(test.checkedIP); got != test.want { - t.Errorf("name: `%s` = %v, want %v", test.name, got, test.want) - } + assert.Nil(t, err, "name: `%s`", test.name) + + assert.Equalf(t, test.b.IsBlacklistIP(test.checkedIP), test.want, "name: `%s`", test.name) } } diff --git a/internal/types/consts.go b/internal/types/consts.go index 833d535..db1798c 100644 --- a/internal/types/consts.go +++ b/internal/types/consts.go @@ -22,7 +22,7 @@ const ( // CONFIG - CONSTS. const ( // - DefaultNameConfigFile = "config.yaml" + DefaultNameConfigFile = "config.yaml" // MaskDir 0x755 is an octal notation for the file permission -rwxr-xr-x. MaskDir = 0x755 // DefaultFilePerm is the default file permission with octal notation 0666. @@ -39,16 +39,16 @@ const ( // PROXY - CONSTS. const ( - // + // DefaultProxyPort = "8080" // DeafultMaxCountConnection = 1000 // DeafultClientDeadLineTime = 30 * time.Second // - DeafultPeerConnectionTimeout = 30 * time.Second + DeafultPeerConnectionTimeout = 30 * time.Second // - DeafultPeerHostDeadLine = 30 * time.Second + DeafultPeerHostDeadLine = 30 * time.Second // DeafultCountMaxDialAttemptsToPeer = 30 -) \ No newline at end of file +) diff --git a/internal/types/types_codes_test.go b/internal/types/types_codes_test.go index a61c346..9017ddf 100644 --- a/internal/types/types_codes_test.go +++ b/internal/types/types_codes_test.go @@ -3,14 +3,16 @@ package types_test import ( "testing" "vbalancer/internal/types" + + "github.com/stretchr/testify/assert" ) func TestResultCodeToStr(t *testing.T) { t.Parallel() - var tests = []struct { - input types.ResultCode - expected string + var testCases = []struct { + input types.ResultCode + want string }{ {types.ResultOK, "SUCCESS"}, {types.ErrProxy, "proxy error"}, @@ -30,28 +32,24 @@ func TestResultCodeToStr(t *testing.T) { {types.ResultCode(0xABC), "unknown result code: 2748"}, } - for _, test := range tests { - if result := test.input.ToStr(); result != test.expected { - t.Errorf("TestResultCodeToStr(%d) = %s; expected = %s", test.input, result, test.expected) - } + for _, test := range testCases { + assert.Equalf(t, test.input.ToStr(), test.want, "input: `%d | want %d`", test.input, test.want) } } func TestResultCodeToUint(t *testing.T) { t.Parallel() - var tests = []struct { - input types.ResultCode - expected uint32 + var testCases = []struct { + input types.ResultCode + want uint32 }{ {types.ResultOK, 0}, {types.ResultUnknown, 4294967295}, {types.ResultCode(0xABC), 2748}, } - for _, test := range tests { - if result := test.input.ToUint(); result != test.expected { - t.Errorf("TestResultCodeToUint(%d) = %d; expected = %d", test.input, result, test.expected) - } + for _, test := range testCases { + assert.Equalf(t, test.input.ToUint(), test.want, "input: `%d | want %d`", test.input, test.want) } } diff --git a/internal/vlog/log_data_types.go b/internal/vlog/log_data_types.go index 977e2fa..12ec95d 100644 --- a/internal/vlog/log_data_types.go +++ b/internal/vlog/log_data_types.go @@ -39,7 +39,7 @@ func ParseValues(values []interface{}) ( var typeLog TypeLog var resultCode types.ResultCode //nolint:wsl var remoteAddr RemoteAddr //nolint:wsl - var peerAddr PeerAddr //nolint:wsl + var peerAddr PeerAddr //nolint:wsl var val strings.Builder //nolint:wsl for _, value := range values { @@ -61,7 +61,7 @@ func ParseValues(values []interface{}) ( } } - return typeLog, resultCode, remoteAddr, peerAddr, val.String() + return typeLog, resultCode, remoteAddr, peerAddr, val.String() } // BuildRecord function takes in several input values such as log type, result code, diff --git a/internal/vlog/log_data_types_test.go b/internal/vlog/log_data_types_test.go index f6d25b2..442a0e8 100644 --- a/internal/vlog/log_data_types_test.go +++ b/internal/vlog/log_data_types_test.go @@ -5,8 +5,11 @@ import ( "strings" "testing" "time" + "vbalancer/internal/types" "vbalancer/internal/vlog" + + "github.com/stretchr/testify/assert" ) // TestBuildRecord. @@ -20,33 +23,25 @@ func TestBuildRecord(t *testing.T) { valuesStr := "value1;value2" // Call the function with the inputs - actualTypeLog, actualRecord := vlog.BuildRecord(typeLog, resultCode, remoteAddr, peerAddr,valuesStr) + actualTypeLog, actualRecord := vlog.BuildRecord(typeLog, resultCode, remoteAddr, peerAddr, valuesStr) // Define the expected output expectedTypeLog := vlog.Info expectedRecord := "INFO;200;192.168.1.40;127.0.0.1:8081;value1;value2;" - // Assert that the actual output is as expected - if actualTypeLog != expectedTypeLog { - t.Errorf("Expected typeLog %d but got %d", expectedTypeLog, actualTypeLog) - } + assert.Equal(t, expectedTypeLog, actualTypeLog) parts := strings.Split(actualRecord, ";") dateTime := parts[:2] _, err := time.Parse("2006-01-02;15:04:05", strings.Join(dateTime, ";")) - if err != nil { - t.Errorf("Expected valid date and time, but got %v", dateTime) - } + + assert.Nilf(t, err, "expected valid date and time, but got %v", dateTime) // Check that the fourth element of parts is equal to resultCode - if parts[3] != strconv.Itoa(int(resultCode.ToUint())) { - t.Errorf("Expected resultCode %d, but got %v", resultCode, parts[3]) - } + assert.Equal(t, strconv.Itoa(int(resultCode.ToUint())), parts[3]) resultStr := strings.Join(parts[2:], ";") - if expectedRecord != resultStr { - t.Errorf("Expected record %s but got %s", expectedRecord, resultStr) - } + assert.Equal(t, expectedRecord, resultStr) } diff --git a/internal/vlog/log_file.go b/internal/vlog/log_file.go index 0de5b54..1b03f49 100644 --- a/internal/vlog/log_file.go +++ b/internal/vlog/log_file.go @@ -1,6 +1,5 @@ package vlog - // LogFile represents information about a file, including its name, size, and kind. type LogFile struct { // FileName is the name of the file. diff --git a/internal/vlog/log_files.go b/internal/vlog/log_files.go index 924f4c6..74fef3e 100644 --- a/internal/vlog/log_files.go +++ b/internal/vlog/log_files.go @@ -13,7 +13,7 @@ import ( func (v *VLog) newFileLog(newFileName string, isNewFileLog bool) error { if isNewFileLog { v.MapLastLogRecords = make([]string, 0) - + err := v.Close() if err != nil { return err diff --git a/internal/vlog/log_test.go b/internal/vlog/log_test.go index c4972c6..35b1332 100644 --- a/internal/vlog/log_test.go +++ b/internal/vlog/log_test.go @@ -8,6 +8,8 @@ import ( "vbalancer/internal/config" "vbalancer/internal/vlog" + + "github.com/stretchr/testify/assert" ) // TestVlogAdd is a test case for vlog.Add. @@ -33,26 +35,20 @@ func helperVlogAdd(t *testing.T) { vLog := vlog.New(cfg) err := vLog.Init() - if err != nil { - t.Fatalf("unexpected error creating VLog: %v", err) - } + + assert.Nil(t, err) vLog.Add(vlog.Debug, "test msg") time.Sleep(1 * time.Second) - if vLog.GetCountRecords() != 1 { - t.Errorf("expected count of log records to be 1, got %d", vLog.GetCountRecords()) - } + assert.Equal(t, vLog.GetCountRecords(), 1, "expected count of log records to be 1, got %d", vLog.GetCountRecords()) err = vLog.Close() - if err != nil { - t.Fatalf("unexpected close log file: %v", err) - } + + assert.Nil(t, err) absolutePath, _ := filepath.Abs(cfg.DirLog) err = os.RemoveAll(absolutePath) - if err != nil { - t.Fatalf("unexpected error delete tempore dir: %v", err) - } + assert.Nil(t, err, "unexpected error delete tempore dir") } diff --git a/internal/vlog/vlog.go b/internal/vlog/vlog.go index ba95239..6155703 100644 --- a/internal/vlog/vlog.go +++ b/internal/vlog/vlog.go @@ -31,10 +31,10 @@ type VLog struct { func New(cfg *config.Log) *VLog { headerCSV := fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;", - "Date", - "Time", - "Type", - "ResultCode", + "Date", + "Time", + "Type", + "ResultCode", "RemoteAddr", "PeerURL", "Description") @@ -58,7 +58,7 @@ func (v *VLog) Init() error { return fmt.Errorf("%w", err) } - return nil + return nil } // GetCountRecords returns the number of records in the log file. diff --git a/mocks/mock_logger.go b/mocks/mock_logger.go index 677e23f..dc81791 100644 --- a/mocks/mock_logger.go +++ b/mocks/mock_logger.go @@ -3,7 +3,7 @@ package mocks type MockLogger struct { } -func (m *MockLogger) Add(values ...interface{}) { +func (m *MockLogger) Add(...interface{}) { } diff --git a/mocks/mock_net_conn.go b/mocks/mock_net_conn.go index cfe66e5..9063e86 100644 --- a/mocks/mock_net_conn.go +++ b/mocks/mock_net_conn.go @@ -59,21 +59,21 @@ func (c *MockConn) RemoteAddr() net.Addr { return nil } -func (c *MockConn) SetDeadline(t time.Time) error { +func (c *MockConn) SetDeadline(time.Time) error { c.mu.Lock() defer c.mu.Unlock() return nil } -func (c *MockConn) SetReadDeadline(t time.Time) error { +func (c *MockConn) SetReadDeadline(time.Time) error { c.mu.Lock() defer c.mu.Unlock() return nil } -func (c *MockConn) SetWriteDeadline(t time.Time) error { +func (c *MockConn) SetWriteDeadline(time.Time) error { c.mu.Lock() defer c.mu.Unlock() diff --git a/mocks/mock_peer.go b/mocks/mock_peer.go index 70fcab9..206a8ca 100644 --- a/mocks/mock_peer.go +++ b/mocks/mock_peer.go @@ -5,10 +5,10 @@ package mocks import ( + context "context" net "net" reflect "reflect" time "time" - vlog "vbalancer/internal/vlog" gomock "github.com/golang/mock/gomock" ) @@ -37,18 +37,18 @@ func (m *MockIPeer) EXPECT() *MockIPeerMockRecorder { } // Dial mocks base method. -func (m *MockIPeer) Dial(timeOut, timeOutDeadLine time.Duration) (net.Conn, error) { +func (m *MockIPeer) Dial(ctx context.Context, timeOut, timeOutDeadLine time.Duration) (net.Conn, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Dial", timeOut, timeOutDeadLine) + ret := m.ctrl.Call(m, "Dial", ctx, timeOut, timeOutDeadLine) ret0, _ := ret[0].(net.Conn) ret1, _ := ret[1].(error) return ret0, ret1 } // Dial indicates an expected call of Dial. -func (mr *MockIPeerMockRecorder) Dial(timeOut, timeOutDeadLine interface{}) *gomock.Call { +func (mr *MockIPeerMockRecorder) Dial(ctx, timeOut, timeOutDeadLine interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dial", reflect.TypeOf((*MockIPeer)(nil).Dial), timeOut, timeOutDeadLine) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dial", reflect.TypeOf((*MockIPeer)(nil).Dial), ctx, timeOut, timeOutDeadLine) } // GetURI mocks base method. @@ -65,14 +65,3 @@ func (mr *MockIPeerMockRecorder) GetURI() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetURI", reflect.TypeOf((*MockIPeer)(nil).GetURI)) } -// SetLogger mocks base method. -func (m *MockIPeer) SetLogger(arg0 vlog.ILog) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLogger", arg0) -} - -// SetLogger indicates an expected call of SetLogger. -func (mr *MockIPeerMockRecorder) SetLogger(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogger", reflect.TypeOf((*MockIPeer)(nil).SetLogger), arg0) -}