File: favicon_source_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 (377 lines) | stat: -rw-r--r-- 14,398 bytes parent folder | download | duplicates (5)
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// 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 "chrome/browser/ui/webui/favicon_source.h"

#include <memory>
#include <utility>

#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/testing_profile.h"
#include "components/favicon/core/history_ui_favicon_request_handler.h"
#include "components/favicon/core/test/mock_favicon_service.h"
#include "components/favicon_base/favicon_url_parser.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/manifest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/native_theme/test_native_theme.h"
#include "ui/resources/grit/ui_resources.h"

using GotDataCallback = content::URLDataSource::GotDataCallback;
using WebContentsGetter = content::WebContents::Getter;
using testing::_;
using testing::NiceMock;
using testing::Return;
using testing::ReturnArg;

namespace {

const int kDummyTaskId = 1;
const char kDummyPrefix[] = "chrome://any-host/";

}  // namespace

class MockHistoryUiFaviconRequestHandler
    : public favicon::HistoryUiFaviconRequestHandler {
 public:
  MockHistoryUiFaviconRequestHandler() = default;
  ~MockHistoryUiFaviconRequestHandler() override = default;

  MOCK_METHOD4(GetRawFaviconForPageURL,
               void(const GURL& page_url,
                    int desired_size_in_pixel,
                    bool fallback_to_host,
                    favicon_base::FaviconRawBitmapCallback callback));

  MOCK_METHOD2(GetFaviconImageForPageURL,
               void(const GURL& page_url,
                    favicon_base::FaviconImageCallback callback));
};

class TestFaviconSource : public FaviconSource {
 public:
  TestFaviconSource(chrome::FaviconUrlFormat format,
                    Profile* profile,
                    ui::NativeTheme* theme,
                    bool serve_untrusted = false)
      : FaviconSource(profile, format, serve_untrusted), theme_(theme) {}

  ~TestFaviconSource() override = default;

  MOCK_METHOD(base::RefCountedMemory*, LoadIconBytes, (float, int));

 protected:
  // FaviconSource:
  ui::NativeTheme* GetNativeTheme(
      const content::WebContents::Getter& wc_getter) override {
    return theme_;
  }

 private:
  const raw_ptr<ui::NativeTheme> theme_;
};

class FaviconSourceTestBase : public testing::Test {
 public:
  explicit FaviconSourceTestBase(chrome::FaviconUrlFormat format,
                                 bool serve_untrusted = false)
      : source_(format, &profile_, &theme_, serve_untrusted) {
    Init();
  }

  void Init() {
    // Setup testing factories for main dependencies.
    mock_history_ui_favicon_request_handler_ =
        static_cast<NiceMock<MockHistoryUiFaviconRequestHandler>*>(
            HistoryUiFaviconRequestHandlerFactory::GetInstance()
                ->SetTestingFactoryAndUse(
                    &profile_, base::BindOnce([](content::BrowserContext*) {
                      return base::WrapUnique<KeyedService>(
                          new NiceMock<MockHistoryUiFaviconRequestHandler>());
                    })));
    mock_favicon_service_ = static_cast<NiceMock<favicon::MockFaviconService>*>(
        FaviconServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            &profile_, base::BindOnce([](content::BrowserContext*) {
              return static_cast<std::unique_ptr<KeyedService>>(
                  std::make_unique<NiceMock<favicon::MockFaviconService>>());
            })));

    // Setup TestWebContents.
    test_web_contents_ =
        content::WebContentsTester::CreateTestWebContents(&profile_, nullptr);
    test_web_contents_getter_ = base::BindLambdaForTesting(
        [&] { return (content::WebContents*)test_web_contents_.get(); });

    // On call, dependencies will return empty favicon by default.
    ON_CALL(*mock_favicon_service_, GetRawFaviconForPageURL(_, _, _, _, _, _))
        .WillByDefault([](auto, auto, auto, auto,
                          favicon_base::FaviconRawBitmapCallback callback,
                          auto) {
          std::move(callback).Run(favicon_base::FaviconRawBitmapResult());
          return kDummyTaskId;
        });
    ON_CALL(*mock_history_ui_favicon_request_handler_, GetRawFaviconForPageURL)
        .WillByDefault([](auto, auto, auto,
                          favicon_base::FaviconRawBitmapCallback callback) {
          std::move(callback).Run(favicon_base::FaviconRawBitmapResult());
        });

