From 441fd1338633c2aafa5b30121142ab24ee9dddcb Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Mon, 26 Jun 2017 14:32:55 -0400 Subject: [PATCH] crypto/x509: fix panic in TestEnvVars, improve style This panic happens when the test fails due to the returned number of certificates (r.certs) being less than expected by test case (tc.cns). When i == len(r.certs) in the for loop, r.certs[i] will cause an index out of range panic. Also improve readability, consistency and style of the code. Use the more common "got x, want y" pattern. See https://golang.org/s/style#useful-test-failures for reference (and grep codebase for most common occurrences). Add a comment, and remove blank line separating two blocks that are both related to verifying that len(r.certs) == len(tc.cns). This should help with readability. Remove space after colon in call to t.Fatal, since it adds spaces between its arguments. Fixes #20801. Change-Id: I40476103f1b5a0fa74b05637c250926b571c92fd Reviewed-on: https://go-review.googlesource.com/46715 Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- src/crypto/x509/root_unix_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/crypto/x509/root_unix_test.go b/src/crypto/x509/root_unix_test.go index b6659d9733..3a997b235d 100644 --- a/src/crypto/x509/root_unix_test.go +++ b/src/crypto/x509/root_unix_test.go @@ -99,7 +99,7 @@ func TestEnvVars(t *testing.T) { r, err := loadSystemRoots() if err != nil { - t.Fatal("unexpected failure: ", err) + t.Fatal("unexpected failure:", err) } if r == nil { @@ -110,17 +110,17 @@ func TestEnvVars(t *testing.T) { t.Fatal("nil roots") } + // Verify len(r.certs) == len(tc.cns), otherwise report where the mismatch is. for i, cn := range tc.cns { - if i > len(r.certs) { + if i >= len(r.certs) { t.Errorf("missing cert %v @ %v", cn, i) } else if r.certs[i].Subject.CommonName != cn { fmt.Printf("%#v\n", r.certs[0].Subject) - t.Errorf("unexpected cert common name %q expected %q", r.certs[i].Subject.CommonName, cn) + t.Errorf("unexpected cert common name %q, want %q", r.certs[i].Subject.CommonName, cn) } } - if len(r.certs) > len(tc.cns) { - t.Errorf("expected %v certs got %v", len(tc.cns), len(r.certs)) + t.Errorf("got %v certs, which is more than %v wanted", len(r.certs), len(tc.cns)) } }) }