File: background_loader_offliner_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 (945 lines) | stat: -rw-r--r-- 38,667 bytes parent folder | download | duplicates (6)
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
// Copyright 2016 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/offline_pages/background_loader_offliner.h"

#include <memory>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/scoped_mock_time_message_loop_task_runner.h"
#include "chrome/browser/offline_pages/offliner_helper.h"
#include "chrome/browser/preloading/preloading_prefs.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/offline_pages/content/background_loader/background_loader_contents_stub.h"
#include "components/offline_pages/core/background/load_termination_listener.h"
#include "components/offline_pages/core/background/offliner.h"
#include "components/offline_pages/core/background/offliner_policy.h"
#include "components/offline_pages/core/background/save_page_request.h"
#include "components/offline_pages/core/offline_page_feature.h"
#include "components/offline_pages/core/stub_offline_page_model.h"
#include "components/prefs/pref_service.h"
#include "components/security_state/core/security_state.h"
#include "content/public/browser/mhtml_extra_parts.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_navigation_handle.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
char kShortSnapshotDelayForTest[] =
    "short-offline-page-snapshot-delay-for-test";
}  // namespace

namespace offline_pages {

namespace {

using security_state::VisibleSecurityState;

constexpr int64_t kRequestId = 7;
const ClientId kClientId("async_loading", "88");
constexpr bool kUserRequested = true;
constexpr char kRequestOrigin[] = "abc.xyz";
constexpr char kHttpUrl[] = "http://www.tunafish.com";

class TestLoadTerminationListener : public LoadTerminationListener {
 public:
  TestLoadTerminationListener() = default;

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

  ~TestLoadTerminationListener() override = default;

  void TerminateLoad() { offliner()->TerminateLoadIfInProgress(); }

  Offliner* offliner() { return offliner_; }
};

// Mock OfflinePageModel for testing the SavePage calls
class MockOfflinePageModel : public StubOfflinePageModel {
 public:
  MockOfflinePageModel() : mock_saving_(false), mock_deleting_(false) {}

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

  ~MockOfflinePageModel() override = default;

  void SavePage(const SavePageParams& save_page_params,
                std::unique_ptr<OfflinePageArchiver> archiver,
                content::WebContents* web_contents,
                SavePageCallback callback) override {
    mock_saving_ = true;
    save_page_callback_ = std::move(callback);
    save_page_params_ = save_page_params;
  }

  void CompleteSavingAsArchiveCreationFailed() {
    DCHECK(mock_saving_);
    mock_saving_ = false;
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(save_page_callback_),
                                  SavePageResult::ARCHIVE_CREATION_FAILED, 0));
  }

  void CompleteSavingAsSuccess() {
    DCHECK(mock_saving_);
    mock_saving_ = false;
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(save_page_callback_),
                                  SavePageResult::SUCCESS, 123456));
  }

  void CompleteSavingAsAlreadyExists() {
    DCHECK(mock_saving_);
    mock_saving_ = false;
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(save_page_callback_),
                                  SavePageResult::ALREADY_EXISTS, 123456));
  }

  void DeletePagesWithCriteria(const PageCriteria& criteria,
                               DeletePageCallback callback) override {
    mock_deleting_ = true;
    std::move(callback).Run(DeletePageResult::SUCCESS);
  }

  bool mock_saving() const { return mock_saving_; }
  bool mock_deleting() const { return mock_deleting_; }
  SavePageParams& save_page_params() { return save_page_params_; }

 private:
  bool mock_saving_;
  bool mock_deleting_;
  SavePageCallback save_page_callback_;
  SavePageParams save_page_params_;
};

}  // namespace

// A BackgroundLoader that we can run tests on.
// Overrides the ResetState so we don't actually try to create any web contents.
// This is a temporary solution to test core BackgroundLoaderOffliner
// functionality until we straighten out assumptions made by RequestCoordinator
// so that the ResetState method is no longer needed.
class TestBackgroundLoaderOffliner : public BackgroundLoaderOffliner {
 public:
  explicit TestBackgroundLoaderOffliner(
      content::BrowserContext* browser_context,
      const OfflinerPolicy* policy,
      OfflinePageModel* offline_page_model,
      std::unique_ptr<LoadTerminationListener> load_termination_listener);
  ~TestBackgroundLoaderOffliner() override;
  content::WebContentsTester* web_contents_tester() {
    return content::WebContentsTester::For(stub_->web_contents());
  }

