forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcast_web_contents_browsertest.cc
1204 lines (1046 loc) · 46.8 KB
/
cast_web_contents_browsertest.cc
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMECAST_BROWSER_CAST_WEB_CONTENTS_BROWSERTEST_H_
#define CHROMECAST_BROWSER_CAST_WEB_CONTENTS_BROWSERTEST_H_
#include <algorithm>
#include <memory>
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind_test_util.h"
#include "chromecast/base/chromecast_switches.h"
#include "chromecast/base/metrics/cast_metrics_helper.h"
#include "chromecast/browser/cast_browser_context.h"
#include "chromecast/browser/cast_browser_process.h"
#include "chromecast/browser/cast_web_contents_impl.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_base.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "mojo/public/cpp/bindings/connector.h"
#include "net/http/http_status_code.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using ::testing::_;
using ::testing::AllOf;
using ::testing::AtLeast;
using ::testing::Eq;
using ::testing::Expectation;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::Property;
namespace content {
class WebContents;
}
namespace chromecast {
namespace {
const base::FilePath::CharType kTestDataPath[] =
FILE_PATH_LITERAL("chromecast/browser/test/data");
base::FilePath GetTestDataPath() {
return base::FilePath(kTestDataPath);
}
base::FilePath GetTestDataFilePath(const std::string& name) {
base::FilePath file_path;
CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path));
return file_path.Append(GetTestDataPath()).AppendASCII(name);
}
std::unique_ptr<net::test_server::HttpResponse> DefaultHandler(
net::HttpStatusCode status_code,
const net::test_server::HttpRequest& request) {
auto http_response = std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(status_code);
return http_response;
}
// =============================================================================
// Mocks
// =============================================================================
class MockCastWebContentsDelegate
: public base::SupportsWeakPtr<MockCastWebContentsDelegate>,
public CastWebContents::Delegate {
public:
MockCastWebContentsDelegate() {}
~MockCastWebContentsDelegate() override = default;
MOCK_METHOD2(InnerContentsCreated,
void(CastWebContents* inner_contents,
CastWebContents* outer_contents));
private:
DISALLOW_COPY_AND_ASSIGN(MockCastWebContentsDelegate);
};
class MockCastWebContentsObserver : public CastWebContents::Observer {
public:
MockCastWebContentsObserver() {}
~MockCastWebContentsObserver() override = default;
MOCK_METHOD1(OnPageStateChanged, void(CastWebContents* cast_web_contents));
MOCK_METHOD2(OnPageStopped,
void(CastWebContents* cast_web_contents, int error_code));
MOCK_METHOD4(
RenderFrameCreated,
void(int render_process_id,
int render_frame_id,
service_manager::InterfaceProvider* frame_interfaces,
blink::AssociatedInterfaceProvider* frame_associated_interfaces));
MOCK_METHOD1(ResourceLoadFailed, void(CastWebContents* cast_web_contents));
MOCK_METHOD1(UpdateTitle, void(const base::string16& title));
private:
DISALLOW_COPY_AND_ASSIGN(MockCastWebContentsObserver);
};
class MockWebContentsDelegate : public content::WebContentsDelegate {
public:
MockWebContentsDelegate() = default;
~MockWebContentsDelegate() override = default;
MOCK_METHOD1(CloseContents, void(content::WebContents* source));
};
class TitleChangeObserver : public CastWebContents::Observer {
public:
TitleChangeObserver() = default;
~TitleChangeObserver() override = default;
// Spins a Runloop until the title of the page matches the |expected_title|
// that have been set.
void RunUntilTitleEquals(base::StringPiece expected_title) {
expected_title_ = expected_title.as_string();
// Spin the runloop until the expected conditions are met.
if (current_title_ != expected_title_) {
expected_title_ = expected_title.as_string();
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
}
// CastWebContents::Observer implementation:
void UpdateTitle(const base::string16& title) override {
// Resumes execution of RunUntilTitleEquals() if |title| matches
// expectations.
std::string title_utf8 = base::UTF16ToUTF8(title);
current_title_ = title_utf8;
if (!quit_closure_.is_null() && current_title_ == expected_title_) {
DCHECK_EQ(current_title_, expected_title_);
std::move(quit_closure_).Run();
}
}
private:
std::string current_title_;
std::string expected_title_;
base::OnceClosure quit_closure_;
DISALLOW_COPY_AND_ASSIGN(TitleChangeObserver);
};
class TestMessageReceiver : public blink::WebMessagePort::MessageReceiver {
public:
TestMessageReceiver() = default;
~TestMessageReceiver() override = default;
void WaitForNextIncomingMessage(
base::OnceCallback<
void(std::string, base::Optional<blink::WebMessagePort>)> callback) {
DCHECK(message_received_callback_.is_null())
<< "Only one waiting event is allowed.";
message_received_callback_ = std::move(callback);
}
void SetOnPipeErrorCallback(base::OnceCallback<void()> callback) {
on_pipe_error_callback_ = std::move(callback);
}
private:
bool OnMessage(blink::WebMessagePort::Message message) override {
std::string message_text;
if (!base::UTF16ToUTF8(message.data.data(), message.data.size(),
&message_text)) {
return false;
}
base::Optional<blink::WebMessagePort> incoming_port = base::nullopt;
// Only one MessagePort should be sent to here.
if (!message.ports.empty()) {
DCHECK(message.ports.size() == 1)
<< "Only one control port can be provided";
incoming_port = base::make_optional<blink::WebMessagePort>(
std::move(message.ports[0]));
}
if (message_received_callback_) {
std::move(message_received_callback_)
.Run(message_text, std::move(incoming_port));
}
return true;
}
void OnPipeError() override {
if (on_pipe_error_callback_)
std::move(on_pipe_error_callback_).Run();
}
base::OnceCallback<void(std::string,
base::Optional<blink::WebMessagePort> incoming_port)>
message_received_callback_;
base::OnceCallback<void()> on_pipe_error_callback_;
DISALLOW_COPY_AND_ASSIGN(TestMessageReceiver);
};
} // namespace
// =============================================================================
// Test class
// =============================================================================
class CastWebContentsBrowserTest : public content::BrowserTestBase,
public content::WebContentsObserver {
protected:
CastWebContentsBrowserTest() = default;
~CastWebContentsBrowserTest() override = default;
void SetUp() final {
SetUpCommandLine(base::CommandLine::ForCurrentProcess());
BrowserTestBase::SetUp();
}
void SetUpCommandLine(base::CommandLine* command_line) final {
command_line->AppendSwitch(switches::kNoWifi);
command_line->AppendSwitchASCII(switches::kTestType, "browser");
}
void PreRunTestOnMainThread() override {
// Pump startup related events.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
base::RunLoop().RunUntilIdle();
metrics::CastMetricsHelper::GetInstance()->SetDummySessionIdForTesting();
content::WebContents::CreateParams create_params(
shell::CastBrowserProcess::GetInstance()->browser_context(), nullptr);
web_contents_ = content::WebContents::Create(create_params);
web_contents_->SetDelegate(&mock_wc_delegate_);
CastWebContents::InitParams init_params;
init_params.delegate = mock_cast_wc_delegate_.AsWeakPtr();
init_params.is_root_window = true;
cast_web_contents_ =
std::make_unique<CastWebContentsImpl>(web_contents_.get(), init_params);
mock_cast_wc_observer_.Observe(cast_web_contents_.get());
title_change_observer_.Observe(cast_web_contents_.get());
render_frames_.clear();
content::WebContentsObserver::Observe(web_contents_.get());
}
void PostRunTestOnMainThread() override {
cast_web_contents_.reset();
web_contents_.reset();
}
// content::WebContentsObserver implementation:
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) final {
render_frames_.insert(render_frame_host);
}
void StartTestServer() {
ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
embedded_test_server()->StartAcceptingConnections();
}
MockWebContentsDelegate mock_wc_delegate_;
MockCastWebContentsDelegate mock_cast_wc_delegate_;
NiceMock<MockCastWebContentsObserver> mock_cast_wc_observer_;
TitleChangeObserver title_change_observer_;
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<CastWebContentsImpl> cast_web_contents_;
base::flat_set<content::RenderFrameHost*> render_frames_;
private:
DISALLOW_COPY_AND_ASSIGN(CastWebContentsBrowserTest);
};
MATCHER_P2(CheckPageState, cwc_ptr, expected_state, "") {
if (arg != cwc_ptr)
return false;
return arg->page_state() == expected_state;
}
// =============================================================================
// Test cases
// =============================================================================
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, Lifecycle) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: Load a blank page successfully, verify LOADED state.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
run_loop->Run();
// ===========================================================================
// Test: Load a blank page via WebContents API, verify LOADED state.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
run_loop = std::make_unique<base::RunLoop>();
web_contents_->GetController().LoadURL(GURL(url::kAboutBlankURL),
content::Referrer(),
ui::PAGE_TRANSITION_TYPED, "");
run_loop->Run();
// ===========================================================================
// Test: Inject an iframe, verify no events are received for the frame.
// ===========================================================================
EXPECT_CALL(mock_cast_wc_observer_, OnPageStateChanged(_)).Times(0);
EXPECT_CALL(mock_cast_wc_observer_, OnPageStopped(_, _)).Times(0);
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);"
"iframe.src = 'about:blank';";
ASSERT_TRUE(ExecJs(web_contents_.get(), script));
// ===========================================================================
// Test: Inject an iframe and navigate it to an error page. Verify no events.
// ===========================================================================
EXPECT_CALL(mock_cast_wc_observer_, OnPageStateChanged(_)).Times(0);
EXPECT_CALL(mock_cast_wc_observer_, OnPageStopped(_, _)).Times(0);
script = "iframe.src = 'https://www.fake-non-existent-cast-page.com';";
ASSERT_TRUE(ExecJs(web_contents_.get(), script));
// ===========================================================================
// Test: Close the CastWebContents. WebContentsDelegate will be told to close
// the page, and then after the timeout elapses CWC will enter the CLOSED
// state and notify that the page has stopped.
// ===========================================================================
EXPECT_CALL(mock_wc_delegate_, CloseContents(web_contents_.get()))
.Times(AtLeast(1));
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::CLOSED),
net::OK))
.WillOnce(InvokeWithoutArgs(quit_closure));
run_loop = std::make_unique<base::RunLoop>();
cast_web_contents_->ClosePage();
run_loop->Run();
// ===========================================================================
// Test: Destroy the underlying WebContents. Verify DESTROYED state.
// ===========================================================================
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::DESTROYED)));
web_contents_.reset();
cast_web_contents_.reset();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, WebContentsDestroyed) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
run_loop->Run();
// ===========================================================================
// Test: Destroy the WebContents. Verify OnPageStopped(DESTROYED, net::OK).
// ===========================================================================
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::DESTROYED),
net::OK));
web_contents_.reset();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorPageCrash) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: If the page's main render process crashes, enter ERROR state.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
run_loop->Run();
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::ERROR),
net::ERR_UNEXPECTED));
CrashTab(web_contents_.get());
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLocalFileMissing) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: Loading a page with an HTTP error should enter ERROR state.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::ERROR),
_))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
base::FilePath path = GetTestDataFilePath("this_file_does_not_exist.html");
cast_web_contents_->LoadUrl(content::GetFileUrlWithQuery(path, ""));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLoadFailSubFrames) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: Ignore load errors in sub-frames.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
run_loop->Run();
// Create a sub-frame.
EXPECT_CALL(mock_cast_wc_observer_, OnPageStateChanged(_)).Times(0);
EXPECT_CALL(mock_cast_wc_observer_, OnPageStopped(_, _)).Times(0);
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);"
"iframe.src = 'about:blank';";
ASSERT_TRUE(ExecJs(web_contents_.get(), script));
ASSERT_EQ(2, (int)render_frames_.size());
auto it =
std::find_if(render_frames_.begin(), render_frames_.end(),
[this](content::RenderFrameHost* frame) {
return frame->GetParent() == web_contents_->GetMainFrame();
});
ASSERT_NE(render_frames_.end(), it);
content::RenderFrameHost* sub_frame = *it;
ASSERT_NE(nullptr, sub_frame);
cast_web_contents_->DidFailLoad(sub_frame, sub_frame->GetLastCommittedURL(),
net::ERR_FAILED);
// ===========================================================================
// Test: Ignore main frame load failures with net::ERR_ABORTED.
// ===========================================================================
EXPECT_CALL(mock_cast_wc_observer_, OnPageStateChanged(_)).Times(0);
EXPECT_CALL(mock_cast_wc_observer_, OnPageStopped(_, _)).Times(0);
cast_web_contents_->DidFailLoad(
web_contents_->GetMainFrame(),
web_contents_->GetMainFrame()->GetLastCommittedURL(), net::ERR_ABORTED);
// ===========================================================================
// Test: If main frame fails to load, page should enter ERROR state.
// ===========================================================================
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::ERROR),
net::ERR_FAILED));
cast_web_contents_->DidFailLoad(
web_contents_->GetMainFrame(),
web_contents_->GetMainFrame()->GetLastCommittedURL(), net::ERR_FAILED);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorHttp4XX) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: If a server responds with an HTTP 4XX error, page should enter ERROR
// state.
// ===========================================================================
embedded_test_server()->RegisterRequestHandler(
base::BindRepeating(&DefaultHandler, net::HTTP_NOT_FOUND));
StartTestServer();
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::ERROR),
net::ERR_HTTP_RESPONSE_CODE_FAILURE))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(embedded_test_server()->GetURL("/dummy.html"));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ErrorLoadFailed) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: When main frame load fails, enter ERROR state. This test simulates a
// load error by intercepting the URL request and failing it with an arbitrary
// error code.
// ===========================================================================
base::FilePath path = GetTestDataFilePath("dummy.html");
GURL gurl = content::GetFileUrlWithQuery(path, "");
content::URLLoaderInterceptor url_interceptor(base::BindRepeating(
[](const GURL& url,
content::URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url != url)
return false;
network::URLLoaderCompletionStatus status;
status.error_code = net::ERR_ADDRESS_UNREACHABLE;
params->client->OnComplete(status);
return true;
},
gurl));
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(mock_cast_wc_observer_,
OnPageStopped(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::ERROR),
net::ERR_ADDRESS_UNREACHABLE))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(gurl);
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, LoadCanceledByApp) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: When the app calls window.stop(), the page should not enter the ERROR
// state. Instead, we treat it as LOADED. This is a historical behavior for
// some apps which intentionally stop the page and reload content.
// ===========================================================================
embedded_test_server()->ServeFilesFromSourceDirectory(GetTestDataPath());
StartTestServer();
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(
embedded_test_server()->GetURL("/load_cancel.html"));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, LocationRedirectLifecycle) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: When the app redirects to another url via window.location. Another
// navigation will be committed. LOADING -> LOADED -> LOADING -> LOADED state
// trasition is expected.
// ===========================================================================
embedded_test_server()->ServeFilesFromSourceDirectory(GetTestDataPath());
StartTestServer();
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
cast_web_contents_->LoadUrl(
embedded_test_server()->GetURL("/location_redirect.html"));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, NotifyMissingResource) {
auto run_loop = std::make_unique<base::RunLoop>();
auto quit_closure = [&run_loop]() {
if (run_loop->running()) {
run_loop->QuitWhenIdle();
}
};
// ===========================================================================
// Test: Loading a page with a missing resource should notify observers.
// ===========================================================================
{
InSequence seq;
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(
cast_web_contents_.get(), CastWebContents::PageState::LOADING)));
EXPECT_CALL(
mock_cast_wc_observer_,
OnPageStateChanged(CheckPageState(cast_web_contents_.get(),
CastWebContents::PageState::LOADED)))
.WillOnce(InvokeWithoutArgs(quit_closure));
}
EXPECT_CALL(mock_cast_wc_observer_,
ResourceLoadFailed(cast_web_contents_.get()));
base::FilePath path = GetTestDataFilePath("missing_resource.html");
cast_web_contents_->LoadUrl(content::GetFileUrlWithQuery(path, ""));
run_loop->Run();
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, ExecuteJavaScriptOnLoad) {
// ===========================================================================
// Test: Injecting script to change title should work.
// ===========================================================================
constexpr char kExpectedTitle[] = "hello";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
// The script should be able to run before HTML <script> tag starts running.
// The original title will be loaded first and then the injected script. Other
// scripts must run after the injected script.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kExpectedTitle)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)));
constexpr char kBindingsId[] = "1234";
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId, {gurl.GetOrigin().spec()}, "stashed_title = 'hello';");
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kExpectedTitle);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptUpdatedOnLoad) {
// ===========================================================================
// Test: Verify that this script replaces the previous script with same
// binding id, as opposed to being injected alongside it. (The latter would
// result in the title being "helloclobber").
// ===========================================================================
constexpr char kReplaceTitle[] = "clobber";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
// The script should be able to run before HTML <script> tag starts running.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kReplaceTitle)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)));
constexpr char kBindingsId[] = "1234";
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId, {gurl.GetOrigin().spec()}, "stashed_title = 'hello';");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId, {gurl.GetOrigin().spec()},
"stashed_title = document.title + 'clobber';");
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kReplaceTitle);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptOnLoadOrdered) {
// ===========================================================================
// Test: Verifies that bindings are injected in order by producing a
// cumulative, non-commutative result.
// ===========================================================================
constexpr char kExpectedTitle[] = "hello there";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
constexpr char kBindingsId1[] = "1234";
constexpr char kBindingsId2[] = "5678";
// The script should be able to run before HTML <script> tag starts running.
// The original title will be loaded first and then the injected script. Other
// scripts must run after the injected script.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kExpectedTitle)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)));
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId1, {gurl.GetOrigin().spec()}, "stashed_title = 'hello';");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId2, {gurl.GetOrigin().spec()}, "stashed_title += ' there';");
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kExpectedTitle);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptOnLoadRemoved) {
// ===========================================================================
// Test: Verifies that bindings could be removed successfully before page
// starts loading.
// ===========================================================================
constexpr char kExpectedTitle[] = "foo";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
constexpr char kBindingsId1[] = "1234";
constexpr char kBindingsId2[] = "5678";
// The script should be able to run before HTML <script> tag starts running.
// The original title will be loaded first and then the injected script. Other
// scripts must run after the injected script.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kExpectedTitle)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)));
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId1, {gurl.GetOrigin().spec()}, "stashed_title = 'foo';");
// Add a script which clobbers "foo".
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId2, {gurl.GetOrigin().spec()}, "stashed_title = 'bar';");
// Deletes the clobbering script.
cast_web_contents_->RemoveBeforeLoadJavaScript(kBindingsId2);
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kExpectedTitle);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptOnLoadWrongOrigin) {
// ===========================================================================
// Test: Injecting script should not happen if the to-be-loaded page's origin
// is not whitelisted for the injection script.
// ===========================================================================
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
constexpr char kBindingsId[] = "1234";
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)));
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId, {"http://example.com"}, "stashed_title = 'hello';");
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kOriginalTitle);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptOnLoadWildcardOrigin) {
// Start test server for hosting test HTML pages.
embedded_test_server()->ServeFilesFromSourceDirectory(GetTestDataPath());
StartTestServer();
// ===========================================================================
// Test: Injecting script should be able to load on arbitrary origins with
// wildcard origin restriction set.
// ===========================================================================
constexpr char kInjectedTitle1[] = "hello";
constexpr char kInjectedTitle2[] = "world";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
constexpr char kBindingsId1[] = "1234";
constexpr char kBindingsId2[] = "5678";
// The script should be able to run before HTML <script> tag starts running.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)))
.Times(2);
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kInjectedTitle1)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kInjectedTitle2)));
GURL gurl{embedded_test_server()->GetURL("/dynamic_title.html")};
cast_web_contents_->AddBeforeLoadJavaScript(kBindingsId1, {"*"},
"stashed_title = 'hello';");
// Test script injection for the origin 127.0.0.1.
// Load title "hello":
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kInjectedTitle1);
// Load AboutBlank page:
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
cast_web_contents_->AddBeforeLoadJavaScript(kBindingsId2, {"*"},
"stashed_title = 'world';");
// Test script injection using a different origin ("localhost"), which should
// still be picked up by the wildcard. And the title should be initialized as
// origianl title first, then as 'world'.
GURL alt_url =
embedded_test_server()->GetURL("localhost", "/dynamic_title.html");
cast_web_contents_->LoadUrl(alt_url);
title_change_observer_.RunUntilTitleEquals(kInjectedTitle2);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest,
ExecuteJavaScriptOnLoadEarlyAndLateRegistrations) {
// ===========================================================================
// Test: Tests that we can inject scripts before and after RenderFrame
// creation.
// ===========================================================================
constexpr char kExpectedTitle1[] = "foo";
constexpr char kExpectedTitle2[] = "foo bar";
constexpr char kOriginalTitle[] =
"Welcome to Stan the Offline Dino's Homepage";
constexpr char kBindingsId1[] = "1234";
constexpr char kBindingsId2[] = "5678";
// The script should be able to run before HTML <script> tag starts running.
// The original title will be loaded first and then the injected script. Other
// scripts must run after the injected script.
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kExpectedTitle2)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kExpectedTitle1)));
EXPECT_CALL(mock_cast_wc_observer_,
UpdateTitle(base::ASCIIToUTF16(kOriginalTitle)))
.Times(2);
GURL gurl = content::GetFileUrlWithQuery(
GetTestDataFilePath("dynamic_title.html"), "");
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId1, {gurl.GetOrigin().spec()}, "stashed_title = 'foo';");
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kExpectedTitle1);
// Inject bindings after RenderFrameCreation
cast_web_contents_->AddBeforeLoadJavaScript(
kBindingsId2, {gurl.GetOrigin().spec()}, "stashed_title += ' bar';");
// Navigate away to clean the state.
cast_web_contents_->LoadUrl(GURL(url::kAboutBlankURL));
// Navigate back and see if both scripts are working.
cast_web_contents_->LoadUrl(gurl);
title_change_observer_.RunUntilTitleEquals(kExpectedTitle2);
}
IN_PROC_BROWSER_TEST_F(CastWebContentsBrowserTest, PostMessageToMainFrame) {
// ===========================================================================
// Test: Tests that we can trigger onmessage event on a web page. This test
// would post a message to the test page to redirect it to |title1.html|.
// ===========================================================================
constexpr char kOriginalTitle[] = "postmessage";