File: remote_suggestions_service_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 (777 lines) | stat: -rw-r--r-- 32,529 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/omnibox/browser/remote_suggestions_service.h"

#include <memory>
#include <string>

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/search_engines/search_engines_test_environment.h"
#include "components/search_engines/template_url_service.h"
#include "components/variations/scoped_variations_ids_provider.h"
#include "net/base/load_flags.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/metrics_proto/omnibox_event.pb.h"

namespace {

using testing::_;
using testing::Invoke;
using testing::NiceMock;

class TestObserver : public RemoteSuggestionsService::Observer {
 public:
  explicit TestObserver(RemoteSuggestionsService* service) : service_(service) {
    service_->AddObserver(this);
  }
  TestObserver(const TestObserver&) = delete;
  TestObserver& operator=(const TestObserver&) = delete;
  ~TestObserver() override { service_->RemoveObserver(this); }

  base::UnguessableToken request_id() { return request_id_; }
  GURL url() { return url_; }
  bool response_received() { return response_received_; }
  std::string response_body() { return response_body_; }

  // RemoteSuggestionsService::Observer:
  void OnRequestCreated(const base::UnguessableToken& request_id,
                        const network::ResourceRequest* request) override {
    request_id_ = request_id;
    url_ = request->url;
  }
  void OnRequestStarted(const base::UnguessableToken& request_id,
                        network::SimpleURLLoader* loader,
                        const std::string& request_body) override {
    ASSERT_EQ(request_id_, request_id);
  }
  void OnRequestCompleted(
      const base::UnguessableToken& request_id,
      const int response_code,
      const std::unique_ptr<std::string>& response_body) override {
    ASSERT_EQ(request_id_, request_id);
    response_received_ = true;
    response_body_ = response_body ? *response_body : "";
  }

 private:
  raw_ptr<RemoteSuggestionsService> service_;
  base::UnguessableToken request_id_;
  GURL url_;
  bool response_received_{false};
  std::string response_body_;
};

class MockDelegate : public NiceMock<RemoteSuggestionsService::Delegate> {
 public:
  explicit MockDelegate(RemoteSuggestionsService* service) {
    service->SetDelegate(weak_ptr_factory_.GetWeakPtr());
  }
  ~MockDelegate() override = default;
  MockDelegate(const MockDelegate&) = delete;
  MockDelegate& operator=(const MockDelegate&) = delete;

  // RemoteSuggestionsService::Delegate:
  MOCK_METHOD(
      void,
      OnRequestCompleted,
      (const network::SimpleURLLoader* source,
       const int response_code,
       std::unique_ptr<std::string> response_body,
       RemoteSuggestionsService::CompletionCallback completion_callback),
      (override));

  MOCK_METHOD(
      void,
      OnIndexedRequestCompleted,
      (const int request_index,
       const network::SimpleURLLoader* source,
       const int response_code,
       std::unique_ptr<std::string> response_body,
       RemoteSuggestionsService::IndexedCompletionCallback completion_callback),
      (override));
};

}  // namespace

class RemoteSuggestionsServiceTest : public testing::Test {
 public:
  RemoteSuggestionsServiceTest() = default;

  scoped_refptr<network::SharedURLLoaderFactory> GetUrlLoaderFactory() {
    return test_url_loader_factory_.GetSafeWeakWrapper();
  }

  void OnRequestCompleted(const network::SimpleURLLoader* source,
                          const int response_code,
                          std::unique_ptr<std::string> response_body) {
    response_body_ = response_body ? *response_body : "";
  }

  TemplateURLService& template_url_service() {
    return *search_engines_test_environment_.template_url_service();
  }

  std::string response_body() { return response_body_; }

 protected:
  base::test::SingleThreadTaskEnvironment task_environment_;
  variations::ScopedVariationsIdsProvider scoped_variations_ids_provider_{
      variations::VariationsIdsProvider::Mode::kUseSignedInState};
  network::TestURLLoaderFactory test_url_loader_factory_;
  search_engines::SearchEnginesTestEnvironment search_engines_test_environment_;
  std::string response_body_;
};

