"""Pruebas de aloha.c: la simulación debe coincidir con las fórmulas, con margen."""
import math
import subprocess
import unittest


def table(seed):
    out = subprocess.run(["build/aloha", str(seed)], text=True, capture_output=True,
                         check=True).stdout
    rows = {}
    for line in out.splitlines()[1:]:
        g, slotted, pure = line.split("|")
        rows[float(g)] = (float(slotted.split()[0]), float(pure.split()[0]))
    return rows


class Aloha(unittest.TestCase):
    def setUp(self):
        self.rows = table(20260303)

    def test_slotted_peak_near_one_over_e_at_load_one(self):
        self.assertAlmostEqual(self.rows[1.0][0], 1 / math.e, delta=0.01)
        self.assertEqual(max(self.rows, key=lambda g: self.rows[g][0]), 1.0)

    def test_pure_peak_near_one_over_2e_at_load_half(self):
        self.assertAlmostEqual(self.rows[0.5][1], 1 / (2 * math.e), delta=0.01)
        self.assertEqual(max(self.rows, key=lambda g: self.rows[g][1]), 0.5)

    def test_more_load_after_the_peak_means_less_throughput(self):
        self.assertLess(self.rows[3.0][0], self.rows[1.0][0])
        self.assertLess(self.rows[3.0][1], self.rows[0.5][1])

    def test_other_seed_gives_similar_result(self):
        other = table(7)
        self.assertAlmostEqual(other[1.0][0], self.rows[1.0][0], delta=0.01)


if __name__ == "__main__":
    unittest.main()
