summaryrefslogtreecommitdiffstats
path: root/net/url_request/url_request_file_job_unittest.cc
blob: 427ed3d011453d833d7c711a5257d20a3042a0b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
267
268
// Copyright 2014 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.

#include "net/url_request/url_request_file_job.h"

#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h"
#include "net/base/filename_util.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

// A URLRequestFileJob for testing OnSeekComplete / OnReadComplete callbacks.
class URLRequestFileJobWithCallbacks : public URLRequestFileJob {
 public:
  URLRequestFileJobWithCallbacks(
      URLRequest* request,
      NetworkDelegate* network_delegate,
      const base::FilePath& file_path,
      const scoped_refptr<base::TaskRunner>& file_task_runner)
      : URLRequestFileJob(request,
                          network_delegate,
                          file_path,
                          file_task_runner),
        seek_position_(0) {
  }

  int64 seek_position() { return seek_position_; }
  const std::vector<std::string>& data_chunks() { return data_chunks_; }

 protected:
  ~URLRequestFileJobWithCallbacks() override {}

  void OnSeekComplete(int64 result) override {
    ASSERT_EQ(seek_position_, 0);
    seek_position_ = result;
  }

  void OnReadComplete(IOBuffer* buf, int result) override {
    data_chunks_.push_back(std::string(buf->data(), result));
  }

  int64 seek_position_;
  std::vector<std::string> data_chunks_;
};

// A URLRequestJobFactory that will return URLRequestFileJobWithCallbacks
// instances for file:// scheme URLs.
class CallbacksJobFactory : public URLRequestJobFactory {
 public:
  class JobObserver {
   public:
    virtual void OnJobCreated(URLRequestFileJobWithCallbacks* job) = 0;
  };

  CallbacksJobFactory(const base::FilePath& path, JobObserver* observer)
      : path_(path), observer_(observer) {
  }

  ~CallbacksJobFactory() override {}

  URLRequestJob* MaybeCreateJobWithProtocolHandler(
      const std::string& scheme,
      URLRequest* request,
      NetworkDelegate* network_delegate) const override {
    URLRequestFileJobWithCallbacks* job = new URLRequestFileJobWithCallbacks(
        request,
        network_delegate,
        path_,
        base::MessageLoop::current()->message_loop_proxy());
    observer_->OnJobCreated(job);
    return job;
  }

  URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
                                        NetworkDelegate* network_delegate,
                                        const GURL& location) const override {
    return nullptr;
  }

  URLRequestJob* MaybeInterceptResponse(
      URLRequest* request,
      NetworkDelegate* network_delegate) const override {
    return nullptr;
  }

  bool IsHandledProtocol(const std::string& scheme) const override {
    return scheme == "file";
  }

  bool IsHandledURL(const GURL& url) const override {
    return IsHandledProtocol(url.scheme());
  }

  bool IsSafeRedirectTarget(const GURL& location) const override {
    return false;
  }

 private:
  base::FilePath path_;
  JobObserver* observer_;
};

// Helper function to create a file in |directory| filled with
// |content|. Returns true on succes and fills in |path| with the full path to
// the file.
bool CreateTempFileWithContent(const std::string& content,
                               const base::ScopedTempDir& directory,
                               base::FilePath* path) {
  if (!directory.IsValid())
    return false;

  if (!base::CreateTemporaryFileInDir(directory.path(), path))
    return false;

  return base::WriteFile(*path, content.c_str(), content.length());
}

class JobObserverImpl : public CallbacksJobFactory::JobObserver {
 public:
  void OnJobCreated(URLRequestFileJobWithCallbacks* job) override {
    jobs_.push_back(job);
  }

  typedef std::vector<scoped_refptr<URLRequestFileJobWithCallbacks> > JobList;

  const JobList& jobs() { return jobs_; }

 protected:
  JobList jobs_;
};

// A simple holder for start/end used in http range requests.
struct Range {
  int start;
  int end;

  Range() {
    start = 0;
    end = 0;
  }