TEST_F(RemoteSuggestionsServiceTest, AttachCookies_ZeroPrefixSuggest) {
  network::ResourceRequest resource_request;
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        resource_request = request;
      }));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());

  TemplateURLRef::SearchTermsArgs search_terms_args;
  search_terms_args.current_page_url = "https://www.google.com/";
  auto loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(), search_terms_args,
      template_url_service().search_terms_data(), base::DoNothing());

  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(net::LOAD_DO_NOT_SAVE_COOKIES, resource_request.load_flags);
  EXPECT_TRUE(resource_request.site_for_cookies.IsEquivalent(
      net::SiteForCookies::FromUrl(resource_request.url)))
      << resource_request.site_for_cookies.ToDebugString();
  const std::string kRequestUrl = "https://www.google.com/complete/search";
  EXPECT_EQ(kRequestUrl,
            resource_request.url.spec().substr(0, kRequestUrl.size()));
}

TEST_F(RemoteSuggestionsServiceTest, AttachCookies_Suggest) {
  network::ResourceRequest resource_request;
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        resource_request = request;
      }));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());

  TemplateURLRef::SearchTermsArgs search_terms_args;
  search_terms_args.current_page_url = "https://www.google.com/";
  auto loader = service.StartSuggestionsRequest(
      RemoteRequestType::kSearch, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(), search_terms_args,
      template_url_service().search_terms_data(), base::DoNothing());

  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(resource_request.site_for_cookies.IsEquivalent(
      net::SiteForCookies::FromUrl(resource_request.url)))
      << resource_request.site_for_cookies.ToDebugString();
  const std::string kRequestUrl = "https://www.google.com/complete/search";
  EXPECT_EQ(kRequestUrl,
            resource_request.url.spec().substr(0, kRequestUrl.size()));
}

TEST_F(RemoteSuggestionsServiceTest, AttachCookies_DeleteSuggest) {
  network::ResourceRequest resource_request;
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        resource_request = request;
      }));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());
  auto loader = service.StartDeletionRequest(
      "https://google.com/complete/delete",
      /*is_off_the_record=*/false, base::DoNothing());

  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(resource_request.site_for_cookies.IsEquivalent(
      net::SiteForCookies::FromUrl(resource_request.url)))
      << resource_request.site_for_cookies.ToDebugString();
}

TEST_F(RemoteSuggestionsServiceTest, BypassCache) {
  network::ResourceRequest resource_request;
  test_url_loader_factory_.SetInterceptor(
      base::BindLambdaForTesting([&](const network::ResourceRequest& request) {
        resource_request = request;
      }));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());

  TemplateURLRef::SearchTermsArgs search_terms_args;
  search_terms_args.current_page_url = "https://www.google.com/";
  search_terms_args.bypass_cache = true;
  auto loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(), search_terms_args,
      template_url_service().search_terms_data(), base::DoNothing());

  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_BYPASS_CACHE,
            resource_request.load_flags);
  EXPECT_TRUE(resource_request.site_for_cookies.IsEquivalent(
      net::SiteForCookies::FromUrl(resource_request.url)))
      << resource_request.site_for_cookies.ToDebugString();
  const std::string kRequestUrl = "https://www.google.com/complete/search";
  EXPECT_EQ(kRequestUrl,
            resource_request.url.spec().substr(0, kRequestUrl.size()));
}

TEST_F(RemoteSuggestionsServiceTest, Observer) {
  base::HistogramTester histogram_tester;

  TemplateURLData template_url_data;
  template_url_data.suggestions_url = "https://www.example.com/suggest";
  template_url_service().SetUserSelectedDefaultSearchProvider(
      template_url_service().Add(
          std::make_unique<TemplateURL>(template_url_data)));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());
  TestObserver observer(&service);
  auto loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(),
      TemplateURLRef::SearchTermsArgs(),
      template_url_service().search_terms_data(),
      base::BindOnce(&RemoteSuggestionsServiceTest::OnRequestCompleted,
                     base::Unretained(this)));

  // Verify request histogram was recorded.
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent", 1);
  histogram_tester.ExpectBucketCount("Omnibox.SuggestRequestsSent", 3, 1);

  // Verify the observer got notified of request start.
  const std::string kRequestUrl = "https://www.example.com/suggest";
  ASSERT_EQ(observer.url().spec(), kRequestUrl);
  ASSERT_FALSE(observer.response_received());

  base::RunLoop().RunUntilIdle();

  // Verify the pending request and resolve it.
  ASSERT_TRUE(test_url_loader_factory_.IsPending(kRequestUrl));
  const std::string kResponseBody = "example response";
  test_url_loader_factory_.AddResponse(kRequestUrl, kResponseBody);

  base::RunLoop().RunUntilIdle();

  // Verify the observer got notified of request completion.
  ASSERT_EQ(observer.url().spec(), kRequestUrl);
  ASSERT_TRUE(observer.response_received());
  ASSERT_EQ(observer.response_body(), kResponseBody);

  // Verify the service client got notified of request completion.
  ASSERT_EQ(response_body(), kResponseBody);
}

