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
|
// Copyright 2017 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.
#include <memory>
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "content/public/test/browser_test.h"
#include "headless/public/devtools/domains/emulation.h"
#include "headless/public/devtools/domains/page.h"
#include "headless/public/devtools/domains/runtime.h"
#include "headless/public/headless_devtools_client.h"
#include "headless/public/util/testing/test_in_memory_protocol_handler.h"
#include "headless/test/headless_browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using testing::ElementsAre;
using testing::Contains;
namespace headless {
class VirtualTimeBrowserTest : public HeadlessAsyncDevTooledBrowserTest,
public emulation::ExperimentalObserver,
public runtime::Observer {
public:
void SetInitialURL(const std::string& initial_url) {
initial_url_ = initial_url;
}
void RunDevTooledTest() override {
devtools_client_->GetEmulation()->GetExperimental()->AddObserver(this);
devtools_client_->GetRuntime()->AddObserver(this);
devtools_client_->GetRuntime()->Enable(base::BindRepeating(
&VirtualTimeBrowserTest::RuntimeEnabled, base::Unretained(this)));
}
void RuntimeEnabled() {
runtime_enabled = true;
MaybeSetVirtualTimePolicy();
}
virtual void MaybeSetVirtualTimePolicy() {
if (!runtime_enabled)
return;
SetVirtualTimePolicy();
}
void SetVirtualTimePolicyDone(
std::unique_ptr<emulation::SetVirtualTimePolicyResult> result) {
// Virtual time is paused, so start navigating.
devtools_client_->GetPage()->Navigate(initial_url_);
}
virtual void SetVirtualTimePolicy() {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(5000)
.SetWaitForNavigation(true)
.Build(),
base::BindRepeating(&VirtualTimeBrowserTest::SetVirtualTimePolicyDone,
base::Unretained(this)));
}
// runtime::Observer implementation:
void OnConsoleAPICalled(
const runtime::ConsoleAPICalledParams& params) override {
// We expect the arguments always to be a single string.
const std::vector<std::unique_ptr<runtime::RemoteObject>>& args =
*params.GetArgs();
if (args.size() == 1u && args[0]->HasValue())
log_.push_back(args[0]->GetValue()->GetString());
}
std::string initial_url_;
std::vector<std::string> log_;
bool initial_load_seen_ = false;
bool runtime_enabled = false;
};
class VirtualTimeObserverTest : public VirtualTimeBrowserTest {
public:
VirtualTimeObserverTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(
embedded_test_server()->GetURL("/virtual_time_test.html").spec());
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
std::vector<std::string> expected_log = {"Paused @ 0ms",
"Advanced to 10ms",
"step1",
"Advanced to 110ms",
"step2",
"Paused @ 110ms",
"Advanced to 210ms",
"step3",
"Paused @ 210ms",
"Advanced to 310ms",
"step4",
"pass"};
// Note after the PASS step there are a number of virtual time advances, but
// this list seems to be non-deterministic because there's all sorts of
// timers in the system. We don't really care about that here.
ASSERT_GE(log_.size(), expected_log.size());
for (size_t i = 0; i < expected_log.size(); i++) {
EXPECT_EQ(expected_log[i], log_[i]) << "At index " << i;
}
EXPECT_THAT(log_, Contains("Advanced to 5000ms"));
EXPECT_THAT(log_, Contains("Paused @ 5000ms"));
FinishAsynchronousTest();
}
void OnVirtualTimeAdvanced(
const emulation::VirtualTimeAdvancedParams& params) override {
log_.push_back(base::StringPrintf("Advanced to %.fms",
params.GetVirtualTimeElapsed()));
}
void OnVirtualTimePaused(
const emulation::VirtualTimePausedParams& params) override {
log_.push_back(
base::StringPrintf("Paused @ %.fms", params.GetVirtualTimeElapsed()));
}
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeObserverTest);
class VirtualTimeBaseTest : public VirtualTimeBrowserTest {
public:
VirtualTimeBaseTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()->GetURL("/blank.html").spec());
}
void SetVirtualTimePolicy() override {
// Set to paused initially.
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(emulation::VirtualTimePolicy::PAUSE)
.Build(),
base::BindRepeating(&VirtualTimeBaseTest::SetFirstVirtualTimePolicyDone,
base::Unretained(this)));
}
void SetFirstVirtualTimePolicyDone(
std::unique_ptr<emulation::SetVirtualTimePolicyResult> result) {
// Should have enabled virtual time, and returned a valid time base.
virtual_time_base_ = result->GetVirtualTimeBase();
EXPECT_NE(0, virtual_time_base_);
// Set with wait_for_navigation, the returned time base shouldn't change.
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(1000)
.SetWaitForNavigation(true)
.Build(),
base::BindRepeating(
&VirtualTimeBaseTest::SetSecondVirtualTimePolicyDone,
base::Unretained(this)));
}
void SetSecondVirtualTimePolicyDone(
std::unique_ptr<emulation::SetVirtualTimePolicyResult> result) {
EXPECT_EQ(virtual_time_base_, result->GetVirtualTimeBase());
SetVirtualTimePolicyDone(std::move(result));
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
FinishAsynchronousTest();
}
private:
double virtual_time_base_ = 0;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeBaseTest);
class MaxVirtualTimeTaskStarvationCountTest : public VirtualTimeBrowserTest {
public:
MaxVirtualTimeTaskStarvationCountTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()
->GetURL("/virtual_time_starvation_test.html")
.spec());
}
void SetVirtualTimePolicy() override {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(4001)
.SetMaxVirtualTimeTaskStarvationCount(100)
.SetWaitForNavigation(true)
.Build(),
base::BindRepeating(&VirtualTimeBrowserTest::SetVirtualTimePolicyDone,
base::Unretained(this)));
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// If SetMaxVirtualTimeTaskStarvationCount was not set, this callback would
// never fire.
FinishAsynchronousTest();
}
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(MaxVirtualTimeTaskStarvationCountTest);
namespace {
static constexpr char kIndexHtml[] = R"(
<html>
<body>
<iframe src="/iframe.html" width="400" height="200" id="iframe1">
</iframe>
</body>
</html>
)";
static constexpr char kIFrame[] = R"(
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hello from the iframe!</h1>
</body>
</html>
)";
static constexpr char kCss[] = R"(
.test {
color: blue;
}
)";
} // namespace
class FrameDetatchWithPendingResourceLoadVirtualTimeTest
: public VirtualTimeBrowserTest,
public TestInMemoryProtocolHandler::RequestDeferrer {
public:
FrameDetatchWithPendingResourceLoadVirtualTimeTest() {
SetInitialURL("http://test.com/index.html");
}
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), this));
http_handler_ = http_handler.get();
http_handler->InsertResponse("http://test.com/index.html",
{kIndexHtml, "text/html"});
http_handler->InsertResponse("http://test.com/iframe.html",
{kIFrame, "text/html"});
http_handler->InsertResponse("http://test.com/style.css",
{kCss, "text/css"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
void OnRequest(const GURL& url, base::Closure complete_request) override {
// Note this is called on the IO thread.
if (url.spec() == "http://test.com/style.css") {
// Detach the iframe but leave the css resource fetch hanging.
browser()->BrowserMainThread()->PostTask(
FROM_HERE, base::BindRepeating(
&FrameDetatchWithPendingResourceLoadVirtualTimeTest::
DetatchIFrame,
base::Unretained(this)));
} else {
complete_request.Run();
}
}
void DetatchIFrame() {
devtools_client_->GetRuntime()->Evaluate(
"let elem = document.getElementById('iframe1');\n"
"elem.parentNode.removeChild(elem);");
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
EXPECT_THAT(
http_handler_->urls_requested(),
ElementsAre("http://test.com/index.html", "http://test.com/iframe.html",
"http://test.com/style.css"));
// Virtual time should still expire, despite the CSS resource load not
// finishing.
FinishAsynchronousTest();
}
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(
FrameDetatchWithPendingResourceLoadVirtualTimeTest);
class VirtualTimeLocalStorageTest : public VirtualTimeBrowserTest {
public:
VirtualTimeLocalStorageTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()
->GetURL("/virtual_time_local_storage.html")
.spec());
}
void OnConsoleAPICalled(
const runtime::ConsoleAPICalledParams& params) override {
EXPECT_EQ(runtime::ConsoleAPICalledType::LOG, params.GetType());
ASSERT_EQ(1u, params.GetArgs()->size());
ASSERT_EQ(runtime::RemoteObjectType::STRING,
(*params.GetArgs())[0]->GetType());
std::string count_string = (*params.GetArgs())[0]->GetValue()->GetString();
int count;
ASSERT_TRUE(base::StringToInt(count_string, &count)) << count_string;
EXPECT_EQ(count, 400);
console_log_seen_ = true;
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// If SetMaxVirtualTimeTaskStarvationCount was not set, this callback would
// never fire.
EXPECT_TRUE(console_log_seen_);
FinishAsynchronousTest();
}
bool console_log_seen_ = false;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeLocalStorageTest);
class VirtualTimeSessionStorageTest : public VirtualTimeBrowserTest {
public:
VirtualTimeSessionStorageTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()
->GetURL("/virtual_time_session_storage.html")
.spec());
}
void OnConsoleAPICalled(
const runtime::ConsoleAPICalledParams& params) override {
EXPECT_EQ(runtime::ConsoleAPICalledType::LOG, params.GetType());
ASSERT_EQ(1u, params.GetArgs()->size());
ASSERT_EQ(runtime::RemoteObjectType::STRING,
(*params.GetArgs())[0]->GetType());
std::string count_string = (*params.GetArgs())[0]->GetValue()->GetString();
int count;
ASSERT_TRUE(base::StringToInt(count_string, &count)) << count_string;
EXPECT_EQ(count, 400);
console_log_seen_ = true;
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// If SetMaxVirtualTimeTaskStarvationCount was not set, this callback would
// never fire.
EXPECT_TRUE(console_log_seen_);
FinishAsynchronousTest();
}
bool console_log_seen_ = false;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeSessionStorageTest);
class DeferredLoadDoesntBlockVirtualTimeTest : public VirtualTimeBrowserTest {
public:
DeferredLoadDoesntBlockVirtualTimeTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()->GetURL("/video.html").spec());
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// The video should not block virtual time.
FinishAsynchronousTest();
}
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(DeferredLoadDoesntBlockVirtualTimeTest);
class Http404DoesntBlockVirtualTimeTest : public VirtualTimeBrowserTest {
public:
Http404DoesntBlockVirtualTimeTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(embedded_test_server()->GetURL("/NoSuchFile.html").spec());
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// The video should not block virtual time.
FinishAsynchronousTest();
}
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(Http404DoesntBlockVirtualTimeTest);
class RedirectVirtualTimeTest : public VirtualTimeBrowserTest {
public:
RedirectVirtualTimeTest() { SetInitialURL("http://test.com/index.html"); }
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), nullptr));
http_handler_ = http_handler.get();
http_handler->InsertResponse("http://test.com/index.html",
{kIndexHtml, "text/html"});
http_handler->InsertResponse(
"http://test.com/iframe.html",
{"HTTP/1.1 302 Found\r\nLocation: iframe2.html\r\n\r\n"});
http_handler->InsertResponse("http://test.com/iframe2.html",
{kIFrame, "text/html"});
http_handler->InsertResponse(
"http://test.com/style.css",
{"HTTP/1.1 302 Found\r\nLocation: style2.css\r\n\r\n"});
http_handler->InsertResponse("http://test.com/style2.css",
{kCss, "text/css"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
EXPECT_THAT(
http_handler_->urls_requested(),
ElementsAre("http://test.com/index.html", "http://test.com/iframe.html",
"http://test.com/iframe2.html", "http://test.com/style.css",
"http://test.com/style2.css"));
// Virtual time should still expire, despite the CSS resource load not
// finishing.
FinishAsynchronousTest();
}
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(RedirectVirtualTimeTest);
namespace {
static constexpr char kFooDotCom[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
<iframe src='/a/'></iframe>\n"
</body>
</html>
)";
static constexpr char kFooDotComSlashA[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
</body>
</html>
)";
static constexpr char kBarDotCom[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
<iframe src='/b/' id='frame_b'></iframe>
<iframe src='/c/'></iframe>
</body>
</html>
)";
static constexpr char kBarDotComSlashB[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
<iframe src='/d/'></iframe>
</body>
</html>
)";
static constexpr char kBarDotComSlashC[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
</body>
</html>
)";
static constexpr char kBarDotComSlashD[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
</body>
</html>
)";
static constexpr char kBarDotComSlashE[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
<iframe src='/f/'></iframe>
</body>
</html>
)";
static constexpr char kBarDotComSlashF[] = R"(
<html>
<body>
<script> console.log(document.location.href); </script>
</body>
</html>
)";
} // namespace
class VirtualTimeAndHistoryNavigationTest : public VirtualTimeBrowserTest {
public:
VirtualTimeAndHistoryNavigationTest() { SetInitialURL("http://foo.com/"); }
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), nullptr));
http_handler_ = http_handler.get();
http_handler->InsertResponse("http://foo.com/", {kFooDotCom, "text/html"});
http_handler->InsertResponse("http://foo.com/a/",
{kFooDotComSlashA, "text/html"});
http_handler->InsertResponse("http://bar.com/", {kBarDotCom, "text/html"});
http_handler->InsertResponse("http://bar.com/b/",
{kBarDotComSlashB, "text/html"});
http_handler->InsertResponse("http://bar.com/c/",
{kBarDotComSlashC, "text/html"});
http_handler->InsertResponse("http://bar.com/d/",
{kBarDotComSlashD, "text/html"});
http_handler->InsertResponse("http://bar.com/e/",
{kBarDotComSlashE, "text/html"});
http_handler->InsertResponse("http://bar.com/f/",
{kBarDotComSlashF, "text/html"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
if (step_ < test_commands_.size()) {
devtools_client_->GetRuntime()->Evaluate(
test_commands_[step_++],
base::BindRepeating(
&VirtualTimeAndHistoryNavigationTest::OnEvaluateResult,
base::Unretained(this)));
} else {
FinishAsynchronousTest();
}
}
void OnEvaluateResult(std::unique_ptr<runtime::EvaluateResult>) {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(5000)
.Build());
}
const std::vector<std::string> test_commands_ = {
"document.location.href = 'http://bar.com/'",
"document.getElementById('frame_b').src = '/e/'",
"history.back()",
"history.forward()",
"history.go(-1)",
};
size_t step_ = 0;
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeAndHistoryNavigationTest);
namespace {
static constexpr char kIndexHtmlWithScript[] = R"(
<html>
<body>
<script src="/large.js"></script>
</body>
</html>
)";
static constexpr char kLargeDotJS[] = R"(
(function() {
var setTitle = function(newTitle) {
document.title = newTitle;
};
%s
setTitle('Test PASS');
})();
)";
} // namespace
class PendingScriptVirtualTimeTest : public VirtualTimeBrowserTest {
public:
PendingScriptVirtualTimeTest() {
SetInitialURL("http://test.com/index.html");
}
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), nullptr));
http_handler_ = http_handler.get();
http_handler_->InsertResponse("http://test.com/index.html",
{kIndexHtmlWithScript, "text/html"});
// We want to pad |kLargeDotJS| out with some dummy code which is parsed
// asynchronously to make sure the virtual_time_pauser in PendingScript
// actually does something. We construct a large number of long unused
// function declarations which seems to trigger the desired code path.
std::string dummy;
dummy.reserve(1024 * 1024 * 4);
for (int i = 0; i < 1024; i++) {
dummy.append(base::StringPrintf("var i%d=function(){return '", i));
dummy.append(1024, 'A');
dummy.append("';}\n");
}
large_js_ = base::StringPrintf(kLargeDotJS, dummy.c_str());
http_handler_->InsertResponse(
"http://test.com/large.js",
{large_js_.c_str(), "application/javascript"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
devtools_client_->GetRuntime()->Evaluate(
"document.title",
base::BindRepeating(&PendingScriptVirtualTimeTest::OnEvaluateResult,
base::Unretained(this)));
}
void OnEvaluateResult(std::unique_ptr<runtime::EvaluateResult> result) {
EXPECT_EQ("Test PASS", result->GetResult()->GetValue()->GetString());
FinishAsynchronousTest();
}
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
std::string large_js_;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(PendingScriptVirtualTimeTest);
namespace {
static constexpr char kResourceErrorLoop[] = R"(
<html>
<script>
var counter = 1;
</script>
<img src="1" onerror="this.src='' + ++counter;">
</html>
)";
}
class VirtualTimeAndResourceErrorLoopTest : public VirtualTimeBrowserTest {
public:
VirtualTimeAndResourceErrorLoopTest() { SetInitialURL("http://foo.com/"); }
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), nullptr));
http_handler_ = http_handler.get();
http_handler->InsertResponse("http://foo.com/",
{kResourceErrorLoop, "text/html"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
void SetVirtualTimePolicy() override {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(5000)
.SetMaxVirtualTimeTaskStarvationCount(1000000) // Prevent flakes.
.SetWaitForNavigation(true)
.Build(),
base::BindRepeating(&VirtualTimeBrowserTest::SetVirtualTimePolicyDone,
base::Unretained(this)));
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// The budget is 5000 virtual ms. The resources are delivered with 10
// virtual ms delay, so we should have 500 urls.
EXPECT_EQ(500u, http_handler_->urls_requested().size());
FinishAsynchronousTest();
}
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(VirtualTimeAndResourceErrorLoopTest);
class DateDotNowInitialOverrideTest : public HeadlessAsyncDevTooledBrowserTest {
public:
void CustomizeHeadlessBrowserContext(
HeadlessBrowserContext::Builder& builder) override {
builder.SetInitialVirtualTime(base::Time::FromJsTime(123450.0));
}
void RunDevTooledTest() override {
devtools_client_->GetRuntime()->Evaluate(
"Date.now()",
base::BindRepeating(&DateDotNowInitialOverrideTest::OnEvaluateResult,
base::Unretained(this)));
}
void OnEvaluateResult(std::unique_ptr<runtime::EvaluateResult> result) {
EXPECT_EQ(123450.0, result->GetResult()->GetValue()->GetDouble());
FinishAsynchronousTest();
}
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(DateDotNowInitialOverrideTest);
class JavascriptTimeAlwaysAdvancesTest : public VirtualTimeBrowserTest,
public page::Observer {
public:
JavascriptTimeAlwaysAdvancesTest() {
EXPECT_TRUE(embedded_test_server()->Start());
SetInitialURL(
embedded_test_server()->GetURL("/virtual_time_and_date.html").spec());
}
void RunDevTooledTest() override {
devtools_client_->GetPage()->AddObserver(this);
devtools_client_->GetPage()->Enable();
devtools_client_->GetPage()->AddScriptToEvaluateOnNewDocument(
R"( (function() {
let realDateNow = Date.now;
let prevDate = 0;
Date.now = function() {
let nextDate = realDateNow();
if (prevDate >= nextDate) {
nextDate = prevDate + 1;
}
prevDate = nextDate;
return nextDate;
};
})();)",
base::BindRepeating(&JavascriptTimeAlwaysAdvancesTest::
AfterAddScriptToEvaluateOnNewDocument,
base::Unretained(this)));
}
void AfterAddScriptToEvaluateOnNewDocument(
std::unique_ptr<page::AddScriptToEvaluateOnNewDocumentResult>) {
VirtualTimeBrowserTest::RunDevTooledTest();
}
void CustomizeHeadlessBrowserContext(
HeadlessBrowserContext::Builder& builder) override {
builder.SetInitialVirtualTime(base::Time::FromJsTime(1000000.0));
}
void OnConsoleAPICalled(
const runtime::ConsoleAPICalledParams& params) override {
EXPECT_EQ(runtime::ConsoleAPICalledType::LOG, params.GetType());
ASSERT_EQ(1u, params.GetArgs()->size());
ASSERT_EQ(runtime::RemoteObjectType::STRING,
(*params.GetArgs())[0]->GetType());
std::string result_string = (*params.GetArgs())[0]->GetValue()->GetString();
EXPECT_EQ("pass", result_string);
console_log_seen_ = true;
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// If SetMaxVirtualTimeTaskStarvationCount was not set, this callback would
// never fire.
EXPECT_TRUE(console_log_seen_);
FinishAsynchronousTest();
}
bool console_log_seen_ = false;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(JavascriptTimeAlwaysAdvancesTest);
namespace {
static constexpr char kSiteA[] = R"(
<html>
<body>
<script>
setTimeout(function() {
window.location.href = "http://b.com/";
}, 1000);
</script>
</body>
</html>
)";
static constexpr char kSiteB[] = R"(
<html>
<body>
<script>
setTimeout(function() {
window.location.href = "http://c.com/";
}, 1000);
</script>
</body>
</html>
)";
static constexpr char kSiteC[] = R"(
<html>
<body>
<script>
setTimeout(function() {
window.location.href = "http://d.com/";
}, 1000);
</script>
</body>
</html>
)";
static constexpr char kSiteD[] = R"(
<html>
<body>
</body>
</html>
)";
} // namespace
class CrossOriginNavigationVirtualTimeTest
: public VirtualTimeBrowserTest,
public TestInMemoryProtocolHandler::RequestDeferrer {
public:
CrossOriginNavigationVirtualTimeTest() { SetInitialURL("http://a.com/"); }
ProtocolHandlerMap GetProtocolHandlers() override {
ProtocolHandlerMap protocol_handlers;
std::unique_ptr<TestInMemoryProtocolHandler> http_handler(
new TestInMemoryProtocolHandler(browser()->BrowserIOThread(), this));
http_handler_ = http_handler.get();
http_handler->InsertResponse("http://a.com/", {kSiteA, "text/html"});
http_handler->InsertResponse("http://b.com/", {kSiteB, "text/html"});
http_handler->InsertResponse("http://c.com/", {kSiteC, "text/html"});
http_handler->InsertResponse("http://d.com/", {kSiteD, "text/html"});
protocol_handlers[url::kHttpScheme] = std::move(http_handler);
return protocol_handlers;
}
void RunDevTooledTest() override {
http_handler_->SetHeadlessBrowserContext(browser_context_);
VirtualTimeBrowserTest::RunDevTooledTest();
}
void CustomizeHeadlessBrowserContext(
HeadlessBrowserContext::Builder& builder) override {
// Make sure the navigations spawn new processes.
builder.SetSitePerProcess(true);
}
void SetVirtualTimePolicy() override {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(
emulation::VirtualTimePolicy::PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(100)
.SetWaitForNavigation(true)
.Build(),
base::BindRepeating(&VirtualTimeBrowserTest::SetVirtualTimePolicyDone,
base::Unretained(this)));
}
void OnRequest(const GURL& url,
base::RepeatingClosure complete_request) override {
log_.push_back(
base::StringPrintf("url: %s @ %f", url.spec().c_str(), virtual_time_));
complete_request.Run();
}
void OnVirtualTimeAdvanced(
const emulation::VirtualTimeAdvancedParams& params) override {
virtual_time_ = params.GetVirtualTimeElapsed();
}
void OnVirtualTimePaused(
const emulation::VirtualTimePausedParams& params) override {
virtual_time_ = params.GetVirtualTimeElapsed();
}
// emulation::Observer implementation:
void OnVirtualTimeBudgetExpired(
const emulation::VirtualTimeBudgetExpiredParams& params) override {
// Issue virtual time in chunks of 100 virtual ms. We do this because that's
// how virtual time is used in reality, but also because this wouldn't work
// otherwise. The state of the Emulation domain (like every domain) is only
// serialized in a protocol command response so if we didn't do this,
// progress would be lost and the loads would happen at the wrong virtual
// time offsets.
if (++count_ < 50) {
devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy(
emulation::SetVirtualTimePolicyParams::Builder()
.SetPolicy(emulation::VirtualTimePolicy::
PAUSE_IF_NETWORK_FETCHES_PENDING)
.SetBudget(100)
.Build());
} else {
EXPECT_THAT(log_, ElementsAre("url: http://a.com/ @ 0.000000",
"url: http://b.com/ @ 1010.000000",
"url: http://c.com/ @ 2010.000000",
"url: http://d.com/ @ 3010.000000"));
FinishAsynchronousTest();
}
}
TestInMemoryProtocolHandler* http_handler_; // NOT OWNED
std::vector<std::string> log_;
double virtual_time_ = 0;
int count_ = 0;
};
HEADLESS_ASYNC_DEVTOOLED_TEST_F(CrossOriginNavigationVirtualTimeTest);
} // namespace headless
|