  content::WebContents* web_contents() { return stub_->web_contents(); }
  background_loader::BackgroundLoaderContents* stub() { return stub_; }

  bool is_loading() { return loader_ && stub_->is_loading(); }

  void set_custom_visible_security_state(
      std::unique_ptr<VisibleSecurityState> visible_security_state) {
    custom_visible_security_state_ = std::move(visible_security_state);
  }
  void set_page_type(content::PageType page_type) { page_type_ = page_type; }

 private:
  // BackgroundLoaderOffliner overrides.
  void ResetLoader() override;
  std::unique_ptr<VisibleSecurityState> GetVisibleSecurityState(
      content::WebContents* web_contents) override;
  content::PageType GetPageType(content::WebContents* web_contents) override;

  raw_ptr<background_loader::BackgroundLoaderContentsStub> stub_;
  std::unique_ptr<VisibleSecurityState> custom_visible_security_state_;
  content::PageType page_type_ = content::PageType::PAGE_TYPE_NORMAL;
};

TestBackgroundLoaderOffliner::TestBackgroundLoaderOffliner(
    content::BrowserContext* browser_context,
    const OfflinerPolicy* policy,
    OfflinePageModel* offline_page_model,
    std::unique_ptr<LoadTerminationListener> load_termination_listener)
    : BackgroundLoaderOffliner(browser_context,
                               policy,
                               offline_page_model,
                               std::move(load_termination_listener)) {}

TestBackgroundLoaderOffliner::~TestBackgroundLoaderOffliner() = default;

void TestBackgroundLoaderOffliner::ResetLoader() {
  stub_ = new background_loader::BackgroundLoaderContentsStub(browser_context_);
  loader_.reset(stub_);
  loader_->SetDelegate(this);
}

std::unique_ptr<VisibleSecurityState>
TestBackgroundLoaderOffliner::GetVisibleSecurityState(
    content::WebContents* web_contents) {
  if (custom_visible_security_state_)
    return std::move(custom_visible_security_state_);
  return BackgroundLoaderOffliner::GetVisibleSecurityState(web_contents);
}

content::PageType TestBackgroundLoaderOffliner::GetPageType(
    content::WebContents* web_contents) {
  return page_type_;
}

class BackgroundLoaderOfflinerTest : public testing::Test {
 public:
  BackgroundLoaderOfflinerTest();

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

  ~BackgroundLoaderOfflinerTest() override;

  void SetUp() override;

  TestBackgroundLoaderOffliner* offliner() const { return offliner_.get(); }
  Offliner::CompletionCallback completion_callback() {
    return base::BindOnce(&BackgroundLoaderOfflinerTest::OnCompletion,
                          base::Unretained(this));
  }
  Offliner::ProgressCallback const progress_callback() {
    return base::BindRepeating(&BackgroundLoaderOfflinerTest::OnProgress,
                               base::Unretained(this));
  }
  Offliner::CancelCallback cancel_callback() {
    return base::BindOnce(&BackgroundLoaderOfflinerTest::OnCancel,
                          base::Unretained(this));
  }
  base::OnceCallback<void(bool)> can_download_callback() {
    return base::BindOnce(&BackgroundLoaderOfflinerTest::OnCanDownload,
                          base::Unretained(this));
  }
  Profile* profile() { return &profile_; }
  bool completion_callback_called() { return completion_callback_called_; }
  Offliner::RequestStatus request_status() { return request_status_; }
  bool cancel_callback_called() { return cancel_callback_called_; }
  bool can_download_callback_called() { return can_download_callback_called_; }
  bool can_download() { return can_download_; }
  bool SaveInProgress() const { return model_->mock_saving(); }
  bool DeleteCalled() const { return model_->mock_deleting(); }
  MockOfflinePageModel* model() const { return model_; }
  const base::HistogramTester& histograms() const { return histogram_tester_; }
  int64_t progress() { return progress_; }
  OfflinerPolicy* policy() const { return policy_.get(); }
  TestLoadTerminationListener* load_termination_listener() {
    return load_termination_listener_;
  }

  void PumpLoop() { base::RunLoop().RunUntilIdle(); }

  void CompleteLoading() {
    // Reset snapshot controller.
    auto snapshot_controller = std::make_unique<BackgroundSnapshotController>(
        base::SingleThreadTaskRunner::GetCurrentDefault(), offliner_.get(),
        false /* RenovationsEnabled */);
    offliner_->SetBackgroundSnapshotControllerForTest(
        std::move(snapshot_controller));
    // Call complete loading.
    offliner()->PrimaryMainDocumentElementAvailable();
    offliner()->DocumentOnLoadCompletedInPrimaryMainFrame();
    PumpLoop();
  }

