update_engine: Fix leaking unit tests

Some of the unit tests have been leaking temp files because they don't
properly unlink them. In this CL, we did some rearrangement of the
ScopedTempFile class and moved it into the utils.h (instead of testing
only location) so it can be used everywhere and more efficiently. Also
added functionality to open an file descriptor too so users don't have
to keep a different object for the file descriptor.

BUG=b:162766400
TEST=cros_workon_make --board reef --test; Then looked at the
/build/reef/tmp directory and no files were leaked.

Change-Id: Id64a2923d30f27628120497fdefe16bf65fa3fb0
Reviewed-on: https://chromium-review.googlesource.com/c/aosp/platform/system/update_engine/+/2500772
Tested-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Jae Hoon Kim <kimjae@chromium.org>
Commit-Queue: Amin Hassani <ahassani@chromium.org>
diff --git a/payload_consumer/bzip_extent_writer_unittest.cc b/payload_consumer/bzip_extent_writer_unittest.cc
index 125e1e5..b587040 100644
--- a/payload_consumer/bzip_extent_writer_unittest.cc
+++ b/payload_consumer/bzip_extent_writer_unittest.cc
@@ -49,7 +49,7 @@
   void TearDown() override { fd_->Close(); }
 
   FileDescriptorPtr fd_;
-  test_utils::ScopedTempFile temp_file_{"BzipExtentWriterTest-file.XXXXXX"};
+  ScopedTempFile temp_file_{"BzipExtentWriterTest-file.XXXXXX"};
 };
 
 TEST_F(BzipExtentWriterTest, SimpleTest) {
diff --git a/payload_consumer/cached_file_descriptor_unittest.cc b/payload_consumer/cached_file_descriptor_unittest.cc
index d2965fc..b64420a 100644
--- a/payload_consumer/cached_file_descriptor_unittest.cc
+++ b/payload_consumer/cached_file_descriptor_unittest.cc
@@ -73,7 +73,7 @@
 
  protected:
   FileDescriptorPtr fd_{new EintrSafeFileDescriptor};
-  test_utils::ScopedTempFile temp_file_{"CachedFileDescriptor-file.XXXXXX"};
+  ScopedTempFile temp_file_{"CachedFileDescriptor-file.XXXXXX"};
   int value_{1};
   FileDescriptorPtr cfd_;
 };
