"""Pruebas del paso 6, que es opcional. LAB_DIR dice dónde están sus archivos: lab o solution."""
import os
import pathlib
import subprocess
import unittest

HERE = pathlib.Path(__file__).parent
LAB_DIR = os.environ.get("LAB_DIR", "solution")
BINARY = HERE / "build" / LAB_DIR / "optional_tests"
LIMIT_SECONDS = 60


def add_cases(cls, names):
    for name in names:
        def case(self, name=name):
            done = subprocess.run(
                [str(BINARY), name, "lab/tests"], cwd=HERE, text=True, encoding="utf-8", errors="replace",
                stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=LIMIT_SECONDS,
            )
            self.assertEqual(done.returncode, 0, done.stdout.strip())
        setattr(cls, f"test_{name}", case)


class OptionalCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        done = subprocess.run(
            ["make", "--no-print-directory", f"LAB_DIR={LAB_DIR}", f"build/{LAB_DIR}/optional_tests"],
            cwd=HERE, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
        )
        if done.returncode != 0:
            raise AssertionError(done.stdout)


@unittest.skipUnless((HERE / LAB_DIR).is_dir(), f"no existe la carpeta {LAB_DIR}")
class TestTrie(OptionalCase):
    """Paso 6: el trie."""


@unittest.skipUnless((HERE / LAB_DIR).is_dir(), f"no existe la carpeta {LAB_DIR}")
class TestBloom(OptionalCase):
    """Paso 6: el filtro de Bloom."""


add_cases(TestTrie, [
    "trie_insert_and_find", "trie_shares_prefixes", "trie_prefix_in_byte_order", "trie_random_against_map",
])
add_cases(TestBloom, [
    "bloom_sets_the_right_bits", "bloom_no_false_negatives", "bloom_false_positives_fall_with_size",
    "bloom_uses_all_hashes",
])


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