v0.2.2: Minor fixes and testing

- Replaced log.Fatal() with log.Fatalf() since we provide %v
- Added proper testing and benchmarking
This commit is contained in:
Winni Neessen 2021-03-20 18:31:32 +01:00
parent a8514f6c0e
commit 2a970b9bce
Signed by: wneessen
GPG key ID: 385AC9889632126E
2 changed files with 57 additions and 4 deletions

4
apg.go
View file

@ -12,7 +12,7 @@ import (
// Constants
const DefaultPwLenght int = 20
const VersionString string = "0.2.1"
const VersionString string = "0.2.2"
const PwLowerCharsHuman string = "abcdefghjkmnpqrstuvwxyz"
const PwUpperCharsHuman string = "ABCDEFGHJKMNPQRSTUVWXYZ"
const PwLowerChars string = "abcdefghijklmnopqrstuvwxyz"
@ -131,7 +131,7 @@ func getRandNum(maxNum int) int {
maxNumBigInt := big.NewInt(int64(maxNum))
randNum64, err := rand.Int(rand.Reader, maxNumBigInt)
if err != nil {
log.Fatal("An error occured generating random number: %v", err)
log.Fatalf("An error occured generating random number: %v", err)
}
randNum := int(randNum64.Int64())
return randNum

View file

@ -2,6 +2,59 @@ package main
import "testing"
func TestSkipForNow(t *testing.T) {
t.Logf("All good.")
// Make sure the flags are initalized
var _ = func() bool {
testing.Init()
return true
}()
// Test getRandNum with max 1000
func TestGetRandNumMax1000(t *testing.T) {
randNum := getRandNum(1000)
if randNum > 1000 {
t.Errorf("Generated random number between 0 and 1000 is too big: %d", randNum)
}
if randNum < 0 {
t.Errorf("Generated random number between 0 and 1000 is too small: %d", randNum)
}
}
// Test getRandNum with max 1
func TestGetRandNumMax1(t *testing.T) {
randNum := getRandNum(1)
if randNum > 1 {
t.Errorf("Generated random number between 0 and 1 is too big: %d", randNum)
}
if randNum < 0 {
t.Errorf("Generated random number between 0 and 1 is too small: %d", randNum)
}
}
// Test getRandChar
func TestGetRandChar(t *testing.T) {
charRange := "ABC"
randChar := getRandChar(&charRange, 1)
if randChar != "A" && randChar != "B" && randChar != "C" {
t.Errorf("Random character generation failed. Expected A, B or C but got: %v", randChar)
}
randChar = getRandChar(&charRange, 1000)
if len(randChar) != 1000 {
t.Errorf("Generated random characters with 1000 chars returned wrong amount of chars: %v", len(randChar))
}
}
// Benchmark: Random number generation
func BenchmarkGetRandNum(b *testing.B) {
for i := 0; i < b.N; i++ {
getRandNum(100000)
}
}
// Benchmark: Random char generation
func BenchmarkGetRandChar(b *testing.B) {
charRange := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\"#/!\\$%&+-*.,?=()[]{}:;~^|"
for i := 0; i < b.N; i++ {
getRandChar(&charRange, 20)
}
}