TEST_F(RemoteSuggestionsServiceTest, ResponseTimeHistograms) {
  base::HistogramTester histogram_tester;

  TemplateURLData template_url_data;
  template_url_data.suggestions_url = "https://www.example.com/suggest";
  template_url_service().SetUserSelectedDefaultSearchProvider(
      template_url_service().Add(
          std::make_unique<TemplateURL>(template_url_data)));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());
  TestObserver observer(&service);

  // Add a mock response.
  const std::string kRequestUrl = "https://www.example.com/suggest";
  const std::string kResponseBody = "example response";
  test_url_loader_factory_.AddResponse(kRequestUrl, kResponseBody);

  // Start the request.
  auto loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(),
      TemplateURLRef::SearchTermsArgs(),
      template_url_service().search_terms_data(),
      base::BindOnce(&RemoteSuggestionsServiceTest::OnRequestCompleted,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();

  // Verify request histogram was recorded.
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent", 1);
  histogram_tester.ExpectBucketCount("Omnibox.SuggestRequestsSent", 3, 1);

  // Verify slicing by INVALID_SPEC is not recorded.
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent.INVALID_SPEC",
                                    0);

  // Verify response histograms were recorded.
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.ZeroSuggest", 1);
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent.ResponseTime",
                                    1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.ZeroSuggest", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.Successful", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.ZeroSuggest.Successful", 1);

  // Verify slicing by INVALID_SPEC is not recorded.
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.INVALID_SPEC", 0);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.INVALID_SPEC.ZeroSuggest."
      "Successful",
      0);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.INVALID_SPEC", 0);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.INVALID_SPEC.ZeroSuggest",
      0);

  // Try a new request with a different response code and a page classification.
  test_url_loader_factory_.ClearResponses();
  test_url_loader_factory_.AddResponse(kRequestUrl, kResponseBody,
                                       net::HTTP_NOT_FOUND);
  auto search_terms_args = TemplateURLRef::SearchTermsArgs();
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::CONTEXTUAL_SEARCHBOX;
  loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(), search_terms_args,
      template_url_service().search_terms_data(),
      base::BindOnce(&RemoteSuggestionsServiceTest::OnRequestCompleted,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();

  // Verify request histogram was recorded.
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent", 2);
  histogram_tester.ExpectBucketCount("Omnibox.SuggestRequestsSent", 3, 2);

  // Verify slicing by page classification is recorded.
  histogram_tester.ExpectBucketCount(
      "Omnibox.SuggestRequestsSent.CONTEXTUAL_SEARCHBOX", 3, 1);

  // Verify response histograms were recorded.
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode", 2);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.ZeroSuggest", 2);
  histogram_tester.ExpectTotalCount("Omnibox.SuggestRequestsSent.ResponseTime",
                                    2);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.ZeroSuggest", 2);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.Successful", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.Failed", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.ZeroSuggest.Successful", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.ZeroSuggest.Failed", 1);

  // Verify slicing by page classification is recorded.
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.CONTEXTUAL_SEARCHBOX", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.ResponseTime.CONTEXTUAL_SEARCHBOX."
      "ZeroSuggest."
      "Failed",
      1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.CONTEXTUAL_SEARCHBOX", 1);
  histogram_tester.ExpectTotalCount(
      "Omnibox.SuggestRequestsSent.HttpResponseCode.CONTEXTUAL_SEARCHBOX."
      "ZeroSuggest",
      1);
}

