aboutsummaryrefslogtreecommitdiff
path: root/chromeos/http/http_connection_curl_unittest.cc
blob: 06869ad1a71fe1e9434382255f3df8d36ecb8c4d (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
269
270
271
272
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
// Copyright 2014 The Chromium OS 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 <chromeos/http/http_connection_curl.h>

#include <algorithm>
#include <set>

#include <base/callback.h>
#include <chromeos/http/http_request.h>
#include <chromeos/http/http_transport.h>
#include <chromeos/http/mock_curl_api.h>
#include <chromeos/http/mock_transport.h>
#include <chromeos/streams/memory_stream.h>
#include <chromeos/streams/mock_stream.h>
#include <chromeos/strings/string_utils.h>
#include <chromeos/mime_utils.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

using testing::DoAll;
using testing::Invoke;
using testing::Return;
using testing::SetArgPointee;
using testing::_;

namespace chromeos {
namespace http {
namespace curl {

namespace {

using ReadWriteCallback =
    size_t(char* ptr, size_t size, size_t num, void* data);

// A helper class to simulate curl_easy_perform action. It invokes the
// read callbacks to obtain the request data from the Connection and then
// calls the header and write callbacks to "send" the response header and body.
class CurlPerformer {
 public:
  // During the tests, use the address of |this| as the CURL* handle.
  // This allows the static Perform() method to obtain the instance pointer
  // having only CURL*.
  CURL* GetCurlHandle() { return reinterpret_cast<CURL*>(this); }

  // Callback to be invoked when mocking out curl_easy_perform() method.
  static CURLcode Perform(CURL* curl) {
    CurlPerformer* me = reinterpret_cast<CurlPerformer*>(curl);
    return me->DoPerform();
  }

  // CURL callback functions and |connection| pointer needed to invoke the
  // callbacks from the Connection class.
  Connection* connection{nullptr};
  ReadWriteCallback* write_callback{nullptr};
  ReadWriteCallback* read_callback{nullptr};
  ReadWriteCallback* header_callback{nullptr};

  // Request body read from the connection.
  std::string request_body;

  // Response data to be sent back to connection.
  std::string status_line;
  HeaderList response_headers;
  std::string response_body;

 private:
  // The actual implementation of curl_easy_perform() fake.
  CURLcode DoPerform() {
    // Read request body.
    char buffer[1024];
    for (;;) {
      size_t size_read = read_callback(buffer, sizeof(buffer), 1, connection);
      if (size_read == CURL_READFUNC_ABORT)
        return CURLE_ABORTED_BY_CALLBACK;
      if (size_read == CURL_READFUNC_PAUSE)
        return CURLE_READ_ERROR;  // Shouldn't happen.
      if (size_read == 0)
        break;
      request_body.append(buffer, size_read);
    }

    // Send the response headers.
    std::vector<std::string> header_lines;
    header_lines.push_back(status_line + "\r\n");
    for (const auto& pair : response_headers) {
      header_lines.push_back(string_utils::Join(": ", pair.first, pair.second) +
                             "\r\n");
    }

    for (const std::string& line : header_lines) {
      CURLcode code = WriteString(header_callback, line);
      if (code != CURLE_OK)
        return code;
    }

    // Send response body.
    return WriteString(write_callback, response_body);
  }

  // Helper method to send a string to a write callback. Keeps calling
  // the callback until all the data is written.
  CURLcode WriteString(ReadWriteCallback* callback, const std::string& str) {
    size_t pos = 0;
    size_t size_remaining = str.size();
    while (size_remaining) {
      size_t size_written = callback(
          const_cast<char*>(str.data() + pos), size_remaining, 1, connection);
      if (size_written == CURL_WRITEFUNC_PAUSE)
        return CURLE_WRITE_ERROR;  // Shouldn't happen.
      CHECK(size_written <= size_remaining) << "Unexpected size returned";
      size_remaining -= size_written;
      pos += size_written;
    }
    return CURLE_OK;
  }
};

// Custom matcher to validate the parameter of CURLOPT_HTTPHEADER CURL option
// which contains the request headers as curl_slist* chain.
MATCHER_P(HeadersMatch, headers, "") {
  std::multiset<std::string> test_headers;
  for (const auto& pair : headers)
    test_headers.insert(string_utils::Join(": ", pair.first, pair.second));

  std::multiset<std::string> src_headers;
  const curl_slist* head = static_cast<const curl_slist*>(arg);
  while (head) {
    src_headers.insert(head->data);
    head = head->next;
  }

  std::vector<std::string> difference;
  std::set_symmetric_difference(src_headers.begin(), src_headers.end(),
                                test_headers.begin(), test_headers.end(),
                                std::back_inserter(difference));
  return difference.empty();
}

// Custom action to save a CURL callback pointer into a member of CurlPerformer.
ACTION_TEMPLATE(SaveCallback,
                HAS_1_TEMPLATE_PARAMS(int, k),
                AND_2_VALUE_PARAMS(performer, mem_ptr)) {
  performer->*mem_ptr = reinterpret_cast<ReadWriteCallback*>(std::get<k>(args));
}

}  // anonymous namespace

class HttpCurlConnectionTest : public testing::Test {
 public:
  void SetUp() override {
    curl_api_ = std::make_shared<MockCurlInterface>();
    transport_ = std::make_shared<MockTransport>();
    EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_PRIVATE, _))
        .WillOnce(Return(CURLE_OK));
    connection_ = std::make_shared<Connection>(
        handle_, request_type::kPost, curl_api_, transport_);
    performer_.connection = connection_.get();
  }

  void TearDown() override {
    EXPECT_CALL(*curl_api_, EasyCleanup(handle_)).Times(1);
    connection_.reset();
    transport_.reset();
    curl_api_.reset();
  }

 protected:
  std::shared_ptr<MockCurlInterface> curl_api_;
  std::shared_ptr<MockTransport> transport_;
  CurlPerformer performer_;
  CURL* handle_{performer_.GetCurlHandle()};
  std::shared_ptr<Connection> connection_;
};

TEST_F(HttpCurlConnectionTest, FinishRequestAsync) {
  std::string request_data{"Foo Bar Baz"};
  StreamPtr stream = MemoryStream::OpenRef(request_data, nullptr);
  EXPECT_TRUE(connection_->SetRequestData(std::move(stream), nullptr));
  EXPECT_TRUE(connection_->SendHeaders({{"X-Foo", "bar"}}, nullptr));

  if (VLOG_IS_ON(3)) {
    EXPECT_CALL(*curl_api_,
                EasySetOptCallback(handle_, CURLOPT_DEBUGFUNCTION, _))
        .WillOnce(Return(CURLE_OK));
    EXPECT_CALL(*curl_api_, EasySetOptInt(handle_, CURLOPT_VERBOSE, 1))
        .WillOnce(Return(CURLE_OK));
  }

  EXPECT_CALL(
      *curl_api_,
      EasySetOptOffT(handle_, CURLOPT_POSTFIELDSIZE_LARGE, request_data.size()))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasySetOptCallback(handle_, CURLOPT_READFUNCTION, _))
      .WillOnce(Return(CURLE_OK));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_READDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_HTTPHEADER, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasySetOptCallback(handle_, CURLOPT_WRITEFUNCTION, _))
      .WillOnce(Return(CURLE_OK));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_WRITEDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_,
              EasySetOptCallback(handle_, CURLOPT_HEADERFUNCTION, _))
      .WillOnce(Return(CURLE_OK));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_HEADERDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*transport_, StartAsyncTransfer(connection_.get(), _, _))
      .Times(1);
  connection_->FinishRequestAsync({}, {});
}

