File: commerce_ui_tab_helper_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 (353 lines) | stat: -rw-r--r-- 13,810 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
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
// Copyright 2023 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/commerce/commerce_ui_tab_helper.h"

#include <memory>
#include <vector>

#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/default_clock.h"
#include "chrome/browser/ui/views/side_panel/side_panel_entry.h"
#include "chrome/browser/ui/views/side_panel/side_panel_registry.h"
#include "chrome/browser/ui/views/side_panel/side_panel_util.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/test_bookmark_client.h"
#include "components/commerce/core/commerce_feature_list.h"
#include "components/commerce/core/mock_account_checker.h"
#include "components/commerce/core/mock_shopping_service.h"
#include "components/commerce/core/price_tracking_utils.h"
#include "components/commerce/core/shopping_service.h"
#include "components/commerce/core/subscriptions/commerce_subscription.h"
#include "components/commerce/core/test_utils.h"
#include "components/image_fetcher/core/mock_image_fetcher.h"
#include "components/tabs/public/mock_tab_interface.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_web_contents_factory.h"
#include "content/public/test/web_contents_tester.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace commerce {

namespace {

const char kProductUrl[] = "http://example.com";
const char kProductImageUrl[] = "http://example.com/image.png";
const uint64_t kClusterId = 12345L;
const char kProductClusterTitle[] = "Product Cluster Title";

// Build a ProductInfo with the specified cluster ID, image URL and cluster
// title.
//   * If the image URL is not specified, it is left empty in the info object.
//   * If the cluster_title is not specified, it is left empty in the info
//   object.
std::optional<ProductInfo> CreateProductInfo(
    uint64_t cluster_id,
    const GURL& url = GURL(),
    const std::string cluster_title = std::string()) {
  std::optional<ProductInfo> info;
  info.emplace();
  info->product_cluster_id = cluster_id;
  if (!url.is_empty()) {
    info->image_url = url;
  }
  if (!cluster_title.empty()) {
    info->product_cluster_title = cluster_title;
  }
  return info;
}

}  // namespace

using ukm::builders::Shopping_ShoppingInformation;

class CommerceUiTabHelperTest : public testing::Test {
 public:
  CommerceUiTabHelperTest()
      : shopping_service_(std::make_unique<MockShoppingService>()),
        image_fetcher_(std::make_unique<image_fetcher::MockImageFetcher>()),
        account_checker_(std::make_unique<MockAccountChecker>()) {
    auto client = std::make_unique<bookmarks::TestBookmarkClient>();
    client->SetIsSyncFeatureEnabledIncludingBookmarks(true);
    bookmark_model_ =
        bookmarks::TestBookmarkClient::CreateModelWithClient(std::move(client));
    shopping_service_->SetAccountChecker(account_checker_.get());
  }

  CommerceUiTabHelperTest(const CommerceUiTabHelperTest&) = delete;
  CommerceUiTabHelperTest operator=(const CommerceUiTabHelperTest&) = delete;
  ~CommerceUiTabHelperTest() override = default;

  void SetUp() override {
    web_contents_ = test_web_contents_factory_.CreateWebContents(&profile_);
    ON_CALL(tab_interface_, GetContents())
        .WillByDefault(testing::Return(web_contents_));

    side_panel_registry_ = std::make_unique<SidePanelRegistry>(&tab_interface_);
    tab_helper_ = std::make_unique<commerce::CommerceUiTabHelper>(
        tab_interface_, shopping_service_.get(), bookmark_model_.get(),
        image_fetcher_.get(), side_panel_registry_.get());
  }

  void TestBody() override {}

  void TearDown() override {
    // Make sure the tab helper id destroyed before any of its dependencies are.
    tab_helper_.reset();
  }

  void SetupImageFetcherForSimpleImage() {
    ON_CALL(*image_fetcher_, FetchImageAndData_)
        .WillByDefault(
            [](const GURL& image_url,
               image_fetcher::ImageDataFetcherCallback* image_data_callback,
               image_fetcher::ImageFetcherCallback* image_callback,
               image_fetcher::ImageFetcherParams params) {
              SkBitmap bitmap;
              bitmap.allocN32Pixels(1, 1);
              gfx::Image image =
                  gfx::Image(gfx::ImageSkia::CreateFrom1xBitmap(bitmap));

              std::move(*image_callback)
                  .Run(std::move(image), image_fetcher::RequestMetadata());
            });
  }

  void SimulateNavigationCommitted(const GURL& url) {
    auto* web_content_tester =
        content::WebContentsTester::For(web_contents_.get());
    web_content_tester->SetLastCommittedURL(url);
    web_content_tester->NavigateAndCommit(url);
    web_content_tester->TestDidFinishLoad(url);

    base::RunLoop().RunUntilIdle();
  }

