File: network_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (241 lines) | stat: -rw-r--r-- 8,979 bytes parent folder | download | duplicates (3)
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
// 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 "chrome/updater/net/network.h"

#include <cstdint>
#include <memory>
#include <string>

#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/updater/net/network.h"
#include "chrome/updater/policy/service.h"
#include "chrome/updater/test/unit_test_util.h"
#include "components/update_client/network.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_WIN)
#include <Urlmon.h>
#endif

namespace updater {
namespace {

using ::base::test::RunClosure;
using ResponseStartedCallback =
    ::update_client::NetworkFetcher::ResponseStartedCallback;
using ProgressCallback = ::update_client::NetworkFetcher::ProgressCallback;
using PostRequestCompleteCallback =
    ::update_client::NetworkFetcher::PostRequestCompleteCallback;
using DownloadToFileCompleteCallback =
    ::update_client::NetworkFetcher::DownloadToFileCompleteCallback;

class UpdaterNetworkTest : public ::testing::Test {
 public:
  void StartedCallback(int response_code, int64_t content_length) {
    EXPECT_EQ(response_code, 200);
  }

  void ProgressCallback(int64_t current) {
    EXPECT_GE(current, 0);
    EXPECT_LE(current, 100);
  }

  void PostRequestCompleteCallback(const std::string& expected_body,
                                   std::optional<std::string> response_body,
                                   int net_error,
                                   const std::string& header_etag,
                                   const std::string& header_x_cup_server_proof,
                                   const std::string& header_set_cookie,
                                   int64_t xheader_retry_after_sec) {
    EXPECT_EQ(*response_body, expected_body);
    EXPECT_EQ(net_error, 0);
    EXPECT_EQ(header_etag, "Wfhw789h");
    EXPECT_EQ(header_x_cup_server_proof, "server-proof");
    EXPECT_EQ(header_set_cookie, "cookie");
    EXPECT_EQ(xheader_retry_after_sec, 67);
    PostRequestCompleted();
  }

  void DownloadCallback(const base::FilePath& test_file_path,
                        int net_error,
                        int64_t content_size) {
    EXPECT_EQ(net_error, 0);
    EXPECT_GT(content_size, 0);
    EXPECT_FALSE(test_file_path.empty());
    DownloadToFileCompleted();
  }

  std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
      const net::test_server::HttpRequest& request) {
    auto http_response =
        std::make_unique<net::test_server::BasicHttpResponse>();

    if (request.method == net::test_server::HttpMethod::METHOD_POST) {
      // Echo the posted data back.
      http_response->set_content(request.content);
      http_response->AddCustomHeader("x-retry-after", "67");
      http_response->AddCustomHeader("etag", "Wfhw789h");
      http_response->AddCustomHeader("x-cup-server-proof", "server-proof");
      http_response->AddCustomHeader(
          update_client::NetworkFetcher::kHeaderSetCookie, "cookie");
    } else if (request.method == net::test_server::HttpMethod::METHOD_GET) {
      http_response->set_content("hello");
      http_response->set_content_type("application/octet-stream");
    } else {
      ADD_FAILURE();
    }

    http_response->set_code(net::HTTP_OK);
    return http_response;
  }

  MOCK_METHOD(void, DownloadToFileCompleted, ());
  MOCK_METHOD(void, PostRequestCompleted, ());

 protected:
  base::test::TaskEnvironment task_environment_;
  base::RunLoop run_loop_;
  net::test_server::EmbeddedTestServer test_server_;
  std::unique_ptr<update_client::NetworkFetcher> fetcher_;

 private:
  void SetUp() override {
    test_server_.RegisterRequestHandler(base::BindRepeating(
        &UpdaterNetworkTest::HandleRequest, base::Unretained(this)));
    server_handle_ = test_server_.StartAndReturnHandle();
    ASSERT_TRUE(server_handle_);
    network_fetcher_factory_ = base::MakeRefCounted<NetworkFetcherFactory>(
        PolicyServiceProxyConfiguration::Get(test::CreateTestPolicyService()),
        /*event_logger=*/nullptr);
    fetcher_ = network_fetcher_factory_->Create();
  }

  net::test_server::EmbeddedTestServerHandle server_handle_;
  scoped_refptr<NetworkFetcherFactory> network_fetcher_factory_;
};

// Sets up a download for "chrome/updater/test/data/signed.exe" using the
// embedded test server running on localhost.
class UpdaterDownloadTest : public ::testing::Test {
 protected:
  base::FilePath dest_;
  GURL gurl_;

