Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions tests/test_indexer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Compléments de couverture de `src/indexer.py` (issue #159 : le pont
omprog asynchrone doit garder acquittements et DLQ à l'identique).

L'indexer délègue aux sorties PyStashTemplate depuis #160 — ces tests
couvrent les branches restées hors des tests existants : avertissement
multi-nœuds, authentification transmise au client HTTP, client partagé
avec `install_index_template`, et action invalide sans DLQ (renvoyée à
rsyslog comme un échec transitoire).
"""

from __future__ import annotations

import asyncio
import base64
from pathlib import Path
from typing import Any

import httpx
from loguru import logger
from test_integration import make_bridge

from indexer import OpenSearchIndexer, SendOutcome


def _run(coro):
# Sans pytest-asyncio (convention du dépôt) : asyncio.run direct.
return asyncio.run(coro)


def _indexer(**kwargs: Any) -> OpenSearchIndexer:
options: dict[str, Any] = {
"hosts": [{"host": "127.0.0.1", "port": 9200}],
"auth": None,
"index_pattern": "i-%Y.%m.%d",
"use_ssl": False,
"verify_certs": False,
}
options.update(kwargs)
return OpenSearchIndexer(**options)


class ClientAvecEntetes:
"""Double réseau qui capture l'en-tête Authorization des requêtes _bulk."""

def __init__(self) -> None:
self.authorization: str | None = None
self.transport = httpx.MockTransport(self._handler)

def _handler(self, request: httpx.Request) -> httpx.Response:
if request.method == "POST":
self.authorization = request.headers.get("authorization")
return httpx.Response(200, json={"items": [{"index": {"status": 201}}]})


class TestConstructeur:
def test_plusieurs_noeuds_avertit(self) -> None:
# Seul le PREMIER nœud est utilisé (failover à l'appelant) : un
# avertissement le dit, plutôt qu'un échec silencieux.
messages: list[str] = []
sink = logger.add(lambda m: messages.append(str(m)), level="WARNING")
try:
_indexer(hosts=[{"host": "a", "port": 9200}, {"host": "b", "port": 9200}])
finally:
logger.remove(sink)
assert any("Plusieurs nœuds configurés" in m and "seul le premier est utilisé" in m for m in messages)

def test_auth_transmise_au_client_en_basic(self) -> None:
indexer = _indexer(auth=("admin", "s3cret"))
client = ClientAvecEntetes()
indexer.sortie._transport = client.transport

async def scenario() -> SendOutcome:
resultat = await indexer.send({"m": 1})
await indexer.close()
return resultat

assert _run(scenario()) is SendOutcome.INDEXED
attendu = "Basic " + base64.b64encode(b"admin:s3cret").decode()
assert client.authorization == attendu

def test_client_http_partage_avec_install_template(self) -> None:
# omprog installe le gabarit d'index via ce client paresseux.
indexer = _indexer()

async def scenario() -> None:
client = await indexer._client()
assert isinstance(client, httpx.AsyncClient)
await client.aclose()

_run(scenario())


def test_action_invalide_sans_dlq_renvoie_a_rsyslog(tmp_path: Path) -> None:
# Action impossible (update sans _id) sans --dlq-path : comportement
# historique, l'échec permanent reste RETRYABLE et repart vers rsyslog.
bridge, _ = make_bridge(
tmp_path,
pipeline_conf='output { opensearch { index => "i" action => "update" } }',
dlq=False,
)

async def scenario() -> Any:
resultat = await bridge.handle_doc({"v": 1})
await bridge.close()
return resultat

assert _run(scenario()) is SendOutcome.RETRYABLE
11 changes: 11 additions & 0 deletions tests/test_omprog.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,17 @@ def test_pipeline_output_opensearch_donne_index_et_id(tmp_path):
assert [(i, d) for _, i, d in bridge.indexer.sent] == [("logs-a", "42")]


def test_pipeline_clone_deux_evenements_deux_indexations(tmp_path):
# #159 : clone produit deux événements, tous deux indexés — au second
# passage de la boucle, l'issue du premier est conservée (branche
# 318->316 de handle_doc, non RETRYABLE et outcome déjà fixé).
conf = tmp_path / "p.conf"
conf.write_text('filter { clone { clones => ["copie"] } }', encoding="utf-8")
bridge = _bridge("--pipeline-conf", str(conf))
assert _run(bridge.handle_line('{"msg": "x"}')) == "OK"
assert len(bridge.indexer.sent) == 2


def test_pipeline_dossier_lu_par_ordre_de_nom(tmp_path):
(tmp_path / "20_b.conf").write_text('filter { mutate { add_field => { "b" => "2" } } }', encoding="utf-8")
(tmp_path / "10_a.conf").write_text('filter { mutate { add_field => { "a" => "1" } } }', encoding="utf-8")
Expand Down
Loading