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

feat: unit testcases for increasing coverage #311

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
94 changes: 94 additions & 0 deletions cmd/kubeconform/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package main

import (
"context"
"testing"

"github.com/yannh/kubeconform/pkg/validator"
)

type MockOutput struct{}

func (m *MockOutput) Write(res validator.Result) error {
return nil
}

func (m *MockOutput) Flush() error {
return nil
}

// Test generated using Keploy
func TestProcessResults_SuccessWithValidResults(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

validationResults := make(chan validator.Result, 2)
validationResults <- validator.Result{Status: validator.Valid}
validationResults <- validator.Result{Status: validator.Valid}
close(validationResults)

outputMock := &MockOutput{}
exitOnError := false

resultChan := processResults(cancel, outputMock, validationResults, exitOnError)
success := <-resultChan

if !success {
t.Errorf("Expected success to be true, got false")
}

if ctx.Err() != nil {
t.Errorf("Context should not be canceled")
}
}

// Test generated using Keploy
func TestProcessResults_FailureWithInvalidResults(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

validationResults := make(chan validator.Result, 2)
validationResults <- validator.Result{Status: validator.Valid}
validationResults <- validator.Result{Status: validator.Invalid}
close(validationResults)

outputMock := &MockOutput{}
exitOnError := false

resultChan := processResults(cancel, outputMock, validationResults, exitOnError)
success := <-resultChan

if success {
t.Errorf("Expected success to be false, got true")
}

if ctx.Err() != nil {
t.Errorf("Context should not be canceled when exitOnError is false")
}
}

// Test generated using Keploy
func TestProcessResults_CancelOnInvalidWithExitOnError(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())

validationResults := make(chan validator.Result, 2)
validationResults <- validator.Result{Status: validator.Valid}
validationResults <- validator.Result{Status: validator.Invalid}
close(validationResults)

outputMock := &MockOutput{}
exitOnError := true

resultChan := processResults(cancel, outputMock, validationResults, exitOnError)
success := <-resultChan

if success {
t.Errorf("Expected success to be false, got true")
}

select {
case <-ctx.Done():
default:
t.Errorf("Expected context to be canceled when exitOnError is true")
}
}
45 changes: 26 additions & 19 deletions pkg/output/output.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
package output

import (
"fmt"
"io"
"fmt"
"io"

"github.com/yannh/kubeconform/pkg/validator"
"github.com/yannh/kubeconform/pkg/validator"
)

type Output interface {
Write(validator.Result) error
Flush() error
Write(validator.Result) error
Flush() error
}

func New(w io.Writer, outputFormat string, printSummary, isStdin, verbose bool) (Output, error) {
switch {
case outputFormat == "json":
return jsonOutput(w, printSummary, isStdin, verbose), nil
case outputFormat == "junit":
return junitOutput(w, printSummary, isStdin, verbose), nil
case outputFormat == "pretty":
return prettyOutput(w, printSummary, isStdin, verbose), nil
case outputFormat == "tap":
return tapOutput(w, printSummary, isStdin, verbose), nil
case outputFormat == "text":
return textOutput(w, printSummary, isStdin, verbose), nil
default:
return nil, fmt.Errorf("'outputFormat' must be 'json', 'junit', 'pretty', 'tap' or 'text'")
}
switch outputFormat {
case "json":
return jsonOutput(w, printSummary, isStdin, verbose), nil
case "junit":
return junitOutput(w, printSummary, isStdin, verbose), nil
case "pretty":
return prettyOutput(w, printSummary, isStdin, verbose), nil
case "tap":
return tapOutput(w, printSummary, isStdin, verbose), nil
case "text":
return textOutput(w, printSummary, isStdin, verbose), nil
default:
return nil, fmt.Errorf("'outputFormat' must be 'json', 'junit', 'pretty', 'tap' or 'text'")
}
}

// Mock writer for testing purposes
type mockWriter struct{}

func (m *mockWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}
84 changes: 84 additions & 0 deletions pkg/output/output_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package output

import (
"testing"
)


// Test generated using Keploy
func TestNew_JSONOutput(t *testing.T) {
writer := &mockWriter{}
output, err := New(writer, "json", false, false, false)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if output == nil {
t.Fatalf("Expected a valid Output implementation, got nil")
}
}


