From 9244d7f0c4871e14792d169fef265fa6c342c162 Mon Sep 17 00:00:00 2001 From: Mark van der Velden Date: Wed, 11 Jul 2018 13:55:34 +0200 Subject: [PATCH] Adding tests around the tolerane --- finder/find.go | 8 ++++++-- finder/find_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/finder/find.go b/finder/find.go index eb6ad67..6259daa 100644 --- a/finder/find.go +++ b/finder/find.go @@ -89,12 +89,16 @@ func (t Finder) FindCtx(ctx context.Context, input string) (string, float64, boo return best, hs, false } -// meetsLengthTolerance checks if the input meets the length tolerance criteria +// meetsLengthTolerance checks if the input meets the length tolerance criteria. The percentage is based on the input func meetsLengthTolerance(t float64, input, reference string) bool { - if t == 0 { + if t <= 0 { return true } + if t > 1 { + return false + } + inputLen := len(input) refLen := len(reference) threshold := int(math.Ceil(float64(inputLen) * t)) diff --git a/finder/find_test.go b/finder/find_test.go index 3b5da71..e59653f 100644 --- a/finder/find_test.go +++ b/finder/find_test.go @@ -94,6 +94,34 @@ func TestContextCancel(t *testing.T) { } } +func TestMeetsLengthTolerance(t *testing.T) { + testData := []struct { + Expect bool + Input string + Reference string + Tolerance float64 + }{ + {Expect: true, Input: "foo", Reference: "bar", Tolerance: -1}, + {Expect: true, Input: "foo", Reference: "bar", Tolerance: 0}, + {Expect: true, Input: "foo", Reference: "bar", Tolerance: 1}, + {Expect: false, Input: "foo", Reference: "bar", Tolerance: 2}, // erroneous situation + + {Expect: true, Input: "smooth", Reference: "smoothie", Tolerance: 0.2}, + {Expect: false, Input: "smooth", Reference: "smoothie", Tolerance: 0.1}, + + {Expect: true, Input: "abc", Reference: "defghi", Tolerance: 0.9}, + {Expect: true, Input: "abc", Reference: "defg", Tolerance: 0.5}, + } + + for _, td := range testData { + r := meetsLengthTolerance(td.Tolerance, td.Input, td.Reference) + if r != td.Expect { + t.Errorf("Expected the tolerance to be %t\n%+v", td.Expect, td) + } + } + +} + func BenchmarkSliceOrMap(b *testing.B) { size := 50 var hashMap = make(map[int]int, size)