  offline_pages::RequestStats* GetRequestStats() {
    return offliner_->GetRequestStatsForTest();
  }

  std::unique_ptr<VisibleSecurityState> BaseVisibleSecurityState() {
    auto visible_security_state = std::make_unique<VisibleSecurityState>();
    visible_security_state->connection_info_initialized = true;
    visible_security_state->url = GURL("https://www.yellowtail.com");
    visible_security_state->certificate =
        net::ImportCertFromFile(net::GetTestCertsDirectory(), "sha1_2016.pem");
    visible_security_state->cert_status =
        net::CERT_STATUS_SHA1_SIGNATURE_PRESENT;
    return visible_security_state;
  }

 private:
  void OnCompletion(const SavePageRequest& request,
                    Offliner::RequestStatus status);
  void OnProgress(const SavePageRequest& request, int64_t bytes);
  void OnCancel(const SavePageRequest& request);
  void OnCanDownload(bool allowed);
  content::BrowserTaskEnvironment task_environment_;
  content::RenderViewHostTestEnabler rvhte_;
  TestingProfile profile_;
  std::unique_ptr<OfflinerPolicy> policy_;
  raw_ptr<TestLoadTerminationListener> load_termination_listener_;
  std::unique_ptr<TestBackgroundLoaderOffliner> offliner_;
  raw_ptr<MockOfflinePageModel> model_;
  bool completion_callback_called_;
  bool cancel_callback_called_;
  bool can_download_callback_called_;
  bool can_download_;
  int64_t progress_;
  Offliner::RequestStatus request_status_;
  base::HistogramTester histogram_tester_;
};

BackgroundLoaderOfflinerTest::BackgroundLoaderOfflinerTest()
    : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP),
      load_termination_listener_(nullptr),
      model_(nullptr),
      completion_callback_called_(false),
      cancel_callback_called_(false),
      can_download_callback_called_(false),
      can_download_(false),
      progress_(0LL),
      request_status_(Offliner::RequestStatus::UNKNOWN) {}

BackgroundLoaderOfflinerTest::~BackgroundLoaderOfflinerTest() = default;

void BackgroundLoaderOfflinerTest::SetUp() {
  // Set the snapshot controller delay command line switch to short delays.
  base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
  cl->AppendSwitch(kShortSnapshotDelayForTest);

  std::unique_ptr<TestLoadTerminationListener> listener =
      std::make_unique<TestLoadTerminationListener>();
  load_termination_listener_ = listener.get();
  model_ = new MockOfflinePageModel();
  policy_ = std::make_unique<OfflinerPolicy>();
  offliner_ = std::make_unique<TestBackgroundLoaderOffliner>(
      profile(), policy_.get(), model_, std::move(listener));
}

void BackgroundLoaderOfflinerTest::OnCompletion(
    const SavePageRequest& request,
    Offliner::RequestStatus status) {
  DCHECK(!completion_callback_called_);  // Expect 1 callback per request.
  completion_callback_called_ = true;
  request_status_ = status;
}

void BackgroundLoaderOfflinerTest::OnProgress(const SavePageRequest& request,
                                              int64_t bytes) {
  progress_ = bytes;
}

void BackgroundLoaderOfflinerTest::OnCancel(const SavePageRequest& request) {
  DCHECK(!cancel_callback_called_);
  cancel_callback_called_ = true;
}

void BackgroundLoaderOfflinerTest::OnCanDownload(bool allowed) {
  can_download_callback_called_ = true;
  can_download_ = allowed;
}

TEST_F(BackgroundLoaderOfflinerTest, LoadTerminationListenerSetup) {
  // Verify that back pointer to offliner is set up in the listener.
  Offliner* base_offliner = offliner();
  EXPECT_NE(base_offliner, nullptr);
  EXPECT_EQ(base_offliner, load_termination_listener()->offliner());
}

TEST_F(BackgroundLoaderOfflinerTest,
       LoadAndSaveBlockThirdPartyCookiesForCustomTabs) {
  base::Time creation_time = base::Time::Now();
  ClientId custom_tabs_client_id("custom_tabs", "88");
  SavePageRequest request(kRequestId, GURL(kHttpUrl), custom_tabs_client_id,
                          creation_time, kUserRequested);

  profile()->GetPrefs()->SetInteger(
      prefs::kCookieControlsMode,
      static_cast<int>(content_settings::CookieControlsMode::kBlockThirdParty));
  EXPECT_FALSE(offliner()->LoadAndSave(request, completion_callback(),
                                       progress_callback()));
}