  Range(int start, int end) {
    this->start = start;
    this->end = end;
  }
};

// A superclass for tests of the OnSeekComplete / OnReadComplete functions of
// URLRequestFileJob.
class URLRequestFileJobEventsTest : public testing::Test {
 public:
  URLRequestFileJobEventsTest();

 protected:
  // This creates a file with |content| as the contents, and then creates and
  // runs a URLRequestFileJobWithCallbacks job to get the contents out of it,
  // and makes sure that the callbacks observed the correct bytes. If a Range
  // is provided, this function will add the appropriate Range http header to
  // the request and verify that only the bytes in that range (inclusive) were
  // observed.
  void RunRequest(const std::string& content, const Range* range);

  JobObserverImpl observer_;
  TestURLRequestContext context_;
  TestDelegate delegate_;
};

URLRequestFileJobEventsTest::URLRequestFileJobEventsTest() {}

void URLRequestFileJobEventsTest::RunRequest(const std::string& content,
                                             const Range* range) {
  base::ScopedTempDir directory;
  ASSERT_TRUE(directory.CreateUniqueTempDir());
  base::FilePath path;
  ASSERT_TRUE(CreateTempFileWithContent(content, directory, &path));
  CallbacksJobFactory factory(path, &observer_);
  context_.set_job_factory(&factory);

  scoped_ptr<URLRequest> request(context_.CreateRequest(
      FilePathToFileURL(path), DEFAULT_PRIORITY, &delegate_));
  if (range) {
    ASSERT_GE(range->start, 0);
    ASSERT_GE(range->end, 0);
    ASSERT_LE(range->start, range->end);
    ASSERT_LT(static_cast<unsigned int>(range->end), content.length());
    std::string range_value =
        base::StringPrintf("bytes=%d-%d", range->start, range->end);
    request->SetExtraRequestHeaderByName(
        HttpRequestHeaders::kRange, range_value, true /*overwrite*/);
  }
  request->Start();

  base::RunLoop loop;
  loop.Run();

  EXPECT_FALSE(delegate_.request_failed());
  int expected_length =
      range ? (range->end - range->start + 1) : content.length();
  EXPECT_EQ(delegate_.bytes_received(), expected_length);

  std::string expected_content;
  if (range) {
    expected_content.insert(0, content, range->start, expected_length);
  } else {
    expected_content = content;
  }
  EXPECT_TRUE(delegate_.data_received() == expected_content);

  ASSERT_EQ(observer_.jobs().size(), 1u);
  ASSERT_EQ(observer_.jobs().at(0)->seek_position(), range ? range->start : 0);

  std::string observed_content;
  const std::vector<std::string>& chunks =
      observer_.jobs().at(0)->data_chunks();
  for (std::vector<std::string>::const_iterator i = chunks.begin();
       i != chunks.end();
       ++i) {
    observed_content.append(*i);
  }
  EXPECT_EQ(expected_content, observed_content);
}

// Helper function to make a character array filled with |size| bytes of
// test content.
std::string MakeContentOfSize(int size) {
  EXPECT_GE(size, 0);
  std::string result;
  result.reserve(size);
  for (int i = 0; i < size; i++) {
    result.append(1, static_cast<char>(i % 256));
  }
  return result;
}

TEST_F(URLRequestFileJobEventsTest, TinyFile) {
  RunRequest(std::string("hello world"), NULL);
}

TEST_F(URLRequestFileJobEventsTest, SmallFile) {
  RunRequest(MakeContentOfSize(17 * 1024), NULL);
}

TEST_F(URLRequestFileJobEventsTest, BigFile) {
  RunRequest(MakeContentOfSize(3 * 1024 * 1024), NULL);
}

TEST_F(URLRequestFileJobEventsTest, Range) {
  // Use a 15KB content file and read a range chosen somewhat arbitrarily but
  // not aligned on any likely page boundaries.
  int size = 15 * 1024;
  Range range(1701, (6 * 1024) + 3);
  RunRequest(MakeContentOfSize(size), &range);
}

}  // namespace

}  // namespace net