From 2af756e872b951eaec9ad7063730475cce727ca5 Mon Sep 17 00:00:00 2001 From: Kevin Schoonover Date: Tue, 16 Apr 2024 22:53:48 -0700 Subject: [PATCH] add tests --- dependency/vault_pki_test.go | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/dependency/vault_pki_test.go b/dependency/vault_pki_test.go index ece8a7490..5479a5868 100644 --- a/dependency/vault_pki_test.go +++ b/dependency/vault_pki_test.go @@ -7,10 +7,14 @@ package dependency import ( "bytes" + "crypto/x509" + "crypto/x509/pkix" "errors" + "fmt" "os" "strings" "testing" + "time" "github.com/hashicorp/consul-template/renderer" "github.com/hashicorp/vault/api" @@ -53,6 +57,46 @@ func Test_VaultPKI_notGoodFor(t *testing.T) { } } +func Test_VaulkPKI_goodFor(t *testing.T) { + tests := map[string]struct { + CertificateTTL time.Duration + }{ + "one minute": {CertificateTTL: time.Minute}, + "one hour": {CertificateTTL: time.Hour}, + "one day": {CertificateTTL: time.Hour * 24}, + "one week": {CertificateTTL: time.Hour * 24 * 7}, + } + for name, tc := range tests { + NotBefore := time.Now() + NotAfter := time.Now().Add(tc.CertificateTTL) + certificate := x509.Certificate{ + Subject: pkix.Name{ + Organization: []string{"Acme Co"}, + }, + NotBefore: NotBefore, + NotAfter: NotAfter, + } + + dur, ok := goodFor(&certificate) + if ok == false { + t.Errorf("%v: should be true", name) + } + + ratio := dur.Seconds() / (NotAfter.Sub(NotBefore).Seconds()) + // allow for a .01 epsilon for floating point comparison to prevent flakey tests + if ratio < .86 || ratio > .94 { + fmt.Println(ratio) + t.Errorf( + "%v: should be between 87 and 93, but was %.2f. NotBefore: %s, NotAfter: %s", + name, + ratio, + NotBefore, + NotAfter, + ) + } + } +} + func Test_VaultPKI_pemsCert(t *testing.T) { // tests w/ valid pems, and having it hidden behind various things want := strings.TrimRight(strings.TrimSpace(validCert), "\n")