1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9 #include <executorch/extension/testing_util/temp_file.h>
10
11 #include <memory>
12 #include <string>
13
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <string.h>
17
18 #include <gtest/gtest.h>
19
20 using namespace ::testing;
21 using executorch::extension::testing::TempFile;
22
TEST(TempFileTest,Smoke)23 TEST(TempFileTest, Smoke) {
24 std::string path;
25 {
26 // Create a TempFile with known contents.
27 const char contents[] = "12345678";
28 TempFile tf(contents, sizeof(contents));
29 EXPECT_NE(tf.path(), "");
30
31 // Hold onto the path so we can check again later.
32 path = tf.path();
33
34 // Open the file by name.
35 int fd = open(tf.path().c_str(), O_RDONLY);
36 ASSERT_GE(fd, 0) << "Failed to open " << tf.path() << ": "
37 << strerror(errno);
38
39 // Read back the contents.
40 char buffer[128] = {};
41 ssize_t nread = read(fd, buffer, sizeof(buffer));
42 EXPECT_EQ(nread, sizeof(contents))
43 << "read(" << fd << ", ...) of " << sizeof(buffer)
44 << " bytes failed: " << strerror(errno);
45 close(fd);
46
47 // Make sure they're the same as what was provided.
48 EXPECT_EQ(0, memcmp(buffer, contents, sizeof(contents)));
49 }
50
51 // Destroying the TempFile should have deleted the file.
52 int fd = open(path.c_str(), O_RDONLY);
53 EXPECT_LT(fd, 0) << "File " << path << " should not exist";
54 }
55
TEST(TempFileTest,StringCtor)56 TEST(TempFileTest, StringCtor) {
57 // Create a TempFile using the std::string ctor.
58 std::string contents = "abcdefgh";
59 TempFile tf(contents);
60
61 // Open the file by name.
62 int fd = open(tf.path().c_str(), O_RDONLY);
63 ASSERT_GE(fd, 0) << "Failed to open " << tf.path() << ": " << strerror(errno);
64
65 // Read back the contents.
66 char buffer[128] = {};
67 ssize_t nread = read(fd, buffer, sizeof(buffer));
68 EXPECT_EQ(nread, contents.size())
69 << "read(" << fd << ", ...) of " << sizeof(buffer)
70 << " bytes failed: " << strerror(errno);
71 close(fd);
72
73 // Make sure they're the same as what was provided.
74 std::string actual(buffer, nread);
75 EXPECT_EQ(contents, actual);
76 }
77