#!/usr/bin/env python3

import importlib.util
from pathlib import Path
import unittest


MODULE_PATH = Path(__file__).with_name("build_progress.py")
SPEC = importlib.util.spec_from_file_location("build_progress", MODULE_PATH)
assert SPEC is not None and SPEC.loader is not None
BUILD_PROGRESS = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(BUILD_PROGRESS)


class BuildProgressTests(unittest.TestCase):
    def test_unique_crates_deduplicates_repeated_tree_entries(self) -> None:
        output = "editor v0.1.0\nserde v1.0.0\nserde v1.0.0\n"
        self.assertEqual(
            BUILD_PROGRESS.unique_crates(output),
            {"editor v0.1.0", "serde v1.0.0"},
        )

    def test_completed_crate_counts_each_package_once(self) -> None:
        completed: set[str] = set()
        message = {
            "reason": "compiler-artifact",
            "package_id": "path+file:///workspace#editor@0.1.0",
            "target": {"name": "editor"},
        }
        self.assertEqual(
            BUILD_PROGRESS.completed_crate(message, completed), (True, "editor")
        )
        self.assertEqual(
            BUILD_PROGRESS.completed_crate(message, completed), (False, "")
        )

    def test_non_artifact_does_not_advance_progress(self) -> None:
        completed: set[str] = set()
        self.assertEqual(
            BUILD_PROGRESS.completed_crate({"reason": "build-script-executed"}, completed),
            (False, ""),
        )
        self.assertFalse(completed)


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