TEST_F(RemoteSuggestionsServiceTest, Delegate) {
  base::HistogramTester histogram_tester;

  TemplateURLData template_url_data;
  template_url_data.suggestions_url = "https://www.example.com/suggest";
  template_url_service().SetUserSelectedDefaultSearchProvider(
      template_url_service().Add(
          std::make_unique<TemplateURL>(template_url_data)));

  RemoteSuggestionsService service(
      /*document_suggestions_service_=*/nullptr,
      /*enterprise_search_aggregator_suggestions_service_*/ nullptr,
      GetUrlLoaderFactory());

  // Set up a delegate that will be replaced.
  MockDelegate delegate1(&service);
  EXPECT_CALL(delegate1, OnRequestCompleted(_, _, _, _)).Times(0);

  // Set up a delegate that will be deallocated.
  {
    MockDelegate delegate2(&service);
    EXPECT_CALL(delegate2, OnRequestCompleted(_, _, _, _)).Times(0);
  }

  // Set up a delegate that will call the completion callback asynchronously.
  MockDelegate delegate3(&service);
  EXPECT_CALL(delegate3, OnRequestCompleted(_, _, _, _))
      .WillOnce(Invoke(
          [](const network::SimpleURLLoader* source, const int response_code,
             std::unique_ptr<std::string> response_body,
             RemoteSuggestionsService::CompletionCallback completion_callback) {
            base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
                FROM_HERE,
                base::BindOnce(std::move(completion_callback), source,
                               response_code, std::move(response_body)));
          }));

  auto loader = service.StartZeroPrefixSuggestionsRequest(
      RemoteRequestType::kZeroSuggest, /*is_off_the_record=*/false,
      template_url_service().GetDefaultSearchProvider(),
      TemplateURLRef::SearchTermsArgs(),
      template_url_service().search_terms_data(),
      base::BindOnce(&RemoteSuggestionsServiceTest::OnRequestCompleted,
                     base::Unretained(this)));

  base::RunLoop().RunUntilIdle();

  // Verify the pending request and resolve it.
  const std::string kRequestUrl = "https://www.example.com/suggest";
  ASSERT_TRUE(test_url_loader_factory_.IsPending(kRequestUrl));
  const std::string kResponseBody = "example response";
  test_url_loader_factory_.AddResponse(kRequestUrl, kResponseBody);

  base::RunLoop().RunUntilIdle();

  // Verify the service client got notified of request completion.
  ASSERT_EQ(response_body(), kResponseBody);
}

TEST_F(RemoteSuggestionsServiceTest, CrOSOverridenOrAppendedQueryParams) {
  // Set up a non-Google search provider.
  TemplateURLData template_url_data;
  template_url_data.SetURL("https://www.example.com/search?q={searchTerms}");
  template_url_data.suggestions_url =
      "https://www.example.com/suggest?q={searchTerms}";
  TemplateURL template_url(template_url_data);

  TemplateURLRef::SearchTermsArgs search_terms_args(u"query");
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::NTP_REALBOX;

  GURL endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());

  // No additional query params is appended for the realbox entry point.
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");

  // No additional query params is appended for the ChromeOS app_list launcher
  // entry point for non-Google template URL.
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::CHROMEOS_APP_LIST;
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");

  // Set up a Google search provider.
  TemplateURLData google_template_url_data;
  google_template_url_data.SetURL(
      "https://www.google.com/search?q={searchTerms}");
  google_template_url_data.suggestions_url =
      "https://www.google.com/suggest?q={searchTerms}";
  google_template_url_data.id = SEARCH_ENGINE_GOOGLE;
  TemplateURL google_template_url(google_template_url_data);

  // `sclient=` is appended for the ChromeOS app_list launcher entry point for
  // Google template URL.
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/suggest?q=query&sclient=cros-launcher");
}