diff --git a/payload_consumer/delta_performer_integration_test.cc b/payload_consumer/delta_performer_integration_test.cc
index 6857018..74ddd27 100644
--- a/payload_consumer/delta_performer_integration_test.cc
+++ b/payload_consumer/delta_performer_integration_test.cc
@@ -52,7 +52,9 @@
 
 namespace chromeos_update_engine {
 
+using std::list;
 using std::string;
+using std::unique_ptr;
 using std::vector;
 using test_utils::GetBuildArtifactsPath;
 using test_utils::kRandomString;
@@ -76,22 +78,24 @@
 
 namespace {
 struct DeltaState {
-  string a_img;
-  string b_img;
-  string result_img;
+  unique_ptr<ScopedTempFile> a_img;
+  unique_ptr<ScopedTempFile> b_img;
+  unique_ptr<ScopedTempFile> result_img;
   size_t image_size;
 
-  string delta_path;
+  unique_ptr<ScopedTempFile> delta_file;
+  // The in-memory copy of delta file.
+  brillo::Blob delta;
   uint64_t metadata_size;
   uint32_t metadata_signature_size;
 
-  string old_kernel;
+  unique_ptr<ScopedTempFile> old_kernel;
   brillo::Blob old_kernel_data;
 
-  string new_kernel;
+  unique_ptr<ScopedTempFile> new_kernel;
   brillo::Blob new_kernel_data;
 
-  string result_kernel;
+  unique_ptr<ScopedTempFile> result_kernel;
   brillo::Blob result_kernel_data;
   size_t kernel_size;
 
@@ -99,9 +103,6 @@
   // the DeltaPerformer.
   InstallPlan install_plan;
 
-  // The in-memory copy of delta file.
-  brillo::Blob delta;
-
   // Mock and fake instances used by the delta performer.
   FakeBootControl fake_boot_control_;
   FakeHardware fake_hardware_;
@@ -155,7 +156,7 @@
     EXPECT_EQ(expected, performer.ValidateManifest());
   }
   void AddPartition(DeltaArchiveManifest* manifest,
-                    std::string name,
+                    string name,
                     int timestamp) {
     auto& partition = *manifest->add_partitions();
     partition.set_version(std::to_string(timestamp));
@@ -259,8 +260,7 @@
   }
   string signature_size_string = base::JoinString(signature_size_strings, ":");
 
-  test_utils::ScopedTempFile hash_file("hash.XXXXXX"),
-      metadata_hash_file("hash.XXXXXX");
+  ScopedTempFile hash_file("hash.XXXXXX"), metadata_hash_file("hash.XXXXXX");
   string delta_generator_path = GetBuildArtifactsPath("delta_generator");
   ASSERT_EQ(0,
             System(base::StringPrintf(
@@ -273,29 +273,27 @@
                 metadata_hash_file.path().c_str())));
 
   // Sign the hash with all private keys.
-  vector<test_utils::ScopedTempFile> sig_files, metadata_sig_files;
+  list<ScopedTempFile> sig_files, metadata_sig_files;
   vector<string> sig_file_paths, metadata_sig_file_paths;
   for (const auto& key_path : private_key_paths) {
     brillo::Blob hash, signature;
     ASSERT_TRUE(utils::ReadFile(hash_file.path(), &hash));
     ASSERT_TRUE(PayloadSigner::SignHash(hash, key_path, &signature));
 
-    test_utils::ScopedTempFile sig_file("signature.XXXXXX");
-    ASSERT_TRUE(test_utils::WriteFileVector(sig_file.path(), signature));
-    sig_file_paths.push_back(sig_file.path());
-    sig_files.push_back(std::move(sig_file));
+    sig_files.emplace_back("signature.XXXXXX");
+    ASSERT_TRUE(
+        test_utils::WriteFileVector(sig_files.back().path(), signature));
+    sig_file_paths.push_back(sig_files.back().path());
 
     brillo::Blob metadata_hash, metadata_signature;
     ASSERT_TRUE(utils::ReadFile(metadata_hash_file.path(), &metadata_hash));
     ASSERT_TRUE(
         PayloadSigner::SignHash(metadata_hash, key_path, &metadata_signature));
 
-    test_utils::ScopedTempFile metadata_sig_file("signature.XXXXXX");
-    ASSERT_TRUE(test_utils::WriteFileVector(metadata_sig_file.path(),
+    metadata_sig_files.emplace_back("metadata_signature.XXXXXX");
+    ASSERT_TRUE(test_utils::WriteFileVector(metadata_sig_files.back().path(),
                                             metadata_signature));
-
-    metadata_sig_file_paths.push_back(metadata_sig_file.path());
-    metadata_sig_files.push_back(std::move(metadata_sig_file));
+    metadata_sig_file_paths.push_back(metadata_sig_files.back().path());
   }
   string sig_files_string = base::JoinString(sig_file_paths, ":");
   string metadata_sig_files_string =
@@ -377,7 +375,7 @@
         GetBuildArtifactsPath(kUnittestPrivateKey2Path));
   }
 
-  std::string public_key;
+  string public_key;
   if (signature_test == kSignatureGeneratedShellRotateCl2) {
     public_key = GetBuildArtifactsPath(kUnittestPublicKey2Path);
   } else if (signature_test == kSignatureGeneratedShellECKey) {
@@ -397,24 +395,23 @@
                               SignatureTest signature_test,
                               DeltaState* state,
                               uint32_t minor_version) {
-  EXPECT_TRUE(utils::MakeTempFile("a_img.XXXXXX", &state->a_img, nullptr));
-  EXPECT_TRUE(utils::MakeTempFile("b_img.XXXXXX", &state->b_img, nullptr));
+  state->a_img.reset(new ScopedTempFile("a_img.XXXXXX"));
+  state->b_img.reset(new ScopedTempFile("b_img.XXXXXX"));
 
   // result_img is used in minor version 2. Instead of applying the update
   // in-place on A, we apply it to a new image, result_img.
-  EXPECT_TRUE(
-      utils::MakeTempFile("result_img.XXXXXX", &state->result_img, nullptr));
+  state->result_img.reset(new ScopedTempFile("result_img.XXXXXX"));
 
   EXPECT_TRUE(
       base::CopyFile(GetBuildArtifactsPath().Append("gen/disk_ext2_4k.img"),
-                     base::FilePath(state->a_img)));
+                     base::FilePath(state->a_img->path())));
 
-  state->image_size = utils::FileSize(state->a_img);
+  state->image_size = utils::FileSize(state->a_img->path());
 
   // Make some changes to the A image.
   {
     string a_mnt;
-    ScopedLoopMounter b_mounter(state->a_img, &a_mnt, 0);
+    ScopedLoopMounter b_mounter(state->a_img->path(), &a_mnt, 0);
 
     brillo::Blob hardtocompress;
     while (hardtocompress.size() < 3 * kBlockSize) {
@@ -451,17 +448,18 @@
 
   // Create a result image with image_size bytes of garbage.
   brillo::Blob ones(state->image_size, 0xff);
-  EXPECT_TRUE(
-      utils::WriteFile(state->result_img.c_str(), ones.data(), ones.size()));
-  EXPECT_EQ(utils::FileSize(state->a_img), utils::FileSize(state->result_img));
+  EXPECT_TRUE(utils::WriteFile(
+      state->result_img->path().c_str(), ones.data(), ones.size()));
+  EXPECT_EQ(utils::FileSize(state->a_img->path()),
+            utils::FileSize(state->result_img->path()));
 
   EXPECT_TRUE(
       base::CopyFile(GetBuildArtifactsPath().Append("gen/disk_ext2_4k.img"),
-                     base::FilePath(state->b_img)));
+                     base::FilePath(state->b_img->path())));
   {
     // Make some changes to the B image.
     string b_mnt;
-    ScopedLoopMounter b_mounter(state->b_img, &b_mnt, 0);
+    ScopedLoopMounter b_mounter(state->b_img->path(), &b_mnt, 0);
     base::FilePath mnt_path(b_mnt);
 
     EXPECT_TRUE(base::CopyFile(mnt_path.Append("regular-small"),
@@ -509,18 +507,9 @@
         hardtocompress.size()));
   }
 
-  string old_kernel;
-  EXPECT_TRUE(
-      utils::MakeTempFile("old_kernel.XXXXXX", &state->old_kernel, nullptr));
-
-  string new_kernel;
-  EXPECT_TRUE(
-      utils::MakeTempFile("new_kernel.XXXXXX", &state->new_kernel, nullptr));
-
-  string result_kernel;
-  EXPECT_TRUE(utils::MakeTempFile(
-      "result_kernel.XXXXXX", &state->result_kernel, nullptr));
-
+  state->old_kernel.reset(new ScopedTempFile("old_kernel.XXXXXX"));
+  state->new_kernel.reset(new ScopedTempFile("new_kernel.XXXXXX"));
+  state->result_kernel.reset(new ScopedTempFile("result_kernel.XXXXXX"));
   state->kernel_size = kDefaultKernelSize;
   state->old_kernel_data.resize(kDefaultKernelSize);
   state->new_kernel_data.resize(state->old_kernel_data.size());
@@ -534,18 +523,17 @@
       std::begin(kNewData), std::end(kNewData), state->new_kernel_data.begin());
 
   // Write kernels to disk