  // Passthrough to private methods in ShoppindListUiTabHelper:
  void HandleProductInfoResponse(const GURL& url,
                                 const std::optional<ProductInfo>& info) {
    tab_helper_->HandleProductInfoResponse(url, info);
  }

  // Passthrough methods for access to protected members.
  const std::optional<bool>& GetPendingTrackingStateForTesting() {
    return tab_helper_->GetPendingTrackingStateForTesting();
  }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  TestingProfile profile_;
  // Must outlive `web_contents_`.
  content::TestWebContentsFactory test_web_contents_factory_;
  raw_ptr<content::WebContents> web_contents_;
  tabs::MockTabInterface tab_interface_;
  std::unique_ptr<CommerceUiTabHelper> tab_helper_;
  std::unique_ptr<MockShoppingService> shopping_service_;
  std::unique_ptr<bookmarks::BookmarkModel> bookmark_model_;
  std::unique_ptr<image_fetcher::MockImageFetcher> image_fetcher_;
  std::unique_ptr<SidePanelRegistry> side_panel_registry_;
  std::unique_ptr<MockAccountChecker> account_checker_;
  base::test::ScopedFeatureList features_;
};

// The price tracking icon shouldn't be available if no image URL was provided
// by the shopping service.
TEST_F(CommerceUiTabHelperTest, TestPriceTrackingIconAvailabilityIfNoImage) {
  ASSERT_FALSE(tab_helper_->IsPriceTracking());

  AddProductBookmark(bookmark_model_.get(), u"title", GURL(kProductUrl),
                     kClusterId, true);

  // Intentionally exclude the image here.
  std::optional<ProductInfo> info = CreateProductInfo(kClusterId);
  // We do the setup for the image fetcher, but it won't be used since the
  // shopping service doesn't return an image URL.
  SetupImageFetcherForSimpleImage();

  shopping_service_->SetIsShoppingListEligible(true);
  shopping_service_->SetResponseForGetProductInfoForUrl(info);

  SimulateNavigationCommitted(GURL(kProductUrl));

  base::RunLoop().RunUntilIdle();

  ASSERT_FALSE(tab_helper_->ShouldShowPriceTrackingIconView());
  ASSERT_TRUE(tab_helper_->GetProductImageURL().is_empty());
}

// The price tracking state should not update in the helper if there is no image
// returbed by the shopping service.
TEST_F(CommerceUiTabHelperTest, TestPriceTrackingIconAvailabilityWithImage) {
  ASSERT_FALSE(tab_helper_->IsPriceTracking());

  AddProductBookmark(bookmark_model_.get(), u"title", GURL(kProductUrl),
                     kClusterId, true);

  std::optional<ProductInfo> info =
      CreateProductInfo(kClusterId, GURL(kProductImageUrl));
  SetupImageFetcherForSimpleImage();

  shopping_service_->SetIsShoppingListEligible(true);
  shopping_service_->SetResponseForGetProductInfoForUrl(info);
  shopping_service_->SetIsSubscribedCallbackValue(true);

  SimulateNavigationCommitted(GURL(kProductUrl));

  base::RunLoop().RunUntilIdle();

  ASSERT_TRUE(tab_helper_->ShouldShowPriceTrackingIconView());
  ASSERT_EQ(GURL(kProductImageUrl), tab_helper_->GetProductImageURL());
}

// Make sure unsubscribe without a bookmark for the current page is functional.
TEST_F(CommerceUiTabHelperTest, TestSubscriptionChangeNoBookmark) {
  // Intentionally create a bookmark with a URL different from the known
  // product URL but use the same cluster ID.
  AddProductBookmark(bookmark_model_.get(), u"title",
                     GURL("https://example.com/different_url.html"), kClusterId,
                     true);

  std::optional<ProductInfo> info =
      CreateProductInfo(kClusterId, GURL(kProductImageUrl));

  shopping_service_->SetResponseForGetProductInfoForUrl(info);
  shopping_service_->SetIsSubscribedCallbackValue(true);
  shopping_service_->SetSubscribeCallbackValue(true);

  SimulateNavigationCommitted(GURL(kProductUrl));

  EXPECT_CALL(
      *shopping_service_,
      Unsubscribe(VectorHasSubscriptionWithId(base::NumberToString(kClusterId)),
                  testing::_))
      .Times(1);

  tab_helper_->SetPriceTrackingState(false, true, base::DoNothing());
  base::RunLoop().RunUntilIdle();
}

