Skip to content

Commit

Permalink
Improve unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
grahamgilbert committed Jan 17, 2025
1 parent 8a2e5a6 commit 5849855
Show file tree
Hide file tree
Showing 22 changed files with 447 additions and 89 deletions.
8 changes: 0 additions & 8 deletions .testcoverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,9 @@ exclude:
# Exclude files or packages matching their paths
paths:
- main.go
- pkg/utils/exec.go
- tables/fileline/file_line.go
- tables/unifiedlog/unified_log.go
- ^tables/networkquality$
- ^tables/unifiedlog$
- ^tables/puppet$
- ^tables/unifiedlog$
- ^tables/pendingappleupdates$
- ^tables/fileline$
- tables/unifiedlog/unified_log.go
- tables/networkquality/networkquality.go
- tables/pendingappleupdates/pendingappleupdates.go
- tables/puppet/puppet_facts.go
- tables/puppet/puppet_info.go
Expand Down
1 change: 1 addition & 0 deletions pkg/utils/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ go_library(
"exec_mocks.go",
"osquery.go",
"utils.go",
"utils_mocks.go",
],
importpath = "github.com/macadmins/osquery-extension/pkg/utils",
visibility = ["//visibility:public"],
Expand Down
47 changes: 29 additions & 18 deletions pkg/utils/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRunCmd(t *testing.T) {
Expand All @@ -14,32 +16,41 @@ func TestRunCmd(t *testing.T) {
},
}
output, err := runner.RunCmd("echo", "test")
if err != nil {
t.Fatalf("RunCmd() error = %v, wantErr nil", err)
return
}
got := string(output)
if got != runner.Commands["echo test"].Output {
t.Errorf("RunCmd() = %q, want %q", got, runner.Commands["echo test"].Output)
}
assert.NoError(t, err)
assert.Equal(t, "test output", string(output))
}

