import tempfile import unittest from pathlib import Path from release_refs import read_images, replace_images class ReleaseReferenceTests(unittest.TestCase): def test_replaces_both_refs_as_one_expected_state_and_preserves_other_config(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "production.env" path.write_text( "DATA_ROOT=/srv/data\nBACKEND_IMAGE=akyldash/backend:local\n" "OPENSEARCH_IMAGE=akyldash/opensearch:local\n", encoding="utf-8", ) old = { "BACKEND_IMAGE": "akyldash/backend:local", "OPENSEARCH_IMAGE": "akyldash/opensearch:local", } new = { "BACKEND_IMAGE": "git.vakanaut.ru/admin/akyldash/backend@sha256:" + "a" * 64, "OPENSEARCH_IMAGE": "git.vakanaut.ru/admin/akyldash/opensearch@sha256:" + "b" * 64, } replace_images(path, old, new, require_root=False) text, actual = read_images(path) self.assertEqual(actual, new) self.assertTrue(text.startswith("DATA_ROOT=/srv/data\n")) def test_stale_or_partial_reference_set_is_unchanged(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "production.env" original = "BACKEND_IMAGE=old/backend:tag\nOPENSEARCH_IMAGE=old/search:tag\n" path.write_text(original, encoding="utf-8") with self.assertRaisesRegex(ValueError, "changed"): replace_images(path, {"BACKEND_IMAGE": "stale", "OPENSEARCH_IMAGE": "old/search:tag"}, { "BACKEND_IMAGE": "new/backend:tag", "OPENSEARCH_IMAGE": "new/search:tag" }, require_root=False) self.assertEqual(path.read_text(encoding="utf-8"), original) def test_duplicate_and_missing_variables_fail_closed(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "production.env" path.write_text("BACKEND_IMAGE=a/b:tag\nBACKEND_IMAGE=a/b:tag\nOPENSEARCH_IMAGE=c/d:tag\n") with self.assertRaisesRegex(ValueError, "duplicate"): read_images(path) path.write_text("BACKEND_IMAGE=a/b:tag\n") with self.assertRaisesRegex(ValueError, "exactly one"): read_images(path) def test_indented_duplicate_assignment_is_not_ignored(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "production.env" path.write_text( "BACKEND_IMAGE=a/b:tag\n OPENSEARCH_IMAGE=attacker/search:tag\n" "OPENSEARCH_IMAGE=c/d:tag\n", encoding="utf-8", ) with self.assertRaisesRegex(ValueError, "plain KEY=value"): read_images(path) if __name__ == "__main__": unittest.main()