"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch).""" import io import json import zipfile import pytest import upstream def make_xlsx(sheet_name, cells, strings=None): """Construit un classeur minimal respectant la structure réelle lue sur la VM.""" text_values = {ref: value for ref, value in cells.items() if isinstance(value, str)} numeric = {ref: value for ref, value in cells.items() if not isinstance(value, str)} shared = list(dict.fromkeys(text_values.values())) index = {value: position for position, value in enumerate(shared)} def cell_xml(ref, value): if isinstance(value, str): return f'{index[value]}' return f'{value}' sheet_rows = {} for ref in list(numeric) + list(text_values): row = ''.join(ch for ch in ref if ch.isdigit()) sheet_rows.setdefault(int(row), []).append(cell_xml(ref, {**numeric, **text_values}[ref])) body = ''.join(f'{"".join(cells_xml)}' for number, cells_xml in sorted(sheet_rows.items())) shared_xml = ('' + ''.join(f'{value}' for value in shared) + '') workbook = ('' f'') rels = ('' '') sheet = ('' f'{body}') buffer = io.BytesIO() with zipfile.ZipFile(buffer, 'w') as archive: archive.writestr('xl/workbook.xml', workbook) archive.writestr('xl/_rels/workbook.xml.rels', rels) archive.writestr('xl/sharedStrings.xml', shared_xml) archive.writestr('xl/worksheets/sheet1.xml', sheet) return buffer.getvalue() def test_excel_date_conversion_and_rejection(): assert upstream.excel_date(42005) == '2015-01-01' assert upstream.excel_date(46272) == '2026-09-07' assert upstream.excel_date('2025') is None assert upstream.excel_date(None) is None def test_parse_dgec_brent_keeps_monthly_rows_only(): raw = make_xlsx('Cours du Brent', {'A3': 42005, 'B3': 47.708, 'A4': 42036, 'B4': 58.0955, 'A157': '2025', 'B157': 69.1}) out = upstream.parse_dgec_brent(raw) assert out == [{'day': '2015-01-01', 'value': 47.71}, {'day': '2015-02-01', 'value': 58.1}] def test_parse_dgec_brent_rejects_garbage(): with pytest.raises(ValueError): upstream.parse_dgec_brent(make_xlsx('Cours du Brent', {'B1': 'rien'})) def test_parse_dgec_margin_keeps_both_units(): raw = make_xlsx('Marge brute raffinage sur Brent', {'A3': 42005, 'B3': 6.9877, 'C3': 45.253}) assert upstream.parse_dgec_margin(raw) == [{'day': '2015-01-01', 'usd_per_bbl': 6.99, 'eur_per_tonne': 45.25}] def test_parse_dgec_prices_splits_htt_and_ttc(): cells = {'A3': 46272, 'B2': 'Gazole', 'H2': 'Gazole', 'B3': 1.653, 'H3': 1.99} out = upstream.parse_dgec_prices(make_xlsx('Carburants routiers', cells)) assert out == [{'day': '2026-09-07', 'htt': {'Gazole': 1.653}, 'ttc': {'Gazole': 1.99}}] def test_parse_eu_bulletin_converts_thousands_of_litres(): cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_with_tax_diesel', 'CN4': 2041.66, 'CO1': 'FR_price_with_tax_euro95', 'CO4': 1899.99} out = upstream.parse_eu_bulletin(make_xlsx('Prices with taxes', cells)) assert out == [{'day': '2026-09-07', 'prices': {'diesel': 2.042, 'euro95': 1.9}}] def test_parse_eu_bulletin_accepts_without_tax_sheet(): # Le bulletin nomme le second onglet « Prices wo taxes » : les en-têtes diffèrent. cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_wo_tax_diesel', 'CN4': 1500.0} out = upstream.parse_eu_bulletin(make_xlsx('Prices wo taxes', cells), 'FR', 'Prices wo taxes') assert out == [{'day': '2026-09-07', 'prices': {'diesel': 1.5}}] def test_parse_eu_bulletin_rejects_missing_country(): raw = make_xlsx('Prices with taxes', {'A3': 'Date', 'A4': 46272, 'CN1': 'BE_price_with_tax_diesel', 'CN4': 1500}) with pytest.raises(ValueError): upstream.parse_eu_bulletin(raw) def test_parse_chokepoints_keeps_latest_per_watched_strait(): payload = json.dumps({'features': [ {'attributes': {'date': '2026-08-30', 'portname': 'Strait of Hormuz', 'n_tanker': 40, 'n_total': 90}}, {'attributes': {'date': '2026-09-06', 'portname': 'Strait of Hormuz', 'n_tanker': 2, 'n_total': 6, 'capacity_tanker': 60280, 'capacity': 150000}}, {'attributes': {'date': '2026-09-06', 'portname': 'Bab el-Mandeb Strait', 'n_tanker': 6, 'n_total': 23}}, {'attributes': {'date': '2026-09-06', 'portname': 'Port of Nantes', 'n_tanker': 99}}, ]}).encode() out = upstream.parse_chokepoints(payload) assert set(out) == {'Strait of Hormuz', 'Bab el-Mandeb Strait'} assert out['Strait of Hormuz']['day'] == '2026-09-06' assert out['Strait of Hormuz']['transit_tankers'] == 2 assert out['Strait of Hormuz']['capacity_total'] == 150000 def test_parse_chokepoints_rejects_garbage(): with pytest.raises(ValueError): upstream.parse_chokepoints(b'{"error": "bad query"}') def test_freshness_never_assumes_current(): assert upstream.freshness('2026-09-10', today=__import__('datetime').date(2026, 9, 12)) == { 'state': 'fresh', 'age_days': 2} assert upstream.freshness('2026-07-01', today=__import__('datetime').date(2026, 9, 12))['state'] == 'stale' assert upstream.freshness(None) == {'state': 'unknown', 'age_days': None}