1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
package gencsr
import (
"encoding/json"
"errors"
"io"
"os"
"testing"
"github.com/cloudflare/cfssl/cli"
)
const (
testKeyFile = "testdata/test-key.pem"
testCAKeyFile = "../testdata/ca-key.pem"
testCACertFile = "../testdata/ca.pem"
)
type stdoutRedirect struct {
r *os.File
w *os.File
saved *os.File
}
func newStdoutRedirect() (*stdoutRedirect, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
pipe := &stdoutRedirect{r, w, os.Stdout}
os.Stdout = pipe.w
return pipe, nil
}
func (pipe *stdoutRedirect) readAll() ([]byte, error) {
pipe.w.Close()
os.Stdout = pipe.saved
return io.ReadAll(pipe.r)
}
func checkResponse(out []byte) error {
var response map[string]interface{}
if err := json.Unmarshal(out, &response); err != nil {
return err
}
if response["key"] == nil {
return errors.New("no key is outputted")
}
if response["csr"] == nil {
return errors.New("no csr is outputted")
}
return nil
}
func TestGencsr(t *testing.T) {
var pipe *stdoutRedirect
var out []byte
var err error
if pipe, err = newStdoutRedirect(); err != nil {
t.Fatal(err)
}
if err := gencsrMain([]string{"testdata/csr.json"}, cli.Config{KeyFile: testKeyFile}); err != nil {
t.Fatal(err)
}
if out, err = pipe.readAll(); err != nil {
t.Fatal(err)
}
if err := checkResponse(out); err != nil {
t.Fatal(err)
}
}
func TestGencsrFromCert(t *testing.T) {
var pipe *stdoutRedirect
var out []byte
var err error
if pipe, err = newStdoutRedirect(); err != nil {
t.Fatal(err)
}
if err := gencsrMain([]string{}, cli.Config{KeyFile: testCAKeyFile, CertFile: testCACertFile}); err != nil {
t.Fatal(err)
}
if out, err = pipe.readAll(); err != nil {
t.Fatal(err)
}
if err := checkResponse(out); err != nil {
t.Fatal(err)
}
}
func TestGencsrError(t *testing.T) {
if err := gencsrMain([]string{"testdata/csr.json"}, cli.Config{}); err == nil {
t.Fatal("should have erred.")
}
}
|