TEST_F(BackgroundLoaderOfflinerTest,
       LoadAndSaveNetworkPredictionDisabledForCustomTabs) {
  base::Time creation_time = base::Time::Now();
  ClientId custom_tabs_client_id("custom_tabs", "88");
  SavePageRequest request(kRequestId, GURL(kHttpUrl), custom_tabs_client_id,
                          creation_time, kUserRequested);

  prefetch::SetPreloadPagesState(profile()->GetPrefs(),
                                 prefetch::PreloadPagesState::kNoPreloading);
  EXPECT_FALSE(offliner()->LoadAndSave(request, completion_callback(),
                                       progress_callback()));
}

TEST_F(BackgroundLoaderOfflinerTest, LoadAndSaveStartsLoading) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  EXPECT_TRUE(offliner()->is_loading());
  EXPECT_FALSE(SaveInProgress());
  EXPECT_FALSE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, BytesReportedWillUpdateProgress) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->OnNetworkBytesChanged(5LL);
  EXPECT_EQ(progress(), 5LL);
  offliner()->OnNetworkBytesChanged(10LL);
  EXPECT_EQ(progress(), 15LL);
}

TEST_F(BackgroundLoaderOfflinerTest, CompleteLoadingInitiatesSave) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  request.set_request_origin(kRequestOrigin);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  CompleteLoading();
  PumpLoop();
  // Verify that request origin is propagated.
  EXPECT_EQ(kRequestOrigin, model()->save_page_params().request_origin);
  EXPECT_FALSE(completion_callback_called());
  EXPECT_TRUE(SaveInProgress());
  EXPECT_EQ(Offliner::RequestStatus::UNKNOWN, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, CancelWhenLoading) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->Cancel(cancel_callback());
  PumpLoop();
  offliner()->OnNetworkBytesChanged(15LL);
  EXPECT_TRUE(cancel_callback_called());
  EXPECT_FALSE(completion_callback_called());
  EXPECT_FALSE(offliner()->is_loading());  // Offliner reset.
  EXPECT_EQ(progress(), 0LL);  // network bytes not recorded when not busy.
}

TEST_F(BackgroundLoaderOfflinerTest, CancelWhenLoadTerminated) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  load_termination_listener()->TerminateLoad();
  PumpLoop();
  EXPECT_TRUE(completion_callback_called());
  EXPECT_FALSE(offliner()->is_loading());  // Offliner reset.
  EXPECT_EQ(Offliner::RequestStatus::FOREGROUND_CANCELED, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, CancelWhenLoaded) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  CompleteLoading();
  PumpLoop();
  offliner()->Cancel(cancel_callback());
  PumpLoop();

  // Subsequent save callback cause no crash.
  model()->CompleteSavingAsArchiveCreationFailed();
  PumpLoop();
  EXPECT_TRUE(cancel_callback_called());
  EXPECT_TRUE(DeleteCalled());
  EXPECT_FALSE(completion_callback_called());
  EXPECT_FALSE(SaveInProgress());
  EXPECT_FALSE(offliner()->is_loading());  // Offliner reset.
}

TEST_F(BackgroundLoaderOfflinerTest, LoadedButSaveFails) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  CompleteLoading();
  PumpLoop();
  model()->CompleteSavingAsArchiveCreationFailed();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::SAVE_FAILED, request_status());
  EXPECT_FALSE(offliner()->is_loading());
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, ProgressDoesNotUpdateDuringSave) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->OnNetworkBytesChanged(10LL);
  CompleteLoading();
  PumpLoop();
  offliner()->OnNetworkBytesChanged(15LL);
  EXPECT_EQ(progress(), 10LL);
}

