File: drivefs_http_client_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (251 lines) | stat: -rw-r--r-- 10,258 bytes parent folder | download | duplicates (8)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/drivefs/drivefs_http_client.h"

#include <initializer_list>
#include <string_view>
#include <utility>

#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/gmock_move_support.h"
#include "base/test/task_environment.h"
#include "chromeos/ash/components/drivefs/mojom/drivefs.mojom-shared.h"
#include "chromeos/ash/components/drivefs/mojom/drivefs.mojom-test-utils.h"
#include "chromeos/ash/components/drivefs/mojom/drivefs.mojom.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/data_pipe_utils.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/data_pipe_getter.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drivefs {
namespace mojom {

// This HttpResponsePtr ostream printer pretty prints the response in test
// failures.
std::ostream& operator<<(std::ostream& os, const HttpResponsePtr& response) {
  os << "response_code: " << response->response_code << std::endl;
  os << "headers: " << std::endl;
  for (const auto& header : response->headers) {
    os << "  " << header->key << ": " << header->value << std::endl;
  }
  return os;
}

}  // namespace mojom

namespace {

using testing::_;
using testing::Eq;
using testing::IsEmpty;
using testing::NiceMock;
using testing::Pointee;

using HttpHeaders = std::vector<mojom::HttpHeaderPtr>;
using HttpHeadersInitializerList =
    std::initializer_list<std::pair<std::string_view, std::string_view>>;

class MockHttpDelegate : public mojom::HttpDelegate {
 public:
  MOCK_METHOD(void,
              GetRequestBody,
              (mojo::ScopedDataPipeProducerHandle),
              (override));
  MOCK_METHOD(void, OnReceiveResponse, (mojom::HttpResponsePtr), (override));
  MOCK_METHOD(void,
              OnReceiveBody,
              (mojo::ScopedDataPipeConsumerHandle),
              (override));
  MOCK_METHOD(void,
              OnRequestComplete,
              (mojom::HttpCompletionStatusPtr),
              (override));
};

class DriveFsHttpClientTest : public testing::Test {
 public:
  DriveFsHttpClientTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        http_client_(
            base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
                &test_url_loader_factory_)) {}

  void BlockingCopyToString(std::string* result,
                            mojo::ScopedDataPipeConsumerHandle source) {
    EXPECT_TRUE(mojo::BlockingCopyToString(std::move(source), result));
  }

 protected:
  base::test::TaskEnvironment task_environment_;
  scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;
  network::TestURLLoaderFactory test_url_loader_factory_;

  DriveFsHttpClient http_client_;
};

struct ConsumeAllDataAndCompareWith {
  void operator()(mojo::ScopedDataPipeConsumerHandle handle) {
    std::string data;
    EXPECT_TRUE(mojo::BlockingCopyToString(std::move(handle), &data));
    EXPECT_EQ(data, expected_data);
  }

  std::string_view expected_data;
};

struct ProduceAllData {
  void operator()(mojo::ScopedDataPipeProducerHandle handle) {
    EXPECT_TRUE(mojo::BlockingCopyFromString(std::string(data), handle));
  }

  std::string_view data;
};

HttpHeaders HttpHeadersFromInitializerList(
    HttpHeadersInitializerList input_headers) {
  HttpHeaders headers;
  for (const auto& header : input_headers) {
    headers.push_back(mojom::HttpHeader::New(std::string{header.first},
                                             std::string{header.second}));
  }
  return headers;
}

network::mojom::URLResponseHeadPtr CreateURLResponseHead(
    net::HttpStatusCode http_status,
    HttpHeadersInitializerList input_headers) {
  auto head = network::mojom::URLResponseHead::New();
  const std::string status_line(
      base::StringPrintf("HTTP/1.1 %d %s", static_cast<int>(http_status),
                         net::GetHttpReasonPhrase(http_status)));
  head->headers = base::MakeRefCounted<net::HttpResponseHeaders>(
      net::HttpUtil::AssembleRawHeaders(status_line));
  for (const auto& header : input_headers) {
    head->headers->AddHeader(header.first, header.second);
  }
  return head;
}