    // Mock default icon loading.
    ON_CALL(*source(), LoadIconBytes(_, _))
        .WillByDefault(Return(kDummyIconBytes.get()));
  }

  void SetDarkMode(bool dark_mode) { theme_.SetDarkMode(dark_mode); }

  NiceMock<TestFaviconSource>* source() { return &source_; }

 protected:
  const scoped_refptr<base::RefCountedBytes> kDummyIconBytes;
  content::BrowserTaskEnvironment task_environment_;
  content::RenderViewHostTestEnabler test_render_host_factories_;
  ui::TestNativeTheme theme_;
  TestingProfile profile_;
  raw_ptr<NiceMock<MockHistoryUiFaviconRequestHandler>>
      mock_history_ui_favicon_request_handler_;
  raw_ptr<NiceMock<favicon::MockFaviconService>> mock_favicon_service_;
  std::unique_ptr<content::WebContents> test_web_contents_;
  WebContentsGetter test_web_contents_getter_;
  NiceMock<TestFaviconSource> source_;
};

class FaviconSourceTestWithLegacyFormat : public FaviconSourceTestBase {
 public:
  FaviconSourceTestWithLegacyFormat()
      : FaviconSourceTestBase(chrome::FaviconUrlFormat::kFaviconLegacy) {}
};

TEST_F(FaviconSourceTestWithLegacyFormat, DarkDefault) {
  SetDarkMode(true);
  EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON_DARK));
  source()->StartDataRequest(GURL(kDummyPrefix), test_web_contents_getter_,
                             base::DoNothing());
}

TEST_F(FaviconSourceTestWithLegacyFormat, LightDefault) {
  SetDarkMode(false);
  EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON));
  source()->StartDataRequest(GURL(kDummyPrefix), test_web_contents_getter_,
                             base::DoNothing());
}

