blob: 8e76154a6af8c527f29558483c6ce09f713971f6 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/util/file.h"
Brian Silverman61175fb2016-03-13 15:35:56 -04002
Tyler Chatowbf0609c2021-07-31 16:13:27 -07003#include <cstdlib>
Brian Silverman61175fb2016-03-13 15:35:56 -04004#include <string>
5
6#include "gtest/gtest.h"
James Kuszmaul0625b0d2022-09-21 11:38:48 -07007#include "aos/realtime.h"
8
9DECLARE_bool(die_on_malloc);
Brian Silverman61175fb2016-03-13 15:35:56 -040010
Brian Silverman61175fb2016-03-13 15:35:56 -040011namespace aos {
12namespace util {
13namespace testing {
14
Brian Silverman61175fb2016-03-13 15:35:56 -040015// Basic test of reading a normal file.
Alex Perrycb7da4b2019-08-28 19:35:56 -070016TEST(FileTest, ReadNormalFile) {
Brian Silverman61175fb2016-03-13 15:35:56 -040017 const ::std::string tmpdir(getenv("TEST_TMPDIR"));
18 const ::std::string test_file = tmpdir + "/test_file";
19 ASSERT_EQ(0, system(("echo contents > " + test_file).c_str()));
20 EXPECT_EQ("contents\n", ReadFileToStringOrDie(test_file));
21}
22
23// Tests reading a file with 0 size, among other weird things.
Alex Perrycb7da4b2019-08-28 19:35:56 -070024TEST(FileTest, ReadSpecialFile) {
Brian Silverman61175fb2016-03-13 15:35:56 -040025 const ::std::string stat = ReadFileToStringOrDie("/proc/self/stat");
26 EXPECT_EQ('\n', stat[stat.size() - 1]);
27 const ::std::string my_pid = ::std::to_string(getpid());
28 EXPECT_EQ(my_pid, stat.substr(0, my_pid.size()));
29}
30
James Kuszmaulf8178092020-05-10 18:46:45 -070031// Tests that the PathExists function works under normal conditions.
32TEST(FileTest, PathExistsTest) {
33 const std::string tmpdir(getenv("TEST_TMPDIR"));
34 const std::string test_file = tmpdir + "/test_file";
35 // Make sure the test_file doesn't exist.
36 unlink(test_file.c_str());
37 EXPECT_FALSE(PathExists(test_file));
38
39 WriteStringToFileOrDie(test_file, "abc");
40
41 EXPECT_TRUE(PathExists(test_file));
42}
43
James Kuszmaul0625b0d2022-09-21 11:38:48 -070044// Basic test of reading a normal file.
45TEST(FileTest, ReadNormalFileNoMalloc) {
46 const ::std::string tmpdir(getenv("TEST_TMPDIR"));
47 const ::std::string test_file = tmpdir + "/test_file";
48 ASSERT_EQ(0, system(("echo 971 > " + test_file).c_str()));
49
50 FileReader reader(test_file);
51
52 FLAGS_die_on_malloc = true;
53 RegisterMallocHook();
54 aos::ScopedRealtime realtime;
55 EXPECT_EQ("971\n", reader.ReadContents());
56 EXPECT_EQ(971, reader.ReadInt());
57}
58
Brian Silverman61175fb2016-03-13 15:35:56 -040059} // namespace testing
60} // namespace util
61} // namespace aos