"""A cache hit survives source edits but never a lock or toolchain change."""
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch

import native_cache


class NativeCacheTests(unittest.TestCase):
    def test_dependency_identity_and_reusable_paths(self):
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            subprocess.run(["git", "init", "-q", str(root)], check=True)
            for name in ("Podfile", "Podfile.lock", "Gemfile", "Gemfile.lock", "App.swift"):
                (root / name).write_text(name)
            subprocess.run(["git", "-C", str(root), "add", "."], check=True)
            original = native_cache.command
            toolchain = b"version-1"
            def command(*words):
                return original(*words) if words[0] == "git" else toolchain
            with patch.object(native_cache, "command", side_effect=command):
                first = native_cache.describe(root)
                self.assertEqual(first["paths"], ["Pods", ".factory/toolchain/gems"])
                (root / "App.swift").write_text("fixed crash")
                self.assertEqual(first, native_cache.describe(root))
                (root / "Podfile.lock").write_text("new dependency")
                changed = native_cache.describe(root)
                self.assertNotEqual(first["key"], changed["key"])
                toolchain = b"version-2"
                self.assertNotEqual(changed["key"], native_cache.describe(root)["key"])

    def test_no_lock_has_no_cache_and_does_not_probe_tools(self):
        with patch.object(native_cache, "command", return_value=b"App.swift\0") as command:
            self.assertEqual(native_cache.describe(Path(".")), {"key": "", "paths": []})
            self.assertEqual(command.call_count, 1)