TEST_F(HttpCurlConnectionTest, FinishRequest) {
  std::string request_data{"Foo Bar Baz"};
  std::string response_data{"<html><body>OK</body></html>"};
  StreamPtr stream = MemoryStream::OpenRef(request_data, nullptr);
  HeaderList headers{
      {request_header::kAccept, "*/*"},
      {request_header::kContentType, mime::text::kPlain},
      {request_header::kContentLength, std::to_string(request_data.size())},
      {"X-Foo", "bar"},
  };
  std::unique_ptr<MockStream> response_stream(new MockStream);
  EXPECT_CALL(*response_stream, WriteAllBlocking(_, response_data.size(), _))
      .WillOnce(Return(true));
  EXPECT_CALL(*response_stream, CanSeek())
      .WillOnce(Return(false));
  connection_->SetResponseData(std::move(response_stream));
  EXPECT_TRUE(connection_->SetRequestData(std::move(stream), nullptr));
  EXPECT_TRUE(connection_->SendHeaders(headers, nullptr));

  // Expectations for Connection::FinishRequest() call.
  if (VLOG_IS_ON(3)) {
    EXPECT_CALL(*curl_api_,
                EasySetOptCallback(handle_, CURLOPT_DEBUGFUNCTION, _))
        .WillOnce(Return(CURLE_OK));
    EXPECT_CALL(*curl_api_, EasySetOptInt(handle_, CURLOPT_VERBOSE, 1))
        .WillOnce(Return(CURLE_OK));
  }

  EXPECT_CALL(
      *curl_api_,
      EasySetOptOffT(handle_, CURLOPT_POSTFIELDSIZE_LARGE, request_data.size()))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasySetOptCallback(handle_, CURLOPT_READFUNCTION, _))
      .WillOnce(
          DoAll(SaveCallback<2>(&performer_, &CurlPerformer::read_callback),
                Return(CURLE_OK)));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_READDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_,
              EasySetOptPtr(handle_, CURLOPT_HTTPHEADER, HeadersMatch(headers)))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasySetOptCallback(handle_, CURLOPT_WRITEFUNCTION, _))
      .WillOnce(
          DoAll(SaveCallback<2>(&performer_, &CurlPerformer::write_callback),
                Return(CURLE_OK)));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_WRITEDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_,
              EasySetOptCallback(handle_, CURLOPT_HEADERFUNCTION, _))
      .WillOnce(
          DoAll(SaveCallback<2>(&performer_, &CurlPerformer::header_callback),
                Return(CURLE_OK)));
  EXPECT_CALL(*curl_api_, EasySetOptPtr(handle_, CURLOPT_HEADERDATA, _))
      .WillOnce(Return(CURLE_OK));

  EXPECT_CALL(*curl_api_, EasyPerform(handle_))
      .WillOnce(Invoke(&CurlPerformer::Perform));

  EXPECT_CALL(*curl_api_, EasyGetInfoInt(handle_, CURLINFO_RESPONSE_CODE, _))
      .WillOnce(DoAll(SetArgPointee<2>(status_code::Ok), Return(CURLE_OK)));

  // Set up the CurlPerformer with the response data expected to be received.
  HeaderList response_headers{
      {response_header::kContentLength, std::to_string(response_data.size())},
      {response_header::kContentType, mime::text::kHtml},
      {"X-Foo", "baz"},
  };
  performer_.status_line = "HTTP/1.1 200 OK";
  performer_.response_body = response_data;
  performer_.response_headers = response_headers;

  // Perform the request.
  EXPECT_TRUE(connection_->FinishRequest(nullptr));

  // Make sure we sent out the request body correctly.
  EXPECT_EQ(request_data, performer_.request_body);

  // Validate the parsed response data.
  EXPECT_CALL(*curl_api_, EasyGetInfoInt(handle_, CURLINFO_RESPONSE_CODE, _))
      .WillOnce(DoAll(SetArgPointee<2>(status_code::Ok), Return(CURLE_OK)));
  EXPECT_EQ(status_code::Ok, connection_->GetResponseStatusCode());
  EXPECT_EQ("HTTP/1.1", connection_->GetProtocolVersion());
  EXPECT_EQ("OK", connection_->GetResponseStatusText());
  EXPECT_EQ(std::to_string(response_data.size()),
            connection_->GetResponseHeader(response_header::kContentLength));
  EXPECT_EQ(mime::text::kHtml,
            connection_->GetResponseHeader(response_header::kContentType));
  EXPECT_EQ("baz", connection_->GetResponseHeader("X-Foo"));
  auto data_stream = connection_->ExtractDataStream(nullptr);
  ASSERT_NE(nullptr, data_stream.get());
}

}  // namespace curl
}  // namespace http
}  // namespace chromeos