 private:
  void SetUp() override {
    server_.ServeFilesFromSourceDirectory("chrome/updater/test/data");
    server_handle_ = server_.StartAndReturnHandle();
    ASSERT_TRUE(scoped_dir_.CreateUniqueTempDir());
    dest_ = scoped_dir_.GetPath().AppendUTF8("updater-signed.exe");
    gurl_ = GURL(base::StrCat({server_.base_url().spec(), "signed.exe"}));
  }

  base::test::TaskEnvironment task_environment_;
  net::test_server::EmbeddedTestServer server_;
  net::test_server::EmbeddedTestServerHandle server_handle_;
  base::ScopedTempDir scoped_dir_;
};

}  // namespace

TEST_F(UpdaterNetworkTest, NetworkFetcherPostRequest) {
  base::ScopedDisallowBlocking no_blocking_allowed_on_sequence;
  const std::string kPostData = "\x01\x00\x55\x33\xda\x10\x44";
  EXPECT_CALL(*this, PostRequestCompleted())
      .WillOnce(RunClosure(run_loop_.QuitClosure()));
  fetcher_->PostRequest(
      test_server_.GetURL("/echo"), kPostData, {}, {},
      base::BindRepeating(&UpdaterNetworkTest::StartedCallback,
                          base::Unretained(this)),
      base::BindRepeating(&UpdaterNetworkTest::ProgressCallback,
                          base::Unretained(this)),
      base::BindOnce(&UpdaterNetworkTest::PostRequestCompleteCallback,
                     base::Unretained(this), kPostData));
  run_loop_.Run();
}

TEST_F(UpdaterNetworkTest, NetworkFetcherDownloadToFile) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath test_file_path =
      temp_dir.GetPath().Append(FILE_PATH_LITERAL("downloaded_file"));

  {
    base::ScopedDisallowBlocking no_blocking_allowed_on_sequence;

    EXPECT_CALL(*this, DownloadToFileCompleted())
        .WillOnce(RunClosure(run_loop_.QuitClosure()));
    fetcher_->DownloadToFile(
        test_server_.GetURL("/echo"), test_file_path,
        base::BindRepeating(&UpdaterNetworkTest::StartedCallback,
                            base::Unretained(this)),
        base::BindRepeating(&UpdaterNetworkTest::ProgressCallback,
                            base::Unretained(this)),
        base::BindOnce(&UpdaterNetworkTest::DownloadCallback,
                       base::Unretained(this), test_file_path));
    run_loop_.Run();
  }

  EXPECT_TRUE(base::PathExists(test_file_path));
}

TEST_F(UpdaterDownloadTest, NetworkFetcher) {
  EXPECT_FALSE(base::PathExists(dest_));

  base::RunLoop run_loop;
  auto factory = base::MakeRefCounted<NetworkFetcherFactory>(
      PolicyServiceProxyConfiguration::Get(test::CreateTestPolicyService()),
      /*event_logger=*/nullptr);
  ASSERT_NE(factory, nullptr);
  {
    base::ScopedDisallowBlocking no_blocking_allowed_on_sequence;
    std::unique_ptr<update_client::NetworkFetcher> fetcher = factory->Create();
    ASSERT_NE(fetcher, nullptr);
    fetcher->DownloadToFile(
        gurl_, dest_,
        base::BindRepeating([](int response_code, int64_t /*content_length*/) {
          EXPECT_EQ(response_code, 200);
        }),
        base::BindRepeating([](int64_t /*current*/) {}),
        base::BindOnce([](int net_error, int64_t content_size) {
          EXPECT_EQ(net_error, 0);
        }).Then(run_loop.QuitClosure()));
    run_loop.Run();
  }
  EXPECT_TRUE(base::PathExists(dest_));
}

#if BUILDFLAG(IS_WIN)
// Tests that a direct download through URL moniker from a local HTTP server is
// reasonably fast. This provides a baseline to compare the network throughput
// of various fetchers.
TEST_F(UpdaterDownloadTest, URLMonFetcher) {
  EXPECT_FALSE(base::PathExists(dest_));
  EXPECT_HRESULT_SUCCEEDED(
      ::URLDownloadToFile(nullptr, base::UTF8ToWide(gurl_.spec()).c_str(),
                          dest_.value().c_str(), 0, nullptr));
  EXPECT_TRUE(base::PathExists(dest_));
}
#endif
}  // namespace updater