Skip to content

Commit

Permalink
Increased test coverage for util/random
Browse files Browse the repository at this point in the history
  • Loading branch information
matteosz committed Feb 15, 2024
1 parent 5fad44c commit 2d94d52
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions util/random/rand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package random
import (
"bytes"
"crypto/rand"
"math/big"
"strings"
"testing"
)
Expand Down Expand Up @@ -84,3 +85,59 @@ func TestIncorrectSize(t *testing.T) {
dst := make([]byte, size+1)
cipher.XORKeyStream(dst, src)
}

func TestBits(t *testing.T) {
testCases := []struct {
bitlen uint // input bit length
exact bool // whether the exact bit length should be enforced
}{
{bitlen: 128, exact: false},
{bitlen: 256, exact: true},
{bitlen: 512, exact: false},
{bitlen: 1024, exact: true},
}

for _, tc := range testCases {
r := strings.NewReader("some io.Reader stream to be used for testing")
cipher := New(r, rand.Reader)

bigIntBytes := Bits(tc.bitlen, tc.exact, cipher)
bigInt := new(big.Int).SetBytes(bigIntBytes)

// Check if the bit length matches the expected length
expectedBitLen := tc.bitlen
if tc.exact && uint(bigInt.BitLen()) != expectedBitLen {
t.Errorf("Generated BigInt with exact bits doesn't match the expected bit length: got %d, expected %d", bigInt.BitLen(), expectedBitLen)
} else if !tc.exact && uint(bigInt.BitLen()) > expectedBitLen {
t.Errorf("Generated BigInt with more bits than maximum bit length: got %d, expected at most %d", bigInt.BitLen(), expectedBitLen)
}
}
}

func TestInt(t *testing.T) {
testCases := []struct {
modulusBitLen uint // Bit length of the modulus
}{
{128},
{256},
{512},
{1024},
}

for _, tc := range testCases {
modulus, err := rand.Prime(rand.Reader, int(tc.modulusBitLen))
if err != nil {
t.Fatalf("Failed to generate random prime: %v", err)
}

r := strings.NewReader("some io.Reader stream to be used for testing")
cipher := New(r, rand.Reader)

randomInt := Int(modulus, cipher)

// Check if the generated BigInt is less than the modulus
if randomInt.Cmp(modulus) >= 0 {
t.Errorf("Generated BigInt %v is not less than the modulus %v", randomInt, modulus)
}
}
}

0 comments on commit 2d94d52

Please sign in to comment.