1 /*
2 * Copyright 2021 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/system/file_wrapper.h"
12
13 #include "rtc_base/checks.h"
14 #include "test/gtest.h"
15 #include "test/testsupport/file_utils.h"
16
17 namespace webrtc {
18
TEST(FileWrapper,FileSize)19 TEST(FileWrapper, FileSize) {
20 auto test_info = ::testing::UnitTest::GetInstance()->current_test_info();
21 std::string test_name =
22 std::string(test_info->test_case_name()) + "_" + test_info->name();
23 std::replace(test_name.begin(), test_name.end(), '/', '_');
24 const std::string temp_filename = test::OutputPath() + test_name;
25
26 // Write
27 {
28 FileWrapper file = FileWrapper::OpenWriteOnly(temp_filename);
29 ASSERT_TRUE(file.is_open());
30 EXPECT_EQ(file.FileSize(), 0);
31
32 EXPECT_TRUE(file.Write("foo", 3));
33 EXPECT_EQ(file.FileSize(), 3);
34
35 // FileSize() doesn't change the file size.
36 EXPECT_EQ(file.FileSize(), 3);
37
38 // FileSize() doesn't move the write position.
39 EXPECT_TRUE(file.Write("bar", 3));
40 EXPECT_EQ(file.FileSize(), 6);
41 }
42
43 // Read
44 {
45 FileWrapper file = FileWrapper::OpenReadOnly(temp_filename);
46 ASSERT_TRUE(file.is_open());
47 EXPECT_EQ(file.FileSize(), 6);
48
49 char buf[10];
50 size_t bytes_read = file.Read(buf, 3);
51 EXPECT_EQ(bytes_read, 3u);
52 EXPECT_EQ(memcmp(buf, "foo", 3), 0);
53
54 // FileSize() doesn't move the read position.
55 EXPECT_EQ(file.FileSize(), 6);
56
57 // Attempting to read past the end reads what is available
58 // and sets the EOF flag.
59 bytes_read = file.Read(buf, 5);
60 EXPECT_EQ(bytes_read, 3u);
61 EXPECT_EQ(memcmp(buf, "bar", 3), 0);
62 EXPECT_TRUE(file.ReadEof());
63 }
64
65 // Clean up temporary file.
66 remove(temp_filename.c_str());
67 }
68
69 } // namespace webrtc
70