Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/fixtures.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0813# Last Modified : 2026-08-2714#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# fixtures.py : enregistrement/rejeu des réponses HTTP des sources.91# `python run.py record <source>` capture toutes les réponses (HTML/JSON)92# dans tests/fixtures/<source>/ + un instantané `expected.json` du parsing.93# Les tests (tests/test_connectors.py) rejouent ces fixtures hors-ligne :94# si un connecteur régresse, le test casse — sans toucher au site réel.95# -----------------------------------------------------------------------------96from __future__ import annotations9798import hashlib99import json100import re101from pathlib import Path102103import requests104from requests.adapters import BaseAdapter, HTTPAdapter105106from .schema import Listing107108ROOT = Path(__file__).resolve().parent.parent109FIXTURES_DIR = ROOT / "tests" / "fixtures"110111112class MissingFixture(Exception):113 """Le connecteur a demandé une URL absente des fixtures enregistrées."""114115116# Secrets tiers présents dans le HTML public des sites sources (clés Google117# Maps, jetons) : caviardés à l'enregistrement — les fixtures sont publiées118# sur GitHub et ces clés n'ont aucun rôle dans le parsing.119_SECRET_RES = [120 (re.compile(rb"AIza[0-9A-Za-z_-]{35}"), b"AIza_CLE_CAVIARDEE_LOUKA_000000000000000"),121 # jetons Mapbox (sk. = secret, pk. = public) embarqués par certains sites122 (re.compile(rb"(sk|pk)\.eyJ[A-Za-z0-9_.=-]+"), rb"\1.JETON_CAVIARDE_LOUKA"),123]124125126def _redact(content: bytes) -> bytes:127 for rx, repl in _SECRET_RES:128 content = rx.sub(repl, content)129 return content130131132def _req_key(method: str, url: str, body: bytes | str | None) -> str:133 if isinstance(body, str):134 body = body.encode("utf-8")135 h = hashlib.sha1()136 h.update(f"{method.upper()} {url} ".encode())137 if body:138 h.update(body)139 return h.hexdigest()[:20]140141142def _ext_for(content_type: str) -> str:143 if "json" in content_type:144 return ".json"145 if "html" in content_type:146 return ".html"147 return ".txt"148149150# ---------------------------------------------------------------------------151# Enregistrement152# ---------------------------------------------------------------------------153154class _RecordAdapter(HTTPAdapter):155 def __init__(self, store: dict, out_dir: Path):156 super().__init__()157 self.store = store158 self.out_dir = out_dir159160 def send(self, request, **kwargs): # type: ignore[override]161 resp = super().send(request, **kwargs)162 key = _req_key(request.method or "GET", request.url or "", request.body)163 ctype = resp.headers.get("Content-Type", "")164 fname = key + _ext_for(ctype)165 (self.out_dir / fname).write_bytes(_redact(resp.content))166 self.store[key] = {167 "method": request.method, "url": request.url,168 "status": resp.status_code, "content_type": ctype, "file": fname,169 }170 if resp.headers.get("Location"):171 self.store[key]["location"] = resp.headers["Location"]172 return resp173174175def record(source_id: str) -> dict:176 """Exécute le connecteur en enregistrant chaque réponse HTTP en fixture.177178 Écrit tests/fixtures/<source>/{index.json, expected.json, *.html|json}.179 Retourne un résumé {source, requests, listings}.180 """181 from .connectors import CONNECTORS182 cls = CONNECTORS[source_id]183 out_dir = FIXTURES_DIR / source_id184 out_dir.mkdir(parents=True, exist_ok=True)185 for old in out_dir.iterdir():186 old.unlink()187188 inst = cls()189 inst.use_detail_cache = False # capturer aussi les pages détail190 store: dict = {}191 adapter = _RecordAdapter(store, out_dir)192 inst.session.mount("https://", adapter)193 inst.session.mount("http://", adapter)194195 # get_rendered (Scrapfly render_js) : enregistrer le HTML rendu, clé = URL196 # cible (les args supplémentaires — wait_ms — n'entrent pas dans la clé)197 orig_rendered = inst.get_rendered198199 def _rec_rendered(url: str, *args, **kw) -> str:200 html = orig_rendered(url, *args, **kw)201 key = _req_key("RENDERED", url, None)202 fname = key + ".html"203 (out_dir / fname).write_text(204 _redact(html.encode("utf-8")).decode("utf-8"), encoding="utf-8")205 store[key] = {"method": "RENDERED", "url": url, "status": 200,206 "content_type": "text/html", "file": fname}207 return html208209 inst.get_rendered = _rec_rendered # type: ignore[method-assign]210211 listings = inst.fetch()212 (out_dir / "index.json").write_text(213 json.dumps(store, ensure_ascii=False, indent=1), encoding="utf-8")214 (out_dir / "expected.json").write_text(215 json.dumps(snapshot(listings), ensure_ascii=False, indent=1),216 encoding="utf-8")217 return {"source": source_id, "requests": len(store),218 "listings": len(listings)}219220221def snapshot(listings: list[Listing]) -> dict:222 """Instantané compact et déterministe du parsing (champs bruts, pré-finalize).223224 La date de disponibilité normalisée dépend du jour d'exécution : on ne225 snapshotte que les champs stables pour éviter les tests fragiles.226 """227 rows = []228 for l in sorted(listings, key=lambda x: x.uid):229 rows.append({230 "uid": l.uid, "url": l.url, "title": l.title,231 "address": l.address, "sector": l.sector, "city": l.city,232 "unit_type": l.unit_type, "price": l.price,233 "availability": l.availability, "area_sqft": l.area_sqft,234 "n_images": len(l.images), "n_amenities": len(l.amenities),235 })236 return {"count": len(rows), "listings": rows}237238239# ---------------------------------------------------------------------------240# Rejeu241# ---------------------------------------------------------------------------242243class _ReplayAdapter(BaseAdapter):244 def __init__(self, index: dict, fixtures_dir: Path):245 super().__init__()246 self.index = index247 self.dir = fixtures_dir248249 def send(self, request, **kwargs): # type: ignore[override]250 key = _req_key(request.method or "GET", request.url or "", request.body)251 meta = self.index.get(key)252 if meta is None:253 raise MissingFixture(f"{request.method} {request.url}")254 resp = requests.models.Response()255 resp.status_code = meta["status"]256 resp._content = (self.dir / meta["file"]).read_bytes()257 resp.headers["Content-Type"] = meta.get("content_type", "")258 if meta.get("location"):259 resp.headers["Location"] = meta["location"]260 resp.url = request.url or ""261 resp.request = request262 resp.encoding = "utf-8"263 return resp264265 def close(self):266 pass267268269def replay_connector(source_id: str):270 """Instancie le connecteur branché sur ses fixtures (aucun réseau)."""271 from .connectors import CONNECTORS272 cls = CONNECTORS[source_id]273 fdir = FIXTURES_DIR / source_id274 index = json.loads((fdir / "index.json").read_text(encoding="utf-8"))275276 inst = cls()277 inst.request_delay = 0.0 # pas de politesse hors-ligne278 inst.use_detail_cache = False # tests indépendants de la BD279 adapter = _ReplayAdapter(index, fdir)280 inst.session.mount("https://", adapter)281 inst.session.mount("http://", adapter)282283 def _replay_rendered(url: str, *args, **kw) -> str:284 key = _req_key("RENDERED", url, None)285 meta = index.get(key)286 if meta is None:287 raise MissingFixture(f"RENDERED {url}")288 return (fdir / meta["file"]).read_text(encoding="utf-8")289290 inst.get_rendered = _replay_rendered # type: ignore[method-assign]291 return inst292293294def recorded_sources() -> list[str]:295 """Sources ayant des fixtures enregistrées (pour paramétrer les tests)."""296 if not FIXTURES_DIR.exists():297 return []298 return sorted(p.name for p in FIXTURES_DIR.iterdir()299 if (p / "index.json").exists())300