Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
ph4r05 committed May 23, 2024
1 parent 6c3868f commit 01c069e
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions cmd/keymaster/main_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package main

import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
Expand Down Expand Up @@ -277,11 +280,50 @@ func TestInsertSSHCertIntoAgentORWriteToFilesystem(t *testing.T) {
}

func TestMainPrintVersion(t *testing.T) {
// Backup and defer restore of original os.Stdout and os.Args
Version = "1.0.0-test"
origStdout := os.Stdout
origArgs := os.Args
defer func() {
os.Stdout = origStdout
os.Args = origArgs
}()

// Create a pipe to capture the output
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("failed to create pipe: %v", err)
}
os.Stdout = w

// Set up the command-line arguments to include the -version flag
os.Args = []string{"cmd", "-version"}

// Reset the command-line flags for testing
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
printVersion = flag.Bool("version", false, "Print version and exit")

// Call the main function in a separate goroutine
done := make(chan struct{})
go func() {
main()
w.Close()
close(done)
}()

// Read the captured output
var buf bytes.Buffer
_, err = io.Copy(&buf, r)
if err != nil {
t.Fatalf("failed to read captured output: %v", err)
}

// Wait for the goroutine to finish
<-done

// Check the output
expectedOutput := "1.0.0-test\n"
if buf.String() != expectedOutput {
t.Errorf("expected %q, got %q", expectedOutput, buf.String())
}
}

0 comments on commit 01c069e

Please sign in to comment.