TEST_F(BackgroundLoaderOfflinerTest, LoadAndSaveSuccess) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  CompleteLoading();
  PumpLoop();
  model()->CompleteSavingAsSuccess();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::SAVED, request_status());
  EXPECT_FALSE(offliner()->is_loading());
  EXPECT_FALSE(can_download_callback_called());
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, LoadAndSaveAlreadyExists) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  CompleteLoading();
  PumpLoop();
  model()->CompleteSavingAsAlreadyExists();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::SAVED, request_status());
  EXPECT_FALSE(offliner()->is_loading());
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, ResetsWhenDownloadStarts) {
  base::Time creation_time = base::Time::Now();
  ClientId browser_actions("browser_actions", "123");
  SavePageRequest request(kRequestId, GURL(kHttpUrl), browser_actions,
                          creation_time, kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->stub()->CanDownload(GURL(kHttpUrl), "foo",
                                  can_download_callback());
  PumpLoop();
  EXPECT_TRUE(can_download_callback_called());
  EXPECT_TRUE(can_download());
  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::DOWNLOAD_THROTTLED, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, ResetsWhenDownloadEncountered) {
  base::Time creation_time = base::Time::Now();
  ClientId prefetching("suggested_articles", "123");
  SavePageRequest request(kRequestId, GURL(kHttpUrl), prefetching,
                          creation_time, kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->stub()->CanDownload(GURL(kHttpUrl), "foo",
                                  can_download_callback());
  PumpLoop();
  EXPECT_TRUE(can_download_callback_called());
  EXPECT_FALSE(can_download());
  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED_DOWNLOAD, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, CanDownloadReturnsIfNoPendingRequest) {
  offliner()->CanDownload(can_download_callback());
  PumpLoop();
  EXPECT_TRUE(can_download_callback_called());
  EXPECT_FALSE(can_download());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnInvalidURL) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL("file://salmon.png"), kClientId,
                          creation_time, kUserRequested);
  EXPECT_FALSE(offliner()->LoadAndSave(request, completion_callback(),
                                       progress_callback()));
}

TEST_F(BackgroundLoaderOfflinerTest, ReturnsOnRenderCrash) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->PrimaryMainFrameRenderProcessGone(
      base::TerminationStatus::TERMINATION_STATUS_PROCESS_CRASHED);

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED_NO_NEXT, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, ReturnsOnRenderKilled) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->PrimaryMainFrameRenderProcessGone(
      base::TerminationStatus::TERMINATION_STATUS_PROCESS_WAS_KILLED);

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, ReturnsOnWebContentsDestroyed) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  offliner()->WebContentsDestroyed();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnErrorPage) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  // Create handle with net error code.
  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  handle.set_is_error_page(true);
  handle.set_net_error_code(net::Error::ERR_NAME_NOT_RESOLVED);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED_NET_ERROR,
            request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnCertificateError) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Sets the certificate status as having been revoked.
  std::unique_ptr<VisibleSecurityState> visible_security_state =
      BaseVisibleSecurityState();
  visible_security_state->cert_status |= net::CERT_STATUS_REVOKED;
  offliner()->set_custom_visible_security_state(
      std::move(visible_security_state));

  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_FALSE(SaveInProgress());
  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADED_PAGE_HAS_CERTIFICATE_ERROR,
            request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnRevocationCheckingFailure) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Sets a revocation checking failure certificate error that should not be
  // allowed.
  std::unique_ptr<VisibleSecurityState> visible_security_state =
      BaseVisibleSecurityState();
  visible_security_state->cert_status |=
      net::CERT_STATUS_NO_REVOCATION_MECHANISM;
  offliner()->set_custom_visible_security_state(
      std::move(visible_security_state));

  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_FALSE(SaveInProgress());
  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADED_PAGE_HAS_CERTIFICATE_ERROR,
            request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, SucceedsOnHttp) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Sets the URL to HTTP while still setting a major certificate error (should
  // be ignored).
  std::unique_ptr<VisibleSecurityState> visible_security_state =
      BaseVisibleSecurityState();
  visible_security_state->url = GURL(kHttpUrl);
  visible_security_state->cert_status |= net::CERT_STATUS_REVOKED;
  offliner()->set_custom_visible_security_state(
      std::move(visible_security_state));

  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_TRUE(SaveInProgress());
  EXPECT_FALSE(completion_callback_called());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnUnwantedContent) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Sets the page as containing SafeBrowsing unwanted content.
  std::unique_ptr<VisibleSecurityState> visible_security_state =
      BaseVisibleSecurityState();
  visible_security_state->malicious_content_status = security_state::
      MaliciousContentStatus::MALICIOUS_CONTENT_STATUS_SOCIAL_ENGINEERING;
  offliner()->set_custom_visible_security_state(
      std::move(visible_security_state));
  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_FALSE(SaveInProgress());
  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADED_PAGE_IS_BLOCKED, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, FailsOnInternetDisconnected) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Create handle with net error code.
  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  handle.set_is_error_page(true);
  handle.set_net_error_code(net::Error::ERR_INTERNET_DISCONNECTED);
  offliner()->DidFinishNavigation(&handle);

  CompleteLoading();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::LOADING_FAILED_NET_ERROR,
            request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, DoesNotCrashWithNullResponseHeaders) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Called after calling LoadAndSave so we have web_contents to work with.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  offliner()->DidFinishNavigation(&handle);
}

