"""Dependency ping collector: reachable / unreachable / 5xx (never-raise)."""
from watchdog.collectors import deps as deps_mod

from .conftest import http_error, make_opener


def test_ping_reachable():
    assert deps_mod.ping("http://x", 1.0, opener=make_opener(status=200)) is True


def test_ping_4xx_still_reachable():
    # A 4xx proves the host is up (we ping for liveness, not auth).
    assert deps_mod.ping("http://x", 1.0, opener=make_opener(exc=http_error(404))) is True


def test_ping_5xx_is_down():
    assert deps_mod.ping("http://x", 1.0, opener=make_opener(exc=http_error(503))) is False


def test_ping_timeout_is_down():
    assert deps_mod.ping(
        "http://x", 1.0, opener=make_opener(exc=TimeoutError())
    ) is False


def test_ping_all_mixed():
    def opener_factory(url):
        return make_opener(status=200) if "good" in url else make_opener(
            exc=ConnectionError()
        )

    def opener(req, timeout=None):
        url = req.full_url if hasattr(req, "full_url") else req
        return opener_factory(url)(req, timeout)

    res = deps_mod.ping_all(
        {"good": "http://good", "bad": "http://bad"}, 1.0, opener=opener
    )
    assert res == {"good": True, "bad": False}