TEST_F(CommerceUiTabHelperTest, TestShoppingInsightsSidePanelAvailable) {
  ASSERT_FALSE(side_panel_registry_->GetEntryForKey(
      SidePanelEntry::Key(SidePanelEntry::Id::kShoppingInsights)));

  commerce::SetUpPriceInsightsEligibility(&features_, account_checker_.get(),
                                          true);

  std::optional<ProductInfo> product_info = CreateProductInfo(
      kClusterId, GURL(kProductImageUrl), kProductClusterTitle);
  shopping_service_->SetResponseForGetProductInfoForUrl(product_info);

  std::optional<PriceInsightsInfo> price_insights_info =
      CreateValidPriceInsightsInfo(true, true, PriceBucket::kLowPrice);
  shopping_service_->SetResponseForGetPriceInsightsInfoForUrl(
      price_insights_info);

  SimulateNavigationCommitted(GURL(kProductUrl));

  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(side_panel_registry_->GetEntryForKey(
      SidePanelEntry::Key(SidePanelEntry::Id::kShoppingInsights)));
}

TEST_F(CommerceUiTabHelperTest, TestShoppingInsightsSidePanelUnavailable) {
  ASSERT_FALSE(side_panel_registry_->GetEntryForKey(
      SidePanelEntry::Key(SidePanelEntry::Id::kShoppingInsights)));

  shopping_service_->SetResponseForGetProductInfoForUrl(std::nullopt);
  commerce::SetUpPriceInsightsEligibility(&features_, account_checker_.get(),
                                          true);

  SimulateNavigationCommitted(GURL(kProductUrl));

  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(side_panel_registry_->GetEntryForKey(
      SidePanelEntry::Key(SidePanelEntry::Id::kShoppingInsights)));
}

TEST_F(CommerceUiTabHelperTest,
       TestPriceInsightsIconNotAvailableIfEmptyProductInfo) {
  commerce::SetUpPriceInsightsEligibility(&features_, account_checker_.get(),
                                          true);
  shopping_service_->SetResponseForGetProductInfoForUrl(std::nullopt);

  SimulateNavigationCommitted(GURL(kProductUrl));
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(tab_helper_->ShouldShowPriceInsightsIconView());
}

TEST_F(CommerceUiTabHelperTest,
       TestPriceInsightsIconNotAvailableIfNoProductClusterTitle) {
  commerce::SetUpPriceInsightsEligibility(&features_, account_checker_.get(),
                                          true);

  std::optional<ProductInfo> info =
      CreateProductInfo(kClusterId, GURL(kProductImageUrl));
  shopping_service_->SetResponseForGetProductInfoForUrl(info);

  SimulateNavigationCommitted(GURL(kProductUrl));
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(tab_helper_->ShouldShowPriceInsightsIconView());
}

TEST_F(CommerceUiTabHelperTest, TestRecordShoppingInformationUKM) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;

  features_.InitWithFeatures(
      {commerce::kPriceInsights, commerce::kEnableDiscountInfoApi}, {});
  commerce::SetUpDiscountEligibilityForAccount(account_checker_.get(), true);

  std::optional<ProductInfo> product_info = CreateProductInfo(
      kClusterId, GURL(kProductImageUrl), kProductClusterTitle);
  shopping_service_->SetResponseForGetProductInfoForUrl(product_info);

  std::optional<PriceInsightsInfo> price_insights_info =
      CreateValidPriceInsightsInfo(true, true, PriceBucket::kLowPrice);
  shopping_service_->SetResponseForGetPriceInsightsInfoForUrl(
      price_insights_info);
  shopping_service_->SetResponseForGetDiscountInfoForUrl(
      {commerce::CreateValidDiscountInfo(
          /*detail=*/"Get 10% off",
          /*terms_and_conditions=*/"",
          /*value_in_text=*/"$10 off", /*discount_code=*/"discount_code",
          /*id=*/123,
          /*is_merchant_wide=*/true,
          (base::DefaultClock::GetInstance()->Now() + base::Days(2))
              .InSecondsFSinceUnixEpoch())});

  SimulateNavigationCommitted(GURL(kProductUrl));

  base::RunLoop().RunUntilIdle();

  auto entries =
      ukm_recorder.GetEntriesByName(Shopping_ShoppingInformation::kEntryName);
  ASSERT_EQ(1u, entries.size());
  ukm_recorder.ExpectEntryMetric(
      entries[0], Shopping_ShoppingInformation::kHasPriceInsightsName, 1);
  ukm_recorder.ExpectEntryMetric(
      entries[0], Shopping_ShoppingInformation::kIsPriceTrackableName, 1);
  ukm_recorder.ExpectEntryMetric(
      entries[0], Shopping_ShoppingInformation::kIsShoppingContentName, 1);
  ukm_recorder.ExpectEntryMetric(
      entries[0], Shopping_ShoppingInformation::kHasDiscountName, 1);
}

}  // namespace commerce