@@ -826,3 +826,61 @@ def test_push_calls(mock_docker, mock_config, tagged_images, expected_call_count
826826 mpib .push ()
827827
828828 assert mock_docker .call_count == expected_call_count
829+
830+
831+ @pytest .mark .serial
832+ @patch ("buildrunner.docker.multiplatform_image_builder.new_client" )
833+ @patch ("buildrunner.docker.multiplatform_image_builder.docker.image.remove" )
834+ @patch ("buildrunner.docker.multiplatform_image_builder.docker.push" )
835+ @patch (
836+ "buildrunner.docker.multiplatform_image_builder.docker.buildx.imagetools.inspect"
837+ )
838+ @patch ("buildrunner.docker.multiplatform_image_builder.docker.buildx.build" )
839+ def test_cleanup_intermediate_images_on_exit (
840+ mock_build ,
841+ mock_imagetools_inspect ,
842+ mock_push ,
843+ mock_pow_remove ,
844+ mock_new_client ,
845+ ):
846+ mock_docker_client = MagicMock ()
847+ mock_new_client .return_value = mock_docker_client
848+ mock_imagetools_inspect .return_value = MagicMock ()
849+ mock_imagetools_inspect .return_value .config .digest = "fakedigest"
850+
851+ platforms = ["linux/amd64" , "linux/arm64" ]
852+ test_path = f"{ TEST_DIR } /test-files/multiplatform"
853+
854+ with MultiplatformImageBuilder () as mpib :
855+ built_image = mpib .build_multiple_images (
856+ platforms = platforms ,
857+ path = test_path ,
858+ file = f"{ test_path } /Dockerfile" ,
859+ use_threading = False ,
860+ )
861+ image_refs = [img .image_ref for img in built_image .built_images ]
862+ assert len (image_refs ) == 2
863+
864+ remove_calls = mock_docker_client .remove_image .call_args_list
865+ removed_refs = [c [0 ][0 ] for c in remove_calls ]
866+ for ref in image_refs :
867+ assert ref in removed_refs , f"Expected { ref } to be removed on exit"
868+
869+
870+ def test_cleanup_intermediate_images_on_exit_integration ():
871+ test_path = f"{ TEST_DIR } /test-files/multiplatform"
872+ platforms = ["linux/arm64" ]
873+
874+ with MultiplatformImageBuilder () as mpib :
875+ built_image = mpib .build_multiple_images (
876+ platforms = platforms ,
877+ path = test_path ,
878+ file = f"{ test_path } /Dockerfile" ,
879+ use_threading = False ,
880+ )
881+ image_ref = built_image .built_images [0 ].image_ref
882+ found = docker .image .list (filters = {"reference" : image_ref })
883+ assert len (found ) == 1 , "Image should exist before exit"
884+
885+ found = docker .image .list (filters = {"reference" : image_ref })
886+ assert len (found ) == 0 , "Intermediate image should be removed after exit"
0 commit comments