|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Shared test fixtures. |
| 4 | +
|
| 5 | +Mocks all external HTTP calls (Toolforge API, Google Sheets, Wikimedia |
| 6 | +API) so tests run without network access. The ``responses`` library |
| 7 | +intercepts at the ``requests`` adapter level; any unmocked call raises |
| 8 | +``ConnectionError`` (passthrough=False, the default). |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import absolute_import |
| 12 | + |
| 13 | +import json |
| 14 | +import re |
| 15 | + |
| 16 | +import pytest |
| 17 | +import responses as responses_lib |
| 18 | + |
| 19 | +from urllib.parse import parse_qs, urlparse |
| 20 | + |
| 21 | +# --------------------------------------------------------------------------- |
| 22 | +# URLs exactly as constructed by montage code |
| 23 | +# --------------------------------------------------------------------------- |
| 24 | +TOOLFORGE_CATEGORY_URL = 'https://montage.toolforge.org/v1/utils//category' |
| 25 | +TOOLFORGE_FILE_URL = 'https://montage.toolforge.org/v1/utils//file' |
| 26 | + |
| 27 | +# Matches any Google Sheets CSV-export URL regardless of doc ID. |
| 28 | +GSHEET_CSV_URL_RE = re.compile( |
| 29 | + r'https://docs\.google\.com/spreadsheets/d/.+/gviz/tq\?tqx=out:csv' |
| 30 | +) |
| 31 | + |
| 32 | +# Matches any Wikimedia API user-lookup call. |
| 33 | +MW_API_URL_RE = re.compile( |
| 34 | + r'https://commons\.wikimedia\.org/w/api\.php\?.*' |
| 35 | +) |
| 36 | + |
| 37 | +# --------------------------------------------------------------------------- |
| 38 | +# Fixture data -- 20 synthetic entries with resolution > 2 megapixels. |
| 39 | +# Enough entries to survive disqualification AND give every juror >=2 |
| 40 | +# tasks regardless of random.shuffle ordering during task allocation. |
| 41 | +# --------------------------------------------------------------------------- |
| 42 | + |
| 43 | + |
| 44 | +def _generate_file_infos(n): |
| 45 | + """Build *n* unique file-info dicts with high resolution.""" |
| 46 | + infos = [] |
| 47 | + for i in range(n): |
| 48 | + infos.append({ |
| 49 | + 'img_name': 'Test_WLM_2015_image_%03d.jpg' % (i + 1), |
| 50 | + 'img_major_mime': 'image', |
| 51 | + 'img_minor_mime': 'jpeg', |
| 52 | + 'img_width': '3264', |
| 53 | + 'img_height': '2448', # 3264*2448 = 7,990,272 > 2M |
| 54 | + 'img_user': '5193613', |
| 55 | + 'img_user_text': 'Khoshamadgou', |
| 56 | + # All timestamps after campaign open_date (2015-09-01) |
| 57 | + 'img_timestamp': '201509060%05d' % (20000 + i), |
| 58 | + }) |
| 59 | + return infos |
| 60 | + |
| 61 | + |
| 62 | +FIXTURE_FILE_INFOS = _generate_file_infos(20) |
| 63 | + |
| 64 | +# Entry returned for the single-filename import in test_web_basic.py |
| 65 | +SELECTED_FILE_INFO = { |
| 66 | + 'img_name': u'Reynisfjara, Su\u00f0urland, Islandia, 2014-08-17, DD 164.JPG', |
| 67 | + 'img_major_mime': 'image', |
| 68 | + 'img_minor_mime': 'jpeg', |
| 69 | + 'img_width': '4928', |
| 70 | + 'img_height': '3280', |
| 71 | + 'img_user': '12345', |
| 72 | + 'img_user_text': 'TestUploader', |
| 73 | + 'img_timestamp': '20140817120000', |
| 74 | +} |
| 75 | + |
| 76 | +CSV_FULL_COLS = [ |
| 77 | + 'img_name', 'img_major_mime', 'img_minor_mime', |
| 78 | + 'img_width', 'img_height', 'img_user', |
| 79 | + 'img_user_text', 'img_timestamp', |
| 80 | +] |
| 81 | + |
| 82 | + |
| 83 | +def build_full_csv(file_infos=None): |
| 84 | + """Build a CSV string with all required columns from file_info dicts.""" |
| 85 | + if file_infos is None: |
| 86 | + file_infos = FIXTURE_FILE_INFOS |
| 87 | + lines = [','.join(CSV_FULL_COLS)] |
| 88 | + for fi in file_infos: |
| 89 | + lines.append(','.join(str(fi[c]) for c in CSV_FULL_COLS)) |
| 90 | + return '\n'.join(lines) + '\n' |
| 91 | + |
| 92 | + |
| 93 | +def build_filename_csv(file_infos=None): |
| 94 | + """Build a CSV string with only a 'filename' column.""" |
| 95 | + if file_infos is None: |
| 96 | + file_infos = FIXTURE_FILE_INFOS |
| 97 | + lines = ['filename'] |
| 98 | + for fi in file_infos: |
| 99 | + lines.append(fi['img_name']) |
| 100 | + return '\n'.join(lines) + '\n' |
| 101 | + |
| 102 | + |
| 103 | +FIXTURE_FULL_CSV = build_full_csv() |
| 104 | +FIXTURE_FILENAME_CSV = build_filename_csv() |
| 105 | + |
| 106 | + |
| 107 | +# --------------------------------------------------------------------------- |
| 108 | +# Disable pdb in error handler -- devtest sets debug_errors=True which |
| 109 | +# calls pdb.post_mortem() on unhandled exceptions. Under pytest's output |
| 110 | +# capture this crashes with OSError. Patching pdb to no-ops is safe |
| 111 | +# because no test relies on interactive debugging. |
| 112 | +# --------------------------------------------------------------------------- |
| 113 | +@pytest.fixture(autouse=True) |
| 114 | +def _disable_pdb(monkeypatch): |
| 115 | + monkeypatch.setattr('pdb.set_trace', lambda *a, **kw: None) |
| 116 | + monkeypatch.setattr('pdb.post_mortem', lambda *a, **kw: None) |
| 117 | + |
| 118 | +# --------------------------------------------------------------------------- |
| 119 | +# Wikimedia API callback -- returns a plausible user record for any username |
| 120 | +# --------------------------------------------------------------------------- |
| 121 | +def _wikimedia_user_callback(request): |
| 122 | + """Return a mock globalallusers response matching the requested username.""" |
| 123 | + parsed = urlparse(request.url) |
| 124 | + params = parse_qs(parsed.query) |
| 125 | + username = params.get('agufrom', ['Unknown'])[0] |
| 126 | + # Deterministic fake user ID derived from username |
| 127 | + user_id = abs(hash(username)) % 10**8 |
| 128 | + body = json.dumps({ |
| 129 | + 'query': { |
| 130 | + 'globalallusers': [ |
| 131 | + {'name': username, 'id': str(user_id)} |
| 132 | + ] |
| 133 | + } |
| 134 | + }) |
| 135 | + return (200, {}, body) |
| 136 | + |
| 137 | + |
| 138 | +# --------------------------------------------------------------------------- |
| 139 | +# Fixture: mock_external_apis |
| 140 | +# --------------------------------------------------------------------------- |
| 141 | +@pytest.fixture |
| 142 | +def mock_external_apis(): |
| 143 | + """Activate ``responses`` and register mocks for every external endpoint. |
| 144 | +
|
| 145 | + Covers: |
| 146 | + - Toolforge category lookup (POST /v1/utils//category) |
| 147 | + - Toolforge file lookup (POST /v1/utils//file) |
| 148 | + - Google Sheets CSV export (GET docs.google.com/spreadsheets/...) |
| 149 | + - Wikimedia user lookup (GET commons.wikimedia.org/w/api.php) |
| 150 | +
|
| 151 | + Any request to an unregistered URL raises ``ConnectionError``, |
| 152 | + ensuring no live HTTP traffic leaks from tests. |
| 153 | + """ |
| 154 | + with responses_lib.RequestsMock(assert_all_requests_are_fired=False) as rsps: |
| 155 | + # -- Toolforge category endpoint -- |
| 156 | + rsps.add( |
| 157 | + responses_lib.POST, |
| 158 | + TOOLFORGE_CATEGORY_URL, |
| 159 | + json={'file_infos': FIXTURE_FILE_INFOS, 'no_info': []}, |
| 160 | + status=200, |
| 161 | + ) |
| 162 | + |
| 163 | + # -- Toolforge file-lookup endpoint -- |
| 164 | + # Returns both fixture entries and the single "selected" entry so |
| 165 | + # that both bulk-filename and single-filename imports succeed. |
| 166 | + rsps.add( |
| 167 | + responses_lib.POST, |
| 168 | + TOOLFORGE_FILE_URL, |
| 169 | + json={ |
| 170 | + 'file_infos': FIXTURE_FILE_INFOS + [SELECTED_FILE_INFO], |
| 171 | + 'no_info': [], |
| 172 | + }, |
| 173 | + status=200, |
| 174 | + ) |
| 175 | + |
| 176 | + # -- Google Sheets CSV export (any doc ID) -- |
| 177 | + rsps.add( |
| 178 | + responses_lib.GET, |
| 179 | + GSHEET_CSV_URL_RE, |
| 180 | + body=FIXTURE_FULL_CSV, |
| 181 | + status=200, |
| 182 | + content_type='text/csv', |
| 183 | + ) |
| 184 | + |
| 185 | + # -- Wikimedia user-lookup API -- |
| 186 | + # Called by get_mw_userid() when creating new users. |
| 187 | + rsps.add_callback( |
| 188 | + responses_lib.GET, |
| 189 | + MW_API_URL_RE, |
| 190 | + callback=_wikimedia_user_callback, |
| 191 | + ) |
| 192 | + |
| 193 | + yield rsps |
0 commit comments