-  EXPECT_TRUE(utils::WriteFile(state->old_kernel.c_str(),
+  EXPECT_TRUE(utils::WriteFile(state->old_kernel->path().c_str(),
                                state->old_kernel_data.data(),
                                state->old_kernel_data.size()));
-  EXPECT_TRUE(utils::WriteFile(state->new_kernel.c_str(),
+  EXPECT_TRUE(utils::WriteFile(state->new_kernel->path().c_str(),
                                state->new_kernel_data.data(),
                                state->new_kernel_data.size()));
-  EXPECT_TRUE(utils::WriteFile(state->result_kernel.c_str(),
+  EXPECT_TRUE(utils::WriteFile(state->result_kernel->path().c_str(),
                                state->result_kernel_data.data(),
                                state->result_kernel_data.size()));
 
-  EXPECT_TRUE(utils::MakeTempFile("delta.XXXXXX", &state->delta_path, nullptr));
-  LOG(INFO) << "delta path: " << state->delta_path;
+  state->delta_file.reset(new ScopedTempFile("delta.XXXXXX"));
   {
     const string private_key =
         signature_test == kSignatureGenerator
@@ -561,9 +549,10 @@
     if (!full_rootfs) {
       payload_config.source.partitions.emplace_back(kPartitionNameRoot);
       payload_config.source.partitions.emplace_back(kPartitionNameKernel);
-      payload_config.source.partitions.front().path = state->a_img;
+      payload_config.source.partitions.front().path = state->a_img->path();
       if (!full_kernel)
-        payload_config.source.partitions.back().path = state->old_kernel;
+        payload_config.source.partitions.back().path =
+            state->old_kernel->path();
       EXPECT_TRUE(payload_config.source.LoadImageSize());
       for (PartitionConfig& part : payload_config.source.partitions)
         EXPECT_TRUE(part.OpenFilesystem());
@@ -573,28 +562,30 @@
         payload_config.hard_chunk_size = 1024 * 1024;
     }
     payload_config.target.partitions.emplace_back(kPartitionNameRoot);
-    payload_config.target.partitions.back().path = state->b_img;
+    payload_config.target.partitions.back().path = state->b_img->path();
     payload_config.target.partitions.emplace_back(kPartitionNameKernel);
-    payload_config.target.partitions.back().path = state->new_kernel;
+    payload_config.target.partitions.back().path = state->new_kernel->path();
     EXPECT_TRUE(payload_config.target.LoadImageSize());
     for (PartitionConfig& part : payload_config.target.partitions)
       EXPECT_TRUE(part.OpenFilesystem());
 
     EXPECT_TRUE(payload_config.Validate());
-    EXPECT_TRUE(GenerateUpdatePayloadFile(
-        payload_config, state->delta_path, private_key, &state->metadata_size));
+    EXPECT_TRUE(GenerateUpdatePayloadFile(payload_config,
+                                          state->delta_file->path(),
+                                          private_key,
+                                          &state->metadata_size));
   }
   // Extend the "partitions" holding the file system a bit.
   EXPECT_EQ(0,
-            HANDLE_EINTR(truncate(state->a_img.c_str(),
+            HANDLE_EINTR(truncate(state->a_img->path().c_str(),
                                   state->image_size + 1024 * 1024)));
   EXPECT_EQ(static_cast<off_t>(state->image_size + 1024 * 1024),
-            utils::FileSize(state->a_img));
+            utils::FileSize(state->a_img->path()));
   EXPECT_EQ(0,
-            HANDLE_EINTR(truncate(state->b_img.c_str(),
+            HANDLE_EINTR(truncate(state->b_img->path().c_str(),
                                   state->image_size + 1024 * 1024)));
   EXPECT_EQ(static_cast<off_t>(state->image_size + 1024 * 1024),
-            utils::FileSize(state->b_img));
+            utils::FileSize(state->b_img->path()));
 
   if (signature_test == kSignatureGeneratedPlaceholder ||
       signature_test == kSignatureGeneratedPlaceholderMismatch) {
@@ -603,13 +594,13 @@
         GetBuildArtifactsPath(kUnittestPrivateKeyPath), &signature_size));
     LOG(INFO) << "Inserting placeholder signature.";
     ASSERT_TRUE(InsertSignaturePlaceholder(
-        signature_size, state->delta_path, &state->metadata_size));
+        signature_size, state->delta_file->path(), &state->metadata_size));
 
     if (signature_test == kSignatureGeneratedPlaceholderMismatch) {
       signature_size -= 1;
       LOG(INFO) << "Inserting mismatched placeholder signature.";
       ASSERT_FALSE(InsertSignaturePlaceholder(
-          signature_size, state->delta_path, &state->metadata_size));
+          signature_size, state->delta_file->path(), &state->metadata_size));
       return;
     }
   }
@@ -621,13 +612,13 @@
     // reflect the new size after adding the signature operation to the
     // manifest.
     LOG(INFO) << "Signing payload.";
-    SignGeneratedPayload(state->delta_path, &state->metadata_size);
+    SignGeneratedPayload(state->delta_file->path(), &state->metadata_size);
   } else if (signature_test == kSignatureGeneratedShell ||
              signature_test == kSignatureGeneratedShellECKey ||
              signature_test == kSignatureGeneratedShellBadKey ||
              signature_test == kSignatureGeneratedShellRotateCl1 ||
              signature_test == kSignatureGeneratedShellRotateCl2) {
-    SignGeneratedShellPayload(signature_test, state->delta_path);
+    SignGeneratedShellPayload(signature_test, state->delta_file->path());
   }
 }
 