TEST_F(RemoteSuggestionsServiceTest,
       LensOverlaySuggestInputsAppendedQueryParamsForContextualSearchbox) {
  // Set up a Google search provider.
  TemplateURLData google_template_url_data;
  google_template_url_data.SetURL(
      "https://www.google.com/search?q={searchTerms}");
  google_template_url_data.suggestions_url =
      "https://www.google.com/suggest?q={searchTerms}";
  google_template_url_data.id = SEARCH_ENGINE_GOOGLE;
  TemplateURL google_template_url(google_template_url_data);

  TemplateURLRef::SearchTermsArgs search_terms_args(u"query");
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::CONTEXTUAL_SEARCHBOX;
  search_terms_args.lens_overlay_suggest_inputs =
      std::make_optional<lens::proto::LensOverlaySuggestInputs>();
  search_terms_args.lens_overlay_suggest_inputs->set_encoded_image_signals(
      "iil");

  GURL endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // No additional query params is appended for empty Lens suggest inputs.
  // iil is not expected to be sent for contextual searchbox requests.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-contextual&gs_ps=1");

  search_terms_args.lens_overlay_suggest_inputs->set_encoded_request_id(
      "vsrid");
  search_terms_args.lens_overlay_suggest_inputs->set_search_session_id(
      "gsessionid");
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // No additional query params are appended for empty Lens suggest inputs
  // because send_gsession_vsrid_for_contextual_suggest is false.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-contextual&gs_ps=1");

  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_gsession_vsrid_for_contextual_suggest(true);
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Appended gsessionid and vsrids.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-contextual&gs_ps=1&vsrid=vsrid&"
            "gsessionid=gsessionid");

  search_terms_args.lens_overlay_suggest_inputs
      ->set_contextual_visual_input_type("vit");
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Appended vit.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-contextual&gs_ps=1&vit=vit&vsrid="
            "vsrid&gsessionid=gsessionid");
}

TEST_F(RemoteSuggestionsServiceTest,
       LensOverlaySuggestInputsAppendedQueryParamsForLensSearchbox) {
  // Set up a Google search provider.
  TemplateURLData google_template_url_data;
  google_template_url_data.SetURL(
      "https://www.google.com/search?q={searchTerms}");
  google_template_url_data.suggestions_url =
      "https://www.google.com/suggest?q={searchTerms}";
  google_template_url_data.id = SEARCH_ENGINE_GOOGLE;
  TemplateURL google_template_url(google_template_url_data);

  TemplateURLRef::SearchTermsArgs search_terms_args(u"query");
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::LENS_SIDE_PANEL_SEARCHBOX;
  search_terms_args.lens_overlay_suggest_inputs =
      std::make_optional<lens::proto::LensOverlaySuggestInputs>();

  GURL endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Just just the client param is appended.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-multimodal");

  search_terms_args.lens_overlay_suggest_inputs->set_encoded_image_signals(
      "iil");

  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // The iil query param is appended.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-multimodal&iil=iil");

  search_terms_args.lens_overlay_suggest_inputs->set_encoded_request_id(
      "vsrid");
  search_terms_args.lens_overlay_suggest_inputs->set_search_session_id(
      "gsessionid");
  search_terms_args.lens_overlay_suggest_inputs
      ->set_encoded_visual_search_interaction_log_data("vsint");

  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // No additional query params are appended for empty Lens suggest inputs
  // because send_gsession_vsrid_vit_for_lens_suggest and
  // send_vsint_for_lens_suggest are false.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-multimodal&iil=iil");

  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_gsession_vsrid_vit_for_lens_suggest(true);
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Appended gsessionid and vsrids.
  ASSERT_EQ(endpoint_url.spec(),
            "https://www.google.com/"
            "suggest?q=query&client=chrome-multimodal&iil=iil&vsrid=vsrid&"
            "gsessionid=gsessionid");

  search_terms_args.lens_overlay_suggest_inputs
      ->set_contextual_visual_input_type("vit");
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Appended vit.
  ASSERT_EQ(
      endpoint_url.spec(),
      "https://www.google.com/"
      "suggest?q=query&client=chrome-multimodal&iil=iil&vit=vit&vsrid=vsrid&"
      "gsessionid=gsessionid");

  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_vsint_for_lens_suggest(true);
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Appended vsint.
  ASSERT_EQ(
      endpoint_url.spec(),
      "https://www.google.com/"
      "suggest?q=query&client=chrome-multimodal&iil=iil&vsint=vsint&vit=vit&"
      "vsrid=vsrid&gsessionid=gsessionid");
}

