From f682b4786a4093efb23bf80d69bf80eb274b145b Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Fri, 6 Feb 2015 12:19:48 -0800 Subject: Clean up reading and writing in init. This isn't particularly useful in and of itself, but it does introduce the first (trivial) unit test, improves the documentation (including details about how to debug init crashes), and made me aware of how unpleasant the existing parser is. I also fixed a bug in passing --- unless you thought the "peboot" and "pm" commands were features... Bug: 19217569 Change-Id: I6ab76129a543ce3ed3dab52ef2c638009874c3de --- libutils/tests/file_test.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) (limited to 'libutils/tests') diff --git a/libutils/tests/file_test.cpp b/libutils/tests/file_test.cpp index acf66a6..3703a49 100644 --- a/libutils/tests/file_test.cpp +++ b/libutils/tests/file_test.cpp @@ -17,21 +17,68 @@ #include "utils/file.h" #include +#include +#include #include +class TemporaryFile { + public: + TemporaryFile() { + init("/data/local/tmp"); + if (fd == -1) { + init("/tmp"); + } + } + + ~TemporaryFile() { + close(fd); + unlink(filename); + } + + int fd; + char filename[1024]; + + private: + void init(const char* tmp_dir) { + snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir); + fd = mkstemp(filename); + } +}; + TEST(file, ReadFileToString_ENOENT) { std::string s("hello"); errno = 0; - EXPECT_FALSE(android::ReadFileToString("/proc/does-not-exist", &s)); + ASSERT_FALSE(android::ReadFileToString("/proc/does-not-exist", &s)); EXPECT_EQ(ENOENT, errno); EXPECT_EQ("", s); // s was cleared. } TEST(file, ReadFileToString_success) { std::string s("hello"); - EXPECT_TRUE(android::ReadFileToString("/proc/version", &s)); + ASSERT_TRUE(android::ReadFileToString("/proc/version", &s)) << errno; EXPECT_GT(s.length(), 6U); EXPECT_EQ('\n', s[s.length() - 1]); s[5] = 0; EXPECT_STREQ("Linux", s.c_str()); } + +TEST(file, WriteStringToFile) { + TemporaryFile tf; + ASSERT_TRUE(tf.fd != -1); + ASSERT_TRUE(android::WriteStringToFile("abc", tf.filename)) << errno; + std::string s; + ASSERT_TRUE(android::ReadFileToString(tf.filename, &s)) << errno; + EXPECT_EQ("abc", s); +} + +TEST(file, WriteStringToFd) { + TemporaryFile tf; + ASSERT_TRUE(tf.fd != -1); + ASSERT_TRUE(android::WriteStringToFd("abc", tf.fd)); + + ASSERT_EQ(0, lseek(tf.fd, 0, SEEK_SET)) << errno; + + std::string s; + ASSERT_TRUE(android::ReadFdToString(tf.fd, &s)) << errno; + EXPECT_EQ("abc", s); +} -- cgit v1.1