"""
Tests for rna.process
"""

import gc
import logging
import os

import pytest
import rna.process


def _open_fds():
    gc.collect()
    return len(os.listdir("/proc/self/fd"))


def test_subprocess_no_fd_leak():
    """rna.process.execute must not leak file descriptors (regression for EMFILE / errno 24)."""
    logger = logging.getLogger("test_fd_leak")
    n_iterations = 200

    before = _open_fds()
    for _ in range(n_iterations):
        rna.process.execute("echo x", logger=logger)
    after = _open_fds()

    assert after - before < 10, f"FD leak detected: {before} -> {after} (+{after - before})"


def test_subprocess_no_fd_leak_output():
    """rna.process.execute must not leak file descriptors when output=True."""
    n_iterations = 200

    before = _open_fds()
    for _ in range(n_iterations):
        rna.process.execute("echo x", output=True)
    after = _open_fds()

    assert after - before < 10, f"FD leak detected: {before} -> {after} (+{after - before})"


def test_timeout_raises():
    with pytest.raises(Exception):
        rna.process.execute("sleep 5", timeout=0.1, level=None)


def test_timeout_no_fd_leak():
    """Timed-out calls must not leak file descriptors."""
    logger = logging.getLogger("test_fd_leak_timeout")

    before = _open_fds()
    for _ in range(20):
        try:
            rna.process.execute("sleep 5", timeout=0.05, logger=logger)
        except Exception:
            pass
    after = _open_fds()

    assert after - before < 10, f"FD leak on timeout: {before} -> {after} (+{after - before})"
