file_unittest.cc 15.9 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7 8
#include "butil/file_util.h"
#include "butil/files/file.h"
#include "butil/files/scoped_temp_dir.h"
#include "butil/time/time.h"
gejun's avatar
gejun committed
9 10
#include <gtest/gtest.h>

11 12
using butil::File;
using butil::FilePath;
gejun's avatar
gejun committed
13 14

TEST(FileTest, Create) {
15
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
16 17 18 19 20 21 22
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("create_file_1");

  {
    // Don't create a File at all.
    File file;
    EXPECT_FALSE(file.IsValid());
23
    EXPECT_EQ(butil::File::FILE_ERROR_FAILED, file.error_details());
gejun's avatar
gejun committed
24

25
    File file2(butil::File::FILE_ERROR_TOO_MANY_OPENED);
gejun's avatar
gejun committed
26
    EXPECT_FALSE(file2.IsValid());
27
    EXPECT_EQ(butil::File::FILE_ERROR_TOO_MANY_OPENED, file2.error_details());
gejun's avatar
gejun committed
28 29 30 31
  }

  {
    // Open a file that doesn't exist.
32
    File file(file_path, butil::File::FLAG_OPEN | butil::File::FLAG_READ);
gejun's avatar
gejun committed
33
    EXPECT_FALSE(file.IsValid());
34
    EXPECT_EQ(butil::File::FILE_ERROR_NOT_FOUND, file.error_details());
gejun's avatar
gejun committed
35 36 37 38
  }

  {
    // Open or create a file.
39
    File file(file_path, butil::File::FLAG_OPEN_ALWAYS | butil::File::FLAG_READ);
gejun's avatar
gejun committed
40 41
    EXPECT_TRUE(file.IsValid());
    EXPECT_TRUE(file.created());
42
    EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
43 44 45 46
  }

  {
    // Open an existing file.
47
    File file(file_path, butil::File::FLAG_OPEN | butil::File::FLAG_READ);
gejun's avatar
gejun committed
48 49
    EXPECT_TRUE(file.IsValid());
    EXPECT_FALSE(file.created());
50
    EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
51 52 53 54 55 56 57 58 59

    // This time verify closing the file.
    file.Close();
    EXPECT_FALSE(file.IsValid());
  }

  {
    // Open an existing file through Initialize
    File file;
60
    file.Initialize(file_path, butil::File::FLAG_OPEN | butil::File::FLAG_READ);
gejun's avatar
gejun committed
61 62
    EXPECT_TRUE(file.IsValid());
    EXPECT_FALSE(file.created());
63
    EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
64 65 66 67 68 69 70 71

    // This time verify closing the file.
    file.Close();
    EXPECT_FALSE(file.IsValid());
  }

  {
    // Create a file that exists.
72
    File file(file_path, butil::File::FLAG_CREATE | butil::File::FLAG_READ);
gejun's avatar
gejun committed
73 74
    EXPECT_FALSE(file.IsValid());
    EXPECT_FALSE(file.created());
75
    EXPECT_EQ(butil::File::FILE_ERROR_EXISTS, file.error_details());
gejun's avatar
gejun committed
76 77 78 79 80
  }

  {
    // Create or overwrite a file.
    File file(file_path,
81
              butil::File::FLAG_CREATE_ALWAYS | butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
82 83
    EXPECT_TRUE(file.IsValid());
    EXPECT_TRUE(file.created());
84
    EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
85 86 87 88 89 90
  }

  {
    // Create a delete-on-close file.
    file_path = temp_dir.path().AppendASCII("create_file_2");
    File file(file_path,
91 92
              butil::File::FLAG_OPEN_ALWAYS | butil::File::FLAG_READ |
                  butil::File::FLAG_DELETE_ON_CLOSE);
gejun's avatar
gejun committed
93 94
    EXPECT_TRUE(file.IsValid());
    EXPECT_TRUE(file.created());
95
    EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
96 97
  }

98
  EXPECT_FALSE(butil::PathExists(file_path));
gejun's avatar
gejun committed
99 100 101
}

TEST(FileTest, Async) {
102
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
103 104 105 106
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("create_file");

  {
107
    File file(file_path, butil::File::FLAG_OPEN_ALWAYS | butil::File::FLAG_ASYNC);
gejun's avatar
gejun committed
108 109 110 111 112
    EXPECT_TRUE(file.IsValid());
    EXPECT_TRUE(file.async());
  }

  {
113
    File file(file_path, butil::File::FLAG_OPEN_ALWAYS);
gejun's avatar
gejun committed
114 115 116 117 118 119
    EXPECT_TRUE(file.IsValid());
    EXPECT_FALSE(file.async());
  }
}

TEST(FileTest, DeleteOpenFile) {
120
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
121 122 123 124 125
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("create_file_1");

  // Create a file.
  File file(file_path,
126 127
            butil::File::FLAG_OPEN_ALWAYS | butil::File::FLAG_READ |
                butil::File::FLAG_SHARE_DELETE);
gejun's avatar
gejun committed
128 129
  EXPECT_TRUE(file.IsValid());
  EXPECT_TRUE(file.created());
130
  EXPECT_EQ(butil::File::FILE_OK, file.error_details());
gejun's avatar
gejun committed
131 132 133

  // Open an existing file and mark it as delete on close.
  File same_file(file_path,
134 135
                 butil::File::FLAG_OPEN | butil::File::FLAG_DELETE_ON_CLOSE |
                     butil::File::FLAG_READ);
gejun's avatar
gejun committed
136 137
  EXPECT_TRUE(file.IsValid());
  EXPECT_FALSE(same_file.created());
138
  EXPECT_EQ(butil::File::FILE_OK, same_file.error_details());
gejun's avatar
gejun committed
139 140 141 142

  // Close both handles and check that the file is gone.
  file.Close();
  same_file.Close();
143
  EXPECT_FALSE(butil::PathExists(file_path));
gejun's avatar
gejun committed
144 145 146
}

TEST(FileTest, ReadWrite) {
147
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
148 149 150
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("read_write_file");
  File file(file_path,
151 152
            butil::File::FLAG_CREATE | butil::File::FLAG_READ |
                butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  ASSERT_TRUE(file.IsValid());

  char data_to_write[] = "test";
  const int kTestDataSize = 4;

  // Write 0 bytes to the file.
  int bytes_written = file.Write(0, data_to_write, 0);
  EXPECT_EQ(0, bytes_written);

  // Write "test" to the file.
  bytes_written = file.Write(0, data_to_write, kTestDataSize);
  EXPECT_EQ(kTestDataSize, bytes_written);

  // Read from EOF.
  char data_read_1[32];
  int bytes_read = file.Read(kTestDataSize, data_read_1, kTestDataSize);
  EXPECT_EQ(0, bytes_read);

  // Read from somewhere in the middle of the file.
  const int kPartialReadOffset = 1;
  bytes_read = file.Read(kPartialReadOffset, data_read_1, kTestDataSize);
  EXPECT_EQ(kTestDataSize - kPartialReadOffset, bytes_read);
  for (int i = 0; i < bytes_read; i++)
    EXPECT_EQ(data_to_write[i + kPartialReadOffset], data_read_1[i]);

  // Read 0 bytes.
  bytes_read = file.Read(0, data_read_1, 0);
  EXPECT_EQ(0, bytes_read);

  // Read the entire file.
  bytes_read = file.Read(0, data_read_1, kTestDataSize);
  EXPECT_EQ(kTestDataSize, bytes_read);
  for (int i = 0; i < bytes_read; i++)
    EXPECT_EQ(data_to_write[i], data_read_1[i]);

  // Read again, but using the trivial native wrapper.
  bytes_read = file.ReadNoBestEffort(0, data_read_1, kTestDataSize);
  EXPECT_LE(bytes_read, kTestDataSize);
  for (int i = 0; i < bytes_read; i++)
    EXPECT_EQ(data_to_write[i], data_read_1[i]);

  // Write past the end of the file.
  const int kOffsetBeyondEndOfFile = 10;
  const int kPartialWriteLength = 2;
  bytes_written = file.Write(kOffsetBeyondEndOfFile,
                             data_to_write, kPartialWriteLength);
  EXPECT_EQ(kPartialWriteLength, bytes_written);

  // Make sure the file was extended.
  int64_t file_size = 0;
  EXPECT_TRUE(GetFileSize(file_path, &file_size));
  EXPECT_EQ(kOffsetBeyondEndOfFile + kPartialWriteLength, file_size);

  // Make sure the file was zero-padded.
  char data_read_2[32];
  bytes_read = file.Read(0, data_read_2, static_cast<int>(file_size));
  EXPECT_EQ(file_size, bytes_read);
  for (int i = 0; i < kTestDataSize; i++)
    EXPECT_EQ(data_to_write[i], data_read_2[i]);
  for (int i = kTestDataSize; i < kOffsetBeyondEndOfFile; i++)
    EXPECT_EQ(0, data_read_2[i]);
  for (int i = kOffsetBeyondEndOfFile; i < file_size; i++)
    EXPECT_EQ(data_to_write[i - kOffsetBeyondEndOfFile], data_read_2[i]);
}

TEST(FileTest, Append) {
219
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
220 221
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("append_file");
222
  File file(file_path, butil::File::FLAG_CREATE | butil::File::FLAG_APPEND);
gejun's avatar
gejun committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
  ASSERT_TRUE(file.IsValid());

  char data_to_write[] = "test";
  const int kTestDataSize = 4;

  // Write 0 bytes to the file.
  int bytes_written = file.Write(0, data_to_write, 0);
  EXPECT_EQ(0, bytes_written);

  // Write "test" to the file.
  bytes_written = file.Write(0, data_to_write, kTestDataSize);
  EXPECT_EQ(kTestDataSize, bytes_written);

  file.Close();
  File file2(file_path,
238 239
             butil::File::FLAG_OPEN | butil::File::FLAG_READ |
                 butil::File::FLAG_APPEND);
gejun's avatar
gejun committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  ASSERT_TRUE(file2.IsValid());

  // Test passing the file around.
  file = file2.Pass();
  EXPECT_FALSE(file2.IsValid());
  ASSERT_TRUE(file.IsValid());

  char append_data_to_write[] = "78";
  const int kAppendDataSize = 2;

  // Append "78" to the file.
  bytes_written = file.Write(0, append_data_to_write, kAppendDataSize);
  EXPECT_EQ(kAppendDataSize, bytes_written);

  // Read the entire file.
  char data_read_1[32];
  int bytes_read = file.Read(0, data_read_1,
                             kTestDataSize + kAppendDataSize);
  EXPECT_EQ(kTestDataSize + kAppendDataSize, bytes_read);
  for (int i = 0; i < kTestDataSize; i++)
    EXPECT_EQ(data_to_write[i], data_read_1[i]);
  for (int i = 0; i < kAppendDataSize; i++)
    EXPECT_EQ(append_data_to_write[i], data_read_1[kTestDataSize + i]);
}


TEST(FileTest, Length) {
267
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
268 269 270
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("truncate_file");
  File file(file_path,
271 272
            butil::File::FLAG_CREATE | butil::File::FLAG_READ |
                butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  ASSERT_TRUE(file.IsValid());
  EXPECT_EQ(0, file.GetLength());

  // Write "test" to the file.
  char data_to_write[] = "test";
  int kTestDataSize = 4;
  int bytes_written = file.Write(0, data_to_write, kTestDataSize);
  EXPECT_EQ(kTestDataSize, bytes_written);

  // Extend the file.
  const int kExtendedFileLength = 10;
  int64_t file_size = 0;
  EXPECT_TRUE(file.SetLength(kExtendedFileLength));
  EXPECT_EQ(kExtendedFileLength, file.GetLength());
  EXPECT_TRUE(GetFileSize(file_path, &file_size));
  EXPECT_EQ(kExtendedFileLength, file_size);

  // Make sure the file was zero-padded.
  char data_read[32];
  int bytes_read = file.Read(0, data_read, static_cast<int>(file_size));
  EXPECT_EQ(file_size, bytes_read);
  for (int i = 0; i < kTestDataSize; i++)
    EXPECT_EQ(data_to_write[i], data_read[i]);
  for (int i = kTestDataSize; i < file_size; i++)
    EXPECT_EQ(0, data_read[i]);

  // Truncate the file.
  const int kTruncatedFileLength = 2;
  EXPECT_TRUE(file.SetLength(kTruncatedFileLength));
  EXPECT_EQ(kTruncatedFileLength, file.GetLength());
  EXPECT_TRUE(GetFileSize(file_path, &file_size));
  EXPECT_EQ(kTruncatedFileLength, file_size);

  // Make sure the file was truncated.
  bytes_read = file.Read(0, data_read, kTestDataSize);
  EXPECT_EQ(file_size, bytes_read);
  for (int i = 0; i < file_size; i++)
    EXPECT_EQ(data_to_write[i], data_read[i]);
}

// Flakily fails: http://crbug.com/86494
#if defined(OS_ANDROID)
TEST(FileTest, TouchGetInfo) {
#else
TEST(FileTest, DISABLED_TouchGetInfo) {
#endif
319
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
320 321
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  File file(temp_dir.path().AppendASCII("touch_get_info_file"),
322 323
            butil::File::FLAG_CREATE | butil::File::FLAG_WRITE |
                butil::File::FLAG_WRITE_ATTRIBUTES);
gejun's avatar
gejun committed
324 325 326
  ASSERT_TRUE(file.IsValid());

  // Get info for a newly created file.
327
  butil::File::Info info;
gejun's avatar
gejun committed
328 329 330 331
  EXPECT_TRUE(file.GetInfo(&info));

  // Add 2 seconds to account for possible rounding errors on
  // filesystems that use a 1s or 2s timestamp granularity.
332
  butil::Time now = butil::Time::Now() + butil::TimeDelta::FromSeconds(2);
gejun's avatar
gejun committed
333 334 335 336 337 338
  EXPECT_EQ(0, info.size);
  EXPECT_FALSE(info.is_directory);
  EXPECT_FALSE(info.is_symbolic_link);
  EXPECT_LE(info.last_accessed.ToInternalValue(), now.ToInternalValue());
  EXPECT_LE(info.last_modified.ToInternalValue(), now.ToInternalValue());
  EXPECT_LE(info.creation_time.ToInternalValue(), now.ToInternalValue());
339
  butil::Time creation_time = info.creation_time;
gejun's avatar
gejun committed
340 341 342 343 344 345 346 347 348 349 350

  // Write "test" to the file.
  char data[] = "test";
  const int kTestDataSize = 4;
  int bytes_written = file.Write(0, data, kTestDataSize);
  EXPECT_EQ(kTestDataSize, bytes_written);

  // Change the last_accessed and last_modified dates.
  // It's best to add values that are multiples of 2 (in seconds)
  // to the current last_accessed and last_modified times, because
  // FATxx uses a 2s timestamp granularity.
351 352 353 354
  butil::Time new_last_accessed =
      info.last_accessed + butil::TimeDelta::FromSeconds(234);
  butil::Time new_last_modified =
      info.last_modified + butil::TimeDelta::FromMinutes(567);
gejun's avatar
gejun committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

  EXPECT_TRUE(file.SetTimes(new_last_accessed, new_last_modified));

  // Make sure the file info was updated accordingly.
  EXPECT_TRUE(file.GetInfo(&info));
  EXPECT_EQ(info.size, kTestDataSize);
  EXPECT_FALSE(info.is_directory);
  EXPECT_FALSE(info.is_symbolic_link);

  // ext2/ext3 and HPS/HPS+ seem to have a timestamp granularity of 1s.
#if defined(OS_POSIX)
  EXPECT_EQ(info.last_accessed.ToTimeVal().tv_sec,
            new_last_accessed.ToTimeVal().tv_sec);
  EXPECT_EQ(info.last_modified.ToTimeVal().tv_sec,
            new_last_modified.ToTimeVal().tv_sec);
#else
  EXPECT_EQ(info.last_accessed.ToInternalValue(),
            new_last_accessed.ToInternalValue());
  EXPECT_EQ(info.last_modified.ToInternalValue(),
            new_last_modified.ToInternalValue());
#endif

  EXPECT_EQ(info.creation_time.ToInternalValue(),
            creation_time.ToInternalValue());
}

TEST(FileTest, ReadAtCurrentPosition) {
382
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
383 384 385
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("read_at_current_position");
  File file(file_path,
386 387
            butil::File::FLAG_CREATE | butil::File::FLAG_READ |
                butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
388 389 390 391 392 393
  EXPECT_TRUE(file.IsValid());

  const char kData[] = "test";
  const int kDataSize = sizeof(kData) - 1;
  EXPECT_EQ(kDataSize, file.Write(0, kData, kDataSize));

394
  EXPECT_EQ(0, file.Seek(butil::File::FROM_BEGIN, 0));
gejun's avatar
gejun committed
395 396 397 398 399 400 401 402 403 404 405

  char buffer[kDataSize];
  int first_chunk_size = kDataSize / 2;
  EXPECT_EQ(first_chunk_size, file.ReadAtCurrentPos(buffer, first_chunk_size));
  EXPECT_EQ(kDataSize - first_chunk_size,
            file.ReadAtCurrentPos(buffer + first_chunk_size,
                                  kDataSize - first_chunk_size));
  EXPECT_EQ(std::string(buffer, buffer + kDataSize), std::string(kData));
}

TEST(FileTest, WriteAtCurrentPosition) {
406
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
407 408 409
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("write_at_current_position");
  File file(file_path,
410 411
            butil::File::FLAG_CREATE | butil::File::FLAG_READ |
                butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  EXPECT_TRUE(file.IsValid());

  const char kData[] = "test";
  const int kDataSize = sizeof(kData) - 1;

  int first_chunk_size = kDataSize / 2;
  EXPECT_EQ(first_chunk_size, file.WriteAtCurrentPos(kData, first_chunk_size));
  EXPECT_EQ(kDataSize - first_chunk_size,
            file.WriteAtCurrentPos(kData + first_chunk_size,
                                   kDataSize - first_chunk_size));

  char buffer[kDataSize];
  EXPECT_EQ(kDataSize, file.Read(0, buffer, kDataSize));
  EXPECT_EQ(std::string(buffer, buffer + kDataSize), std::string(kData));
}

TEST(FileTest, Seek) {
429
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
430 431 432
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath file_path = temp_dir.path().AppendASCII("seek_file");
  File file(file_path,
433 434
            butil::File::FLAG_CREATE | butil::File::FLAG_READ |
                butil::File::FLAG_WRITE);
gejun's avatar
gejun committed
435 436 437
  ASSERT_TRUE(file.IsValid());

  const int64_t kOffset = 10;
438 439 440
  EXPECT_EQ(kOffset, file.Seek(butil::File::FROM_BEGIN, kOffset));
  EXPECT_EQ(2 * kOffset, file.Seek(butil::File::FROM_CURRENT, kOffset));
  EXPECT_EQ(kOffset, file.Seek(butil::File::FROM_CURRENT, -kOffset));
gejun's avatar
gejun committed
441
  EXPECT_TRUE(file.SetLength(kOffset * 2));
442
  EXPECT_EQ(kOffset, file.Seek(butil::File::FROM_END, -kOffset));
gejun's avatar
gejun committed
443 444 445 446
}

#if defined(OS_WIN)
TEST(FileTest, GetInfoForDirectory) {
447
  butil::ScopedTempDir temp_dir;
gejun's avatar
gejun committed
448 449 450 451
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  FilePath empty_dir = temp_dir.path().Append(FILE_PATH_LITERAL("gpfi_test"));
  ASSERT_TRUE(CreateDirectory(empty_dir));

452
  butil::File dir(
gejun's avatar
gejun committed
453 454 455 456 457 458 459 460 461
      ::CreateFile(empty_dir.value().c_str(),
                   FILE_ALL_ACCESS,
                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                   NULL,
                   OPEN_EXISTING,
                   FILE_FLAG_BACKUP_SEMANTICS,  // Needed to open a directory.
                   NULL));
  ASSERT_TRUE(dir.IsValid());

462
  butil::File::Info info;
gejun's avatar
gejun committed
463 464 465 466 467 468
  EXPECT_TRUE(dir.GetInfo(&info));
  EXPECT_TRUE(info.is_directory);
  EXPECT_FALSE(info.is_symbolic_link);
  EXPECT_EQ(0, info.size);
}
#endif  // defined(OS_WIN)