TEST_F(DriveFsHttpClientTest, RequestHandlesRequestData) {
  constexpr char kTestURL[] = "https://drive.google.com";
  constexpr std::string_view kTestRequestData = "Test Request Data";
  const HttpHeadersInitializerList kTestRequestHeaders = {
      {"Test-Request-Header", "Test-Value"},
  };
  base::RunLoop run_loop;
  NiceMock<MockHttpDelegate> http_delegate;
  mojom::HttpCompletionStatus expected_status(mojom::NetError::kOk, 0);
  EXPECT_CALL(http_delegate,
              OnRequestComplete(Pointee(Eq(std::ref(expected_status)))))
      .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  EXPECT_CALL(http_delegate, GetRequestBody)
      .WillOnce(ProduceAllData{kTestRequestData});
  mojo::Receiver<mojom::HttpDelegate> http_receiver(&http_delegate);
  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  ASSERT_EQ(mojo::CreateDataPipe(nullptr, producer, consumer), MOJO_RESULT_OK);
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        const std::vector<network::DataElement>* elements =
            request.request_body->elements();
        ASSERT_EQ(elements->size(), 1UL);
        const network::DataElement& element = elements->front();
        mojo::Remote<network::mojom::DataPipeGetter> remote(
            element.As<network::DataElementDataPipe>().CloneDataPipeGetter());
        remote->Read(std::move(producer),
                     base::BindOnce([](int32_t, uint64_t) {}));
      }));
  http_client_.ExecuteHttpRequest(
      mojom::HttpRequest::New(
          /*method=*/"GET",
          /*url=*/kTestURL,
          /*headers=*/HttpHeadersFromInitializerList(kTestRequestHeaders),
          /*request_body_bytes=*/kTestRequestData.size()),
      http_receiver.BindNewPipeAndPassRemote());
  EXPECT_TRUE(
      test_url_loader_factory_.SimulateResponseForPendingRequest(kTestURL, ""));
  run_loop.Run();
  EXPECT_EQ(test_url_loader_factory_.NumPending(), 0);
  std::string data;
  EXPECT_TRUE(mojo::BlockingCopyToString(std::move(consumer), &data));
  EXPECT_EQ(data, kTestRequestData);
}

TEST_F(DriveFsHttpClientTest, RequestHandlesResponseData) {
  constexpr char kTestURL[] = "https://drive.google.com";
  constexpr std::string_view kTestResponseData = "Test Response Data";
  const HttpHeadersInitializerList kTestResponseHeaders = {
      {"Test-Response-Header", "Test-Value"},
  };
  base::RunLoop run_loop;
  NiceMock<MockHttpDelegate> http_delegate;
  mojom::HttpCompletionStatus expected_status(mojom::NetError::kOk,
                                              kTestResponseData.size());
  EXPECT_CALL(http_delegate,
              OnRequestComplete(Pointee(Eq(std::ref(expected_status)))))
      .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  mojom::HttpResponse expected_response(
      net::HTTP_OK, HttpHeadersFromInitializerList(kTestResponseHeaders));
  EXPECT_CALL(http_delegate,
              OnReceiveResponse(Pointee(Eq(std::ref(expected_response)))));
  EXPECT_CALL(http_delegate, OnReceiveBody)
      .WillOnce(ConsumeAllDataAndCompareWith{kTestResponseData});
  mojo::Receiver<mojom::HttpDelegate> http_receiver(&http_delegate);
  http_client_.ExecuteHttpRequest(mojom::HttpRequest::New(
                                      /*method=*/"GET",
                                      /*url=*/kTestURL,
                                      /*headers=*/HttpHeaders(),
                                      /*request_body_bytes=*/0),
                                  http_receiver.BindNewPipeAndPassRemote());
  EXPECT_TRUE(test_url_loader_factory_.SimulateResponseForPendingRequest(
      GURL(kTestURL), network::URLLoaderCompletionStatus(net::OK),
      CreateURLResponseHead(net::HTTP_OK, kTestResponseHeaders),
      std::string(kTestResponseData)));
  run_loop.Run();
  EXPECT_EQ(test_url_loader_factory_.NumPending(), 0);
}

TEST_F(DriveFsHttpClientTest, RequestCancelledOnRedirect) {
  constexpr char kTestURL[] = "https://drive.google.com";
  // Populate the URLLoaderFactory with a redirect.
  net::RedirectInfo redirect;
  redirect.status_code = 301;
  redirect.new_url = GURL("https://not_a_virus.google.com/");
  network::TestURLLoaderFactory::Redirects redirects;
  redirects.push_back({redirect, network::mojom::URLResponseHead::New()});
  test_url_loader_factory_.AddResponse(
      GURL(kTestURL), network::mojom::URLResponseHead::New(),
      /*content=*/"", network::URLLoaderCompletionStatus(),
      std::move(redirects),
      network::TestURLLoaderFactory::kResponseOnlyRedirectsNoDestination);
  // Run until the delegate is disconnected, there should be no callbacks.
  base::RunLoop run_loop;
  NiceMock<MockHttpDelegate> http_delegate;
  EXPECT_CALL(http_delegate, OnReceiveResponse).Times(0);
  EXPECT_CALL(http_delegate, OnRequestComplete).Times(0);
  mojo::Receiver<mojom::HttpDelegate> http_receiver(&http_delegate);
  mojo::PendingRemote<mojom::HttpDelegate> http_remote =
      http_receiver.BindNewPipeAndPassRemote();
  http_receiver.set_disconnect_handler(run_loop.QuitClosure());
  http_client_.ExecuteHttpRequest(mojom::HttpRequest::New(
                                      /*method=*/"GET",
                                      /*url=*/kTestURL,
                                      /*headers=*/HttpHeaders(),
                                      /*request_body_bytes=*/0),
                                  std::move(http_remote));
  run_loop.Run();
  EXPECT_EQ(test_url_loader_factory_.NumPending(), 0);
}

}  // namespace
}  // namespace drivefs