@@ -641,7 +632,7 @@
                            uint32_t minor_version) {
   // Check the metadata.
   {
-    EXPECT_TRUE(utils::ReadFile(state->delta_path, &state->delta));
+    EXPECT_TRUE(utils::ReadFile(state->delta_file->path(), &state->delta));
     PayloadMetadata payload_metadata;
     EXPECT_TRUE(payload_metadata.ParsePayloadHeader(state->delta));
     state->metadata_size = payload_metadata.GetMetadataSize();
@@ -794,9 +785,10 @@
   (*performer)->set_public_key_path(public_key_path);
   (*performer)->set_update_certificates_path("");
 
-  EXPECT_EQ(static_cast<off_t>(state->image_size),
-            HashCalculator::RawHashOfFile(
-                state->a_img, state->image_size, &root_part.source_hash));
+  EXPECT_EQ(
+      static_cast<off_t>(state->image_size),
+      HashCalculator::RawHashOfFile(
+          state->a_img->path(), state->image_size, &root_part.source_hash));
   EXPECT_TRUE(HashCalculator::RawHashOfData(state->old_kernel_data,
                                             &kernel_part.source_hash));
 
@@ -804,13 +796,15 @@
   install_plan->partitions.clear();
 
   state->fake_boot_control_.SetPartitionDevice(
-      kPartitionNameRoot, install_plan->source_slot, state->a_img);
+      kPartitionNameRoot, install_plan->source_slot, state->a_img->path());
+  state->fake_boot_control_.SetPartitionDevice(kPartitionNameKernel,
+                                               install_plan->source_slot,
+                                               state->old_kernel->path());
   state->fake_boot_control_.SetPartitionDevice(
-      kPartitionNameKernel, install_plan->source_slot, state->old_kernel);
-  state->fake_boot_control_.SetPartitionDevice(
-      kPartitionNameRoot, install_plan->target_slot, state->result_img);
-  state->fake_boot_control_.SetPartitionDevice(
-      kPartitionNameKernel, install_plan->target_slot, state->result_kernel);
+      kPartitionNameRoot, install_plan->target_slot, state->result_img->path());
+  state->fake_boot_control_.SetPartitionDevice(kPartitionNameKernel,
+                                               install_plan->target_slot,
+                                               state->result_kernel->path());
 
   ErrorCode expected_error, actual_error;
   bool continue_writing;