func TestRunCmdWithStdin(t *testing.T) {
runner := MultiMockCmdRunner{
Commands: map[string]MockCmdRunner{
"echo": {
"cat": {
Output: "test output",
Err: nil,
},
},
}
output, err := runner.RunCmdWithStdin("echo", "test")
if err != nil {
t.Fatalf("RunCmdWithStdin() error = %v, wantErr nil", err)
return
}
got := string(output)
if got != runner.Commands["echo"].Output {
t.Errorf("RunCmdWithStdin() = %q, want %q", got, runner.Commands["echo"].Output)
}
output, err := runner.RunCmdWithStdin("cat", "test")
assert.NoError(t, err)
assert.Equal(t, "test output", string(output))
}

func TestNewRunner(t *testing.T) {
runner := NewRunner()

assert.NotNil(t, runner.Runner, "Expected Runner to be initialized, but got nil")
assert.IsType(t, &ExecCmdRunner{}, runner.Runner, "Expected Runner to be of type *ExecCmdRunner")
}

func TestExecCmdRunner_RunCmd(t *testing.T) {
runner := &ExecCmdRunner{}
output, err := runner.RunCmd("echo", "test")
assert.NoError(t, err)
assert.Equal(t, "test\n", string(output))
}

func TestExecCmdRunner_RunCmdWithStdin(t *testing.T) {
runner := &ExecCmdRunner{}
output, err := runner.RunCmdWithStdin("cat", "test")
assert.NoError(t, err)
assert.Equal(t, "test", string(output))
}
14 changes: 13 additions & 1 deletion pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package utils

import "os"

func FileExists(filename string) bool {
func FileExists(fs FileSystem, filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
Expand All @@ -16,3 +16,15 @@ func BoolToString(b bool) string {
}
return "false"
}

// FileSystem interface for os.Stat
type FileSystem interface {
Stat(name string) (os.FileInfo, error)
}

// OSFileSystem is a concrete implementation of FileSystem using os package
type OSFileSystem struct{}

func (OSFileSystem) Stat(name string) (os.FileInfo, error) {
return os.Stat(name)
}
19 changes: 19 additions & 0 deletions pkg/utils/utils_mocks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package utils

import "os"

// MockFileSystem is a mock implementation of FileSystem for testing
type MockFileSystem struct {
FileExists bool
Err error
}

func (m MockFileSystem) Stat(name string) (os.FileInfo, error) {
if m.Err != nil {
return nil, m.Err
}
if m.FileExists {
return nil, nil
}
return nil, os.ErrNotExist
}
8 changes: 6 additions & 2 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,24 @@ import (

func TestFileExists(t *testing.T) {
// Create a temporary file for testing
fs := MockFileSystem{
FileExists: true,
Err: nil,
}
tempFile, err := os.CreateTemp("", "test")
assert.NoError(t, err, "Failed to create temp file")

defer os.Remove(tempFile.Name())
tempFile.Close()

// Test that FileExists returns true for an existing file
assert.True(t, FileExists(tempFile.Name()), "Expected file to exist")
assert.True(t, FileExists(fs, tempFile.Name()), "Expected file to exist")

// Delete the temporary file
os.Remove(tempFile.Name())

// Test that FileExists returns false for a non-existing file
assert.False(t, FileExists(tempFile.Name()), "Expected file to not exist")
assert.False(t, FileExists(fs, tempFile.Name()), "Expected file to not exist")
}

func TestBoolToString(t *testing.T) {
Expand Down
12 changes: 11 additions & 1 deletion tables/fileline/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")

go_library(
name = "fileline",
Expand All @@ -10,3 +10,13 @@ go_library(
"@com_github_osquery_osquery_go//plugin/table",
],
)

go_test(
name = "fileline_test",
srcs = ["file_line_test.go"],
embed = [":fileline"],
deps = [
"//pkg/utils",
"@com_github_stretchr_testify//assert",
],
)
15 changes: 8 additions & 7 deletions tables/fileline/file_line.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ func FileLineGenerate(ctx context.Context, queryContext table.QueryContext) ([]m
}
}
var results []map[string]string
output, err := processFile(path, wildcard)
fs := utils.OSFileSystem{}
output, err := processFile(path, wildcard, fs)
if err != nil {
return results, err
}
Expand All @@ -61,7 +62,7 @@ func FileLineGenerate(ctx context.Context, queryContext table.QueryContext) ([]m
return results, nil
}

func processFile(path string, wildcard bool) ([]FileLine, error) {
func processFile(path string, wildcard bool, fs utils.FileSystem) ([]FileLine, error) {

var output []FileLine

Expand All @@ -73,24 +74,24 @@ func processFile(path string, wildcard bool) ([]FileLine, error) {
return nil, err
}
for _, file := range files {
lines, _ := readLines(file)
lines, _ := readLines(file, fs)
output = append(output, lines...)

}
} else {
lines, _ := readLines(path)
lines, _ := readLines(path, fs)
output = append(output, lines...)
}

return output, nil

}

func readLines(path string) ([]FileLine, error) {
func readLines(path string, fs utils.FileSystem) ([]FileLine, error) {
var output []FileLine

if !utils.FileExists(path) {
err := errors.New("File does not exist")
if !utils.FileExists(fs, path) {
err := errors.New("file does not exist")
return nil, err
}
file, err := os.Open(path)
Expand Down
79 changes: 79 additions & 0 deletions tables/fileline/file_line_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package fileline

import (
"os"
"path/filepath"
"testing"

"github.com/macadmins/osquery-extension/pkg/utils"
"github.com/stretchr/testify/assert"
)

func TestProcessFile(t *testing.T) {
t.Run("processFile with wildcard", func(t *testing.T) {
// Create temporary files for testing
tmpFile1, err := os.CreateTemp("", "testfile1-*.txt")
assert.NoError(t, err)
defer os.Remove(tmpFile1.Name())

tmpFile2, err := os.CreateTemp("", "testfile2-*.txt")
assert.NoError(t, err)
defer os.Remove(tmpFile2.Name())

_, err = tmpFile1.WriteString("line1\nline2\n")
assert.NoError(t, err)
_, err = tmpFile2.WriteString("line3\nline4\n")
assert.NoError(t, err)

tmpFile1.Close()
tmpFile2.Close()

path := filepath.Join(filepath.Dir(tmpFile1.Name()), "testfile%-*.txt")
fs := utils.MockFileSystem{FileExists: true, Err: nil}
lines, err := processFile(path, true, fs)
assert.NoError(t, err)
assert.Len(t, lines, 4)
})

t.Run("processFile without wildcard", func(t *testing.T) {
// Create a temporary file for testing
tmpFile, err := os.CreateTemp("", "testfile-*.txt")
assert.NoError(t, err)
defer os.Remove(tmpFile.Name())

_, err = tmpFile.WriteString("line1\nline2\n")
assert.NoError(t, err)
tmpFile.Close()

fs := utils.MockFileSystem{FileExists: true, Err: nil}

lines, err := processFile(tmpFile.Name(), false, fs)
assert.NoError(t, err)
assert.Len(t, lines, 2)
})
}

func TestReadLines(t *testing.T) {
t.Run("readLines file exists", func(t *testing.T) {
// Create a temporary file for testing
tmpFile, err := os.CreateTemp("", "testfile-*.txt")
assert.NoError(t, err)
defer os.Remove(tmpFile.Name())

_, err = tmpFile.WriteString("line1\nline2\n")
assert.NoError(t, err)
tmpFile.Close()
fs := utils.MockFileSystem{FileExists: true, Err: nil}
lines, err := readLines(tmpFile.Name(), fs)
assert.NoError(t, err)
assert.Len(t, lines, 2)
})

t.Run("readLines file does not exist", func(t *testing.T) {
fs := utils.MockFileSystem{FileExists: false, Err: nil}
lines, err := readLines("nonexistentfile.txt", fs)
assert.Error(t, err)
assert.Nil(t, lines)
assert.Equal(t, "file does not exist", err.Error())
})
}
1 change: 1 addition & 0 deletions tables/mdm/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ go_test(
srcs = ["mdm_test.go"],
embed = [":mdm"],
deps = [
"//pkg/utils",
"@com_github_osquery_osquery_go//plugin/table",
"@com_github_stretchr_testify//assert",
],
Expand Down
Loading

0 comments on commit 5849855

Please sign in to comment.