-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_unit.py
More file actions
462 lines (378 loc) · 17.4 KB
/
test_unit.py
File metadata and controls
462 lines (378 loc) · 17.4 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
test_unit.py — Unit tests for core.py logic.
Run with: python3 -m pytest test_unit.py -v
"""
import pytest
import pandas as pd
from unittest.mock import MagicMock, patch
from core import (
similar,
_format_grade,
_classify_age,
normalise_grade,
safe_fillna,
_pick_best_match,
GetEbayPrice,
GetEbayPriceGraded,
GetEbayPriceUngraded,
SearchComicVine,
CV_CONFIDENCE_THRESHOLD,
GRADE_SCALE,
_EbayRateLimited,
)
# =============================================================================
# similar()
# =============================================================================
class TestSimilar:
def test_identical(self):
assert similar("ACTION COMICS #1", "ACTION COMICS #1") == 1.0
def test_completely_different(self):
assert similar("BATMAN #1", "SUPERMAN #500") < 0.5
def test_partial_match(self):
score = similar("ACTION COMICS #684", "ACTION COMICS #685")
assert score > 0.8
def test_case_insensitive_via_caller(self):
# similar() is case-sensitive; callers upper() before passing
assert similar("action comics #1".upper(), "ACTION COMICS #1") == 1.0
# =============================================================================
# _format_grade()
# =============================================================================
class TestFormatGrade:
def test_whole_number(self):
assert _format_grade(9) == "9.0"
def test_decimal(self):
assert _format_grade(9.8) == "9.8"
def test_low_grade(self):
assert _format_grade(0.5) == "0.5"
def test_perfect(self):
assert _format_grade(10.0) == "10.0"
# =============================================================================
# _classify_age()
# =============================================================================
class TestClassifyAge:
def test_platinum(self):
assert _classify_age("1930-01-01") == "Platinum Age"
def test_golden(self):
assert _classify_age("1945-06-01") == "Golden Age"
def test_silver(self):
assert _classify_age("1963-03-01") == "Silver Age"
def test_bronze(self):
assert _classify_age("1975-08-01") == "Bronze Age"
def test_copper(self):
assert _classify_age("1988-01-01") == "Copper Age"
def test_modern(self):
assert _classify_age("2005-05-01") == "Modern Age"
def test_unknown_blank(self):
assert _classify_age("") == "Unknown"
def test_unknown_none(self):
assert _classify_age(None) == "Unknown"
def test_unknown_nan_string(self):
assert _classify_age("nan") == "Unknown"
def test_year_only(self):
assert _classify_age("1968") == "Silver Age"
def test_boundary_1956(self):
assert _classify_age("1956-01-01") == "Silver Age"
def test_boundary_1970(self):
assert _classify_age("1970-01-01") == "Bronze Age"
# =============================================================================
# normalise_grade()
# =============================================================================
class TestNormaliseGrade:
def test_whole_number_string(self):
assert normalise_grade("9") == "9.0"
def test_decimal_string(self):
assert normalise_grade("9.8") == "9.8"
def test_blank(self):
assert normalise_grade("") is None
def test_nan_string(self):
assert normalise_grade("nan") is None
def test_none(self):
assert normalise_grade(None) is None
def test_text_grade(self):
# Text grades like 'NM' are not numeric — return None
assert normalise_grade("NM") is None
def test_low_grade(self):
assert normalise_grade("0.5") == "0.5"
def test_perfect(self):
assert normalise_grade("10") == "10.0"
def test_already_normalised(self):
assert normalise_grade("4.0") == "4.0"
# =============================================================================
# safe_fillna()
# =============================================================================
class TestSafeFillna:
def test_object_columns_filled_with_empty_string(self):
df = pd.DataFrame({'title': ['Batman', None, 'Superman']})
result = safe_fillna(df)
assert result['title'].iloc[1] == ''
def test_numeric_columns_filled_with_zero(self):
df = pd.DataFrame({'value': [1.0, None, 3.0]})
result = safe_fillna(df)
assert result['value'].iloc[1] == 0.0
def test_no_mutation_on_clean_df(self):
df = pd.DataFrame({'title': ['Batman'], 'value': [9.8]})
result = safe_fillna(df)
assert result['title'].iloc[0] == 'Batman'
assert result['value'].iloc[0] == 9.8
def test_mixed_columns(self):
df = pd.DataFrame({'title': [None], 'value': [None]})
df['value'] = df['value'].astype(float)
result = safe_fillna(df)
assert result['title'].iloc[0] == ''
assert result['value'].iloc[0] == 0.0
# =============================================================================
# _pick_best_match()
# =============================================================================
class TestPickBestMatch:
def _make_result(self, vol_name, issue_num, publisher_name=None):
r = {'volume': {'name': vol_name}, 'issue_number': str(issue_num)}
if publisher_name:
r['publisher'] = {'name': publisher_name}
return r
def test_exact_match(self):
results = [
self._make_result('Action Comics', '684'),
self._make_result('Detective Comics', '684'),
]
best, score = _pick_best_match(results, 'ACTION COMICS #684', issue_number=684)
assert best['volume']['name'] == 'Action Comics'
assert score > 0.9
def test_no_results(self):
best, score = _pick_best_match([], 'ACTION COMICS #684')
assert best is None
assert score == 0.0
def test_picks_higher_score(self):
results = [
self._make_result('Batman', '1'),
self._make_result('Action Comics', '684'),
]
best, score = _pick_best_match(results, 'ACTION COMICS #684', issue_number=684)
assert best['volume']['name'] == 'Action Comics'
def test_numeric_title_low_confidence(self):
# "1963 #1" should NOT strongly match "True 3-D #1"
results = [self._make_result('True 3-D', '1')]
best, score = _pick_best_match(results, '1963 #1', issue_number=1)
assert score < CV_CONFIDENCE_THRESHOLD
def test_issue_number_mismatch_penalised(self):
# "2099 Unlimited #2" should not match "2099 Unlimited #4"
results = [self._make_result('2099 Unlimited', '4')]
best, score = _pick_best_match(results, '2099 UNLIMITED #2', issue_number=2)
assert score < CV_CONFIDENCE_THRESHOLD
def test_publisher_bonus_breaks_tie(self):
# Use a slightly-off title so base score < 1.0, leaving room for publisher bonus
results_no_pub = [self._make_result('Amazing Spiderman', '1')]
results_with_pub = [self._make_result('Amazing Spiderman', '1')]
results_with_pub[0]['publisher'] = {'name': 'Marvel'}
_, score_no_pub = _pick_best_match(
results_no_pub, 'AMAZING SPIDER-MAN #1', issue_number=1, publisher='Marvel'
)
_, score_with_pub = _pick_best_match(
results_with_pub, 'AMAZING SPIDER-MAN #1', issue_number=1, publisher='Marvel'
)
assert score_with_pub > score_no_pub
def test_foreign_publisher_penalised(self):
results_foreign = [self._make_result('Amazing Spider-Man', '1')]
results_foreign[0]['publisher'] = {'name': 'Panini'}
results_us = [self._make_result('Amazing Spider-Man', '1')]
results_us[0]['publisher'] = {'name': 'Marvel'}
_, score_foreign = _pick_best_match(results_foreign, 'AMAZING SPIDER-MAN #1', issue_number=1)
_, score_us = _pick_best_match(results_us, 'AMAZING SPIDER-MAN #1', issue_number=1)
assert score_us > score_foreign
def test_score_clamped_to_zero_one(self):
# A very bad match with a penalty should still produce score in [0, 1]
results = [self._make_result('2099 Unlimited', '99')]
results[0]['publisher'] = {'name': 'Panini'}
_, score = _pick_best_match(results, 'BATMAN #1', issue_number=1)
assert 0.0 <= score <= 1.0
# =============================================================================
# GetEbayPrice() — blank/invalid grade handling
# =============================================================================
class TestGetEbayPriceGradeHandling:
def _mock_session(self):
return MagicMock()
def test_blank_grade_returns_none(self):
result = GetEbayPrice(self._mock_session(), 'BATMAN', 1, '', 'No')
assert result is None
def test_nan_grade_returns_none(self):
result = GetEbayPrice(self._mock_session(), 'BATMAN', 1, 'nan', 'No')
assert result is None
def test_text_grade_returns_none(self):
result = GetEbayPrice(self._mock_session(), 'BATMAN', 1, 'NM', 'No')
assert result is None
def test_valid_grade_calls_ebay(self):
session = self._mock_session()
with patch('core._ebay_listing_prices', return_value=[25.00]) as mock_ebay:
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result == 25.00
mock_ebay.assert_called_once()
def test_no_sales_exact_tries_neighbours(self):
session = self._mock_session()
call_count = [0]
def fake_prices(sess, query, target_grade=None):
call_count[0] += 1
# Return price on the second call (first neighbour)
return [30.00] if call_count[0] > 1 else []
with patch('core._ebay_listing_prices', side_effect=fake_prices):
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result is not None
assert call_count[0] > 1
def test_interpolation(self):
session = self._mock_session()
# Simulate: 9.6 = $20, 10.0 = $40, so 9.8 should interpolate to $30
def fake_prices(sess, query, target_grade=None):
if '9.6' in query: return [20.00]
if '10.0' in query: return [40.00]
return []
with patch('core._ebay_listing_prices', side_effect=fake_prices):
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result == 30.00
# =============================================================================
# GetEbayPrice() — bracket fallback and rate-limit propagation
# =============================================================================
class TestGetEbayPriceFallback:
def _mock_session(self):
return MagicMock()
def test_lower_bracket_only_returns_lower_price(self):
session = self._mock_session()
def fake_prices(sess, query, target_grade=None):
if '9.6' in query: return [18.00]
return []
with patch('core._ebay_listing_prices', side_effect=fake_prices):
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result == 18.00
def test_upper_bracket_only_returns_upper_price(self):
session = self._mock_session()
def fake_prices(sess, query, target_grade=None):
if '10.0' in query: return [50.00]
return []
with patch('core._ebay_listing_prices', side_effect=fake_prices):
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result == 50.00
def test_no_brackets_returns_none(self):
session = self._mock_session()
with patch('core._ebay_listing_prices', return_value=[]):
result = GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
assert result is None
def test_rate_limited_propagates(self):
session = self._mock_session()
with patch('core._ebay_listing_prices', side_effect=_EbayRateLimited):
with pytest.raises(_EbayRateLimited):
GetEbayPrice(session, 'BATMAN', 1, '9.8', 'No')
# =============================================================================
# GetEbayPriceGraded / GetEbayPriceUngraded — wiring
# =============================================================================
class TestGetEbayPriceConvenience:
def _mock_session(self):
return MagicMock()
def test_graded_includes_cgc_in_query(self):
session = self._mock_session()
with patch('core._ebay_listing_prices', return_value=[40.00]) as mock_ebay:
GetEbayPriceGraded(session, 'BATMAN', 1, '9.8')
query = mock_ebay.call_args[0][1]
assert 'CGC' in query
def test_ungraded_excludes_cgc_from_query(self):
session = self._mock_session()
with patch('core._ebay_listing_prices', return_value=[20.00]) as mock_ebay:
GetEbayPriceUngraded(session, 'BATMAN', 1, '9.8')
query = mock_ebay.call_args[0][1]
assert 'CGC' not in query
# =============================================================================
# SearchComicVine() — confidence threshold enforcement
# =============================================================================
class TestSearchComicVineConfidence:
def _mock_session(self):
return MagicMock()
def test_low_confidence_returns_none(self):
"""A bad match (< threshold) should return None, not pollute the sheet."""
with patch('core._cv_get') as mock_cv:
# Return a result that won't match well
mock_cv.return_value = [
{'volume': {'name': 'True 3-D', 'id': 1},
'issue_number': '1',
'description': '', 'deck': '',
'image': None, 'cover_date': '1953-01-01',
'cover_price': '0.10', 'site_detail_url': '',
'character_credits': [], 'name': 'True 3-D #1'}
]
result = SearchComicVine(self._mock_session(), 'FAKE_KEY', '1963', 1)
assert result is None
def test_high_confidence_returns_data(self):
"""A good match should return metadata."""
mock_issue = {
'volume': {'name': 'Action Comics', 'id': 12345},
'issue_number': '684',
'description': 'Death of Superman tie-in',
'deck': 'Key issue — first appearance',
'image': {'original_url': 'https://example.com/cover.jpg'},
'cover_date': '1993-01-01',
'cover_price': '1.25',
'site_detail_url': 'https://comicvine.com/action-comics-684',
'character_credits': [{'name': 'Superman'}],
'name': 'Action Comics #684',
'resource_type': 'issue',
}
with patch('core._cv_get') as mock_cv:
mock_cv.return_value = [mock_issue]
result = SearchComicVine(
self._mock_session(), 'FAKE_KEY', 'ACTION COMICS', 684
)
assert result is not None
assert result['cover_image'] == 'https://example.com/cover.jpg'
assert result['key_issue'] == 'Yes'
assert result['comic_age'] == 'Modern Age'
assert result['confidence'] > CV_CONFIDENCE_THRESHOLD
def test_volume_fallback_used_when_direct_search_fails(self):
"""Strategy 2 (volume lookup) should fire when Strategy 1 scores below threshold."""
mock_volume = {
'resource_type': 'volume',
'id': 99,
'name': '1963',
'publisher': {'name': 'Image Comics'},
'start_year': 1993,
'count_of_issues': 6,
}
mock_issue = {
'volume': {'name': '1963', 'id': 99},
'issue_number': '1',
'description': '',
'deck': '',
'image': None,
'cover_date': '1993-04-01',
'cover_price': '1.95',
'site_detail_url': 'https://comicvine.com/1963-1',
'character_credits': [],
'name': '1963 #1',
'resource_type': 'issue',
}
call_results = {
# Strategy 1: /search for issue — bad match
'search_issue': [],
# Strategy 2a: /search for volume — returns the volume
'search_volume': [mock_volume],
# Strategy 2b: /issues on that volume
'issues': [mock_issue],
# Publisher detail call
'volume_detail': {'name': '1963', 'publisher': {'name': 'Image Comics'}},
}
call_seq = [0]
def fake_cv_get(session, key, endpoint, params):
if endpoint == 'search' and params.get('resources') == 'issue':
return call_results['search_issue']
if endpoint == 'search' and params.get('resources') == 'volume':
return call_results['search_volume']
if endpoint == 'issues':
return call_results['issues']
if endpoint.startswith('volume/'):
return call_results['volume_detail']
return None
with patch('core._cv_get', side_effect=fake_cv_get):
result = SearchComicVine(self._mock_session(), 'FAKE_KEY', '1963', 1)
assert result is not None
assert result['volume'] == '1963'
assert result['comic_age'] == 'Modern Age'
def test_cv_returns_none_on_network_failure(self):
with patch('core._cv_get', return_value=None):
result = SearchComicVine(self._mock_session(), 'FAKE_KEY', 'BATMAN', 1)
assert result is None
if __name__ == '__main__':
pytest.main([__file__, '-v'])