TEST_F(FaviconSourceTestWithLegacyFormat,
       ShouldNotQueryHistoryUiFaviconRequestHandler) {
  content::WebContentsTester::For(test_web_contents_.get())
      ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));

  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);

  source()->StartDataRequest(
      GURL(base::StrCat({kDummyPrefix, "size/16@1x/https://www.google.com"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_F(FaviconSourceTestWithLegacyFormat, ShouldNotQueryIfDesiredSizeTooLarge) {
  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFavicon).Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFaviconForPageURL).Times(0);

  // 1000x scale factor runs into the max cap.
  source()->StartDataRequest(
      GURL(
          base::StrCat({kDummyPrefix, "size/16@1000x/https://www.google.com"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_F(FaviconSourceTestWithLegacyFormat, ShouldNotQueryIfInvalidScaleFactor) {
  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFavicon).Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFaviconForPageURL).Times(0);

  // A negative scale factor cannot be parsed.
  source()->StartDataRequest(
      GURL(base::StrCat({kDummyPrefix, "size/16@-2x/https://www.google.com"})),
      test_web_contents_getter_, base::DoNothing());
}

class FaviconSourceTestWithFavicon2Format
    : public FaviconSourceTestBase,
      public testing::WithParamInterface<bool> {
 public:
  FaviconSourceTestWithFavicon2Format()
      : FaviconSourceTestBase(chrome::FaviconUrlFormat::kFavicon2,
                              /*serve_untrusted=*/GetParam()) {}
};

INSTANTIATE_TEST_SUITE_P(,
                         FaviconSourceTestWithFavicon2Format,
                         /*serve_untrusted=*/testing::Bool());

TEST_P(FaviconSourceTestWithFavicon2Format,
       ShouldNotRecordFaviconResourceHistogram) {
  base::HistogramTester tester;
  source()->StartDataRequest(
      GURL(base::StrCat({kDummyPrefix, "size/16@1x/https://www.google.com"})),
      test_web_contents_getter_, base::DoNothing());
  std::unique_ptr<base::HistogramSamples> samples(
      tester.GetHistogramSamplesSinceCreation(
          "Extensions.FaviconResourceUsed"));
  EXPECT_TRUE(samples);
  EXPECT_EQ(0, samples->TotalCount());
}

TEST_P(FaviconSourceTestWithFavicon2Format, DarkDefault) {
  SetDarkMode(true);
  EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON_DARK));
  source()->StartDataRequest(GURL(kDummyPrefix), test_web_contents_getter_,
                             base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format, LightDefault) {
  SetDarkMode(false);
  EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON));
  source()->StartDataRequest(GURL(kDummyPrefix), test_web_contents_getter_,
                             base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format, LightOverride) {
  SetDarkMode(true);
  EXPECT_CALL(*source(), LoadIconBytes(_, IDR_DEFAULT_FAVICON));
  source()->StartDataRequest(
      GURL(base::StrCat({kDummyPrefix,
                         "?pageUrl=https%3A%2F%2Fwww.google.com"
                         "&forceLightMode"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format,
       ShouldNotQueryHistoryUiFaviconRequestHandlerIfNotAllowed) {
  content::WebContentsTester::For(test_web_contents_.get())
      ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));

  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);

  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=1x&pageUrl=https%3A%2F%2Fwww.google."
           "com&allowGoogleServerFallback=0"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format,
       ShouldNotQueryHistoryUiFaviconRequestHandlerIfHasNotHistoryUiOrigin) {
  content::WebContentsTester::For(test_web_contents_.get())
      ->SetLastCommittedURL(GURL("chrome://non-history-url"));

  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);

  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=1x&pageUrl=https%3A%2F%2Fwww.google."
           "com&allowGoogleServerFallback=1"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(
    FaviconSourceTestWithFavicon2Format,
    ShouldQueryHistoryUiFaviconRequestHandlerIfHasHistoryUiOriginAndAllowed) {
  content::WebContentsTester::For(test_web_contents_.get())
      ->SetLastCommittedURL(GURL(chrome::kChromeUIHistoryURL));

  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL(GURL("https://www.google.com"), _, _, _))
      .Times(1);

  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=1x&pageUrl=https%3A%2F%2Fwww.google."
           "com&allowGoogleServerFallback=1"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(
    FaviconSourceTestWithFavicon2Format,
    ShouldQueryHistoryUiFaviconRequestHandlerIfHasDataSharingOriginAndAllowed) {
  content::WebContentsTester::For(test_web_contents_.get())
      ->SetLastCommittedURL(GURL(chrome::kChromeUIUntrustedDataSharingURL));

  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL(GURL("https://www.google.com"), _, _, _))
      .Times(1);

  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=1x&pageUrl=https%3A%2F%2Fwww.google."
           "com&allowGoogleServerFallback=1"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format,
       ShouldNotQueryIfDesiredSizeTooLarge) {
  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFavicon).Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFaviconForPageURL).Times(0);

  // 1000x scale factor runs into the max cap.
  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=1000x&pageUrl=https%3A%2F%2Fwww.google.com"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format,
       ShouldNotQueryIfInvalidScaleFactor) {
  EXPECT_CALL(*mock_history_ui_favicon_request_handler_,
              GetRawFaviconForPageURL)
      .Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFavicon).Times(0);
  EXPECT_CALL(*mock_favicon_service_, GetRawFaviconForPageURL).Times(0);

  // A negative scale factor cannot be parsed.
  source()->StartDataRequest(
      GURL(base::StrCat(
          {kDummyPrefix,
           "?size=16&scaleFactor=-2x&pageUrl=https%3A%2F%2Fwww.google.com"})),
      test_web_contents_getter_, base::DoNothing());
}

TEST_P(FaviconSourceTestWithFavicon2Format, ValidateGetSource) {
  bool serveUntrusted = GetParam();
  EXPECT_EQ(serveUntrusted ? chrome::kChromeUIUntrustedFavicon2URL
                           : chrome::kChromeUIFavicon2Host,
            source()->GetSource());
}