Skip to content

Commit

Permalink
adds test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
bentohset committed Mar 30, 2024
1 parent bedc1cf commit 12a8a1d
Show file tree
Hide file tree
Showing 5 changed files with 255 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ BINARY_NAME = gnm
DIST_PATH=./dist
LD_FLAGS = -ldflags "-X main.Version=$(BUILD_VERSION)"

.PHONY: test
test:
@echo 'Running unit tests'
go test -coverpkg=./internal/... -race -vet=off -count=1 -covermode atomic ./...

## build: create binary in ./dist folder for your current platform. Use this option if you build it for personal use.
.PHONY: build
build:
Expand Down
125 changes: 125 additions & 0 deletions internal/logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Package logger incapsulates logger functions
package logger

import (
"bytes"
"fmt"
"os"
"path"
"strings"
"testing"
)

func Test_LoggerConstructor(t *testing.T) {
// Create a temporary directory for testing
tmpDir, err := os.MkdirTemp("", "testlog")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
defer os.RemoveAll(tmpDir)

// Set up test cases
testCases := []struct {
name string
appPath string
userSetLogLevel string
expectedLogLevel LogLevel
expectError bool
}{
{"DebugLevel", tmpDir, "debug", LevelDebug, false},
{"DefaultLevel", tmpDir, "info", LevelInfo, false},
{"InvalidPath", "/nonexistent", "info", LevelInfo, true},
}

// Run tests
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
logger, err := New(tc.appPath, tc.userSetLogLevel)

if tc.expectError {
if err == nil {
t.Errorf("Expected an error but got none")
}
} else {
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

// Check the log level
if logger.logLevel != tc.expectedLogLevel {
t.Errorf("Expected log level %v, but got %v", tc.expectedLogLevel, logger.logLevel)
}

// Check if the log file is created
logFilePath := path.Join(tc.appPath, logFileName)
_, err := os.Stat(logFilePath)
if os.IsNotExist(err) {
t.Errorf("Log file not created at %s", logFilePath)
}

// Cleanup: Close the log file
if logger.logFile != nil {
logger.logFile.Close()
}
}
})
}
}

func Test_LoggerMethods(t *testing.T) {
// Create a temporary directory for testing
tmpDir, err := os.MkdirTemp("", "testlog")
if err != nil {
t.Fatalf("Failed to create temporary directory: %v", err)
}
defer os.RemoveAll(tmpDir)

// Create an appLogger instance for testing
logger, err := New(tmpDir, "debug")
if err != nil {
t.Fatalf("Failed to create appLogger: %v", err)
}
defer logger.Close()

// Set up test cases
testCases := []struct {
name string
logLevel LogLevel
method func(format string, args ...interface{})
expectedPrefix string
expectOutput bool
}{
{"Debug", LevelDebug, logger.Debug, "DEBG", true},
{"Info", LevelInfo, logger.Info, "INFO", true},
// LogLevel is 'info', but we're printing debug message, thus it should not be printed.
{"Debug output should be hushed", LevelInfo, logger.Debug, "", false},
{"Error", LevelInfo, logger.Error, "ERROR", true},
}

// Run tests
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
logger.logLevel = tc.logLevel

// Redirect logger output to a buffer
var buf bytes.Buffer
logger.innerLogger.SetOutput(&buf)

// Call the method
tc.method("Test message %d", 42)

if tc.expectOutput {
// Check if the log was produced as expected
expectedLog := fmt.Sprintf("[%s] Test message 42", tc.expectedPrefix)
if output := buf.String(); !strings.Contains(output, expectedLog) {
t.Errorf("Expected log output:\n%s\nGot:\n%s", expectedLog, output)
}
} else {
// Check if the log was not produced
if buf.Len() > 0 {
t.Errorf("Unexpected log output: %s", buf.String())
}
}
})
}
}
36 changes: 36 additions & 0 deletions internal/mock/stdin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package mock

import (
"os"
"testing"
)

func MockStdin(t *testing.T, dummyInput string) (funcDefer func(), err error) {
t.Helper()

oldOsStdin := os.Stdin

tmpfile, err := os.CreateTemp(t.TempDir(), t.Name())
if err != nil {
return nil, err
}

content := []byte(dummyInput)

if _, err := tmpfile.Write(content); err != nil {
return nil, err
}

if _, err := tmpfile.Seek(0, 0); err != nil {
return nil, err
}

// Set stdin to the temp file
os.Stdin = tmpfile

return func() {
// clean up
os.Stdin = oldOsStdin
os.Remove(tmpfile.Name())
}, nil
}
25 changes: 25 additions & 0 deletions internal/model/host_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package model

import (
"reflect"
"testing"
)

func Test_NewHost(t *testing.T) {
// Create a new host using the NewHost function
expectedHost := Host{
ID: 1,
Alias: "TestAlias",
Description: "TestDescription",
User: "Testuser",
HostName: "TestHost",
PrivateKeyPath: "/path/to/private/key",
}

newHost := NewHost(expectedHost.ID, expectedHost.Alias, expectedHost.User, expectedHost.HostName, expectedHost.Description, expectedHost.PrivateKeyPath)

// Check if the new host matches the expected host
if !reflect.DeepEqual(newHost, expectedHost) {
t.Errorf("NewHost function did not create the expected host. Expected: %v, Got: %v", expectedHost, newHost)
}
}
64 changes: 64 additions & 0 deletions internal/utils/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package utils

import (
"fmt"
"testing"

"github.com/bentohset/gnm/internal/mock"
)

func Test_GetInput(t *testing.T) {
userInput := "test input\n"
funcDefer, err := mock.MockStdin(t, userInput)
if err != nil {
t.Fatal(err)
}
defer funcDefer()

expected := "test input"
actual := GetInput("Enter input: ")

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

func Test_ParseBoolean(t *testing.T) {
testCases := []struct {
input string
expectedValue bool
expectedError error
}{
{"y", true, nil},
{"n", false, nil},
{"", true, nil},
{"invalid", false, fmt.Errorf("invalid input, should be boolean")},
}

// Execute and verify
for _, tc := range testCases {
t.Run(tc.input, func(t *testing.T) {
actualValue, actualError := ParseBoolean(tc.input)

if actualValue != tc.expectedValue {
t.Errorf("Expected value: %t, but got: %t", tc.expectedValue, actualValue)
}

if (actualError == nil && tc.expectedError != nil) || (actualError != nil && tc.expectedError == nil) || (actualError != nil && tc.expectedError != nil && actualError.Error() != tc.expectedError.Error()) {
t.Errorf("Expected error: %v, but got: %v", tc.expectedError, actualError)
}
})
}
}

func TestExecute(t *testing.T) {
err := Execute("", "ls")
if err != nil {
t.Error("should return true")
}

err = Execute("", "aaa")
if err == nil {
t.Error("should return false")
}
}

0 comments on commit 12a8a1d

Please sign in to comment.