@@ -889,12 +883,15 @@
     return;
   }
 
+  CompareFilesByBlock(state->result_kernel->path(),
+                      state->new_kernel->path(),
+                      state->kernel_size);
   CompareFilesByBlock(
-      state->result_kernel, state->new_kernel, state->kernel_size);
-  CompareFilesByBlock(state->result_img, state->b_img, state->image_size);
+      state->result_img->path(), state->b_img->path(), state->image_size);
 
   brillo::Blob updated_kernel_partition;
-  EXPECT_TRUE(utils::ReadFile(state->result_kernel, &updated_kernel_partition));
+  EXPECT_TRUE(
+      utils::ReadFile(state->result_kernel->path(), &updated_kernel_partition));
   ASSERT_GE(updated_kernel_partition.size(), base::size(kNewData));
   EXPECT_TRUE(std::equal(std::begin(kNewData),
                          std::end(kNewData),
@@ -913,9 +910,10 @@
 
   EXPECT_EQ(state->image_size, partitions[0].target_size);
   brillo::Blob expected_new_rootfs_hash;
-  EXPECT_EQ(static_cast<off_t>(state->image_size),
-            HashCalculator::RawHashOfFile(
-                state->b_img, state->image_size, &expected_new_rootfs_hash));
+  EXPECT_EQ(
+      static_cast<off_t>(state->image_size),
+      HashCalculator::RawHashOfFile(
+          state->b_img->path(), state->image_size, &expected_new_rootfs_hash));
   EXPECT_EQ(expected_new_rootfs_hash, partitions[0].target_hash);
 }
 
@@ -953,13 +951,6 @@
                     &state,
                     minor_version);
 
