• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
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 //     http://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 "src/utils/io/tmpfile.h"
16 
17 #include <fstream>
18 
19 #include "gtest/gtest.h"
20 
21 namespace tint {
22 namespace utils {
23 namespace {
24 
TEST(TmpFileTest,WriteReadAppendDelete)25 TEST(TmpFileTest, WriteReadAppendDelete) {
26   std::string path;
27   {
28     TmpFile tmp;
29     if (!tmp) {
30       GTEST_SKIP() << "Unable to create a temporary file";
31     }
32 
33     path = tmp.Path();
34 
35     // Write a string to the temporary file
36     tmp << "hello world\n";
37 
38     // Check the content of the file
39     {
40       std::ifstream file(path);
41       ASSERT_TRUE(file);
42       std::string line;
43       EXPECT_TRUE(std::getline(file, line));
44       EXPECT_EQ(line, "hello world");
45       EXPECT_FALSE(std::getline(file, line));
46     }
47 
48     // Write some more content to the file
49     tmp << 42;
50 
51     // Check the content of the file again
52     {
53       std::ifstream file(path);
54       ASSERT_TRUE(file);
55       std::string line;
56       EXPECT_TRUE(std::getline(file, line));
57       EXPECT_EQ(line, "hello world");
58       EXPECT_TRUE(std::getline(file, line));
59       EXPECT_EQ(line, "42");
60       EXPECT_FALSE(std::getline(file, line));
61     }
62   }
63 
64   // Check the file has been deleted when it fell out of scope
65   std::ifstream file(path);
66   ASSERT_FALSE(file);
67 }
68 
TEST(TmpFileTest,FileExtension)69 TEST(TmpFileTest, FileExtension) {
70   const std::string kExt = ".foo";
71   std::string path;
72   {
73     TmpFile tmp(kExt);
74     if (!tmp) {
75       GTEST_SKIP() << "Unable create a temporary file";
76     }
77     path = tmp.Path();
78   }
79 
80   ASSERT_GT(path.length(), kExt.length());
81   EXPECT_EQ(kExt, path.substr(path.length() - kExt.length()));
82 
83   // Check the file has been deleted when it fell out of scope
84   std::ifstream file(path);
85   ASSERT_FALSE(file);
86 }
87 
88 }  // namespace
89 }  // namespace utils
90 }  // namespace tint
91