#!/usr/bin/env python3
# Copyright: 2026, Maximiliano Curia <maxy@debian.org>
#
# License: ISC
#  Permission to use, copy, modify, and/or distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#  .
#  THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
#  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
#  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
#  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
#  OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
#  PERFORMANCE OF THIS SOFTWARE.

"""Smoke tests for the codesearch-script test harness (tests/dcs_helpers.py)."""

from __future__ import annotations

import urllib.error

import pytest

from tests.dcs_helpers import (
    FakeResponse,
    FakeTransport,
    load_script,
    make_http_error,
)


def test_load_script_loads_hyphenated_rank_module() -> None:
    module = load_script("rank-license-usage-codesearch.py")
    # The importlib path resolved the script's own decopy / sibling imports.
    assert hasattr(module, "DcsClient")
    assert hasattr(module, "Candidate")
    assert callable(module.fetch_results)


def test_fake_response_read_truncates_to_amt() -> None:
    resp = FakeResponse(b"abcdef")
    assert resp.read() == b"abcdef"
    assert resp.read(3) == b"abc"


def test_fake_transport_returns_bytes_as_response() -> None:
    transport = FakeTransport([b"payload"])
    with transport("ignored-request") as resp:
        assert resp.read() == b"payload"
    assert transport.calls == 1


def test_fake_transport_raises_queued_exception() -> None:
    boom = TimeoutError("stalled")
    transport = FakeTransport([boom])
    with pytest.raises(TimeoutError):
        transport("ignored-request")
    assert transport.calls == 1


def test_fake_transport_exhausted_without_repeat_is_a_test_error() -> None:
    transport = FakeTransport([b"once"])
    transport("first")
    with pytest.raises(AssertionError):
        transport("second")


def test_fake_transport_repeat_reuses_last_step() -> None:
    expected_calls = 3
    transport = FakeTransport([make_http_error(503)], repeat=True)
    for _ in range(expected_calls):
        with pytest.raises(urllib.error.HTTPError):
            transport("request")
    assert transport.calls == expected_calls


def test_make_http_error_carries_code_retry_after_and_body() -> None:
    too_many_requests = 429
    exc = make_http_error(too_many_requests, retry_after=7, body=b"slow down")
    assert exc.code == too_many_requests
    assert exc.headers.get("Retry-After") == "7"
    assert exc.read() == b"slow down"
