aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_matching.py
blob: ca94c2acebb771f523f549c954a56947ff41e1de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import collections
import logging
import warnings

import elasticsearch
import pytest
import requests
from fatcat_openapi_client import ReleaseEntity, ReleaseContrib

from fuzzycat.entities import entity_from_dict, entity_from_json
from fuzzycat.matching import anything_to_entity, match_release_fuzzy, FuzzyReleaseMatcher

warnings.filterwarnings(
    "ignore")  # InsecureRequestWarning: Unverified HTTPS request is being made to host ...

from fuzzycat.matching import anything_to_entity, match_release_fuzzy
from fuzzycat.config import settings
from fatcat_openapi_client import ReleaseEntity
import pytest
import elasticsearch
import logging
import yaml
import glob
import json

logger = logging.getLogger('test_matching')
logger.setLevel(logging.DEBUG)

# ad-hoc override search server with: FUZZYCAT_FATCAT_SEARCH_URL=localhost:9200 pytest ...
FATCAT_SEARCH_URL = settings.get("FATCAT_SEARCH_URL", "https://search.fatcat.wiki:443")


def is_not_reachable(url, timeout=3):
    return not is_reachable(url)


def is_reachable(url, timeout=3):
    """
    Return true, if URL is reachable and returns HTTP 200.
    """
    try:
        return requests.get(url, verify=False, timeout=timeout).ok
    except Exception:
        return False


def yaml_to_cases(klass,
                  files="tests/files/fuzzy_release_match_release_exact_title_exact_contrib/*.yaml"):
    """
    Turn yaml files into a collection of named tuple test cases. The glob is
    relative to the project root (i.e. where you usually run `pytest` from).
    """
    cases = []
    for path in glob.glob(files):
        with open(path) as f:
            doc = yaml.load(f, Loader=yaml.Loader)
            cases.append(klass(**doc))
    return cases


@pytest.fixture
def es_client():
    return elasticsearch.Elasticsearch([FATCAT_SEARCH_URL])


# @pytest.mark.skipif(
#     is_not_reachable(FATCAT_SEARCH_URL),
#     reason="{} not reachable, use e.g. FUZZYCAT_FATCAT_SEARCH_URL=localhost:9200 to override".
#     format(FATCAT_SEARCH_URL))
def test_match_release_fuzzy(es_client, caplog):
    """
    This test is tied to the current index contents, so if that changes, this
    test may fail as well.

    Note: Deprecated. We want to get rid of this.
    """
    cases = (
        ("wtv64ahbdzgwnan7rllwr3nurm", 1),
        ("eqcgtpav3na5jh56o5vjsvb4ei", 1),
    )
    for i, (ident, count) in enumerate(cases):
        entity = anything_to_entity(ident, ReleaseEntity)

        result = match_release_fuzzy(entity, es=es_client)
        logger.info("[{}] given {}, found {}".format(i, entity.title, len(result)))
        assert len(result) == count

    # Partial data.
    cases = (
        ({
            "title": "digital libraries",
            "ext_ids": {}
        }, 5),
        ({
            "title": "unlikelytitle",
            "ext_ids": {}
        }, 0),
        ({
            "title": "Imminent dystopia",
            "ext_ids": {}
        }, 2),
        ({
            "title": "",
            "contribs": [{
                "raw_name": "Aristoteles"
            }],
            "ext_ids": {}
        }, 5),
        # ({
        #     "title": "Letter",
        #     "contribs": [{"raw_name": "Claudel"}],
        #     "ext_ids": {}
        # }, 1),
        # ({
        #     "title": "The Future of Digital Scholarship",
        #     "contribs": [{
        #         "raw_name": "Costantino Thanos"
        #     }],
        #     "ext_ids": {}
        # }, 5),
    )
    for i, (doc, count) in enumerate(cases):
        entity = entity_from_dict(doc, ReleaseEntity)
        result = match_release_fuzzy(entity, es=es_client)
        with caplog.at_level(logging.INFO):
            logging.info("[{}] given title '{}', found {}, {}".format(i, entity.title, len(result),
                                                                      [v.title for v in result]))
        assert len(result) == count, doc


def test_matcher_match_release(es_client, caplog):
    cases = (
        ("wtv64ahbdzgwnan7rllwr3nurm", 1),
        ("eqcgtpav3na5jh56o5vjsvb4ei", 1),
    )
    matcher = FuzzyReleaseMatcher(es=es_client, size=5)
    for i, (ident, count) in enumerate(cases):
        entity = anything_to_entity(ident, ReleaseEntity)
        result = matcher.match(entity)
        logger.info("[{}] given {}, found {}".format(i, entity.title, len(result)))
        assert len(result) == count

    # Partial data.
    cases = (
        ({
            "title": "digital libraries",
            "ext_ids": {}
        }, 5),
        ({
            "title": "unlikelytitle",
            "ext_ids": {}
        }, 0),
        ({
            "title": "Imminent dystopia",
            "ext_ids": {}
        }, 5),
        ({
            "title": "",
            "contribs": [{
                "raw_name": "Aristoteles"
            }],
            "ext_ids": {}
        }, 5),
        # ({
        #     "title": "Letter",
        #     "contribs": [{"raw_name": "Claudel"}],
        #     "ext_ids": {}
        # }, 1),
        # ({
        #     "title": "The Future of Digital Scholarship",
        #     "contribs": [{
        #         "raw_name": "Costantino Thanos"
        #     }],
        #     "ext_ids": {}
        # }, 5),
    )
    for i, (doc, count) in enumerate(cases):
        entity = entity_from_dict(doc, ReleaseEntity)
        result = matcher.match(entity)
        with caplog.at_level(logging.INFO):
            logging.info("[{}] given title '{}', found {}, {}".format(i, entity.title, len(result),
                                                                      [v.title for v in result]))
        assert len(result) == count, doc


def test_fuzzy_release_matcher_match_release_by_id(es_client, caplog):
    matcher = FuzzyReleaseMatcher(es=es_client)
    cases = (
        ("wtv64ahbdzgwnan7rllwr3nurm", 1),
        ("eqcgtpav3na5jh56o5vjsvb4ei", 1),
    )
    for i, (ident, count) in enumerate(cases):
        entity = anything_to_entity(ident, ReleaseEntity)
        result = matcher.match_release_by_id(entity)
        assert len(result) == count


def test_fuzzy_release_match_release_exact_title_exact_contrib(es_client, caplog):
    matcher = FuzzyReleaseMatcher(es=es_client)
    Case = collections.namedtuple("Case", "title date input expected")
    cases = yaml_to_cases(
        Case, "tests/files/fuzzy_release_match_release_exact_title_exact_contrib/*.yaml")
    for i, c in enumerate(cases):
        entity = entity_from_json(c.input, ReleaseEntity)
        result = matcher.match_release_exact_title_exact_contrib(entity)
        assert len(result) == c.expected, "[{}] {}".format(c.title, c.input)


def test_fuzzy_release_match_release_exact_title_partial_contrib(es_client, caplog):
    matcher = FuzzyReleaseMatcher(es=es_client)
    Case = collections.namedtuple("Case", "title date input jaccard_index_threshold expected")
    cases = yaml_to_cases(
        Case, "tests/files/fuzzy_release_match_release_exact_title_partial_contrib/*.yaml")
    for i, c in enumerate(cases):
        entity = entity_from_json(c.input, ReleaseEntity)
        result = matcher.match_release_exact_title_partial_contrib(entity)
        assert len(result) == c.expected, "[{}] {}".format(c.title, c.input)