Skip to content

Commit

Permalink
Merge pull request #1777 from andyzhangx/main-test
Browse files Browse the repository at this point in the history
test: add unit test for main function
  • Loading branch information
andyzhangx authored Dec 24, 2024
2 parents c7e463e + 715d92c commit 149b147
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 5 deletions.
14 changes: 9 additions & 5 deletions pkg/blobplugin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ func init() {
driverOptions.AddFlags()
}

// exit is a separate function to handle program termination
var exit = func(code int) {
os.Exit(code)
}

func main() {
klog.InitFlags(nil)
_ = flag.Set("logtostderr", "true")
Expand All @@ -61,12 +66,11 @@ func main() {
klog.Fatalln(err)
}
fmt.Println(info) // nolint
os.Exit(0)
} else {
exportMetrics()
handle()
}

exportMetrics()
handle()
os.Exit(0)
exit(0)
}

func handle() {
Expand Down
82 changes: 82 additions & 0 deletions pkg/blobplugin/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"fmt"
"net"
"os"
"reflect"
"testing"
)

func TestMain(t *testing.T) {
// Set the version flag to true
os.Args = []string{"cmd", "-version"}

// Capture stdout
old := os.Stdout
_, w, _ := os.Pipe()
os.Stdout = w

// Replace exit function with mock function
var exitCode int
exit = func(code int) {
exitCode = code
}

// Call main function
main()

// Restore stdout
w.Close()
os.Stdout = old
exit = func(code int) {
os.Exit(code)
}

if exitCode != 0 {
t.Errorf("Expected exit code 0, but got %d", exitCode)
}
}

func TestTrapClosedConnErr(t *testing.T) {
tests := []struct {
err error
expectedErr error
}{
{
err: net.ErrClosed,
expectedErr: nil,
},
{
err: nil,
expectedErr: nil,
},
{
err: fmt.Errorf("some error"),
expectedErr: fmt.Errorf("some error"),
},
}

for _, test := range tests {
err := trapClosedConnErr(test.err)
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("Expected error %v, but got %v", test.expectedErr, err)
}
}
}

0 comments on commit 149b147

Please sign in to comment.