Skip to content

Commit

Permalink
Merge pull request #894 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 5620c63 + d1fdafa commit 9c7e069
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 8 deletions.
21 changes: 13 additions & 8 deletions cmd/smbplugin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ var (
removeArchivedVolumePath = flag.Bool("remove-archived-volume-path", true, "remove archived volume path in DeleteVolume")
)

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

func main() {
flag.Parse()
if *ver {
Expand All @@ -59,15 +64,15 @@ func main() {
klog.Fatalln(err)
}
fmt.Println(info) // nolint
os.Exit(0)
}
if *nodeID == "" {
// nodeid is not needed in controller component
klog.Warning("nodeid is empty")
} else {
if *nodeID == "" {
// nodeid is not needed in controller component
klog.Warning("nodeid is empty")
}
exportMetrics()
handle()
}
exportMetrics()
handle()
os.Exit(0)
exit(0)
}

func handle() {
Expand Down
82 changes: 82 additions & 0 deletions cmd/smbplugin/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", "-ver"}

// 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 9c7e069

Please sign in to comment.