Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : tests/test_mortgage_store.py10# Module : tests11# Repository : https://git.spboucher.ai/immo-ka12# Created : 2026-08-2413# Last Modified : 2026-08-2414#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# Immo-Ka — Agrégateur de maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# tests/test_mortgage_store.py : historisation par périodes de validité —91# inchangé = simple last_checked ; changé = fermeture + nouvelle ligne ;92# saut aberrant rejeté sans écraser la bonne donnée.93# -----------------------------------------------------------------------------94import tempfile95import time96import unittest97from pathlib import Path9899from immoka.mortgage import store100101102def product(**over) -> dict:103 base = {104 "provider": "test", "institution": "Banque Test",105 "rate_type": "fixed", "term_months": 60, "kind": "special",106 "rate": 4.84, "apr": 4.90, "insured_status": "unknown",107 "purpose": "purchase", "product_name": "Fixe fermé 5 ans (spécial)",108 "source_url": "https://example.com/taux", "raw": {"src": "test"},109 }110 base.update(over)111 return base112113114class StoreTest(unittest.TestCase):115 def setUp(self):116 self._tmp = tempfile.TemporaryDirectory()117 self._old_path = store.DB_PATH118 self._old_ready = store._SCHEMA_READY119 store.DB_PATH = Path(self._tmp.name) / "mortgage.db"120 store._SCHEMA_READY = False121 self.con = store.connect()122123 def tearDown(self):124 self.con.close()125 store.DB_PATH = self._old_path126 store._SCHEMA_READY = self._old_ready127 self._tmp.cleanup()128129 def _count(self, where: str = "1=1") -> int:130 return self.con.execute(131 f"SELECT COUNT(*) AS n FROM rate_observations WHERE {where}"132 ).fetchone()["n"]133134 def test_unchanged_updates_last_checked_only(self):135 store.record_observations(self.con, "test", [product()])136 first = self.con.execute(137 "SELECT last_checked FROM rate_observations").fetchone()[0]138 time.sleep(0.02)139 res = store.record_observations(self.con, "test", [product()])140 self.assertEqual(res["changed"], 0)141 self.assertEqual(self._count(), 1) # aucune nouvelle ligne142 second = self.con.execute(143 "SELECT last_checked FROM rate_observations").fetchone()[0]144 self.assertGreater(second, first)145146 def test_change_closes_and_inserts(self):147 store.record_observations(self.con, "test", [product(rate=4.84)])148 res = store.record_observations(self.con, "test", [product(rate=4.69)])149 self.assertEqual(res["changed"], 1)150 self.assertEqual(self._count(), 2)151 self.assertEqual(self._count("valid_to IS NULL"), 1)152 current = self.con.execute(153 "SELECT rate FROM rate_observations WHERE valid_to IS NULL"154 ).fetchone()["rate"]155 self.assertEqual(current, 4.69)156 closed = self.con.execute(157 "SELECT rate, valid_to FROM rate_observations "158 "WHERE valid_to IS NOT NULL").fetchone()159 self.assertEqual(closed["rate"], 4.84) # historique intact160161 def test_aberrant_jump_rejected(self):162 store.record_observations(self.con, "test", [product(rate=4.19)])163 res = store.record_observations(self.con, "test", [product(rate=8.50)])164 self.assertEqual(res["rejected"], 1)165 self.assertEqual(self._count(), 1) # la bonne donnée n'est pas écrasée166 current = self.con.execute(167 "SELECT rate FROM rate_observations WHERE valid_to IS NULL"168 ).fetchone()["rate"]169 self.assertEqual(current, 4.19)170171 def test_small_change_accepted(self):172 store.record_observations(self.con, "test", [product(rate=4.19)])173 res = store.record_observations(self.con, "test", [product(rate=4.44)])174 self.assertEqual(res["rejected"], 0)175 self.assertEqual(res["changed"], 1)176177 def test_product_key_separates_incomparables(self):178 keys = {store.product_key(product(**over)) for over in (179 {}, {"kind": "posted"}, {"insured_status": "insured"},180 {"term_months": 36}, {"rate_type": "variable"},181 {"product_name": "Autre produit"},182 )}183 self.assertEqual(len(keys), 6) # jamais comparer l'incomparable184185 def test_best_rate_special_beats_posted(self):186 store.record_observations(self.con, "a", [187 product(provider="a", kind="posted", rate=6.09,188 product_name="Fixe affiché"),189 product(provider="a", kind="special", rate=4.84,190 product_name="Fixe spécial"),191 ])192 store.record_observations(self.con, "b", [193 product(provider="b", institution="Banque B", kind="special",194 rate=4.99, product_name="Fixe spécial B"),195 ])196 best = store.best_rate(self.con, "fixed", 60)197 self.assertEqual(best["provider"], "a")198 self.assertEqual(best["rate"], 4.84)199 self.assertEqual(best["kind"], "special")200 self.assertEqual(best["institutions_count"], 2)201 # le posted 6,09 de « a » ne doit pas être candidat202 self.assertEqual([r["rate"] for r in best["per_institution"]],203 [4.84, 4.99])204205 def test_best_rate_none_when_empty(self):206 self.assertIsNone(store.best_rate(self.con, "fixed", 60))207208 def test_rate_at_now(self):209 store.record_observations(self.con, "test", [product(rate=4.84)])210 self.assertEqual(store.rate_at(self.con, "fixed", 60, time.time()), 4.84)211212 def test_history_returns_periods(self):213 store.record_observations(self.con, "test", [product(rate=4.84)])214 store.record_observations(self.con, "test", [product(rate=4.69)])215 rows = store.history(self.con, "fixed", 60)216 self.assertEqual(len(rows), 2)217 self.assertIsNotNone(rows[0]["valid_to"])218 self.assertIsNone(rows[1]["valid_to"])219220 def test_provider_health_levels(self):221 store.record_observations(self.con, "test", [product()])222 store.log_run(self.con, "test", ok=True, status="success", products=1)223 store.log_run(self.con, "vide", ok=False, status="http_error")224 health = {h["provider"]: h for h in store.provider_health(self.con)}225 self.assertEqual(health["test"]["level"], "OK")226 self.assertEqual(health["vide"]["level"], "ERROR")227228229if __name__ == "__main__":230 unittest.main()231