summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDustin Sallings <dustin@spy.net>2018-04-21 11:26:05 -0700
committerDustin Sallings <dustin@spy.net>2018-04-21 11:29:45 -0700
commit02af3965c54e8cacf948b97fef38925c4120652c (patch)
tree6ca9ae447e4bb52953ea9f2602a4736440dc1a4e
parent41f808901d8eb7d8d4e70a79b62b0d1b504e3f9a (diff)
downloadgo-humanize-02af3965c54e8cacf948b97fef38925c4120652c.tar.xz
Added a quickcheck test for stripTrailingDigits
The coverage report showed that the existing tests didn't cover one of the paths, so I made a simple property test to cover the rest. This is slightly awkward in go, but the bulk of the test is generating random input with some number of digits on the left, then some number of digits on the right of a decimal point. If there are no digits on the right, it doesn't add the decimal point. Then it emits a reasonably ranged digit input.
-rw-r--r--ftoa_test.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/ftoa_test.go b/ftoa_test.go
index e5076c4..45ef9c5 100644
--- a/ftoa_test.go
+++ b/ftoa_test.go
@@ -2,9 +2,13 @@ package humanize
import (
"fmt"
+ "math/rand"
+ "reflect"
"regexp"
"strconv"
+ "strings"
"testing"
+ "testing/quick"
)
func TestFtoa(t *testing.T) {
@@ -26,6 +30,61 @@ func TestFtoaWithDigits(t *testing.T) {
}.validate(t)
}
+func TestStripTrailingDigits(t *testing.T) {
+ err := quick.Check(func(s string, digits int) bool {
+ stripped := stripTrailingDigits(s, digits)
+
+ // A stripped string will always be a prefix of its original string
+ if !strings.HasPrefix(s, stripped) {
+ return false
+ }
+
+ if strings.ContainsRune(s, '.') {
+ // If there is a dot, the part on the left of the dot will never change
+ a := strings.Split(s, ".")
+ b := strings.Split(stripped, ".")
+ if a[0] != b[0] {
+ return false
+ }
+ } else {
+ // If there's no dot in the input, the output will always be the same as the input.
+ if stripped != s {
+ return false
+ }
+ }
+
+ return true
+ }, &quick.Config{
+ MaxCount: 10000,
+ Values: func(v []reflect.Value, r *rand.Rand) {
+ rdigs := func(n int) string {
+ digs := []rune{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
+ var rv []rune
+ for i := 0; i < n; i++ {
+ rv = append(rv, digs[r.Intn(len(digs))])
+ }
+ return string(rv)
+ }
+
+ ls := r.Intn(20)
+ rs := r.Intn(20)
+ jc := "."
+ if rs == 0 {
+ jc = ""
+ }
+ s := rdigs(ls) + jc + rdigs(rs)
+ digits := r.Intn(len(s) + 1)
+
+ v[0] = reflect.ValueOf(s)
+ v[1] = reflect.ValueOf(digits)
+ },
+ })
+
+ if err != nil {
+ t.Error(err)
+ }
+}
+
func BenchmarkFtoaRegexTrailing(b *testing.B) {
trailingZerosRegex := regexp.MustCompile(`\.?0+$`)