|
| 1 | +import pytest |
| 2 | +from simstring_rust.database import HashDb |
| 3 | +from simstring_rust.extractors import CharacterNgrams |
| 4 | +from simstring_rust.measures import Dice, Jaccard, Overlap, ExactMatch |
| 5 | +from simstring_rust.searcher import Searcher |
| 6 | + |
| 7 | +class TestMeasures: |
| 8 | + def setup_method(self): |
| 9 | + self.extractor = CharacterNgrams(n=2, endmarker="$") |
| 10 | + self.db = HashDb(self.extractor) |
| 11 | + self.db.insert("foo") |
| 12 | + self.db.insert("bar") |
| 13 | + self.db.insert("fooo") |
| 14 | + |
| 15 | + def test_dice(self): |
| 16 | + searcher = Searcher(self.db, Dice()) |
| 17 | + results = searcher.ranked_search("foo", 0.8) |
| 18 | + # "foo" (4 features) vs "foo" (4 features) -> 2*4 / (4+4) = 1.0 |
| 19 | + # "foo" vs "fooo" (5 features) -> intersect is 4 ($f, fo, oo, o$) -> 2*4 / (4+5) = 8/9 ~= 0.88 |
| 20 | + assert len(results) == 2 |
| 21 | + assert results[0][0] == "foo" |
| 22 | + assert results[0][1] == pytest.approx(1.0) |
| 23 | + assert results[1][0] == "fooo" |
| 24 | + assert results[1][1] == pytest.approx(0.88888888) |
| 25 | + |
| 26 | + def test_jaccard(self): |
| 27 | + searcher = Searcher(self.db, Jaccard()) |
| 28 | + results = searcher.ranked_search("foo", 0.8) |
| 29 | + # "foo" vs "foo" -> 1.0 |
| 30 | + # "foo" vs "fooo" -> 4 / 5 = 0.8 |
| 31 | + assert len(results) == 2 |
| 32 | + assert results[0][0] == "foo" |
| 33 | + assert results[0][1] == pytest.approx(1.0) |
| 34 | + assert results[1][0] == "fooo" |
| 35 | + assert results[1][1] == pytest.approx(0.8) |
| 36 | + |
| 37 | + def test_overlap(self): |
| 38 | + searcher = Searcher(self.db, Overlap()) |
| 39 | + results = searcher.ranked_search("foo", 0.8) |
| 40 | + |
| 41 | + assert len(results) == 2 |
| 42 | + assert results[0][0] == "foo" |
| 43 | + assert results[0][1] == pytest.approx(1.0) |
| 44 | + assert results[1][0] == "fooo" |
| 45 | + assert results[1][1] == pytest.approx(1.0) |
| 46 | + |
| 47 | + def test_exact_match(self): |
| 48 | + searcher = Searcher(self.db, ExactMatch()) |
| 49 | + results = searcher.ranked_search("foo", 1.0) |
| 50 | + assert len(results) == 1 |
| 51 | + assert results[0][0] == "foo" |
| 52 | + assert results[0][1] == pytest.approx(1.0) |
| 53 | + |
| 54 | + results_partial = searcher.ranked_search("foo", 0.5) |
| 55 | + assert len(results_partial) == 1 |
| 56 | + assert results_partial[0][0] == "foo" |
0 commit comments