1// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/basictypes.h"
6#include "base/file_util.h"
7#include "base/string_util.h"
8#include "net/disk_cache/disk_cache_test_base.h"
9#include "net/disk_cache/disk_cache_test_util.h"
10#include "net/disk_cache/mapped_file.h"
11#include "testing/gtest/include/gtest/gtest.h"
12
13namespace {
14
15int g_cache_tests_max_id;
16volatile int g_cache_tests_received;
17volatile bool g_cache_tests_error;
18
19// Implementation of FileIOCallback for the tests.
20class FileCallbackTest: public disk_cache::FileIOCallback {
21 public:
22  explicit FileCallbackTest(int id) : id_(id) {}
23  ~FileCallbackTest() {}
24
25  virtual void OnFileIOComplete(int bytes_copied);
26 private:
27  int id_;
28};
29
30void FileCallbackTest::OnFileIOComplete(int bytes_copied) {
31  if (id_ > g_cache_tests_max_id) {
32    NOTREACHED();
33    g_cache_tests_error = true;
34  }
35
36  g_cache_tests_received++;
37}
38
39}  // namespace
40
41TEST_F(DiskCacheTest, MappedFile_SyncIO) {
42  FilePath filename = GetCacheFilePath().AppendASCII("a_test");
43  scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
44  ASSERT_TRUE(CreateCacheTestFile(filename));
45  ASSERT_TRUE(file->Init(filename, 8192));
46
47  char buffer1[20];
48  char buffer2[20];
49  CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
50  base::strlcpy(buffer1, "the data", arraysize(buffer1));
51  EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 8192));
52  EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 8192));
53  EXPECT_STREQ(buffer1, buffer2);
54}
55
56TEST_F(DiskCacheTest, MappedFile_AsyncIO) {
57  FilePath filename = GetCacheFilePath().AppendASCII("a_test");
58  scoped_refptr<disk_cache::MappedFile> file(new disk_cache::MappedFile);
59  ASSERT_TRUE(CreateCacheTestFile(filename));
60  ASSERT_TRUE(file->Init(filename, 8192));
61
62  FileCallbackTest callback(1);
63  g_cache_tests_error = false;
64  g_cache_tests_max_id = 0;
65  g_cache_tests_received = 0;
66
67  MessageLoopHelper helper;
68
69  char buffer1[20];
70  char buffer2[20];
71  CacheTestFillBuffer(buffer1, sizeof(buffer1), false);
72  base::strlcpy(buffer1, "the data", arraysize(buffer1));
73  bool completed;
74  EXPECT_TRUE(file->Write(buffer1, sizeof(buffer1), 1024 * 1024, &callback,
75              &completed));
76  int expected = completed ? 0 : 1;
77
78  g_cache_tests_max_id = 1;
79  helper.WaitUntilCacheIoFinished(expected);
80
81  EXPECT_TRUE(file->Read(buffer2, sizeof(buffer2), 1024 * 1024, &callback,
82              &completed));
83  if (!completed)
84    expected++;
85
86  helper.WaitUntilCacheIoFinished(expected);
87
88  EXPECT_EQ(expected, g_cache_tests_received);
89  EXPECT_FALSE(g_cache_tests_error);
90  EXPECT_STREQ(buffer1, buffer2);
91}
92