xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/util/temp_file_test.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "sandboxed_api/util/temp_file.h"
16 
17 #include <fcntl.h>
18 #include <unistd.h>
19 
20 #include <string>
21 #include <utility>
22 
23 #include "gmock/gmock.h"
24 #include "gtest/gtest.h"
25 #include "absl/status/status.h"
26 #include "absl/status/statusor.h"
27 #include "sandboxed_api/testing.h"
28 #include "sandboxed_api/util/fileops.h"
29 #include "sandboxed_api/util/path.h"
30 #include "sandboxed_api/util/status_matchers.h"
31 
32 namespace sapi {
33 namespace {
34 
35 using ::testing::Eq;
36 using ::testing::IsTrue;
37 using ::testing::Ne;
38 using ::testing::StartsWith;
39 
TEST(TempFileTest,CreateTempDirTest)40 TEST(TempFileTest, CreateTempDirTest) {
41   const std::string prefix = GetTestTempPath("MakeTempDirTest_");
42   SAPI_ASSERT_OK_AND_ASSIGN(std::string path, CreateTempDir(prefix));
43 
44   EXPECT_THAT(path, StartsWith(prefix));
45   EXPECT_THAT(file_util::fileops::Exists(path, false), IsTrue());
46   EXPECT_THAT(CreateTempDir("non_existing_dir/prefix"),
47               StatusIs(absl::StatusCode::kNotFound));
48 }
49 
TEST(TempFileTest,MakeTempFileTest)50 TEST(TempFileTest, MakeTempFileTest) {
51   const std::string prefix = GetTestTempPath("MakeTempDirTest_");
52 
53   auto result_or = CreateNamedTempFile(prefix);
54   ASSERT_THAT(result_or.status(), IsOk());
55   auto [path, fd] = std::move(result_or).value();
56 
57   EXPECT_THAT(path, StartsWith(prefix));
58   EXPECT_THAT(file_util::fileops::Exists(path, false), IsTrue());
59   EXPECT_THAT(fcntl(fd, F_GETFD), Ne(-1));
60   EXPECT_THAT(close(fd), Eq(0));
61   EXPECT_THAT(CreateNamedTempFile("non_existing_dir/prefix"),
62               StatusIs(absl::StatusCode::kNotFound));
63 }
64 
65 }  // namespace
66 }  // namespace sapi
67