TEST_F(BackgroundLoaderOfflinerTest, OnlySavesOnceOnMultipleLoads) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  // First load
  CompleteLoading();
  // Second load
  CompleteLoading();
  PumpLoop();
  model()->CompleteSavingAsSuccess();
  PumpLoop();

  EXPECT_TRUE(completion_callback_called());
  EXPECT_EQ(Offliner::RequestStatus::SAVED, request_status());
  EXPECT_FALSE(offliner()->is_loading());
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, HandleTimeoutWithLowBarStartedTriesMet) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  request.set_started_attempt_count(policy()->GetMaxStartedTries() - 1);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  // Guarantees low bar for saving is met.
  offliner()->PrimaryMainDocumentElementAvailable();
  // Timeout
  EXPECT_TRUE(offliner()->HandleTimeout(kRequestId));
  EXPECT_TRUE(SaveInProgress());
  model()->CompleteSavingAsSuccess();
  PumpLoop();
  EXPECT_EQ(Offliner::RequestStatus::SAVED_ON_LAST_RETRY, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, HandleTimeoutWithLowBarCompletedTriesMet) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  request.set_completed_attempt_count(policy()->GetMaxCompletedTries() - 1);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  // Guarantees low bar for saving is met.
  offliner()->PrimaryMainDocumentElementAvailable();
  // Timeout
  EXPECT_TRUE(offliner()->HandleTimeout(kRequestId));
  EXPECT_TRUE(SaveInProgress());
  model()->CompleteSavingAsSuccess();
  PumpLoop();
  EXPECT_EQ(Offliner::RequestStatus::SAVED_ON_LAST_RETRY, request_status());
}

TEST_F(BackgroundLoaderOfflinerTest, HandleTimeoutWithNoLowBarStartedTriesMet) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  request.set_started_attempt_count(policy()->GetMaxStartedTries() - 1);
  // Timeout
  EXPECT_FALSE(offliner()->HandleTimeout(kRequestId));
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest,
       HandleTimeoutWithNoLowBarCompletedTriesMet) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  request.set_completed_attempt_count(policy()->GetMaxCompletedTries() - 1);
  // Timeout
  EXPECT_FALSE(offliner()->HandleTimeout(kRequestId));
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, HandleTimeoutWithLowBarNoRetryLimit) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));
  // Sets lowbar.
  offliner()->PrimaryMainDocumentElementAvailable();
  // Timeout
  EXPECT_FALSE(offliner()->HandleTimeout(kRequestId));
  EXPECT_FALSE(SaveInProgress());
}

TEST_F(BackgroundLoaderOfflinerTest, SignalCollectionDisabled) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  CompleteLoading();
  PumpLoop();

  // No extra parts should be added.
  content::MHTMLExtraParts* extra_parts =
      content::MHTMLExtraParts::FromWebContents(offliner()->web_contents());
  EXPECT_EQ(extra_parts->size(), 0);
}

TEST_F(BackgroundLoaderOfflinerTest,
       DoNotRecordErrorMetricInNonPrimaryMainframe) {
  base::Time creation_time = base::Time::Now();
  SavePageRequest request(kRequestId, GURL(kHttpUrl), kClientId, creation_time,
                          kUserRequested);
  EXPECT_TRUE(offliner()->LoadAndSave(request, completion_callback(),
                                      progress_callback()));

  // Simulate that DidFinishNavigation method is called with an error in a
  // non-primary mainframe.
  content::MockNavigationHandle handle(
      GURL(kHttpUrl), offliner()->web_contents()->GetPrimaryMainFrame());
  handle.set_has_committed(true);
  handle.set_is_error_page(true);
  handle.set_net_error_code(net::Error::ERR_NAME_NOT_RESOLVED);
  handle.set_is_in_primary_main_frame(false);
  offliner()->DidFinishNavigation(&handle);

  // The error histogram should be 0.
  CompleteLoading();
  PumpLoop();

  EXPECT_FALSE(completion_callback_called());
}

}  // namespace offline_pages