// Test generated using Keploy
func TestNew_JUnitOutput(t *testing.T) {
writer := &mockWriter{}
output, err := New(writer, "junit", false, false, false)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if output == nil {
t.Fatalf("Expected a valid Output implementation, got nil")
}
}


// Test generated using Keploy
func TestNew_PrettyOutput(t *testing.T) {
writer := &mockWriter{}
output, err := New(writer, "pretty", false, false, false)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if output == nil {
t.Fatalf("Expected a valid Output implementation, got nil")
}
}


// Test generated using Keploy
func TestNew_UnsupportedFormat(t *testing.T) {
writer := &mockWriter{}
_, err := New(writer, "unsupported", false, false, false)
if err == nil {
t.Fatalf("Expected an error, got nil")
}
expectedError := "'outputFormat' must be 'json', 'junit', 'pretty', 'tap' or 'text'"
if err.Error() != expectedError {
t.Errorf("Expected error message '%s', got '%s'", expectedError, err.Error())
}
}


// Test generated using Keploy
func TestNew_TapOutput(t *testing.T) {
writer := &mockWriter{}
output, err := New(writer, "tap", false, false, false)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if output == nil {
t.Fatalf("Expected a valid Output implementation, got nil")
}
}


// Test generated using Keploy
func TestNew_TextOutput(t *testing.T) {
writer := &mockWriter{}
output, err := New(writer, "text", false, false, false)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if output == nil {
t.Fatalf("Expected a valid Output implementation, got nil")
}
}
96 changes: 47 additions & 49 deletions pkg/registry/local.go
Original file line number Diff line number Diff line change
@@ -1,63 +1,61 @@
package registry

import (
"errors"
"fmt"
"io"
"log"
"os"
"errors"
"fmt"
"io"
"log"
"os"
)

type LocalRegistry struct {
pathTemplate string
strict bool
debug bool
pathTemplate string
strict bool
debug bool
schemaPathFunc func(pathTemplate, resourceKind, resourceAPIVersion, k8sVersion string, strict bool) (string, error)
}

// NewLocalSchemas creates a new "registry", that will serve schemas from files, given a list of schema filenames
func newLocalRegistry(pathTemplate string, strict bool, debug bool) (*LocalRegistry, error) {
return &LocalRegistry{
pathTemplate,
strict,
debug,
}, nil
return &LocalRegistry{
pathTemplate: pathTemplate,
strict: strict,
debug: debug,
schemaPathFunc: schemaPath,
}, nil
}

// DownloadSchema retrieves the schema from a file for the resource
func (r LocalRegistry) DownloadSchema(resourceKind, resourceAPIVersion, k8sVersion string) (string, []byte, error) {
schemaFile, err := schemaPath(r.pathTemplate, resourceKind, resourceAPIVersion, k8sVersion, r.strict)
if err != nil {
return schemaFile, []byte{}, nil
}
f, err := os.Open(schemaFile)
if err != nil {
if os.IsNotExist(err) {
msg := fmt.Sprintf("could not open file %s", schemaFile)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, newNotFoundError(errors.New(msg))
}
schemaFile, err := r.schemaPathFunc(r.pathTemplate, resourceKind, resourceAPIVersion, k8sVersion, r.strict)
if err != nil {
return schemaFile, []byte{}, nil
}
f, err := os.Open(schemaFile)
if err != nil {
if os.IsNotExist(err) {
msg := fmt.Sprintf("could not open file %s", schemaFile)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, newNotFoundError(errors.New(msg))
}

msg := fmt.Sprintf("failed to open schema at %s: %s", schemaFile, err)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, errors.New(msg)
}

defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
msg := fmt.Sprintf("failed to read schema at %s: %s", schemaFile, err)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, err
}

if r.debug {
log.Printf("using schema found at %s", schemaFile)
}
return schemaFile, content, nil
msg := fmt.Sprintf("failed to open schema at %s: %s", schemaFile, err)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, errors.New(msg)
}
defer f.Close()
content, err := io.ReadAll(f)
if err != nil {
msg := fmt.Sprintf("failed to read schema at %s: %s", schemaFile, err)
if r.debug {
log.Print(msg)
}
return schemaFile, nil, err
}
if r.debug {
log.Printf("using schema found at %s", schemaFile)
}
return schemaFile, content, nil
}
Loading