File: prediction_model_fetcher_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (178 lines) | stat: -rw-r--r-- 6,836 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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/core/prediction_model_fetcher_impl.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "components/variations/scoped_variations_ids_provider.h"
#include "net/base/url_util.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace optimization_guide {

constexpr char optimization_guide_service_url[] =
    "https://optimizationguideservice.com/";

class PredictionModelFetcherTest : public testing::Test {
 public:
  PredictionModelFetcherTest()
      : task_environment_(base::test::TaskEnvironment::MainThreadType::UI),
        shared_url_loader_factory_(
            base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
                &test_url_loader_factory_)) {
    prediction_model_fetcher_ = std::make_unique<PredictionModelFetcherImpl>(
        shared_url_loader_factory_, GURL(optimization_guide_service_url));
  }

  PredictionModelFetcherTest(const PredictionModelFetcherTest&) = delete;
  PredictionModelFetcherTest& operator=(const PredictionModelFetcherTest&) =
      delete;

  ~PredictionModelFetcherTest() override = default;

  void OnModelsFetched(std::optional<std::unique_ptr<proto::GetModelsResponse>>
                           get_models_response) {
    if (get_models_response)
      models_fetched_ = true;
  }

  bool models_fetched() { return models_fetched_; }

 protected:
  bool FetchModels(const std::vector<proto::ModelInfo> models_request_info,
                   proto::RequestContext request_context,
                   const std::string& locale) {
    bool status =
        prediction_model_fetcher_->FetchOptimizationGuideServiceModels(
            models_request_info, request_context, locale,
            base::BindOnce(&PredictionModelFetcherTest::OnModelsFetched,
                           base::Unretained(this)));
    RunUntilIdle();
    return status;
  }

  // Return a 200 response with provided content to any pending requests.
  bool SimulateResponse(const std::string& content,
                        net::HttpStatusCode http_status) {
    return test_url_loader_factory_.SimulateResponseForPendingRequest(
        optimization_guide_service_url, content, http_status,
        network::TestURLLoaderFactory::kUrlMatchPrefix);
  }

  void VerifyHasPendingFetchRequests() {
    EXPECT_GE(test_url_loader_factory_.NumPending(), 1);
    std::string key_value;
    for (const auto& pending_request :
         *test_url_loader_factory_.pending_requests()) {
      EXPECT_EQ(pending_request.request.method, "POST");
      EXPECT_TRUE(net::GetValueForKeyInQuery(pending_request.request.url, "key",
                                             &key_value));
    }
  }

 private:
  void RunUntilIdle() {
    task_environment_.RunUntilIdle();
    base::RunLoop().RunUntilIdle();
  }

  bool models_fetched_ = false;
  base::test::TaskEnvironment task_environment_;
  variations::ScopedVariationsIdsProvider scoped_variations_ids_provider_{
      variations::VariationsIdsProvider::Mode::kUseSignedInState};

  std::unique_ptr<PredictionModelFetcherImpl> prediction_model_fetcher_;

  scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_;
  network::TestURLLoaderFactory test_url_loader_factory_;
};

TEST_F(PredictionModelFetcherTest, FetchOptimizationGuideServiceModels) {
  std::string response_content;
  proto::ModelInfo model_info;
  model_info.set_optimization_target(
      proto::OptimizationTarget::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD);
  EXPECT_TRUE(FetchModels({model_info},
                          proto::RequestContext::CONTEXT_BATCH_UPDATE_MODELS,
                          "en-US"));
  VerifyHasPendingFetchRequests();

  EXPECT_TRUE(SimulateResponse(response_content, net::HTTP_OK));
  EXPECT_TRUE(models_fetched());
}

// Tests 404 response from request.
TEST_F(PredictionModelFetcherTest, FetchReturned404) {
  base::HistogramTester histogram_tester;
  std::string response_content;

  proto::ModelInfo model_info;
  model_info.set_optimization_target(
      proto::OptimizationTarget::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD);
  EXPECT_TRUE(FetchModels({model_info},
                          proto::RequestContext::CONTEXT_BATCH_UPDATE_MODELS,
                          "en-US"));
  // Send a 404 to HintsFetcher.
  SimulateResponse(response_content, net::HTTP_NOT_FOUND);
  EXPECT_FALSE(models_fetched());
  histogram_tester.ExpectUniqueSample(
      "OptimizationGuide.PredictionModelFetcher."
      "GetModelsResponse.Status",
      net::HTTP_NOT_FOUND, 1);
  histogram_tester.ExpectUniqueSample(
      "OptimizationGuide.PredictionModelFetcher."
      "GetModelsResponse.Status.PainfulPageLoad",
      net::HTTP_NOT_FOUND, 1);

  // Net error codes are negative but UMA histograms require positive values.
  histogram_tester.ExpectUniqueSample(
      "OptimizationGuide.PredictionModelFetcher."
      "GetModelsResponse.NetErrorCode",
      -net::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
  histogram_tester.ExpectUniqueSample(
      "OptimizationGuide.PredictionModelFetcher."
      "GetModelsResponse.NetErrorCode.PainfulPageLoad",
      -net::ERR_HTTP_RESPONSE_CODE_FAILURE, 1);
}

TEST_F(PredictionModelFetcherTest, FetchReturnBadResponse) {
  std::string response_content = "not proto";

  proto::ModelInfo model_info;
  model_info.set_optimization_target(
      proto::OptimizationTarget::OPTIMIZATION_TARGET_PAINFUL_PAGE_LOAD);
  EXPECT_TRUE(FetchModels({model_info},
                          proto::RequestContext::CONTEXT_BATCH_UPDATE_MODELS,
                          "en-US"));
  VerifyHasPendingFetchRequests();
  EXPECT_TRUE(SimulateResponse(response_content, net::HTTP_OK));
  EXPECT_FALSE(models_fetched());
}

TEST_F(PredictionModelFetcherTest, EmptyModelInfo) {
  base::HistogramTester histogram_tester;
  std::string response_content;
  EXPECT_FALSE(FetchModels(/*models_request_info=*/{},
                           proto::RequestContext::CONTEXT_BATCH_UPDATE_MODELS,
                           "en-US"));

  EXPECT_FALSE(models_fetched());
}

}  // namespace optimization_guide