TEST_F(RemoteSuggestionsServiceTest,
       LensOverlaySuggestInputsAppendedNothingForOtherPageClassifications) {
  // Set up a Google search provider.
  TemplateURLData google_template_url_data;
  google_template_url_data.SetURL(
      "https://www.google.com/search?q={searchTerms}");
  google_template_url_data.suggestions_url =
      "https://www.google.com/suggest?q={searchTerms}";
  google_template_url_data.id = SEARCH_ENGINE_GOOGLE;
  TemplateURL google_template_url(google_template_url_data);

  TemplateURLRef::SearchTermsArgs search_terms_args(u"query");
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::NTP_REALBOX;
  search_terms_args.lens_overlay_suggest_inputs =
      std::make_optional<lens::proto::LensOverlaySuggestInputs>();
  search_terms_args.lens_overlay_suggest_inputs->set_encoded_image_signals(
      "iil");
  search_terms_args.lens_overlay_suggest_inputs->set_encoded_request_id(
      "vsrid");
  search_terms_args.lens_overlay_suggest_inputs->set_search_session_id(
      "gsessionid");
  search_terms_args.lens_overlay_suggest_inputs
      ->set_encoded_visual_search_interaction_log_data("vsint");
  search_terms_args.lens_overlay_suggest_inputs
      ->set_contextual_visual_input_type("vit");
  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_gsession_vsrid_for_contextual_suggest(true);
  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_vsint_for_lens_suggest(true);
  search_terms_args.lens_overlay_suggest_inputs
      ->set_send_gsession_vsrid_vit_for_lens_suggest(true);

  GURL endpoint_url = RemoteSuggestionsService::EndpointUrl(
      google_template_url, search_terms_args, SearchTermsData());

  // Nothing appended.
  ASSERT_EQ(endpoint_url.spec(), "https://www.google.com/suggest?q=query");
}

TEST_F(RemoteSuggestionsServiceTest,
       LensOverlaySuggestInputsAppendedNothingForNonGoogleSearch) {
  // Set up a non-Google search provider.
  TemplateURLData template_url_data;
  template_url_data.SetURL("https://www.example.com/search?q={searchTerms}");
  template_url_data.suggestions_url =
      "https://www.example.com/suggest?q={searchTerms}";
  TemplateURL template_url(template_url_data);

  TemplateURLRef::SearchTermsArgs search_terms_args(u"query");
  lens::proto::LensOverlaySuggestInputs lens_overlay_suggest_inputs;
  lens_overlay_suggest_inputs.set_encoded_image_signals("xyz");
  lens_overlay_suggest_inputs.set_encoded_request_id("vsrid");
  lens_overlay_suggest_inputs.set_search_session_id("gsessionid");
  lens_overlay_suggest_inputs.set_encoded_visual_search_interaction_log_data(
      "vsint");
  lens_overlay_suggest_inputs.set_contextual_visual_input_type("vit");
  lens_overlay_suggest_inputs.set_send_gsession_vsrid_for_contextual_suggest(
      true);
  lens_overlay_suggest_inputs.set_send_vsint_for_lens_suggest(true);
  lens_overlay_suggest_inputs.set_send_gsession_vsrid_vit_for_lens_suggest(
      true);
  search_terms_args.lens_overlay_suggest_inputs = lens_overlay_suggest_inputs;

  search_terms_args.page_classification =
      metrics::OmniboxEventProto::NTP_REALBOX;

  GURL endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());

  // No additional query params is appended for the realbox entry point.
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");

  // No additional query params is appended for the multimodal searchbox entry
  // point for non-Google template URL.
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::LENS_SIDE_PANEL_SEARCHBOX;
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");

  // No additional query params is appended for the non-multimodal searchbox
  // entry point for non-Google template URL.
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::SEARCH_SIDE_PANEL_SEARCHBOX;
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");

  // No additional query params is appended for the contextual searchbox entry
  // point for non-Google template URL.
  search_terms_args.page_classification =
      metrics::OmniboxEventProto::CONTEXTUAL_SEARCHBOX;
  endpoint_url = RemoteSuggestionsService::EndpointUrl(
      template_url, search_terms_args, SearchTermsData());
  ASSERT_EQ(endpoint_url.spec(), "https://www.example.com/suggest?q=query");
}