-  ScopedPathUnlinker a_img_unlinker(state.a_img);
-  ScopedPathUnlinker b_img_unlinker(state.b_img);
-  ScopedPathUnlinker new_img_unlinker(state.result_img);
-  ScopedPathUnlinker delta_unlinker(state.delta_path);
-  ScopedPathUnlinker old_kernel_unlinker(state.old_kernel);
-  ScopedPathUnlinker new_kernel_unlinker(state.new_kernel);
-  ScopedPathUnlinker result_kernel_unlinker(state.result_kernel);
   ApplyDeltaFile(full_kernel,
                  full_rootfs,
                  signature_test,
@@ -977,11 +968,6 @@
   DeltaState state;
   uint64_t minor_version = kFullPayloadMinorVersion;
   GenerateDeltaFile(true, true, -1, kSignatureGenerated, &state, minor_version);
-  ScopedPathUnlinker a_img_unlinker(state.a_img);
-  ScopedPathUnlinker b_img_unlinker(state.b_img);
-  ScopedPathUnlinker delta_unlinker(state.delta_path);
-  ScopedPathUnlinker old_kernel_unlinker(state.old_kernel);
-  ScopedPathUnlinker new_kernel_unlinker(state.new_kernel);
   DeltaPerformer* performer = nullptr;
   ApplyDeltaFile(true,
                  true,
diff --git a/payload_consumer/delta_performer_unittest.cc b/payload_consumer/delta_performer_unittest.cc
index 449201c..65b9dac 100644
--- a/payload_consumer/delta_performer_unittest.cc
+++ b/payload_consumer/delta_performer_unittest.cc
@@ -202,7 +202,7 @@
                                uint64_t major_version,
                                uint32_t minor_version,
                                PartitionConfig* old_part = nullptr) {
-    test_utils::ScopedTempFile blob_file("Blob-XXXXXX");
+    ScopedTempFile blob_file("Blob-XXXXXX");
     EXPECT_TRUE(test_utils::WriteFileVector(blob_file.path(), blob_data));
 
     PayloadGenerationConfig config;
@@ -236,7 +236,7 @@
     new_part.size = 0;
     payload.AddPartition(*old_part, new_part, {}, {});
 
-    test_utils::ScopedTempFile payload_file("Payload-XXXXXX");
+    ScopedTempFile payload_file("Payload-XXXXXX");
     string private_key =
         sign_payload ? GetBuildArtifactsPath(kUnittestPrivateKeyPath) : "";
     EXPECT_TRUE(payload.WritePayload(payload_file.path(),
@@ -287,7 +287,7 @@
                                   const string& source_path,
                                   const brillo::Blob& target_data,
                                   bool expect_success) {
-    test_utils::ScopedTempFile new_part("Partition-XXXXXX");
+    ScopedTempFile new_part("Partition-XXXXXX");
     EXPECT_TRUE(test_utils::WriteFileVector(new_part.path(), target_data));
 
     payload_.size = payload_data.size();
@@ -591,7 +591,7 @@
   EXPECT_TRUE(HashCalculator::RawHashOfData(expected_data, &src_hash));
   aop.op.set_src_sha256_hash(src_hash.data(), src_hash.size());
 
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   EXPECT_TRUE(test_utils::WriteFileVector(source.path(), expected_data));
 
   PartitionConfig old_part(kPartitionNameRoot);
@@ -619,7 +619,7 @@
   EXPECT_TRUE(HashCalculator::RawHashOfData(src, &src_hash));
   aop.op.set_src_sha256_hash(src_hash.data(), src_hash.size());
 
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   EXPECT_TRUE(test_utils::WriteFileVector(source.path(), src));
 
   PartitionConfig old_part(kPartitionNameRoot);
@@ -647,7 +647,7 @@
   EXPECT_TRUE(HashCalculator::RawHashOfData(expected_data, &src_hash));
   aop.op.set_src_sha256_hash(src_hash.data(), src_hash.size());
 
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   EXPECT_TRUE(test_utils::WriteFileVector(source.path(), actual_data));
 
   PartitionConfig old_part(kPartitionNameRoot);
@@ -664,7 +664,7 @@
 // since the source partition doesn't match the operation hash.
 TEST_F(DeltaPerformerTest, ErrorCorrectionSourceCopyFallbackTest) {
   constexpr size_t kCopyOperationSize = 4 * 4096;
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   // Write invalid data to the source image, which doesn't match the expected
   // hash.
   brillo::Blob invalid_data(kCopyOperationSize, 0x55);
@@ -692,7 +692,7 @@
 // file descriptor when the size of the error corrected one is too small.
 TEST_F(DeltaPerformerTest, ErrorCorrectionSourceCopyWhenNoHashFallbackTest) {
   constexpr size_t kCopyOperationSize = 4 * 4096;
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   // Setup the source path with the right expected data.
   brillo::Blob expected_data = FakeFileDescriptorData(kCopyOperationSize);
   EXPECT_TRUE(test_utils::WriteFileVector(source.path(), expected_data));
@@ -720,7 +720,7 @@
 
 TEST_F(DeltaPerformerTest, ChooseSourceFDTest) {
   constexpr size_t kSourceSize = 4 * 4096;
-  test_utils::ScopedTempFile source("Source-XXXXXX");
+  ScopedTempFile source("Source-XXXXXX");
   // Write invalid data to the source image, which doesn't match the expected
   // hash.
   brillo::Blob invalid_data(kSourceSize, 0x55);
diff --git a/payload_consumer/download_action_unittest.cc b/payload_consumer/download_action_unittest.cc
index e6ca219..9daa791 100644
--- a/payload_consumer/download_action_unittest.cc
+++ b/payload_consumer/download_action_unittest.cc
@@ -51,7 +51,6 @@
 using base::WriteFile;
 using std::string;
 using std::unique_ptr;
-using test_utils::ScopedTempFile;
 using testing::_;
 using testing::AtLeast;
 using testing::InSequence;
@@ -133,7 +132,6 @@
   loop.SetAsCurrent();
   FakeSystemState fake_system_state;
 
-  // TODO(adlr): see if we need a different file for build bots
   ScopedTempFile output_temp_file;
   TestDirectFileWriter writer;
   EXPECT_EQ(
diff --git a/payload_consumer/extent_reader_unittest.cc b/payload_consumer/extent_reader_unittest.cc
index b7059bc..686f14d 100644
--- a/payload_consumer/extent_reader_unittest.cc
+++ b/payload_consumer/extent_reader_unittest.cc
@@ -72,7 +72,7 @@
   }
 
   FileDescriptorPtr fd_;
-  test_utils::ScopedTempFile temp_file_{"ExtentReaderTest-file.XXXXXX"};
+  ScopedTempFile temp_file_{"ExtentReaderTest-file.XXXXXX"};
   brillo::Blob sample_;
 };
 
diff --git a/payload_consumer/extent_writer_unittest.cc b/payload_consumer/extent_writer_unittest.cc
index aef856b..afebb1a 100644
--- a/payload_consumer/extent_writer_unittest.cc
+++ b/payload_consumer/extent_writer_unittest.cc
@@ -59,7 +59,7 @@
   void WriteAlignedExtents(size_t chunk_size, size_t first_chunk_size);
 
   FileDescriptorPtr fd_;
-  test_utils::ScopedTempFile temp_file_{"ExtentWriterTest-file.XXXXXX"};
+  ScopedTempFile temp_file_{"ExtentWriterTest-file.XXXXXX"};
 };
 
 TEST_F(ExtentWriterTest, SimpleTest) {
diff --git a/payload_consumer/file_descriptor_utils_unittest.cc b/payload_consumer/file_descriptor_utils_unittest.cc
index 48e610f..478893d 100644
--- a/payload_consumer/file_descriptor_utils_unittest.cc
+++ b/payload_consumer/file_descriptor_utils_unittest.cc
@@ -52,14 +52,13 @@
 class FileDescriptorUtilsTest : public ::testing::Test {
  protected:
   void SetUp() override {
-    EXPECT_TRUE(utils::MakeTempFile("fd_tgt.XXXXXX", &tgt_path_, nullptr));
-    EXPECT_TRUE(target_->Open(tgt_path_.c_str(), O_RDWR));
+    EXPECT_TRUE(target_->Open(tgt_file_.path().c_str(), O_RDWR));
   }
 
   // Check that the |target_| file contains |expected_contents|.
   void ExpectTarget(const std::string& expected_contents) {
     std::string target_contents;
-    EXPECT_TRUE(utils::ReadFile(tgt_path_, &target_contents));
+    EXPECT_TRUE(utils::ReadFile(tgt_file_.path(), &target_contents));
     EXPECT_EQ(expected_contents.size(), target_contents.size());
     if (target_contents != expected_contents) {
       ADD_FAILURE() << "Contents don't match.";
@@ -70,8 +69,7 @@
     }
   }
 
-  // Path to the target temporary file.
-  std::string tgt_path_;
+  ScopedTempFile tgt_file_{"fd_tgt.XXXXXX"};
 
   // Source and target file descriptor used for testing the tools.
   FakeFileDescriptor* fake_source_{new FakeFileDescriptor()};
diff --git a/payload_consumer/file_writer_unittest.cc b/payload_consumer/file_writer_unittest.cc
index 59cfe2b..3b959f3 100644
--- a/payload_consumer/file_writer_unittest.cc
+++ b/payload_consumer/file_writer_unittest.cc
@@ -35,8 +35,7 @@
 class FileWriterTest : public ::testing::Test {};
 
 TEST(FileWriterTest, SimpleTest) {
-  // Create a uniquely named file for testing.
-  test_utils::ScopedTempFile file("FileWriterTest-XXXXXX");
+  ScopedTempFile file("FileWriterTest-XXXXXX");
   DirectFileWriter file_writer;
   EXPECT_EQ(0,
             file_writer.Open(file.path().c_str(),
@@ -60,7 +59,7 @@
 
 TEST(FileWriterTest, WriteErrorTest) {
   // Create a uniquely named file for testing.
-  test_utils::ScopedTempFile file("FileWriterTest-XXXXXX");
+  ScopedTempFile file("FileWriterTest-XXXXXX");
   DirectFileWriter file_writer;
   EXPECT_EQ(0,
             file_writer.Open(file.path().c_str(),
diff --git a/payload_consumer/filesystem_verifier_action_unittest.cc b/payload_consumer/filesystem_verifier_action_unittest.cc
index 2971849..2c29b44 100644
--- a/payload_consumer/filesystem_verifier_action_unittest.cc
+++ b/payload_consumer/filesystem_verifier_action_unittest.cc
@@ -92,7 +92,7 @@
 
 bool FilesystemVerifierActionTest::DoTest(bool terminate_early,
                                           bool hash_fail) {
-  test_utils::ScopedTempFile a_loop_file("a_loop_file.XXXXXX");
+  ScopedTempFile a_loop_file("a_loop_file.XXXXXX");
 
   // Make random data for a.
   const size_t kLoopFileSize = 10 * 1024 * 1024 + 512;
@@ -278,7 +278,7 @@
 
 #ifdef __ANDROID__
 TEST_F(FilesystemVerifierActionTest, RunAsRootWriteVerityTest) {
-  test_utils::ScopedTempFile part_file("part_file.XXXXXX");
+  ScopedTempFile part_file("part_file.XXXXXX");
   constexpr size_t filesystem_size = 200 * 4096;
   constexpr size_t part_size = 256 * 4096;
   brillo::Blob part_data(filesystem_size, 0x1);
@@ -340,7 +340,7 @@
 #endif  // __ANDROID__
 
 TEST_F(FilesystemVerifierActionTest, RunAsRootSkipWriteVerityTest) {
-  test_utils::ScopedTempFile part_file("part_file.XXXXXX");
+  ScopedTempFile part_file("part_file.XXXXXX");
   constexpr size_t filesystem_size = 200 * 4096;
   constexpr size_t part_size = 256 * 4096;
   brillo::Blob part_data(part_size);
diff --git a/payload_consumer/verity_writer_android_unittest.cc b/payload_consumer/verity_writer_android_unittest.cc
index f943ce8..ec22ffb 100644
--- a/payload_consumer/verity_writer_android_unittest.cc
+++ b/payload_consumer/verity_writer_android_unittest.cc
@@ -39,7 +39,7 @@
 
   VerityWriterAndroid verity_writer_;
   InstallPlan::Partition partition_;
-  test_utils::ScopedTempFile temp_file_;
+  ScopedTempFile temp_file_;
 };
 
 TEST_F(VerityWriterAndroidTest, SimpleTest) {