Add FileReader flag to decide if errors in opening file fatal/non-fatal

Flag default is fatal and will crash if errors in opening. If non-fatal,
log error instead of crashing. Added tests for the same.

Change-Id: I788416b86628055f137d0fc4a18fb62c0ca9177a
Signed-off-by: James Kuszmaul <james.kuszmaul@bluerivertech.com>
diff --git a/aos/util/file_test.cc b/aos/util/file_test.cc
index bd319b5..fb1befc 100644
--- a/aos/util/file_test.cc
+++ b/aos/util/file_test.cc
@@ -87,6 +87,7 @@
   ASSERT_EQ(0, system(("echo 123456789 > " + test_file).c_str()));
 
   FileReader reader(test_file);
+  EXPECT_TRUE(reader.is_open());
 
   aos::ScopedRealtime realtime;
   {
@@ -105,6 +106,30 @@
   EXPECT_EQ(123456789, reader.ReadInt32());
 }
 
+// Test reading a non-existent file.
+TEST(FileDeathTest, ReadNonExistentFile) {
+  const ::std::string test_file = "/dne";
+
+  // If error_type flag is not set or set to kFatal, this should fail.
+  EXPECT_DEATH(FileReader reader(test_file),
+               "opening " + test_file + ": No such file or directory");
+
+  FileReaderErrorType error_type = FileReaderErrorType::kFatal;
+  EXPECT_DEATH(FileReader reader(test_file, error_type),
+               "opening " + test_file + ": No such file or directory");
+
+  // If warning flag is set to true, read should not fail, is_open() should
+  // return false, ReadContents() and ReadInt32() should fail.
+  error_type = FileReaderErrorType::kNonFatal;
+  FileReader reader(test_file, error_type);
+  EXPECT_FALSE(reader.is_open());
+  std::array<char, 16> contents;
+  EXPECT_DEATH(
+      reader.ReadContents(absl::Span<char>(contents.data(), contents.size())),
+      "Bad file descriptor");
+  EXPECT_DEATH(reader.ReadInt32(), "Bad file descriptor");
+}
+
 // Tests that we can write to a file without malloc'ing.
 TEST(FileTest, WriteNormalFileNoMalloc) {
   const ::std::string tmpdir(aos::testing::TestTmpDir());