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

Add test files #160

Closed
wants to merge 16 commits into from
Closed
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
5 changes: 2 additions & 3 deletions .github/workflows/codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ jobs:
run: go test -v -race -coverprofile=coverage.out -covermode=atomic ./...

- name: Upload coverage reports to Codecov with GitHub Action
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4.0.1
with:
files: ./coverage.out
fail_ci_if_error: true
token: ${{ secrets.CODECOV_TOKEN }}
22 changes: 22 additions & 0 deletions consts/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package utils

import (
"strings"
"testing"
)

func TestPrepareLogMsg(t *testing.T) {
testXICAPMetadata := "example-metadata"
testMsg := "example-message"

expectedJSON := `{"X-ICAP-Metadata":"example-metadata","log":"example-message"}`
expectedResult := strings.ReplaceAll(expectedJSON, `\`, "")

result := PrepareLogMsg(testXICAPMetadata, testMsg)

if result != expectedResult {
t.Errorf("Expected: %s, but got: %s", expectedResult, result)
}

// Additional tests can be added here to cover more cases
}
1,289 changes: 1,289 additions & 0 deletions coverage.ou

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e
github.com/h2non/filetype v1.0.12
github.com/spf13/viper v1.9.0
github.com/stretchr/testify v1.7.0
github.com/xhit/go-str2duration/v2 v2.0.0
go.uber.org/zap v1.22.0
)
Expand All @@ -18,15 +19,18 @@ require (
github.com/mitchellh/mapstructure v1.4.2 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.1.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect
golang.org/x/text v0.3.6 // indirect
gopkg.in/ini.v1 v1.63.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.9.0 h1:yR6EXjTp0y0cLN8OZg1CRZmOBdI88UcGkhgyJhu6nZk=
github.com/spf13/viper v1.9.0/go.mod h1:+i6ajR7OX2XaiBkrcZJFK21htRk7eDeLg7+O6bhUPP4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
Expand Down Expand Up @@ -657,6 +658,7 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
38 changes: 38 additions & 0 deletions http-message/http_message_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package http_message

import (
"net/http/httptest"
"testing"

"icapeg/logging"

"go.uber.org/zap"
)

func init() {
logger, _ := zap.NewDevelopment()
logging.Logger = logger
}

func TestNewHttpMsg(t *testing.T) {
// Create a new HTTP request
req := httptest.NewRequest("GET", "http://example.com", nil)

// Create a new HTTP response recorder (which implements http.ResponseWriter)
rec := httptest.NewRecorder()

// Create a dummy HTTP response using the recorded response
resp := rec.Result()

// Create an instance of HttpMsg using the NewHttpMsg method
httpMsg := (&HttpMsg{}).NewHttpMsg(req, resp)

// Check if the HttpMsg struct is created correctly
if httpMsg.Request != req {
t.Errorf("Expected Request to be %v, got %v", req, httpMsg.Request)
}

if httpMsg.Response != resp {
t.Errorf("Expected Response to be %v, got %v", resp, httpMsg.Response)
}
}
71 changes: 71 additions & 0 deletions icap/chunked_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package icap

import (
"bytes"
"errors"
"io"
"strings"
"testing"
)

// TestNewChunkedReader tests the creation of a new chunkedReader
func TestNewChunkedReader(t *testing.T) {
data := "4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks.\r\n0\r\n\r\n"
reader := newChunkedReader(bytes.NewReader([]byte(data)))

expected := "Wikipedia in\r\n\r\nchunks."
buf := new(bytes.Buffer)
_, err := io.Copy(buf, reader)
if err != nil {
t.Errorf("Error reading chunked data: %v", err)
}

if buf.String() != expected {
t.Errorf("Expected %q, got %q", expected, buf.String())
}
}

// TestNewChunkedWriter tests the creation of a new chunkedWriter
func TestNewChunkedWriter(t *testing.T) {
var buf bytes.Buffer
writer := NewChunkedWriter(&buf)

data := []byte("Wikipedia in\r\n\r\nchunks.")
_, err := writer.Write(data)
if err != nil {
t.Errorf("Error writing chunked data: %v", err)
}
writer.Close()

// The length of "Wikipedia in\r\n\r\nchunks." is 23 bytes, so the chunk length should be "17\r\n" in hexadecimal
expected := "17\r\nWikipedia in\r\n\r\nchunks.\r\n0\r\n\r\n"

// Trim trailing newlines for comparison
expected = strings.TrimSpace(expected)
actual := strings.TrimSpace(buf.String())

if actual != expected {
t.Errorf("Expected %q, got %q", expected, actual)
}
}

// TestParseHexUint tests the parsing of a hexadecimal number
func TestParseHexUint(t *testing.T) {
tests := []struct {
input []byte
expected uint64
err error
}{
{[]byte("4"), 4, nil},
{[]byte("1A"), 26, nil},
{[]byte("1a"), 26, nil},
{[]byte("G"), 0, errors.New("invalid chunk length: 'G'")},
}

for _, test := range tests {
result, err := parseHexUint(test.input)
if result != test.expected || (err != nil && err.Error() != test.err.Error()) {
t.Errorf("parseHexUint(%q) = %d, %v; want %d, %v", test.input, result, err, test.expected, test.err)
}
}
}
38 changes: 38 additions & 0 deletions icap/mux_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package icap

import (
"testing"
)

func TestNewServeMux(t *testing.T) {
mux := NewServeMux()
if mux == nil {
t.Fatal("NewServeMux() returned nil")
}
if len(mux.m) != 0 {
t.Errorf("Expected empty handler map, got %d handlers", len(mux.m))
}
}

func TestPathMatch(t *testing.T) {
tests := []struct {
pattern, path string
want bool
}{
{"/", "/", true},
{"/foo", "/foo", true},
{"/foo/", "/foo/bar", true},
{"/foo", "/foo/bar", false},
{"/foo/", "/foo", false},
{"/foo/bar", "/foo", false},
{"", "/", false},
}

for _, tt := range tests {
t.Run(tt.pattern+"_"+tt.path, func(t *testing.T) {
if got := pathMatch(tt.pattern, tt.path); got != tt.want {
t.Errorf("pathMatch(%q, %q) = %v, want %v", tt.pattern, tt.path, got, tt.want)
}
})
}
}
49 changes: 49 additions & 0 deletions icap/request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// File: icap/icap_test.go

package icap

import (
"bufio"
"bytes"
"strings"
"testing"
)

// Helper function to create a bufio.ReadWriter from a string
func createReadWriter(s string) *bufio.ReadWriter {
reader := strings.NewReader(s)
r := bufio.NewReader(reader)
w := bufio.NewWriter(&bytes.Buffer{})
return bufio.NewReadWriter(r, w)
}

// Test valid ICAP request with REQMOD method
func TestReadRequest_REQMOD(t *testing.T) {
data := "REQMOD icap://icap-server.net/server?arg=87 ICAP/1.0\r\n" +
"Host: icap-server.net\r\n" +
"Encapsulated: req-hdr=0, req-body=51\r\n" + // Correct length of req-body
"\r\n" +
"GET / HTTP/1.1\r\n" +
"Host: www.origin-server.com\r\n" +
"\r\n" +
"4\r\nWiki\r\n" +
"0\r\n" // Correct end of chunked body

rw := createReadWriter(data)
req, err := ReadRequest(rw)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if req.Method != "REQMOD" {
t.Errorf("expected method REQMOD, got %s", req.Method)
}
if req.URL.String() != "icap://icap-server.net/server?arg=87" {
t.Errorf("expected URL icap://icap-server.net/server?arg=87, got %s", req.URL.String())
}
if req.Proto != "ICAP/1.0" {
t.Errorf("expected proto ICAP/1.0, got %s", req.Proto)
}
if req.Header.Get("Host") != "icap-server.net" {
t.Errorf("expected header Host to be icap-server.net, got %s", req.Header.Get("Host"))
}
}
45 changes: 45 additions & 0 deletions icap/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package icap

import (
"net"
"net/http"
"testing"
"time"
)

// MockListener is a mock implementation of net.Listener for testing purposes.
type MockListener struct{}

func (l *MockListener) Accept() (net.Conn, error) {
conn1, _ := net.Pipe()
return conn1, nil
}

func (l *MockListener) Close() error {
return nil
}

func (l *MockListener) Addr() net.Addr {
return nil
}

func TestServeICAP(t *testing.T) {
// Create a new server instance with a dummy handler
server := &Server{
Handler: HandlerFunc(func(w ResponseWriter, r *Request) {
// Dummy handler implementation
w.WriteHeader(http.StatusOK, nil, false)
}),
}

// Serve the ICAP request
go func() {
if err := server.Serve(&MockListener{}); err != nil {
t.Errorf("Serve error: %v", err)
}
}()

// As we're not actually running a real server, let's wait for a while
// to give the goroutine a chance to finish its work.
time.Sleep(100 * time.Millisecond)
}
39 changes: 39 additions & 0 deletions logging/logging_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package logging

import (
"os"
"testing"
)

func TestInitializeLogger(t *testing.T) {
// Test case 1: Initialize logger with console logging enabled
InitializeLogger("debug", true)
if Logger == nil {
t.Error("Logger not initialized")
}

// Test case 2: Initialize logger with console logging disabled
InitializeLogger("debug", false)
if Logger == nil {
t.Error("Logger not initialized")
}

// Test case 3: Check if logs directory and file are created
_, err := os.Stat("./logs/logs.json")
if os.IsNotExist(err) {
t.Error("Logs directory or file does not exist")
}

// Add more test cases as needed...
}

// Example usage of the logger in another test function
func TestLoggerUsage(t *testing.T) {
// Initialize logger
InitializeLogger("debug", true)

// Example log message
Logger.Info("This is an example log message")

// Add assertions or checks based on your actual usage of the logger
}
Loading
Loading