From 1fe33e3cb20295b5120f82b02b0a9ab4ad303cc0 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Tue, 12 Nov 2019 09:48:38 -0800 Subject: [PATCH] math/big: ensure correct test input There is a (theoretical, but possible) chance that the random number values a, b used for TestDiv are 0 or 1, in which case the test would fail. This CL makes sure that a >= 1 and b >= 2 at all times. Fixes #35523. Change-Id: I6451feb94241249516a821cd0066e95a0c65b0ed Reviewed-on: https://go-review.googlesource.com/c/go/+/206818 Run-TryBot: Robert Griesemer Reviewed-by: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- src/math/big/nat_test.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/math/big/nat_test.go b/src/math/big/nat_test.go index da34e95c1f..cbbaf02771 100644 --- a/src/math/big/nat_test.go +++ b/src/math/big/nat_test.go @@ -192,10 +192,22 @@ func TestMulUnbalanced(t *testing.T) { } } +// rndNat returns a random nat value >= 0 of (usually) n words in length. +// In extremely unlikely cases it may be smaller than n words if the top- +// most words are 0. func rndNat(n int) nat { return nat(rndV(n)).norm() } +// rndNat1 is like rndNat but the result is guaranteed to be > 0. +func rndNat1(n int) nat { + x := nat(rndV(n)).norm() + if len(x) == 0 { + x.setWord(1) + } + return x +} + func BenchmarkMul(b *testing.B) { mulx := rndNat(1e4) muly := rndNat(1e4) @@ -747,18 +759,22 @@ func TestNatDiv(t *testing.T) { } for _, i := range sizes { for _, j := range sizes { - a := rndNat(i) - b := rndNat(j) + a := rndNat1(i) + b := rndNat1(j) + // the test requires b >= 2 + if len(b) == 1 && b[0] == 1 { + b[0] = 2 + } x := nat(nil).mul(a, b) addVW(x, x, 1) var q, r nat q, r = q.div(r, x, b) if q.cmp(a) != 0 { - t.Fatal("wrong quotient", i, j) + t.Fatalf("wrong quotient: got %s; want %s for %s/%s", q.utoa(10), a.utoa(10), x.utoa(10), b.utoa(10)) } if len(r) != 1 || r[0] != 1 { - t.Fatal("wrong remainder") + t.Fatalf("wrong remainder: got %s; want 1 for %s/%s", r.utoa(10), x.utoa(10), b.utoa(10)) } } } -- 2.50.0