Skip to content

Commit

Permalink
Add unit tests for inspectCertificateRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
dopey committed Apr 22, 2024
1 parent a99b3eb commit 6a48314
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 6 deletions.
20 changes: 14 additions & 6 deletions command/certificate/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,21 +310,29 @@ func inspectCertificateRequest(ctx *cli.Context, csr *x509.CertificateRequest, w
return err
}
}
fmt.Print(text)
fmt.Fprint(w, text)
return nil
case "json":
zcsr, err := zx509.ParseCertificateRequest(csr.Raw)
if err != nil {
return errors.WithStack(err)
}
b, err := json.MarshalIndent(struct {
*zx509.CertificateRequest
}{zcsr}, "", " ")
if err != nil {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
if err := enc.Encode(zcsr); err != nil {
return errors.WithStack(err)
}
os.Stdout.Write(b)
return nil
/*
b, err := json.MarshalIndent(struct {
*zx509.CertificateRequest
}{zcsr}, "", " ")
if err != nil {
return errors.WithStack(err)
}
os.Stdout.Write(b)
return nil
*/
case "pem":
err := pem.Encode(w, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csr.Raw})
if err != nil {
Expand Down
58 changes: 58 additions & 0 deletions command/certificate/inspect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,61 @@ func TestInspectCertificates(t *testing.T) {
}

}

var csrPEMData = []byte(`-----BEGIN CERTIFICATE REQUEST-----
MIHmMIGNAgEAMAAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASGlyI2t5ibpcG+
hGm0JMW0or/QphyTlc4GGAccapsz4BeXkNucKpeX3nupFbbABHLcN/bjxL87Ims8
jz5sdl6xoCswKQYJKoZIhvcNAQkOMRwwGjAYBgNVHREEETAPggNmb2+CA2JhcoID
YmF6MAoGCCqGSM49BAMCA0gAMEUCIEuWM0UdEeDfvWqssxyoY4cUuv++FrmA97j+
Fbp7Kk6gAiEAuoyrBIvX28Spmeog9Jl4iBJYzceSNz8a7crRNGLTyjs=
-----END CERTIFICATE REQUEST-----
`)

func TestInspectCertificateRequest(t *testing.T) {
// This is just to get a simple CLI context
app := &cli.App{}
set := flag.NewFlagSet("contrive", 0)
_ = set.String("format", "", "")
ctx := cli.NewContext(app, set, nil)

csr, err := pemutil.ParseCertificateRequest(csrPEMData)
assert.FatalError(t, err)

type testCase struct {
format string
verify func(buf *bytes.Buffer)
}

tests := map[string]testCase{
"format text": {"text",
func(buf *bytes.Buffer) {
assert.HasPrefix(t, buf.String(), "Certificate Request:")
},
},
"format json": {"json",
func(buf *bytes.Buffer) {
var v interface{}
err := json.Unmarshal(buf.Bytes(), &v)
assert.NoError(t, err)
},
},
"format pem": {"pem",
func(buf *bytes.Buffer) {
assert.Equals(t, string(csrPEMData), buf.String())
},
},
}

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var buf bytes.Buffer
ctx.Set("format", tc.format)
err := inspectCertificateRequest(ctx, csr, &buf)
assert.NoError(t, err)
if err == nil {
tc.verify(&buf)
}
})
}

}

0 comments on commit 6a48314

Please sign in to comment.