Remove the old signature of NotificationManager::closePersistent().
[chromium-blink-merge.git] / chrome / browser / prerender / prerender_browsertest.cc
blob290fb236a170f41845923d6e31760a873fc15513
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <deque>
6 #include <vector>
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/memory/ref_counted_memory.h"
12 #include "base/memory/scoped_vector.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/path_service.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/run_loop.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/test/histogram_tester.h"
21 #include "base/test/test_timeouts.h"
22 #include "base/values.h"
23 #include "chrome/browser/browsing_data/browsing_data_helper.h"
24 #include "chrome/browser/browsing_data/browsing_data_remover.h"
25 #include "chrome/browser/browsing_data/browsing_data_remover_test_util.h"
26 #include "chrome/browser/chrome_content_browser_client.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h"
29 #include "chrome/browser/extensions/extension_apitest.h"
30 #include "chrome/browser/external_protocol/external_protocol_handler.h"
31 #include "chrome/browser/favicon/favicon_tab_helper.h"
32 #include "chrome/browser/net/prediction_options.h"
33 #include "chrome/browser/predictors/autocomplete_action_predictor.h"
34 #include "chrome/browser/predictors/autocomplete_action_predictor_factory.h"
35 #include "chrome/browser/prerender/prerender_contents.h"
36 #include "chrome/browser/prerender/prerender_field_trial.h"
37 #include "chrome/browser/prerender/prerender_handle.h"
38 #include "chrome/browser/prerender/prerender_link_manager.h"
39 #include "chrome/browser/prerender/prerender_link_manager_factory.h"
40 #include "chrome/browser/prerender/prerender_manager.h"
41 #include "chrome/browser/prerender/prerender_manager_factory.h"
42 #include "chrome/browser/profiles/profile.h"
43 #include "chrome/browser/profiles/profile_io_data.h"
44 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
45 #include "chrome/browser/safe_browsing/database_manager.h"
46 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
47 #include "chrome/browser/safe_browsing/safe_browsing_util.h"
48 #include "chrome/browser/task_manager/task_manager.h"
49 #include "chrome/browser/task_manager/task_manager_browsertest_util.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_navigator.h"
54 #include "chrome/browser/ui/browser_window.h"
55 #include "chrome/browser/ui/location_bar/location_bar.h"
56 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
57 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
58 #include "chrome/browser/ui/omnibox/omnibox_view.h"
59 #include "chrome/browser/ui/tabs/tab_strip_model.h"
60 #include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
61 #include "chrome/common/chrome_paths.h"
62 #include "chrome/common/chrome_switches.h"
63 #include "chrome/common/pref_names.h"
64 #include "chrome/grit/generated_resources.h"
65 #include "chrome/test/base/in_process_browser_test.h"
66 #include "chrome/test/base/test_switches.h"
67 #include "chrome/test/base/ui_test_utils.h"
68 #include "components/content_settings/core/browser/host_content_settings_map.h"
69 #include "components/variations/entropy_provider.h"
70 #include "components/variations/variations_associated_data.h"
71 #include "content/public/browser/browser_message_filter.h"
72 #include "content/public/browser/devtools_agent_host.h"
73 #include "content/public/browser/navigation_controller.h"
74 #include "content/public/browser/navigation_entry.h"
75 #include "content/public/browser/notification_service.h"
76 #include "content/public/browser/render_frame_host.h"
77 #include "content/public/browser/render_process_host.h"
78 #include "content/public/browser/render_view_host.h"
79 #include "content/public/browser/site_instance.h"
80 #include "content/public/browser/web_contents.h"
81 #include "content/public/browser/web_contents_observer.h"
82 #include "content/public/common/url_constants.h"
83 #include "content/public/test/browser_test_utils.h"
84 #include "content/public/test/test_navigation_observer.h"
85 #include "content/public/test/test_utils.h"
86 #include "extensions/common/constants.h"
87 #include "extensions/common/extension_urls.h"
88 #include "extensions/common/manifest_handlers/mime_types_handler.h"
89 #include "extensions/common/switches.h"
90 #include "extensions/test/result_catcher.h"
91 #include "net/base/escape.h"
92 #include "net/cert/x509_certificate.h"
93 #include "net/dns/mock_host_resolver.h"
94 #include "net/ssl/client_cert_store.h"
95 #include "net/ssl/ssl_cert_request_info.h"
96 #include "net/test/url_request/url_request_mock_http_job.h"
97 #include "net/url_request/url_request_context.h"
98 #include "net/url_request/url_request_context_getter.h"
99 #include "net/url_request/url_request_filter.h"
100 #include "net/url_request/url_request_interceptor.h"
101 #include "net/url_request/url_request_job.h"
102 #include "ui/base/l10n/l10n_util.h"
103 #include "url/gurl.h"
105 using chrome_browser_net::NetworkPredictionOptions;
106 using content::BrowserThread;
107 using content::DevToolsAgentHost;
108 using content::NavigationController;
109 using content::OpenURLParams;
110 using content::Referrer;
111 using content::RenderFrameHost;
112 using content::RenderViewHost;
113 using content::RenderWidgetHost;
114 using content::TestNavigationObserver;
115 using content::WebContents;
116 using content::WebContentsObserver;
117 using net::NetworkChangeNotifier;
118 using task_manager::browsertest_util::WaitForTaskManagerRows;
120 // Prerender tests work as follows:
122 // A page with a prefetch link to the test page is loaded. Once prerendered,
123 // its Javascript function DidPrerenderPass() is called, which returns true if
124 // the page behaves as expected when prerendered.
126 // The prerendered page is then displayed on a tab. The Javascript function
127 // DidDisplayPass() is called, and returns true if the page behaved as it
128 // should while being displayed.
130 namespace prerender {
132 namespace {
134 class MockNetworkChangeNotifierWIFI : public NetworkChangeNotifier {
135 public:
136 ConnectionType GetCurrentConnectionType() const override {
137 return NetworkChangeNotifier::CONNECTION_WIFI;
141 class MockNetworkChangeNotifier4G : public NetworkChangeNotifier {
142 public:
143 ConnectionType GetCurrentConnectionType() const override {
144 return NetworkChangeNotifier::CONNECTION_4G;
148 // Constants used in the test HTML files.
149 const char* kReadyTitle = "READY";
150 const char* kPassTitle = "PASS";
152 std::string CreateClientRedirect(const std::string& dest_url) {
153 const char* const kClientRedirectBase = "client-redirect?";
154 return kClientRedirectBase + net::EscapeQueryParamValue(dest_url, false);
157 std::string CreateServerRedirect(const std::string& dest_url) {
158 const char* const kServerRedirectBase = "server-redirect?";
159 return kServerRedirectBase + net::EscapeQueryParamValue(dest_url, false);
162 // Clears the specified data using BrowsingDataRemover.
163 void ClearBrowsingData(Browser* browser, int remove_mask) {
164 BrowsingDataRemover* remover =
165 BrowsingDataRemover::CreateForUnboundedRange(browser->profile());
166 BrowsingDataRemoverCompletionObserver observer(remover);
167 remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
168 observer.BlockUntilCompletion();
169 // BrowsingDataRemover deletes itself.
172 // Returns true if the prerender is expected to abort on its own, before
173 // attempting to swap it.
174 bool ShouldAbortPrerenderBeforeSwap(FinalStatus status) {
175 switch (status) {
176 case FINAL_STATUS_USED:
177 case FINAL_STATUS_WINDOW_OPENER:
178 case FINAL_STATUS_APP_TERMINATING:
179 case FINAL_STATUS_PROFILE_DESTROYED:
180 case FINAL_STATUS_CACHE_OR_HISTORY_CLEARED:
181 // We'll crash the renderer after it's loaded.
182 case FINAL_STATUS_RENDERER_CRASHED:
183 case FINAL_STATUS_CANCELLED:
184 case FINAL_STATUS_DEVTOOLS_ATTACHED:
185 case FINAL_STATUS_PAGE_BEING_CAPTURED:
186 case FINAL_STATUS_NAVIGATION_UNCOMMITTED:
187 case FINAL_STATUS_WOULD_HAVE_BEEN_USED:
188 case FINAL_STATUS_NON_EMPTY_BROWSING_INSTANCE:
189 return false;
190 default:
191 return true;
195 // Convenience function to wait for a title. Handles the case when the
196 // WebContents already has the expected title.
197 void WaitForASCIITitle(WebContents* web_contents,
198 const char* expected_title_ascii) {
199 base::string16 expected_title = base::ASCIIToUTF16(expected_title_ascii);
200 if (web_contents->GetTitle() == expected_title)
201 return;
202 content::TitleWatcher title_watcher(web_contents, expected_title);
203 EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
206 // Waits for the destruction of a RenderProcessHost's IPC channel.
207 // Used to make sure the PrerenderLinkManager's OnChannelClosed function has
208 // been called, before checking its state.
209 class ChannelDestructionWatcher {
210 public:
211 ChannelDestructionWatcher() : channel_destroyed_(false) {
214 ~ChannelDestructionWatcher() {
217 void WatchChannel(content::RenderProcessHost* host) {
218 host->AddFilter(new DestructionMessageFilter(this));
221 void WaitForChannelClose() {
222 run_loop_.Run();
223 EXPECT_TRUE(channel_destroyed_);
226 private:
227 // When destroyed, calls ChannelDestructionWatcher::OnChannelDestroyed.
228 // Ignores all messages.
229 class DestructionMessageFilter : public content::BrowserMessageFilter {
230 public:
231 explicit DestructionMessageFilter(ChannelDestructionWatcher* watcher)
232 : BrowserMessageFilter(0),
233 watcher_(watcher) {
236 private:
237 ~DestructionMessageFilter() override {
238 content::BrowserThread::PostTask(
239 content::BrowserThread::UI, FROM_HERE,
240 base::Bind(&ChannelDestructionWatcher::OnChannelDestroyed,
241 base::Unretained(watcher_)));
244 bool OnMessageReceived(const IPC::Message& message) override {
245 return false;
248 ChannelDestructionWatcher* watcher_;
250 DISALLOW_COPY_AND_ASSIGN(DestructionMessageFilter);
253 void OnChannelDestroyed() {
254 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
256 EXPECT_FALSE(channel_destroyed_);
257 channel_destroyed_ = true;
258 run_loop_.Quit();
261 bool channel_destroyed_;
262 base::RunLoop run_loop_;
264 DISALLOW_COPY_AND_ASSIGN(ChannelDestructionWatcher);
267 // A navigation observer to wait on either a new load or a swap of a
268 // WebContents. On swap, if the new WebContents is still loading, wait for that
269 // load to complete as well. Note that the load must begin after the observer is
270 // attached.
271 class NavigationOrSwapObserver : public WebContentsObserver,
272 public TabStripModelObserver {
273 public:
274 // Waits for either a new load or a swap of |tab_strip_model|'s active
275 // WebContents.
276 NavigationOrSwapObserver(TabStripModel* tab_strip_model,
277 WebContents* web_contents)
278 : WebContentsObserver(web_contents),
279 tab_strip_model_(tab_strip_model),
280 did_start_loading_(false),
281 number_of_loads_(1) {
282 CHECK_NE(TabStripModel::kNoTab,
283 tab_strip_model->GetIndexOfWebContents(web_contents));
284 tab_strip_model_->AddObserver(this);
287 // Waits for either |number_of_loads| loads or a swap of |tab_strip_model|'s
288 // active WebContents.
289 NavigationOrSwapObserver(TabStripModel* tab_strip_model,
290 WebContents* web_contents,
291 int number_of_loads)
292 : WebContentsObserver(web_contents),
293 tab_strip_model_(tab_strip_model),
294 did_start_loading_(false),
295 number_of_loads_(number_of_loads) {
296 CHECK_NE(TabStripModel::kNoTab,
297 tab_strip_model->GetIndexOfWebContents(web_contents));
298 tab_strip_model_->AddObserver(this);
301 ~NavigationOrSwapObserver() override {
302 tab_strip_model_->RemoveObserver(this);
305 void set_did_start_loading() {
306 did_start_loading_ = true;
309 void Wait() {
310 loop_.Run();
313 // WebContentsObserver implementation:
314 void DidStartLoading(RenderViewHost* render_view_host) override {
315 did_start_loading_ = true;
317 void DidStopLoading(RenderViewHost* render_view_host) override {
318 if (!did_start_loading_)
319 return;
320 number_of_loads_--;
321 if (number_of_loads_ == 0)
322 loop_.Quit();
325 // TabStripModelObserver implementation:
326 void TabReplacedAt(TabStripModel* tab_strip_model,
327 WebContents* old_contents,
328 WebContents* new_contents,
329 int index) override {
330 if (old_contents != web_contents())
331 return;
332 // Switch to observing the new WebContents.
333 Observe(new_contents);
334 if (new_contents->IsLoading()) {
335 // If the new WebContents is still loading, wait for it to complete. Only
336 // one load post-swap is supported.
337 did_start_loading_ = true;
338 number_of_loads_ = 1;
339 } else {
340 loop_.Quit();
344 private:
345 TabStripModel* tab_strip_model_;
346 bool did_start_loading_;
347 int number_of_loads_;
348 base::RunLoop loop_;
351 // Waits for a new tab to open and a navigation or swap in it.
352 class NewTabNavigationOrSwapObserver {
353 public:
354 NewTabNavigationOrSwapObserver()
355 : new_tab_observer_(
356 chrome::NOTIFICATION_TAB_ADDED,
357 base::Bind(&NewTabNavigationOrSwapObserver::OnTabAdded,
358 base::Unretained(this))) {
359 // Watch for NOTIFICATION_TAB_ADDED. Add a callback so that the
360 // NavigationOrSwapObserver can be attached synchronously and no events are
361 // missed.
364 void Wait() {
365 new_tab_observer_.Wait();
366 swap_observer_->Wait();
369 bool OnTabAdded(const content::NotificationSource& source,
370 const content::NotificationDetails& details) {
371 if (swap_observer_)
372 return true;
373 WebContents* new_tab = content::Details<WebContents>(details).ptr();
374 // Get the TabStripModel. Assume this is attached to a Browser.
375 TabStripModel* tab_strip_model =
376 static_cast<Browser*>(new_tab->GetDelegate())->tab_strip_model();
377 swap_observer_.reset(new NavigationOrSwapObserver(tab_strip_model,
378 new_tab));
379 swap_observer_->set_did_start_loading();
380 return true;
383 private:
384 content::WindowedNotificationObserver new_tab_observer_;
385 scoped_ptr<NavigationOrSwapObserver> swap_observer_;
388 // PrerenderContents that stops the UI message loop on DidStopLoading().
389 class TestPrerenderContents : public PrerenderContents {
390 public:
391 TestPrerenderContents(
392 PrerenderManager* prerender_manager,
393 Profile* profile,
394 const GURL& url,
395 const content::Referrer& referrer,
396 Origin origin,
397 FinalStatus expected_final_status)
398 : PrerenderContents(prerender_manager, profile, url,
399 referrer, origin, PrerenderManager::kNoExperiment),
400 expected_final_status_(expected_final_status),
401 new_render_view_host_(NULL),
402 was_hidden_(false),
403 was_shown_(false),
404 should_be_shown_(expected_final_status == FINAL_STATUS_USED),
405 skip_final_checks_(false) {
408 ~TestPrerenderContents() override {
409 if (skip_final_checks_)
410 return;
412 if (expected_final_status_ == FINAL_STATUS_MAX) {
413 EXPECT_EQ(MATCH_COMPLETE_REPLACEMENT, match_complete_status());
414 } else {
415 EXPECT_EQ(expected_final_status_, final_status()) <<
416 " when testing URL " << prerender_url().path() <<
417 " (Expected: " << NameFromFinalStatus(expected_final_status_) <<
418 ", Actual: " << NameFromFinalStatus(final_status()) << ")";
420 // Prerendering RenderViewHosts should be hidden before the first
421 // navigation, so this should be happen for every PrerenderContents for
422 // which a RenderViewHost is created, regardless of whether or not it's
423 // used.
424 if (new_render_view_host_)
425 EXPECT_TRUE(was_hidden_);
427 // A used PrerenderContents will only be destroyed when we swap out
428 // WebContents, at the end of a navigation caused by a call to
429 // NavigateToURLImpl().
430 if (final_status() == FINAL_STATUS_USED)
431 EXPECT_TRUE(new_render_view_host_);
433 EXPECT_EQ(should_be_shown_, was_shown_);
436 void RenderProcessGone(base::TerminationStatus status) override {
437 // On quit, it's possible to end up here when render processes are closed
438 // before the PrerenderManager is destroyed. As a result, it's possible to
439 // get either FINAL_STATUS_APP_TERMINATING or FINAL_STATUS_RENDERER_CRASHED
440 // on quit.
442 // It's also possible for this to be called after we've been notified of
443 // app termination, but before we've been deleted, which is why the second
444 // check is needed.
445 if (expected_final_status_ == FINAL_STATUS_APP_TERMINATING &&
446 final_status() != expected_final_status_) {
447 expected_final_status_ = FINAL_STATUS_RENDERER_CRASHED;
450 PrerenderContents::RenderProcessGone(status);
453 bool CheckURL(const GURL& url) override {
454 // Prevent FINAL_STATUS_UNSUPPORTED_SCHEME when navigating to about:crash in
455 // the PrerenderRendererCrash test.
456 if (url.spec() != content::kChromeUICrashURL)
457 return PrerenderContents::CheckURL(url);
458 return true;
461 // For tests that open the prerender in a new background tab, the RenderView
462 // will not have been made visible when the PrerenderContents is destroyed
463 // even though it is used.
464 void set_should_be_shown(bool value) { should_be_shown_ = value; }
466 // For tests which do not know whether the prerender will be used.
467 void set_skip_final_checks(bool value) { skip_final_checks_ = value; }
469 FinalStatus expected_final_status() const { return expected_final_status_; }
471 private:
472 void OnRenderViewHostCreated(RenderViewHost* new_render_view_host) override {
473 // Used to make sure the RenderViewHost is hidden and, if used,
474 // subsequently shown.
475 notification_registrar().Add(
476 this,
477 content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
478 content::Source<RenderWidgetHost>(new_render_view_host));
480 new_render_view_host_ = new_render_view_host;
482 PrerenderContents::OnRenderViewHostCreated(new_render_view_host);
485 void Observe(int type,
486 const content::NotificationSource& source,
487 const content::NotificationDetails& details) override {
488 if (type ==
489 content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED) {
490 EXPECT_EQ(new_render_view_host_,
491 content::Source<RenderWidgetHost>(source).ptr());
492 bool is_visible = *content::Details<bool>(details).ptr();
494 if (!is_visible) {
495 was_hidden_ = true;
496 } else if (is_visible && was_hidden_) {
497 // Once hidden, a prerendered RenderViewHost should only be shown after
498 // being removed from the PrerenderContents for display.
499 EXPECT_FALSE(GetRenderViewHost());
500 was_shown_ = true;
502 return;
504 PrerenderContents::Observe(type, source, details);
507 FinalStatus expected_final_status_;
509 // The RenderViewHost created for the prerender, if any.
510 RenderViewHost* new_render_view_host_;
511 // Set to true when the prerendering RenderWidget is hidden.
512 bool was_hidden_;
513 // Set to true when the prerendering RenderWidget is shown, after having been
514 // hidden.
515 bool was_shown_;
516 // Expected final value of was_shown_. Defaults to true for
517 // FINAL_STATUS_USED, and false otherwise.
518 bool should_be_shown_;
519 // If true, |expected_final_status_| and other shutdown checks are skipped.
520 bool skip_final_checks_;
523 // A handle to a TestPrerenderContents whose lifetime is under the caller's
524 // control. A PrerenderContents may be destroyed at any point. This allows
525 // tracking the final status, etc.
526 class TestPrerender : public PrerenderContents::Observer,
527 public base::SupportsWeakPtr<TestPrerender> {
528 public:
529 TestPrerender()
530 : contents_(NULL),
531 number_of_loads_(0),
532 expected_number_of_loads_(0) {
534 ~TestPrerender() override {
535 if (contents_)
536 contents_->RemoveObserver(this);
539 TestPrerenderContents* contents() const { return contents_; }
540 int number_of_loads() const { return number_of_loads_; }
542 void WaitForCreate() { create_loop_.Run(); }
543 void WaitForStart() { start_loop_.Run(); }
544 void WaitForStop() { stop_loop_.Run(); }
546 // Waits for |number_of_loads()| to be at least |expected_number_of_loads| OR
547 // for the prerender to stop running (just to avoid a timeout if the prerender
548 // dies). Note: this does not assert equality on the number of loads; the
549 // caller must do it instead.
550 void WaitForLoads(int expected_number_of_loads) {
551 DCHECK(!load_waiter_);
552 DCHECK(!expected_number_of_loads_);
553 if (number_of_loads_ < expected_number_of_loads) {
554 load_waiter_.reset(new base::RunLoop);
555 expected_number_of_loads_ = expected_number_of_loads;
556 load_waiter_->Run();
557 load_waiter_.reset();
558 expected_number_of_loads_ = 0;
560 EXPECT_LE(expected_number_of_loads, number_of_loads_);
563 void OnPrerenderCreated(TestPrerenderContents* contents) {
564 DCHECK(!contents_);
565 contents_ = contents;
566 contents_->AddObserver(this);
567 create_loop_.Quit();
570 // PrerenderContents::Observer implementation:
571 void OnPrerenderStart(PrerenderContents* contents) override {
572 start_loop_.Quit();
575 void OnPrerenderStopLoading(PrerenderContents* contents) override {
576 number_of_loads_++;
577 if (load_waiter_ && number_of_loads_ >= expected_number_of_loads_)
578 load_waiter_->Quit();
581 void OnPrerenderStop(PrerenderContents* contents) override {
582 DCHECK(contents_);
583 contents_ = NULL;
584 stop_loop_.Quit();
585 // If there is a WaitForLoads call and it has yet to see the expected number
586 // of loads, stop the loop so the test fails instead of timing out.
587 if (load_waiter_)
588 load_waiter_->Quit();
591 void OnPrerenderCreatedMatchCompleteReplacement(
592 PrerenderContents* contents,
593 PrerenderContents* replacement) override {}
595 private:
596 TestPrerenderContents* contents_;
597 int number_of_loads_;
599 int expected_number_of_loads_;
600 scoped_ptr<base::RunLoop> load_waiter_;
602 base::RunLoop create_loop_;
603 base::RunLoop start_loop_;
604 base::RunLoop stop_loop_;
606 DISALLOW_COPY_AND_ASSIGN(TestPrerender);
609 // PrerenderManager that uses TestPrerenderContents.
610 class TestPrerenderContentsFactory : public PrerenderContents::Factory {
611 public:
612 TestPrerenderContentsFactory() {}
614 ~TestPrerenderContentsFactory() override {
615 EXPECT_TRUE(expected_contents_queue_.empty());
618 scoped_ptr<TestPrerender> ExpectPrerenderContents(FinalStatus final_status) {
619 scoped_ptr<TestPrerender> handle(new TestPrerender());
620 expected_contents_queue_.push_back(
621 ExpectedContents(final_status, handle->AsWeakPtr()));
622 return handle.Pass();
625 PrerenderContents* CreatePrerenderContents(
626 PrerenderManager* prerender_manager,
627 Profile* profile,
628 const GURL& url,
629 const content::Referrer& referrer,
630 Origin origin,
631 uint8 experiment_id) override {
632 ExpectedContents expected;
633 if (!expected_contents_queue_.empty()) {
634 expected = expected_contents_queue_.front();
635 expected_contents_queue_.pop_front();
637 VLOG(1) << "Creating prerender contents for " << url.path() <<
638 " with expected final status " << expected.final_status;
639 VLOG(1) << expected_contents_queue_.size() << " left in the queue.";
640 TestPrerenderContents* contents =
641 new TestPrerenderContents(prerender_manager,
642 profile, url, referrer, origin,
643 expected.final_status);
644 if (expected.handle)
645 expected.handle->OnPrerenderCreated(contents);
646 return contents;
649 private:
650 struct ExpectedContents {
651 ExpectedContents() : final_status(FINAL_STATUS_MAX) { }
652 ExpectedContents(FinalStatus final_status,
653 const base::WeakPtr<TestPrerender>& handle)
654 : final_status(final_status),
655 handle(handle) {
658 FinalStatus final_status;
659 base::WeakPtr<TestPrerender> handle;
662 std::deque<ExpectedContents> expected_contents_queue_;
665 #if defined(FULL_SAFE_BROWSING)
666 // A SafeBrowsingDatabaseManager implementation that returns a fixed result for
667 // a given URL.
668 class FakeSafeBrowsingDatabaseManager : public SafeBrowsingDatabaseManager {
669 public:
670 explicit FakeSafeBrowsingDatabaseManager(SafeBrowsingService* service)
671 : SafeBrowsingDatabaseManager(service),
672 threat_type_(SB_THREAT_TYPE_SAFE) { }
674 // Called on the IO thread to check if the given url is safe or not. If we
675 // can synchronously determine that the url is safe, CheckUrl returns true.
676 // Otherwise it returns false, and "client" is called asynchronously with the
677 // result when it is ready.
678 // Returns true, indicating a SAFE result, unless the URL is the fixed URL
679 // specified by the user, and the user-specified result is not SAFE
680 // (in which that result will be communicated back via a call into the
681 // client, and false will be returned).
682 // Overrides SafeBrowsingService::CheckBrowseUrl.
683 bool CheckBrowseUrl(const GURL& gurl, Client* client) override {
684 if (gurl != url_ || threat_type_ == SB_THREAT_TYPE_SAFE)
685 return true;
687 BrowserThread::PostTask(
688 BrowserThread::IO, FROM_HERE,
689 base::Bind(&FakeSafeBrowsingDatabaseManager::OnCheckBrowseURLDone,
690 this, gurl, client));
691 return false;
694 void SetThreatTypeForUrl(const GURL& url, SBThreatType threat_type) {
695 url_ = url;
696 threat_type_ = threat_type;
699 private:
700 ~FakeSafeBrowsingDatabaseManager() override {}
702 void OnCheckBrowseURLDone(const GURL& gurl, Client* client) {
703 std::vector<SBThreatType> expected_threats;
704 expected_threats.push_back(SB_THREAT_TYPE_URL_MALWARE);
705 expected_threats.push_back(SB_THREAT_TYPE_URL_PHISHING);
706 SafeBrowsingDatabaseManager::SafeBrowsingCheck sb_check(
707 std::vector<GURL>(1, gurl),
708 std::vector<SBFullHash>(),
709 client,
710 safe_browsing_util::MALWARE,
711 expected_threats);
712 sb_check.url_results[0] = threat_type_;
713 client->OnSafeBrowsingResult(sb_check);
716 GURL url_;
717 SBThreatType threat_type_;
718 DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingDatabaseManager);
721 class FakeSafeBrowsingService : public SafeBrowsingService {
722 public:
723 FakeSafeBrowsingService() { }
725 // Returned pointer has the same lifespan as the database_manager_ refcounted
726 // object.
727 FakeSafeBrowsingDatabaseManager* fake_database_manager() {
728 return fake_database_manager_;
731 protected:
732 ~FakeSafeBrowsingService() override {}
734 SafeBrowsingDatabaseManager* CreateDatabaseManager() override {
735 fake_database_manager_ = new FakeSafeBrowsingDatabaseManager(this);
736 return fake_database_manager_;
739 private:
740 FakeSafeBrowsingDatabaseManager* fake_database_manager_;
742 DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingService);
745 // Factory that creates FakeSafeBrowsingService instances.
746 class TestSafeBrowsingServiceFactory : public SafeBrowsingServiceFactory {
747 public:
748 TestSafeBrowsingServiceFactory() :
749 most_recent_service_(NULL) { }
750 ~TestSafeBrowsingServiceFactory() override {}
752 SafeBrowsingService* CreateSafeBrowsingService() override {
753 most_recent_service_ = new FakeSafeBrowsingService();
754 return most_recent_service_;
757 FakeSafeBrowsingService* most_recent_service() const {
758 return most_recent_service_;
761 private:
762 FakeSafeBrowsingService* most_recent_service_;
764 #endif
766 class FakeDevToolsClient : public content::DevToolsAgentHostClient {
767 public:
768 FakeDevToolsClient() {}
769 ~FakeDevToolsClient() override {}
770 void DispatchProtocolMessage(DevToolsAgentHost* agent_host,
771 const std::string& message) override {}
772 void AgentHostClosed(DevToolsAgentHost* agent_host, bool replaced) override {}
775 class RestorePrerenderMode {
776 public:
777 RestorePrerenderMode() : prev_mode_(PrerenderManager::GetMode()) {
780 ~RestorePrerenderMode() { PrerenderManager::SetMode(prev_mode_); }
781 private:
782 PrerenderManager::PrerenderManagerMode prev_mode_;
785 // URLRequestJob (and associated handler) which hangs.
786 class HangingURLRequestJob : public net::URLRequestJob {
787 public:
788 HangingURLRequestJob(net::URLRequest* request,
789 net::NetworkDelegate* network_delegate)
790 : net::URLRequestJob(request, network_delegate) {
793 void Start() override {}
795 private:
796 ~HangingURLRequestJob() override {}
799 class HangingFirstRequestInterceptor : public net::URLRequestInterceptor {
800 public:
801 HangingFirstRequestInterceptor(const base::FilePath& file,
802 base::Closure callback)
803 : file_(file),
804 callback_(callback),
805 first_run_(true) {
807 ~HangingFirstRequestInterceptor() override {}
809 net::URLRequestJob* MaybeInterceptRequest(
810 net::URLRequest* request,
811 net::NetworkDelegate* network_delegate) const override {
812 if (first_run_) {
813 first_run_ = false;
814 if (!callback_.is_null()) {
815 BrowserThread::PostTask(
816 BrowserThread::UI, FROM_HERE, callback_);
818 return new HangingURLRequestJob(request, network_delegate);
820 return new net::URLRequestMockHTTPJob(
821 request,
822 network_delegate,
823 file_,
824 BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
825 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN));
828 private:
829 base::FilePath file_;
830 base::Closure callback_;
831 mutable bool first_run_;
834 // Makes |url| never respond on the first load, and then with the contents of
835 // |file| afterwards. When the first load has been scheduled, runs |callback| on
836 // the UI thread.
837 void CreateHangingFirstRequestInterceptorOnIO(
838 const GURL& url, const base::FilePath& file, base::Closure callback) {
839 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
840 scoped_ptr<net::URLRequestInterceptor> never_respond_handler(
841 new HangingFirstRequestInterceptor(file, callback));
842 net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
843 url, never_respond_handler.Pass());
846 // Wrapper over URLRequestMockHTTPJob that exposes extra callbacks.
847 class MockHTTPJob : public net::URLRequestMockHTTPJob {
848 public:
849 MockHTTPJob(net::URLRequest* request,
850 net::NetworkDelegate* delegate,
851 const base::FilePath& file)
852 : net::URLRequestMockHTTPJob(
853 request,
854 delegate,
855 file,
856 BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
857 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)) {}
859 void set_start_callback(const base::Closure& start_callback) {
860 start_callback_ = start_callback;
863 void Start() override {
864 if (!start_callback_.is_null())
865 start_callback_.Run();
866 net::URLRequestMockHTTPJob::Start();
869 private:
870 ~MockHTTPJob() override {}
872 base::Closure start_callback_;
875 // Dummy counter class to live on the UI thread for counting requests.
876 class RequestCounter : public base::SupportsWeakPtr<RequestCounter> {
877 public:
878 RequestCounter() : count_(0), expected_count_(-1) {}
879 int count() const { return count_; }
881 void RequestStarted() {
882 count_++;
883 if (loop_ && count_ == expected_count_)
884 loop_->Quit();
887 void WaitForCount(int expected_count) {
888 ASSERT_TRUE(!loop_);
889 ASSERT_EQ(-1, expected_count_);
890 if (count_ < expected_count) {
891 expected_count_ = expected_count;
892 loop_.reset(new base::RunLoop);
893 loop_->Run();
894 expected_count_ = -1;
895 loop_.reset();
898 EXPECT_EQ(expected_count, count_);
900 private:
901 int count_;
902 int expected_count_;
903 scoped_ptr<base::RunLoop> loop_;
906 // Protocol handler which counts the number of requests that start.
907 class CountingInterceptor : public net::URLRequestInterceptor {
908 public:
909 CountingInterceptor(const base::FilePath& file,
910 const base::WeakPtr<RequestCounter>& counter)
911 : file_(file),
912 counter_(counter),
913 weak_factory_(this) {
915 ~CountingInterceptor() override {}
917 net::URLRequestJob* MaybeInterceptRequest(
918 net::URLRequest* request,
919 net::NetworkDelegate* network_delegate) const override {
920 MockHTTPJob* job = new MockHTTPJob(request, network_delegate, file_);
921 job->set_start_callback(base::Bind(&CountingInterceptor::RequestStarted,
922 weak_factory_.GetWeakPtr()));
923 return job;
926 void RequestStarted() {
927 BrowserThread::PostTask(
928 BrowserThread::UI, FROM_HERE,
929 base::Bind(&RequestCounter::RequestStarted, counter_));
932 private:
933 base::FilePath file_;
934 base::WeakPtr<RequestCounter> counter_;
935 mutable base::WeakPtrFactory<CountingInterceptor> weak_factory_;
938 // Makes |url| respond to requests with the contents of |file|, counting the
939 // number that start in |counter|.
940 void CreateCountingInterceptorOnIO(
941 const GURL& url,
942 const base::FilePath& file,
943 const base::WeakPtr<RequestCounter>& counter) {
944 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
945 scoped_ptr<net::URLRequestInterceptor> request_interceptor(
946 new CountingInterceptor(file, counter));
947 net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
948 url, request_interceptor.Pass());
951 // Makes |url| respond to requests with the contents of |file|.
952 void CreateMockInterceptorOnIO(const GURL& url, const base::FilePath& file) {
953 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
954 net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
955 url,
956 net::URLRequestMockHTTPJob::CreateInterceptorForSingleFile(
957 file, BrowserThread::GetBlockingPool()));
960 // A ContentBrowserClient that cancels all prerenderers on OpenURL.
961 class TestContentBrowserClient : public chrome::ChromeContentBrowserClient {
962 public:
963 TestContentBrowserClient() {}
964 ~TestContentBrowserClient() override {}
966 // chrome::ChromeContentBrowserClient implementation.
967 bool ShouldAllowOpenURL(content::SiteInstance* site_instance,
968 const GURL& url) override {
969 PrerenderManagerFactory::GetForProfile(
970 Profile::FromBrowserContext(site_instance->GetBrowserContext()))
971 ->CancelAllPrerenders();
972 return chrome::ChromeContentBrowserClient::ShouldAllowOpenURL(site_instance,
973 url);
976 private:
977 DISALLOW_COPY_AND_ASSIGN(TestContentBrowserClient);
980 // A ContentBrowserClient that forces cross-process navigations.
981 class SwapProcessesContentBrowserClient
982 : public chrome::ChromeContentBrowserClient {
983 public:
984 SwapProcessesContentBrowserClient() {}
985 ~SwapProcessesContentBrowserClient() override {}
987 // chrome::ChromeContentBrowserClient implementation.
988 bool ShouldSwapProcessesForRedirect(
989 content::ResourceContext* resource_context,
990 const GURL& current_url,
991 const GURL& new_url) override {
992 return true;
995 private:
996 DISALLOW_COPY_AND_ASSIGN(SwapProcessesContentBrowserClient);
999 // An ExternalProtocolHandler that blocks everything and asserts it never is
1000 // called.
1001 class NeverRunsExternalProtocolHandlerDelegate
1002 : public ExternalProtocolHandler::Delegate {
1003 public:
1004 // ExternalProtocolHandler::Delegate implementation.
1005 ShellIntegration::DefaultProtocolClientWorker* CreateShellWorker(
1006 ShellIntegration::DefaultWebClientObserver* observer,
1007 const std::string& protocol) override {
1008 NOTREACHED();
1009 // This will crash, but it shouldn't get this far with BlockState::BLOCK
1010 // anyway.
1011 return NULL;
1013 ExternalProtocolHandler::BlockState GetBlockState(
1014 const std::string& scheme) override {
1015 // Block everything and fail the test.
1016 ADD_FAILURE();
1017 return ExternalProtocolHandler::BLOCK;
1019 void BlockRequest() override {}
1020 void RunExternalProtocolDialog(const GURL& url,
1021 int render_process_host_id,
1022 int routing_id) override {
1023 NOTREACHED();
1025 void LaunchUrlWithoutSecurityCheck(const GURL& url) override { NOTREACHED(); }
1026 void FinishedProcessingCheck() override { NOTREACHED(); }
1029 base::FilePath GetTestPath(const std::string& file_name) {
1030 return ui_test_utils::GetTestFilePath(
1031 base::FilePath(FILE_PATH_LITERAL("prerender")),
1032 base::FilePath().AppendASCII(file_name));
1035 } // namespace
1037 // Many of these tests are flaky. See http://crbug.com/249179
1038 class PrerenderBrowserTest : virtual public InProcessBrowserTest {
1039 public:
1040 PrerenderBrowserTest()
1041 : autostart_test_server_(true),
1042 prerender_contents_factory_(NULL),
1043 #if defined(FULL_SAFE_BROWSING)
1044 safe_browsing_factory_(new TestSafeBrowsingServiceFactory()),
1045 #endif
1046 call_javascript_(true),
1047 check_load_events_(true),
1048 loader_path_("files/prerender/prerender_loader.html"),
1049 explicitly_set_browser_(NULL) {}
1051 ~PrerenderBrowserTest() override {}
1053 content::SessionStorageNamespace* GetSessionStorageNamespace() const {
1054 WebContents* web_contents = GetActiveWebContents();
1055 if (!web_contents)
1056 return NULL;
1057 return web_contents->GetController().GetDefaultSessionStorageNamespace();
1060 void SetUpInProcessBrowserTestFixture() override {
1061 #if defined(FULL_SAFE_BROWSING)
1062 SafeBrowsingService::RegisterFactory(safe_browsing_factory_.get());
1063 #endif
1066 void TearDownInProcessBrowserTestFixture() override {
1067 #if defined(FULL_SAFE_BROWSING)
1068 SafeBrowsingService::RegisterFactory(NULL);
1069 #endif
1072 void SetUpCommandLine(base::CommandLine* command_line) override {
1073 command_line->AppendSwitchASCII(switches::kPrerenderMode,
1074 switches::kPrerenderModeSwitchValueEnabled);
1075 #if defined(OS_MACOSX)
1076 // The plugins directory isn't read by default on the Mac, so it needs to be
1077 // explicitly registered.
1078 base::FilePath app_dir;
1079 PathService::Get(chrome::DIR_APP, &app_dir);
1080 command_line->AppendSwitchPath(
1081 switches::kExtraPluginDir,
1082 app_dir.Append(FILE_PATH_LITERAL("plugins")));
1083 #endif
1084 command_line->AppendSwitch(switches::kAlwaysAuthorizePlugins);
1085 command_line->AppendSwitch(switches::kEnableNpapi);
1088 void SetPreference(NetworkPredictionOptions value) {
1089 browser()->profile()->GetPrefs()->SetInteger(
1090 prefs::kNetworkPredictionOptions, value);
1093 void CreateTestFieldTrial(const std::string& name,
1094 const std::string& group_name) {
1095 base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial(
1096 name, group_name);
1097 trial->group();
1100 // Verifies, for the current field trial, whether
1101 // ShouldDisableLocalPredictorDueToPreferencesAndNetwork produces the desired
1102 // output.
1103 void TestShouldDisableLocalPredictorPreferenceNetworkMatrix(
1104 bool preference_wifi_network_wifi,
1105 bool preference_wifi_network_4g,
1106 bool preference_always_network_wifi,
1107 bool preference_always_network_4g,
1108 bool preference_never_network_wifi,
1109 bool preference_never_network_4g) {
1110 Profile* profile = browser()->profile();
1112 // Set real NetworkChangeNotifier singleton aside.
1113 scoped_ptr<NetworkChangeNotifier::DisableForTest> disable_for_test(
1114 new NetworkChangeNotifier::DisableForTest);
1116 // Set preference to WIFI_ONLY: prefetch when not on cellular.
1117 SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_WIFI_ONLY);
1119 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI);
1120 EXPECT_EQ(
1121 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1122 preference_wifi_network_wifi);
1125 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G);
1126 EXPECT_EQ(
1127 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1128 preference_wifi_network_4g);
1131 // Set preference to ALWAYS: always prefetch.
1132 SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_ALWAYS);
1134 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI);
1135 EXPECT_EQ(
1136 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1137 preference_always_network_wifi);
1140 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G);
1141 EXPECT_EQ(
1142 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1143 preference_always_network_4g);
1146 // Set preference to NEVER: never prefetch.
1147 SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_NEVER);
1149 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifierWIFI);
1150 EXPECT_EQ(
1151 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1152 preference_never_network_wifi);
1155 scoped_ptr<NetworkChangeNotifier> mock(new MockNetworkChangeNotifier4G);
1156 EXPECT_EQ(
1157 ShouldDisableLocalPredictorDueToPreferencesAndNetwork(profile),
1158 preference_never_network_4g);
1162 void SetUpOnMainThread() override {
1163 current_browser()->profile()->GetPrefs()->SetBoolean(
1164 prefs::kPromptForDownload, false);
1165 IncreasePrerenderMemory();
1166 if (autostart_test_server_)
1167 ASSERT_TRUE(test_server()->Start());
1168 ChromeResourceDispatcherHostDelegate::
1169 SetExternalProtocolHandlerDelegateForTesting(
1170 &external_protocol_handler_delegate_);
1172 PrerenderManager* prerender_manager = GetPrerenderManager();
1173 ASSERT_TRUE(prerender_manager);
1174 prerender_manager->mutable_config().rate_limit_enabled = false;
1175 ASSERT_TRUE(prerender_contents_factory_ == NULL);
1176 prerender_contents_factory_ = new TestPrerenderContentsFactory;
1177 prerender_manager->SetPrerenderContentsFactory(prerender_contents_factory_);
1180 // Convenience function to get the currently active WebContents in
1181 // current_browser().
1182 WebContents* GetActiveWebContents() const {
1183 return current_browser()->tab_strip_model()->GetActiveWebContents();
1186 // Overload for a single expected final status
1187 scoped_ptr<TestPrerender> PrerenderTestURL(
1188 const std::string& html_file,
1189 FinalStatus expected_final_status,
1190 int expected_number_of_loads) {
1191 GURL url = test_server()->GetURL(html_file);
1192 return PrerenderTestURL(url,
1193 expected_final_status,
1194 expected_number_of_loads);
1197 ScopedVector<TestPrerender> PrerenderTestURL(
1198 const std::string& html_file,
1199 const std::vector<FinalStatus>& expected_final_status_queue,
1200 int expected_number_of_loads) {
1201 GURL url = test_server()->GetURL(html_file);
1202 return PrerenderTestURLImpl(url,
1203 expected_final_status_queue,
1204 expected_number_of_loads);
1207 scoped_ptr<TestPrerender> PrerenderTestURL(
1208 const GURL& url,
1209 FinalStatus expected_final_status,
1210 int expected_number_of_loads) {
1211 std::vector<FinalStatus> expected_final_status_queue(
1212 1, expected_final_status);
1213 std::vector<TestPrerender*> prerenders;
1214 PrerenderTestURLImpl(url,
1215 expected_final_status_queue,
1216 expected_number_of_loads).release(&prerenders);
1217 CHECK_EQ(1u, prerenders.size());
1218 return scoped_ptr<TestPrerender>(prerenders[0]);
1221 void NavigateToDestURL() const {
1222 NavigateToDestURLWithDisposition(CURRENT_TAB, true);
1225 // Opens the url in a new tab, with no opener.
1226 void NavigateToDestURLWithDisposition(
1227 WindowOpenDisposition disposition,
1228 bool expect_swap_to_succeed) const {
1229 NavigateToURLWithParams(
1230 content::OpenURLParams(dest_url_, Referrer(), disposition,
1231 ui::PAGE_TRANSITION_TYPED, false),
1232 expect_swap_to_succeed);
1235 void NavigateToURL(const std::string& dest_html_file) const {
1236 NavigateToURLWithDisposition(dest_html_file, CURRENT_TAB, true);
1239 void NavigateToURLWithDisposition(const std::string& dest_html_file,
1240 WindowOpenDisposition disposition,
1241 bool expect_swap_to_succeed) const {
1242 GURL dest_url = test_server()->GetURL(dest_html_file);
1243 NavigateToURLWithDisposition(dest_url, disposition, expect_swap_to_succeed);
1246 void NavigateToURLWithDisposition(const GURL& dest_url,
1247 WindowOpenDisposition disposition,
1248 bool expect_swap_to_succeed) const {
1249 NavigateToURLWithParams(
1250 content::OpenURLParams(dest_url, Referrer(), disposition,
1251 ui::PAGE_TRANSITION_TYPED, false),
1252 expect_swap_to_succeed);
1255 void NavigateToURLWithParams(const content::OpenURLParams& params,
1256 bool expect_swap_to_succeed) const {
1257 NavigateToURLImpl(params, expect_swap_to_succeed);
1260 void OpenDestURLViaClick() const {
1261 OpenURLViaClick(dest_url_);
1264 void OpenURLViaClick(const GURL& url) const {
1265 OpenURLWithJSImpl("Click", url, GURL(), false);
1268 void OpenDestURLViaClickTarget() const {
1269 OpenURLWithJSImpl("ClickTarget", dest_url_, GURL(), true);
1272 void OpenDestURLViaClickPing(const GURL& ping_url) const {
1273 OpenURLWithJSImpl("ClickPing", dest_url_, ping_url, false);
1276 void OpenDestURLViaClickNewWindow() const {
1277 OpenURLWithJSImpl("ShiftClick", dest_url_, GURL(), true);
1280 void OpenDestURLViaClickNewForegroundTab() const {
1281 #if defined(OS_MACOSX)
1282 OpenURLWithJSImpl("MetaShiftClick", dest_url_, GURL(), true);
1283 #else
1284 OpenURLWithJSImpl("CtrlShiftClick", dest_url_, GURL(), true);
1285 #endif
1288 void OpenDestURLViaWindowOpen() const {
1289 OpenURLViaWindowOpen(dest_url_);
1292 void OpenURLViaWindowOpen(const GURL& url) const {
1293 OpenURLWithJSImpl("WindowOpen", url, GURL(), true);
1296 void RemoveLinkElement(int i) const {
1297 GetActiveWebContents()->GetMainFrame()->ExecuteJavaScript(
1298 base::ASCIIToUTF16(base::StringPrintf("RemoveLinkElement(%d)", i)));
1301 void ClickToNextPageAfterPrerender() {
1302 TestNavigationObserver nav_observer(GetActiveWebContents());
1303 RenderFrameHost* render_frame_host = GetActiveWebContents()->GetMainFrame();
1304 render_frame_host->ExecuteJavaScript(base::ASCIIToUTF16("ClickOpenLink()"));
1305 nav_observer.Wait();
1308 void NavigateToNextPageAfterPrerender() const {
1309 ui_test_utils::NavigateToURL(
1310 current_browser(),
1311 test_server()->GetURL("files/prerender/prerender_page.html"));
1314 // Called after the prerendered page has been navigated to and then away from.
1315 // Navigates back through the history to the prerendered page.
1316 void GoBackToPrerender() {
1317 TestNavigationObserver back_nav_observer(GetActiveWebContents());
1318 chrome::GoBack(current_browser(), CURRENT_TAB);
1319 back_nav_observer.Wait();
1320 bool original_prerender_page = false;
1321 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1322 GetActiveWebContents(),
1323 "window.domAutomationController.send(IsOriginalPrerenderPage())",
1324 &original_prerender_page));
1325 EXPECT_TRUE(original_prerender_page);
1328 // Goes back to the page that was active before the prerender was swapped
1329 // in. This must be called when the prerendered page is the current page
1330 // in the active tab.
1331 void GoBackToPageBeforePrerender() {
1332 WebContents* tab = GetActiveWebContents();
1333 ASSERT_TRUE(tab);
1334 EXPECT_FALSE(tab->IsLoading());
1335 TestNavigationObserver back_nav_observer(tab);
1336 chrome::GoBack(current_browser(), CURRENT_TAB);
1337 back_nav_observer.Wait();
1338 bool js_result;
1339 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1340 tab,
1341 "window.domAutomationController.send(DidBackToOriginalPagePass())",
1342 &js_result));
1343 EXPECT_TRUE(js_result);
1346 bool UrlIsInPrerenderManager(const std::string& html_file) const {
1347 return UrlIsInPrerenderManager(test_server()->GetURL(html_file));
1350 bool UrlIsInPrerenderManager(const GURL& url) const {
1351 return GetPrerenderManager()->FindPrerenderData(
1352 url, GetSessionStorageNamespace()) != NULL;
1355 void UseHttpsSrcServer() {
1356 if (https_src_server_)
1357 return;
1358 https_src_server_.reset(
1359 new net::SpawnedTestServer(
1360 net::SpawnedTestServer::TYPE_HTTPS,
1361 net::SpawnedTestServer::kLocalhost,
1362 base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))));
1363 CHECK(https_src_server_->Start());
1366 void DisableJavascriptCalls() {
1367 call_javascript_ = false;
1370 void DisableLoadEventCheck() {
1371 check_load_events_ = false;
1374 TaskManagerModel* GetModel() const {
1375 return TaskManager::GetInstance()->model();
1378 PrerenderManager* GetPrerenderManager() const {
1379 PrerenderManager* prerender_manager =
1380 PrerenderManagerFactory::GetForProfile(current_browser()->profile());
1381 return prerender_manager;
1384 const PrerenderLinkManager* GetPrerenderLinkManager() const {
1385 PrerenderLinkManager* prerender_link_manager =
1386 PrerenderLinkManagerFactory::GetForProfile(
1387 current_browser()->profile());
1388 return prerender_link_manager;
1391 int GetPrerenderEventCount(int index, const std::string& type) const {
1392 int event_count;
1393 std::string expression = base::StringPrintf(
1394 "window.domAutomationController.send("
1395 " GetPrerenderEventCount(%d, '%s'))", index, type.c_str());
1397 CHECK(content::ExecuteScriptAndExtractInt(
1398 GetActiveWebContents(), expression, &event_count));
1399 return event_count;
1402 bool DidReceivePrerenderStartEventForLinkNumber(int index) const {
1403 return GetPrerenderEventCount(index, "webkitprerenderstart") > 0;
1406 int GetPrerenderLoadEventCountForLinkNumber(int index) const {
1407 return GetPrerenderEventCount(index, "webkitprerenderload");
1410 int GetPrerenderDomContentLoadedEventCountForLinkNumber(int index) const {
1411 return GetPrerenderEventCount(index, "webkitprerenderdomcontentloaded");
1414 bool DidReceivePrerenderStopEventForLinkNumber(int index) const {
1415 return GetPrerenderEventCount(index, "webkitprerenderstop") > 0;
1418 void WaitForPrerenderEventCount(int index,
1419 const std::string& type,
1420 int count) const {
1421 int dummy;
1422 std::string expression = base::StringPrintf(
1423 "WaitForPrerenderEventCount(%d, '%s', %d,"
1424 " window.domAutomationController.send.bind("
1425 " window.domAutomationController, 0))",
1426 index, type.c_str(), count);
1428 CHECK(content::ExecuteScriptAndExtractInt(
1429 GetActiveWebContents(), expression, &dummy));
1430 CHECK_EQ(0, dummy);
1433 bool HadPrerenderEventErrors() const {
1434 bool had_prerender_event_errors;
1435 CHECK(content::ExecuteScriptAndExtractBool(
1436 GetActiveWebContents(),
1437 "window.domAutomationController.send(Boolean("
1438 " hadPrerenderEventErrors))",
1439 &had_prerender_event_errors));
1440 return had_prerender_event_errors;
1443 // Asserting on this can result in flaky tests. PrerenderHandles are
1444 // removed from the PrerenderLinkManager when the prerender is canceled from
1445 // the browser, when the prerenders are cancelled from the renderer process,
1446 // or the channel for the renderer process is closed on the IO thread. In the
1447 // last case, the code must be careful to wait for the channel to close, as it
1448 // is done asynchronously after swapping out the old process. See
1449 // ChannelDestructionWatcher.
1450 bool IsEmptyPrerenderLinkManager() const {
1451 return GetPrerenderLinkManager()->IsEmpty();
1454 size_t GetLinkPrerenderCount() const {
1455 return GetPrerenderLinkManager()->prerenders_.size();
1458 size_t GetRunningLinkPrerenderCount() const {
1459 return GetPrerenderLinkManager()->CountRunningPrerenders();
1462 // Returns length of |prerender_manager_|'s history, or -1 on failure.
1463 int GetHistoryLength() const {
1464 scoped_ptr<base::DictionaryValue> prerender_dict(
1465 static_cast<base::DictionaryValue*>(
1466 GetPrerenderManager()->GetAsValue()));
1467 if (!prerender_dict.get())
1468 return -1;
1469 base::ListValue* history_list;
1470 if (!prerender_dict->GetList("history", &history_list))
1471 return -1;
1472 return static_cast<int>(history_list->GetSize());
1475 #if defined(FULL_SAFE_BROWSING)
1476 FakeSafeBrowsingDatabaseManager* GetFakeSafeBrowsingDatabaseManager() {
1477 return safe_browsing_factory_->most_recent_service()->
1478 fake_database_manager();
1480 #endif
1482 TestPrerenderContents* GetPrerenderContentsFor(const GURL& url) const {
1483 PrerenderManager::PrerenderData* prerender_data =
1484 GetPrerenderManager()->FindPrerenderData(url, NULL);
1485 return static_cast<TestPrerenderContents*>(
1486 prerender_data ? prerender_data->contents() : NULL);
1489 void SetLoaderHostOverride(const std::string& host) {
1490 loader_host_override_ = host;
1491 host_resolver()->AddRule(host, "127.0.0.1");
1494 void set_loader_path(const std::string& path) {
1495 loader_path_ = path;
1498 void set_loader_query(const std::string& query) {
1499 loader_query_ = query;
1502 GURL GetCrossDomainTestUrl(const std::string& path) {
1503 static const std::string secondary_domain = "www.foo.com";
1504 host_resolver()->AddRule(secondary_domain, "127.0.0.1");
1505 std::string url_str(base::StringPrintf(
1506 "http://%s:%d/%s",
1507 secondary_domain.c_str(),
1508 test_server()->host_port_pair().port(),
1509 path.c_str()));
1510 return GURL(url_str);
1513 void set_browser(Browser* browser) {
1514 explicitly_set_browser_ = browser;
1517 Browser* current_browser() const {
1518 return explicitly_set_browser_ ? explicitly_set_browser_ : browser();
1521 const GURL& dest_url() const {
1522 return dest_url_;
1525 void IncreasePrerenderMemory() {
1526 // Increase the memory allowed in a prerendered page above normal settings.
1527 // Debug build bots occasionally run against the default limit, and tests
1528 // were failing because the prerender was canceled due to memory exhaustion.
1529 // http://crbug.com/93076
1530 GetPrerenderManager()->mutable_config().max_bytes = 1000 * 1024 * 1024;
1533 bool DidPrerenderPass(WebContents* web_contents) const {
1534 bool prerender_test_result = false;
1535 if (!content::ExecuteScriptAndExtractBool(
1536 web_contents,
1537 "window.domAutomationController.send(DidPrerenderPass())",
1538 &prerender_test_result))
1539 return false;
1540 return prerender_test_result;
1543 bool DidDisplayPass(WebContents* web_contents) const {
1544 bool display_test_result = false;
1545 if (!content::ExecuteScriptAndExtractBool(
1546 web_contents,
1547 "window.domAutomationController.send(DidDisplayPass())",
1548 &display_test_result))
1549 return false;
1550 return display_test_result;
1553 scoped_ptr<TestPrerender> ExpectPrerender(FinalStatus expected_final_status) {
1554 return prerender_contents_factory_->ExpectPrerenderContents(
1555 expected_final_status);
1558 void AddPrerender(const GURL& url, int index) {
1559 std::string javascript = base::StringPrintf(
1560 "AddPrerender('%s', %d)", url.spec().c_str(), index);
1561 RenderFrameHost* render_frame_host = GetActiveWebContents()->GetMainFrame();
1562 render_frame_host->ExecuteJavaScript(base::ASCIIToUTF16(javascript));
1565 // Returns a string for pattern-matching TaskManager tab entries.
1566 base::string16 MatchTaskManagerTab(const char* page_title) {
1567 return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_TAB_PREFIX,
1568 base::ASCIIToUTF16(page_title));
1571 // Returns a string for pattern-matching TaskManager prerender entries.
1572 base::string16 MatchTaskManagerPrerender(const char* page_title) {
1573 return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PRERENDER_PREFIX,
1574 base::ASCIIToUTF16(page_title));
1577 const base::HistogramTester& histogram_tester() { return histogram_tester_; }
1579 protected:
1580 bool autostart_test_server_;
1582 private:
1583 // TODO(davidben): Remove this altogether so the tests don't globally assume
1584 // only one prerender.
1585 TestPrerenderContents* GetPrerenderContents() const {
1586 return GetPrerenderContentsFor(dest_url_);
1589 ScopedVector<TestPrerender> PrerenderTestURLImpl(
1590 const GURL& prerender_url,
1591 const std::vector<FinalStatus>& expected_final_status_queue,
1592 int expected_number_of_loads) {
1593 dest_url_ = prerender_url;
1595 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
1596 replacement_text.push_back(
1597 make_pair("REPLACE_WITH_PRERENDER_URL", prerender_url.spec()));
1598 std::string replacement_path;
1599 CHECK(net::SpawnedTestServer::GetFilePathWithReplacements(
1600 loader_path_,
1601 replacement_text,
1602 &replacement_path));
1604 const net::SpawnedTestServer* src_server = test_server();
1605 if (https_src_server_)
1606 src_server = https_src_server_.get();
1607 GURL loader_url = src_server->GetURL(
1608 replacement_path + "&" + loader_query_);
1610 GURL::Replacements loader_replacements;
1611 if (!loader_host_override_.empty())
1612 loader_replacements.SetHostStr(loader_host_override_);
1613 loader_url = loader_url.ReplaceComponents(loader_replacements);
1615 VLOG(1) << "Running test with queue length " <<
1616 expected_final_status_queue.size();
1617 CHECK(!expected_final_status_queue.empty());
1618 ScopedVector<TestPrerender> prerenders;
1619 for (size_t i = 0; i < expected_final_status_queue.size(); i++) {
1620 prerenders.push_back(
1621 prerender_contents_factory_->ExpectPrerenderContents(
1622 expected_final_status_queue[i]).release());
1625 FinalStatus expected_final_status = expected_final_status_queue.front();
1627 // Navigate to the loader URL and then wait for the first prerender to be
1628 // created.
1629 ui_test_utils::NavigateToURL(current_browser(), loader_url);
1630 prerenders[0]->WaitForCreate();
1631 prerenders[0]->WaitForLoads(expected_number_of_loads);
1633 if (ShouldAbortPrerenderBeforeSwap(expected_final_status)) {
1634 // The prerender will abort on its own. Assert it does so correctly.
1635 prerenders[0]->WaitForStop();
1636 EXPECT_FALSE(prerenders[0]->contents());
1637 EXPECT_TRUE(DidReceivePrerenderStopEventForLinkNumber(0));
1638 } else {
1639 // Otherwise, check that it prerendered correctly.
1640 TestPrerenderContents* prerender_contents = prerenders[0]->contents();
1642 CHECK_NE(static_cast<PrerenderContents*>(NULL), prerender_contents);
1643 EXPECT_EQ(FINAL_STATUS_MAX, prerender_contents->final_status());
1644 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1646 if (call_javascript_) {
1647 // Check if page behaves as expected while in prerendered state.
1648 EXPECT_TRUE(DidPrerenderPass(prerender_contents->prerender_contents()));
1652 // Test that the referring page received the right start and load events.
1653 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1654 if (check_load_events_) {
1655 EXPECT_EQ(expected_number_of_loads, prerenders[0]->number_of_loads());
1656 EXPECT_EQ(expected_number_of_loads,
1657 GetPrerenderLoadEventCountForLinkNumber(0));
1659 EXPECT_FALSE(HadPrerenderEventErrors());
1661 return prerenders.Pass();
1664 void NavigateToURLImpl(const content::OpenURLParams& params,
1665 bool expect_swap_to_succeed) const {
1666 ASSERT_NE(static_cast<PrerenderManager*>(NULL), GetPrerenderManager());
1667 // Make sure in navigating we have a URL to use in the PrerenderManager.
1668 ASSERT_NE(static_cast<PrerenderContents*>(NULL), GetPrerenderContents());
1670 WebContents* web_contents = GetPrerenderContents()->prerender_contents();
1672 // Navigate and wait for either the load to finish normally or for a swap to
1673 // occur.
1674 // TODO(davidben): The only handles CURRENT_TAB navigations, which is the
1675 // only case tested or prerendered right now.
1676 CHECK_EQ(CURRENT_TAB, params.disposition);
1677 NavigationOrSwapObserver swap_observer(current_browser()->tab_strip_model(),
1678 GetActiveWebContents());
1679 WebContents* target_web_contents = current_browser()->OpenURL(params);
1680 swap_observer.Wait();
1682 if (web_contents && expect_swap_to_succeed) {
1683 EXPECT_EQ(web_contents, target_web_contents);
1684 if (call_javascript_)
1685 EXPECT_TRUE(DidDisplayPass(web_contents));
1689 // Opens the prerendered page using javascript functions in the loader
1690 // page. |javascript_function_name| should be a 0 argument function which is
1691 // invoked. |new_web_contents| is true if the navigation is expected to
1692 // happen in a new WebContents via OpenURL.
1693 void OpenURLWithJSImpl(const std::string& javascript_function_name,
1694 const GURL& url,
1695 const GURL& ping_url,
1696 bool new_web_contents) const {
1697 WebContents* web_contents = GetActiveWebContents();
1698 RenderFrameHost* render_frame_host = web_contents->GetMainFrame();
1699 // Extra arguments in JS are ignored.
1700 std::string javascript = base::StringPrintf(
1701 "%s('%s', '%s')", javascript_function_name.c_str(),
1702 url.spec().c_str(), ping_url.spec().c_str());
1704 if (new_web_contents) {
1705 NewTabNavigationOrSwapObserver observer;
1706 render_frame_host->
1707 ExecuteJavaScriptForTests(base::ASCIIToUTF16(javascript));
1708 observer.Wait();
1709 } else {
1710 NavigationOrSwapObserver observer(current_browser()->tab_strip_model(),
1711 web_contents);
1712 render_frame_host->ExecuteJavaScript(base::ASCIIToUTF16(javascript));
1713 observer.Wait();
1717 TestPrerenderContentsFactory* prerender_contents_factory_;
1718 #if defined(FULL_SAFE_BROWSING)
1719 scoped_ptr<TestSafeBrowsingServiceFactory> safe_browsing_factory_;
1720 #endif
1721 NeverRunsExternalProtocolHandlerDelegate external_protocol_handler_delegate_;
1722 GURL dest_url_;
1723 scoped_ptr<net::SpawnedTestServer> https_src_server_;
1724 bool call_javascript_;
1725 bool check_load_events_;
1726 std::string loader_host_override_;
1727 std::string loader_path_;
1728 std::string loader_query_;
1729 Browser* explicitly_set_browser_;
1730 base::HistogramTester histogram_tester_;
1731 scoped_ptr<base::FieldTrialList> field_trial_list_;
1734 // Checks that a page is correctly prerendered in the case of a
1735 // <link rel=prerender> tag and then loaded into a tab in response to a
1736 // navigation.
1737 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPage) {
1738 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
1739 EXPECT_EQ(1, GetPrerenderDomContentLoadedEventCountForLinkNumber(0));
1740 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
1741 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
1742 histogram_tester().ExpectTotalCount(
1743 "Prerender.none_PerceivedPLTMatchedComplete", 0);
1744 histogram_tester().ExpectTotalCount(
1745 "Prerender.websame_PrerenderNotSwappedInPLT", 1);
1747 ChannelDestructionWatcher channel_close_watcher;
1748 channel_close_watcher.WatchChannel(
1749 GetActiveWebContents()->GetRenderProcessHost());
1750 NavigateToDestURL();
1751 channel_close_watcher.WaitForChannelClose();
1753 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLT", 1);
1754 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLTMatched",
1756 histogram_tester().ExpectTotalCount(
1757 "Prerender.websame_PerceivedPLTMatchedComplete", 1);
1759 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
1762 // Checks that cross-domain prerenders emit the correct histograms.
1763 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPageCrossDomain) {
1764 PrerenderTestURL(GetCrossDomainTestUrl("files/prerender/prerender_page.html"),
1765 FINAL_STATUS_USED, 1);
1766 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
1767 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
1768 histogram_tester().ExpectTotalCount(
1769 "Prerender.none_PerceivedPLTMatchedComplete", 0);
1770 histogram_tester().ExpectTotalCount(
1771 "Prerender.webcross_PrerenderNotSwappedInPLT", 1);
1773 NavigateToDestURL();
1774 histogram_tester().ExpectTotalCount("Prerender.webcross_PerceivedPLT", 1);
1775 histogram_tester().ExpectTotalCount("Prerender.webcross_PerceivedPLTMatched",
1777 histogram_tester().ExpectTotalCount(
1778 "Prerender.webcross_PerceivedPLTMatchedComplete", 1);
1781 // Checks that pending prerenders launch and receive proper event treatment.
1782 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPagePending) {
1783 scoped_ptr<TestPrerender> prerender =
1784 PrerenderTestURL("files/prerender/prerender_page_pending.html",
1785 FINAL_STATUS_USED, 1);
1787 // Navigate to the prerender.
1788 scoped_ptr<TestPrerender> prerender2 = ExpectPrerender(FINAL_STATUS_USED);
1789 NavigateToDestURL();
1790 // Abort early if the original prerender didn't swap, so as not to hang.
1791 ASSERT_FALSE(prerender->contents());
1793 // Wait for the new prerender to be ready.
1794 prerender2->WaitForStart();
1795 prerender2->WaitForLoads(1);
1797 const GURL prerender_page_url =
1798 test_server()->GetURL("files/prerender/prerender_page.html");
1799 EXPECT_FALSE(IsEmptyPrerenderLinkManager());
1800 EXPECT_NE(static_cast<TestPrerenderContents*>(NULL),
1801 GetPrerenderContentsFor(prerender_page_url));
1803 // Now navigate to our target page.
1804 NavigationOrSwapObserver swap_observer(current_browser()->tab_strip_model(),
1805 GetActiveWebContents());
1806 ui_test_utils::NavigateToURLWithDisposition(
1807 current_browser(), prerender_page_url, CURRENT_TAB,
1808 ui_test_utils::BROWSER_TEST_NONE);
1809 swap_observer.Wait();
1811 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
1814 // Checks that pending prerenders which are canceled before they are launched
1815 // never get started.
1816 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPageRemovesPending) {
1817 PrerenderTestURL("files/prerender/prerender_page_removes_pending.html",
1818 FINAL_STATUS_USED, 1);
1820 ChannelDestructionWatcher channel_close_watcher;
1821 channel_close_watcher.WatchChannel(
1822 GetActiveWebContents()->GetRenderProcessHost());
1823 NavigateToDestURL();
1824 channel_close_watcher.WaitForChannelClose();
1826 EXPECT_FALSE(DidReceivePrerenderStartEventForLinkNumber(1));
1827 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1828 EXPECT_FALSE(HadPrerenderEventErrors());
1829 // IsEmptyPrerenderLinkManager() is not racy because the earlier DidReceive*
1830 // calls did a thread/process hop to the renderer which insured pending
1831 // renderer events have arrived.
1832 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
1835 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPageRemovingLink) {
1836 scoped_ptr<TestPrerender> prerender =
1837 PrerenderTestURL("files/prerender/prerender_page.html",
1838 FINAL_STATUS_CANCELLED, 1);
1840 // No ChannelDestructionWatcher is needed here, since prerenders in the
1841 // PrerenderLinkManager should be deleted by removing the links, rather than
1842 // shutting down the renderer process.
1843 RemoveLinkElement(0);
1844 prerender->WaitForStop();
1846 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1847 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1848 EXPECT_FALSE(HadPrerenderEventErrors());
1849 // IsEmptyPrerenderLinkManager() is not racy because the earlier DidReceive*
1850 // calls did a thread/process hop to the renderer which insured pending
1851 // renderer events have arrived.
1852 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
1855 IN_PROC_BROWSER_TEST_F(
1856 PrerenderBrowserTest, PrerenderPageRemovingLinkWithTwoLinks) {
1857 GetPrerenderManager()->mutable_config().max_link_concurrency = 2;
1858 GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2;
1860 set_loader_query("links_to_insert=2");
1861 scoped_ptr<TestPrerender> prerender =
1862 PrerenderTestURL("files/prerender/prerender_page.html",
1863 FINAL_STATUS_CANCELLED, 1);
1864 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1865 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1866 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1867 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1869 RemoveLinkElement(0);
1870 RemoveLinkElement(1);
1871 prerender->WaitForStop();
1873 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1874 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1875 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1876 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1877 EXPECT_FALSE(HadPrerenderEventErrors());
1878 // IsEmptyPrerenderLinkManager() is not racy because the earlier DidReceive*
1879 // calls did a thread/process hop to the renderer which insured pending
1880 // renderer events have arrived.
1881 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
1884 IN_PROC_BROWSER_TEST_F(
1885 PrerenderBrowserTest, PrerenderPageRemovingLinkWithTwoLinksOneLate) {
1886 GetPrerenderManager()->mutable_config().max_link_concurrency = 2;
1887 GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2;
1889 GURL url = test_server()->GetURL("files/prerender/prerender_page.html");
1890 scoped_ptr<TestPrerender> prerender =
1891 PrerenderTestURL(url, FINAL_STATUS_CANCELLED, 1);
1893 // Add a second prerender for the same link. It reuses the prerender, so only
1894 // the start event fires here.
1895 AddPrerender(url, 1);
1896 WaitForPrerenderEventCount(1, "webkitprerenderstart", 1);
1897 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1898 EXPECT_EQ(0, GetPrerenderLoadEventCountForLinkNumber(1));
1899 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1901 RemoveLinkElement(0);
1902 RemoveLinkElement(1);
1903 prerender->WaitForStop();
1905 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1906 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1907 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1908 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1909 EXPECT_FALSE(HadPrerenderEventErrors());
1910 // IsEmptyPrerenderLinkManager() is not racy because the earlier DidReceive*
1911 // calls did a thread/process hop to the renderer which insured pending
1912 // renderer events have arrived.
1913 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
1916 IN_PROC_BROWSER_TEST_F(
1917 PrerenderBrowserTest,
1918 PrerenderPageRemovingLinkWithTwoLinksRemovingOne) {
1919 GetPrerenderManager()->mutable_config().max_link_concurrency = 2;
1920 GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2;
1921 set_loader_query("links_to_insert=2");
1922 PrerenderTestURL("files/prerender/prerender_page.html",
1923 FINAL_STATUS_USED, 1);
1924 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1925 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1926 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1927 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1929 RemoveLinkElement(0);
1930 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
1931 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(0));
1932 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(1));
1933 EXPECT_FALSE(DidReceivePrerenderStopEventForLinkNumber(1));
1934 EXPECT_FALSE(HadPrerenderEventErrors());
1935 // IsEmptyPrerenderLinkManager() is not racy because the earlier DidReceive*
1936 // calls did a thread/process hop to the renderer which insured pending
1937 // renderer events have arrived.
1938 EXPECT_FALSE(IsEmptyPrerenderLinkManager());
1940 ChannelDestructionWatcher channel_close_watcher;
1941 channel_close_watcher.WatchChannel(
1942 GetActiveWebContents()->GetRenderProcessHost());
1943 NavigateToDestURL();
1944 channel_close_watcher.WaitForChannelClose();
1946 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
1949 // Checks that the visibility API works.
1950 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderVisibility) {
1951 PrerenderTestURL("files/prerender/prerender_visibility.html",
1952 FINAL_STATUS_USED,
1954 NavigateToDestURL();
1957 // Checks that the prerendering of a page is canceled correctly if we try to
1958 // swap it in before it commits.
1959 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNoCommitNoSwap) {
1960 // Navigate to a page that triggers a prerender for a URL that never commits.
1961 const GURL kNoCommitUrl("http://never-respond.example.com");
1962 base::FilePath file(GetTestPath("prerender_page.html"));
1964 base::RunLoop prerender_start_loop;
1965 BrowserThread::PostTask(
1966 BrowserThread::IO, FROM_HERE,
1967 base::Bind(&CreateHangingFirstRequestInterceptorOnIO, kNoCommitUrl, file,
1968 prerender_start_loop.QuitClosure()));
1969 DisableJavascriptCalls();
1970 PrerenderTestURL(kNoCommitUrl,
1971 FINAL_STATUS_NAVIGATION_UNCOMMITTED,
1973 // Wait for the hanging request to be scheduled.
1974 prerender_start_loop.Run();
1976 // Navigate to the URL, but assume the contents won't be swapped in.
1977 NavigateToDestURLWithDisposition(CURRENT_TAB, false);
1980 // Checks that client redirects don't add alias URLs until after they commit.
1981 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNoCommitNoSwap2) {
1982 // Navigate to a page that then navigates to a URL that never commits.
1983 const GURL kNoCommitUrl("http://never-respond.example.com");
1984 base::FilePath file(GetTestPath("prerender_page.html"));
1986 base::RunLoop prerender_start_loop;
1987 BrowserThread::PostTask(
1988 BrowserThread::IO, FROM_HERE,
1989 base::Bind(&CreateHangingFirstRequestInterceptorOnIO, kNoCommitUrl, file,
1990 prerender_start_loop.QuitClosure()));
1991 DisableJavascriptCalls();
1992 PrerenderTestURL(CreateClientRedirect(kNoCommitUrl.spec()),
1993 FINAL_STATUS_APP_TERMINATING, 1);
1994 // Wait for the hanging request to be scheduled.
1995 prerender_start_loop.Run();
1997 // Navigating to the second URL should not swap.
1998 NavigateToURLWithDisposition(kNoCommitUrl, CURRENT_TAB, false);
2001 // Checks that the prerendering of a page is canceled correctly when a
2002 // Javascript alert is called.
2003 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertBeforeOnload) {
2004 PrerenderTestURL("files/prerender/prerender_alert_before_onload.html",
2005 FINAL_STATUS_JAVASCRIPT_ALERT,
2009 // Checks that the prerendering of a page is canceled correctly when a
2010 // Javascript alert is called.
2011 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAlertAfterOnload) {
2012 PrerenderTestURL("files/prerender/prerender_alert_after_onload.html",
2013 FINAL_STATUS_JAVASCRIPT_ALERT,
2017 // Checks that plugins are not loaded while a page is being preloaded, but
2018 // are loaded when the page is displayed.
2019 #if defined(USE_AURA) && !defined(OS_WIN)
2020 // http://crbug.com/103496
2021 #define MAYBE_PrerenderDelayLoadPlugin DISABLED_PrerenderDelayLoadPlugin
2022 #define MAYBE_PrerenderPluginPowerSaver DISABLED_PrerenderPluginPowerSaver
2023 #elif defined(OS_MACOSX)
2024 // http://crbug.com/100514
2025 #define MAYBE_PrerenderDelayLoadPlugin DISABLED_PrerenderDelayLoadPlugin
2026 #define MAYBE_PrerenderPluginPowerSaver DISABLED_PrerenderPluginPowerSaver
2027 #elif defined(OS_WIN) && defined(ARCH_CPU_X86_64)
2028 // TODO(jschuh): Failing plugin tests. crbug.com/244653
2029 #define MAYBE_PrerenderDelayLoadPlugin DISABLED_PrerenderDelayLoadPlugin
2030 #define MAYBE_PrerenderPluginPowerSaver DISABLED_PrerenderPluginPowerSaver
2031 #elif defined(OS_LINUX)
2032 // http://crbug.com/306715
2033 #define MAYBE_PrerenderDelayLoadPlugin DISABLED_PrerenderDelayLoadPlugin
2034 #define MAYBE_PrerenderPluginPowerSaver DISABLED_PrerenderPluginPowerSaver
2035 #else
2036 #define MAYBE_PrerenderDelayLoadPlugin PrerenderDelayLoadPlugin
2037 #define MAYBE_PrerenderPluginPowerSaver PrerenderPluginPowerSaver
2038 #endif
2039 // http://crbug.com/306715
2040 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MAYBE_PrerenderDelayLoadPlugin) {
2041 PrerenderTestURL("files/prerender/plugin_delay_load.html",
2042 FINAL_STATUS_USED,
2044 NavigateToDestURL();
2047 // For enabled Plugin Power Saver, checks that plugins are not loaded while
2048 // a page is being preloaded, but are loaded when the page is displayed.
2049 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MAYBE_PrerenderPluginPowerSaver) {
2050 // Enable click-to-play.
2051 HostContentSettingsMap* content_settings_map =
2052 current_browser()->profile()->GetHostContentSettingsMap();
2053 content_settings_map->SetDefaultContentSetting(
2054 CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_DETECT_IMPORTANT_CONTENT);
2056 PrerenderTestURL("files/prerender/prerender_plugin_power_saver.html",
2057 FINAL_STATUS_USED, 1);
2058 NavigateToDestURL();
2061 // Checks that we don't load a NaCl plugin when NaCl is disabled.
2062 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNaClPluginDisabled) {
2063 PrerenderTestURL("files/prerender/prerender_plugin_nacl_disabled.html",
2064 FINAL_STATUS_USED,
2066 NavigateToDestURL();
2069 // Run this check again. When we try to load aa ppapi plugin, the
2070 // "loadstart" event is asynchronously posted to a message loop.
2071 // It's possible that earlier call could have been run before the
2072 // the "loadstart" event was posted.
2073 // TODO(mmenke): While this should reliably fail on regressions, the
2074 // reliability depends on the specifics of ppapi plugin
2075 // loading. It would be great if we could avoid that.
2076 EXPECT_TRUE(DidDisplayPass(GetActiveWebContents()));
2079 // Checks that plugins in an iframe are not loaded while a page is
2080 // being preloaded, but are loaded when the page is displayed.
2081 #if defined(USE_AURA) && !defined(OS_WIN)
2082 // http://crbug.com/103496
2083 #define MAYBE_PrerenderIframeDelayLoadPlugin \
2084 DISABLED_PrerenderIframeDelayLoadPlugin
2085 #elif defined(OS_MACOSX)
2086 // http://crbug.com/100514
2087 #define MAYBE_PrerenderIframeDelayLoadPlugin \
2088 DISABLED_PrerenderIframeDelayLoadPlugin
2089 #elif defined(OS_WIN) && defined(ARCH_CPU_X86_64)
2090 // TODO(jschuh): Failing plugin tests. crbug.com/244653
2091 #define MAYBE_PrerenderIframeDelayLoadPlugin \
2092 DISABLED_PrerenderIframeDelayLoadPlugin
2093 #else
2094 #define MAYBE_PrerenderIframeDelayLoadPlugin PrerenderIframeDelayLoadPlugin
2095 #endif
2096 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2097 MAYBE_PrerenderIframeDelayLoadPlugin) {
2098 PrerenderTestURL("files/prerender/prerender_iframe_plugin_delay_load.html",
2099 FINAL_STATUS_USED,
2101 NavigateToDestURL();
2104 // Renders a page that contains a prerender link to a page that contains an
2105 // iframe with a source that requires http authentication. This should not
2106 // prerender successfully.
2107 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHttpAuthentication) {
2108 PrerenderTestURL("files/prerender/prerender_http_auth_container.html",
2109 FINAL_STATUS_AUTH_NEEDED,
2113 // Checks that client-issued redirects work with prerendering.
2114 // This version navigates to the page which issues the redirection, rather
2115 // than the final destination page.
2116 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2117 PrerenderClientRedirectNavigateToFirst) {
2118 PrerenderTestURL(CreateClientRedirect("files/prerender/prerender_page.html"),
2119 FINAL_STATUS_USED,
2121 NavigateToDestURL();
2124 // Checks that client-issued redirects work with prerendering.
2125 // This version navigates to the final destination page, rather than the
2126 // page which does the redirection.
2127 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2128 PrerenderClientRedirectNavigateToSecond) {
2129 PrerenderTestURL(CreateClientRedirect("files/prerender/prerender_page.html"),
2130 FINAL_STATUS_USED,
2132 NavigateToURL("files/prerender/prerender_page.html");
2135 // Checks that redirects with location.replace do not cancel a prerender and
2136 // and swap when navigating to the first page.
2137 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2138 PrerenderLocationReplaceNavigateToFirst) {
2139 PrerenderTestURL("files/prerender/prerender_location_replace.html",
2140 FINAL_STATUS_USED,
2142 NavigateToDestURL();
2145 // Checks that redirects with location.replace do not cancel a prerender and
2146 // and swap when navigating to the second.
2147 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2148 PrerenderLocationReplaceNavigateToSecond) {
2149 PrerenderTestURL("files/prerender/prerender_location_replace.html",
2150 FINAL_STATUS_USED,
2152 NavigateToURL("files/prerender/prerender_page.html");
2155 // Checks that we get the right PPLT histograms for client redirect prerenders
2156 // and navigations when the referring page is Google.
2157 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2158 PrerenderLocationReplaceGWSHistograms) {
2159 DisableJavascriptCalls();
2161 // The loader page should look like Google.
2162 static const char kGoogleDotCom[] = "www.google.com";
2163 SetLoaderHostOverride(kGoogleDotCom);
2164 set_loader_path("files/prerender/prerender_loader_with_replace_state.html");
2166 GURL dest_url = GetCrossDomainTestUrl(
2167 "files/prerender/prerender_deferred_image.html");
2169 GURL prerender_url = test_server()->GetURL(
2170 "files/prerender/prerender_location_replace.html?" +
2171 net::EscapeQueryParamValue(dest_url.spec(), false) +
2172 "#prerender");
2173 GURL::Replacements replacements;
2174 replacements.SetHostStr(kGoogleDotCom);
2175 prerender_url = prerender_url.ReplaceComponents(replacements);
2177 // The prerender will not completely load until after the swap, so wait for a
2178 // title change before calling DidPrerenderPass.
2179 scoped_ptr<TestPrerender> prerender =
2180 PrerenderTestURL(prerender_url, FINAL_STATUS_USED, 1);
2181 WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle);
2182 EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents()));
2183 EXPECT_EQ(1, prerender->number_of_loads());
2185 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
2186 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
2187 histogram_tester().ExpectTotalCount(
2188 "Prerender.none_PerceivedPLTMatchedComplete", 0);
2189 // Although there is a client redirect, it is dropped from histograms because
2190 // it is a Google URL. The target page itself does not load until after the
2191 // swap.
2192 histogram_tester().ExpectTotalCount("Prerender.gws_PrerenderNotSwappedInPLT",
2195 GURL navigate_url = test_server()->GetURL(
2196 "files/prerender/prerender_location_replace.html?" +
2197 net::EscapeQueryParamValue(dest_url.spec(), false) +
2198 "#navigate");
2199 navigate_url = navigate_url.ReplaceComponents(replacements);
2201 NavigationOrSwapObserver swap_observer(
2202 current_browser()->tab_strip_model(),
2203 GetActiveWebContents(), 2);
2204 current_browser()->OpenURL(OpenURLParams(
2205 navigate_url, Referrer(), CURRENT_TAB,
2206 ui::PAGE_TRANSITION_TYPED, false));
2207 swap_observer.Wait();
2209 EXPECT_TRUE(DidDisplayPass(GetActiveWebContents()));
2211 histogram_tester().ExpectTotalCount("Prerender.gws_PrerenderNotSwappedInPLT",
2213 histogram_tester().ExpectTotalCount("Prerender.gws_PerceivedPLT", 1);
2214 histogram_tester().ExpectTotalCount("Prerender.gws_PerceivedPLTMatched", 1);
2215 histogram_tester().ExpectTotalCount(
2216 "Prerender.gws_PerceivedPLTMatchedComplete", 1);
2218 // The client redirect does /not/ count as a miss because it's a Google URL.
2219 histogram_tester().ExpectTotalCount("Prerender.PerceivedPLTFirstAfterMiss",
2223 // Checks that client-issued redirects work with prerendering.
2224 // This version navigates to the final destination page, rather than the
2225 // page which does the redirection via a mouse click.
2226 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2227 PrerenderClientRedirectNavigateToSecondViaClick) {
2228 GURL prerender_url = test_server()->GetURL(
2229 CreateClientRedirect("files/prerender/prerender_page.html"));
2230 GURL destination_url = test_server()->GetURL(
2231 "files/prerender/prerender_page.html");
2232 PrerenderTestURL(prerender_url, FINAL_STATUS_USED, 2);
2233 OpenURLViaClick(destination_url);
2236 // Checks that a page served over HTTPS is correctly prerendered.
2237 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHttps) {
2238 net::SpawnedTestServer https_server(
2239 net::SpawnedTestServer::TYPE_HTTPS, net::SpawnedTestServer::kLocalhost,
2240 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
2241 ASSERT_TRUE(https_server.Start());
2242 GURL https_url = https_server.GetURL("files/prerender/prerender_page.html");
2243 PrerenderTestURL(https_url,
2244 FINAL_STATUS_USED,
2246 NavigateToDestURL();
2249 // Checks that client-issued redirects within an iframe in a prerendered
2250 // page will not count as an "alias" for the prerendered page.
2251 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2252 PrerenderClientRedirectInIframe) {
2253 std::string redirect_path = CreateClientRedirect(
2254 "/files/prerender/prerender_embedded_content.html");
2255 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
2256 replacement_text.push_back(
2257 std::make_pair("REPLACE_WITH_URL", "/" + redirect_path));
2258 std::string replacement_path;
2259 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
2260 "files/prerender/prerender_with_iframe.html",
2261 replacement_text,
2262 &replacement_path));
2263 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 2);
2264 EXPECT_FALSE(UrlIsInPrerenderManager(
2265 "files/prerender/prerender_embedded_content.html"));
2266 NavigateToDestURL();
2269 // Checks that server-issued redirects work with prerendering.
2270 // This version navigates to the page which issues the redirection, rather
2271 // than the final destination page.
2272 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2273 PrerenderServerRedirectNavigateToFirst) {
2274 PrerenderTestURL(CreateServerRedirect("files/prerender/prerender_page.html"),
2275 FINAL_STATUS_USED,
2277 NavigateToDestURL();
2280 // Checks that server-issued redirects work with prerendering.
2281 // This version navigates to the final destination page, rather than the
2282 // page which does the redirection.
2283 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2284 PrerenderServerRedirectNavigateToSecond) {
2285 PrerenderTestURL(CreateServerRedirect("files/prerender/prerender_page.html"),
2286 FINAL_STATUS_USED,
2288 NavigateToURL("files/prerender/prerender_page.html");
2291 // Checks that server-issued redirects work with prerendering.
2292 // This version navigates to the final destination page, rather than the
2293 // page which does the redirection via a mouse click.
2294 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2295 PrerenderServerRedirectNavigateToSecondViaClick) {
2296 GURL prerender_url = test_server()->GetURL(
2297 CreateServerRedirect("files/prerender/prerender_page.html"));
2298 GURL destination_url = test_server()->GetURL(
2299 "files/prerender/prerender_page.html");
2300 PrerenderTestURL(prerender_url, FINAL_STATUS_USED, 1);
2301 OpenURLViaClick(destination_url);
2304 // Checks that server-issued redirects within an iframe in a prerendered
2305 // page will not count as an "alias" for the prerendered page.
2306 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderServerRedirectInIframe) {
2307 std::string redirect_path = CreateServerRedirect(
2308 "/files/prerender/prerender_embedded_content.html");
2309 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
2310 replacement_text.push_back(
2311 std::make_pair("REPLACE_WITH_URL", "/" + redirect_path));
2312 std::string replacement_path;
2313 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
2314 "files/prerender/prerender_with_iframe.html",
2315 replacement_text,
2316 &replacement_path));
2317 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
2318 EXPECT_FALSE(UrlIsInPrerenderManager(
2319 "files/prerender/prerender_embedded_content.html"));
2320 NavigateToDestURL();
2323 // Prerenders a page that contains an automatic download triggered through an
2324 // iframe. This should not prerender successfully.
2325 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadIframe) {
2326 PrerenderTestURL("files/prerender/prerender_download_iframe.html",
2327 FINAL_STATUS_DOWNLOAD,
2331 // Prerenders a page that contains an automatic download triggered through
2332 // Javascript changing the window.location. This should not prerender
2333 // successfully
2334 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadLocation) {
2335 PrerenderTestURL(CreateClientRedirect("files/download-test1.lib"),
2336 FINAL_STATUS_DOWNLOAD,
2340 // Prerenders a page that contains an automatic download triggered through a
2341 // client-issued redirect. This should not prerender successfully.
2342 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDownloadClientRedirect) {
2343 PrerenderTestURL("files/prerender/prerender_download_refresh.html",
2344 FINAL_STATUS_DOWNLOAD,
2348 // Checks that the referrer is set when prerendering.
2349 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderReferrer) {
2350 PrerenderTestURL("files/prerender/prerender_referrer.html",
2351 FINAL_STATUS_USED,
2353 NavigateToDestURL();
2356 // Checks that the referrer is not set when prerendering and the source page is
2357 // HTTPS.
2358 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2359 PrerenderNoSSLReferrer) {
2360 UseHttpsSrcServer();
2361 PrerenderTestURL("files/prerender/prerender_no_referrer.html",
2362 FINAL_STATUS_USED,
2364 NavigateToDestURL();
2367 // Checks that the referrer is set when prerendering is cancelled.
2368 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelReferrer) {
2369 scoped_ptr<TestContentBrowserClient> test_content_browser_client(
2370 new TestContentBrowserClient);
2371 content::ContentBrowserClient* original_browser_client =
2372 content::SetBrowserClientForTesting(test_content_browser_client.get());
2374 PrerenderTestURL("files/prerender/prerender_referrer.html",
2375 FINAL_STATUS_CANCELLED,
2377 OpenDestURLViaClick();
2379 EXPECT_TRUE(DidDisplayPass(GetActiveWebContents()));
2381 content::SetBrowserClientForTesting(original_browser_client);
2384 // Checks that popups on a prerendered page cause cancellation.
2385 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPopup) {
2386 PrerenderTestURL("files/prerender/prerender_popup.html",
2387 FINAL_STATUS_CREATE_NEW_WINDOW,
2391 // Checks that registering a protocol handler causes cancellation.
2392 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRegisterProtocolHandler) {
2393 PrerenderTestURL("files/prerender/prerender_register_protocol_handler.html",
2394 FINAL_STATUS_REGISTER_PROTOCOL_HANDLER,
2398 // Checks that renderers using excessive memory will be terminated.
2399 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderExcessiveMemory) {
2400 ASSERT_TRUE(GetPrerenderManager());
2401 GetPrerenderManager()->mutable_config().max_bytes = 30 * 1024 * 1024;
2402 // The excessive memory kill may happen before or after the load event as it
2403 // happens asynchronously with IPC calls. Even if the test does not start
2404 // allocating until after load, the browser process might notice before the
2405 // message gets through. This happens on XP debug bots because they're so
2406 // slow. Instead, don't bother checking the load event count.
2407 DisableLoadEventCheck();
2408 PrerenderTestURL("files/prerender/prerender_excessive_memory.html",
2409 FINAL_STATUS_MEMORY_LIMIT_EXCEEDED, 0);
2412 // Checks shutdown code while a prerender is active.
2413 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderQuickQuit) {
2414 DisableJavascriptCalls();
2415 DisableLoadEventCheck();
2416 PrerenderTestURL("files/prerender/prerender_page.html",
2417 FINAL_STATUS_APP_TERMINATING,
2421 // Checks that we don't prerender in an infinite loop.
2422 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderInfiniteLoop) {
2423 const char* const kHtmlFileA = "files/prerender/prerender_infinite_a.html";
2424 const char* const kHtmlFileB = "files/prerender/prerender_infinite_b.html";
2426 std::vector<FinalStatus> expected_final_status_queue;
2427 expected_final_status_queue.push_back(FINAL_STATUS_USED);
2428 expected_final_status_queue.push_back(FINAL_STATUS_APP_TERMINATING);
2430 ScopedVector<TestPrerender> prerenders =
2431 PrerenderTestURL(kHtmlFileA, expected_final_status_queue, 1);
2432 ASSERT_TRUE(prerenders[0]->contents());
2433 // Assert that the pending prerender is in there already. This relies on the
2434 // fact that the renderer sends out the AddLinkRelPrerender IPC before sending
2435 // the page load one.
2436 EXPECT_EQ(2U, GetLinkPrerenderCount());
2437 EXPECT_EQ(1U, GetRunningLinkPrerenderCount());
2439 // Next url should be in pending list but not an active entry.
2440 EXPECT_FALSE(UrlIsInPrerenderManager(kHtmlFileB));
2442 NavigateToDestURL();
2444 // Make sure the PrerenderContents for the next url is now in the manager and
2445 // not pending. This relies on pending prerenders being resolved in the same
2446 // event loop iteration as OnPrerenderStop.
2447 EXPECT_TRUE(UrlIsInPrerenderManager(kHtmlFileB));
2448 EXPECT_EQ(1U, GetLinkPrerenderCount());
2449 EXPECT_EQ(1U, GetRunningLinkPrerenderCount());
2452 // Checks that we don't prerender in an infinite loop and multiple links are
2453 // handled correctly.
2454 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2455 PrerenderInfiniteLoopMultiple) {
2456 const char* const kHtmlFileA =
2457 "files/prerender/prerender_infinite_a_multiple.html";
2458 const char* const kHtmlFileB =
2459 "files/prerender/prerender_infinite_b_multiple.html";
2460 const char* const kHtmlFileC =
2461 "files/prerender/prerender_infinite_c_multiple.html";
2463 // This test is conceptually simplest if concurrency is at two, since we
2464 // don't have to worry about which of kHtmlFileB or kHtmlFileC gets evicted.
2465 GetPrerenderManager()->mutable_config().max_link_concurrency = 2;
2466 GetPrerenderManager()->mutable_config().max_link_concurrency_per_launcher = 2;
2468 std::vector<FinalStatus> expected_final_status_queue;
2469 expected_final_status_queue.push_back(FINAL_STATUS_USED);
2470 expected_final_status_queue.push_back(FINAL_STATUS_APP_TERMINATING);
2471 expected_final_status_queue.push_back(FINAL_STATUS_APP_TERMINATING);
2473 ScopedVector<TestPrerender> prerenders =
2474 PrerenderTestURL(kHtmlFileA, expected_final_status_queue, 1);
2475 ASSERT_TRUE(prerenders[0]->contents());
2477 // Next url should be in pending list but not an active entry. This relies on
2478 // the fact that the renderer sends out the AddLinkRelPrerender IPC before
2479 // sending the page load one.
2480 EXPECT_EQ(3U, GetLinkPrerenderCount());
2481 EXPECT_EQ(1U, GetRunningLinkPrerenderCount());
2482 EXPECT_FALSE(UrlIsInPrerenderManager(kHtmlFileB));
2483 EXPECT_FALSE(UrlIsInPrerenderManager(kHtmlFileC));
2485 NavigateToDestURL();
2487 // Make sure the PrerenderContents for the next urls are now in the manager
2488 // and not pending. One and only one of the URLs (the last seen) should be the
2489 // active entry. This relies on pending prerenders being resolved in the same
2490 // event loop iteration as OnPrerenderStop.
2491 bool url_b_is_active_prerender = UrlIsInPrerenderManager(kHtmlFileB);
2492 bool url_c_is_active_prerender = UrlIsInPrerenderManager(kHtmlFileC);
2493 EXPECT_TRUE(url_b_is_active_prerender && url_c_is_active_prerender);
2494 EXPECT_EQ(2U, GetLinkPrerenderCount());
2495 EXPECT_EQ(2U, GetRunningLinkPrerenderCount());
2498 // Checks that pending prerenders are aborted (and never launched) when launched
2499 // by a prerender that itself gets aborted.
2500 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAbortPendingOnCancel) {
2501 const char* const kHtmlFileA = "files/prerender/prerender_infinite_a.html";
2502 const char* const kHtmlFileB = "files/prerender/prerender_infinite_b.html";
2504 scoped_ptr<TestPrerender> prerender =
2505 PrerenderTestURL(kHtmlFileA, FINAL_STATUS_CANCELLED, 1);
2506 ASSERT_TRUE(prerender->contents());
2507 // Assert that the pending prerender is in there already. This relies on the
2508 // fact that the renderer sends out the AddLinkRelPrerender IPC before sending
2509 // the page load one.
2510 EXPECT_EQ(2U, GetLinkPrerenderCount());
2511 EXPECT_EQ(1U, GetRunningLinkPrerenderCount());
2513 // Next url should be in pending list but not an active entry.
2514 EXPECT_FALSE(UrlIsInPrerenderManager(kHtmlFileB));
2516 // Cancel the prerender.
2517 GetPrerenderManager()->CancelAllPrerenders();
2518 prerender->WaitForStop();
2520 // All prerenders are now gone.
2521 EXPECT_TRUE(IsEmptyPrerenderLinkManager());
2524 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, OpenTaskManagerBeforePrerender) {
2525 const base::string16 any_prerender = MatchTaskManagerPrerender("*");
2526 const base::string16 any_tab = MatchTaskManagerTab("*");
2527 const base::string16 original = MatchTaskManagerTab("Preloader");
2528 const base::string16 prerender = MatchTaskManagerPrerender("Prerender Page");
2529 const base::string16 final = MatchTaskManagerTab("Prerender Page");
2531 // Show the task manager. This populates the model.
2532 chrome::OpenTaskManager(current_browser());
2533 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2534 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, any_prerender));
2536 // Prerender a page in addition to the original tab.
2537 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
2539 // A TaskManager entry should appear like "Prerender: Prerender Page"
2540 // alongside the original tab entry. There should be just these two entries.
2541 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, prerender));
2542 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, original));
2543 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, final));
2544 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_prerender));
2545 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2547 // Swap in the prerendered content.
2548 NavigateToDestURL();
2550 // The "Prerender: " TaskManager entry should disappear, being replaced by a
2551 // "Tab: Prerender Page" entry, and nothing else.
2552 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, prerender));
2553 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, original));
2554 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, final));
2555 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2556 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, any_prerender));
2559 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, OpenTaskManagerAfterPrerender) {
2560 const base::string16 any_prerender = MatchTaskManagerPrerender("*");
2561 const base::string16 any_tab = MatchTaskManagerTab("*");
2562 const base::string16 original = MatchTaskManagerTab("Preloader");
2563 const base::string16 prerender = MatchTaskManagerPrerender("Prerender Page");
2564 const base::string16 final = MatchTaskManagerTab("Prerender Page");
2566 // Start with two resources.
2567 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
2569 // Show the task manager. This populates the model. Importantly, we're doing
2570 // this after the prerender WebContents already exists - the task manager
2571 // needs to find it, it can't just listen for creation.
2572 chrome::OpenTaskManager(current_browser());
2574 // A TaskManager entry should appear like "Prerender: Prerender Page"
2575 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, prerender));
2576 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, original));
2577 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, final));
2578 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_prerender));
2579 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2581 // Swap in the tab.
2582 NavigateToDestURL();
2584 // The "Prerender: Prerender Page" TaskManager row should disappear, being
2585 // replaced by "Tab: Prerender Page"
2586 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, prerender));
2587 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, original));
2588 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, final));
2589 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2590 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, any_prerender));
2593 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, OpenTaskManagerAfterSwapIn) {
2594 const base::string16 any_prerender = MatchTaskManagerPrerender("*");
2595 const base::string16 any_tab = MatchTaskManagerTab("*");
2596 const base::string16 final = MatchTaskManagerTab("Prerender Page");
2598 // Prerender, and swap it in.
2599 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
2600 NavigateToDestURL();
2602 // Show the task manager. This populates the model. Importantly, we're doing
2603 // this after the prerender has been swapped in.
2604 chrome::OpenTaskManager(current_browser());
2606 // We should not see a prerender resource in the task manager, just a normal
2607 // page.
2608 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, final));
2609 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, any_tab));
2610 ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(0, any_prerender));
2613 // Checks that audio loads are deferred on prerendering.
2614 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5Audio) {
2615 PrerenderTestURL("files/prerender/prerender_html5_audio.html",
2616 FINAL_STATUS_USED,
2618 NavigateToDestURL();
2619 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2622 // Checks that audio loads are deferred on prerendering and played back when
2623 // the prerender is swapped in if autoplay is set.
2624 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5AudioAutoplay) {
2625 PrerenderTestURL("files/prerender/prerender_html5_audio_autoplay.html",
2626 FINAL_STATUS_USED,
2628 NavigateToDestURL();
2629 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2632 // Checks that audio loads are deferred on prerendering and played back when
2633 // the prerender is swapped in if js starts playing.
2634 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5AudioJsplay) {
2635 PrerenderTestURL("files/prerender/prerender_html5_audio_jsplay.html",
2636 FINAL_STATUS_USED,
2638 NavigateToDestURL();
2639 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2642 // Checks that video loads are deferred on prerendering.
2643 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5Video) {
2644 PrerenderTestURL("files/prerender/prerender_html5_video.html",
2645 FINAL_STATUS_USED,
2647 NavigateToDestURL();
2648 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2651 // Checks that video tags inserted by javascript are deferred and played
2652 // correctly on swap in.
2653 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5VideoJs) {
2654 PrerenderTestURL("files/prerender/prerender_html5_video_script.html",
2655 FINAL_STATUS_USED,
2657 NavigateToDestURL();
2658 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2661 // Checks for correct network events by using a busy sleep the javascript.
2662 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5VideoNetwork) {
2663 DisableJavascriptCalls();
2664 scoped_ptr<TestPrerender> prerender =
2665 PrerenderTestURL("files/prerender/prerender_html5_video_network.html",
2666 FINAL_STATUS_USED,
2668 WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle);
2669 EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents()));
2670 NavigateToDestURL();
2671 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
2674 // Checks that scripts can retrieve the correct window size while prerendering.
2675 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderWindowSize) {
2676 PrerenderTestURL("files/prerender/prerender_size.html",
2677 FINAL_STATUS_USED,
2679 NavigateToDestURL();
2682 // TODO(jam): http://crbug.com/350550
2683 #if !(defined(OS_CHROMEOS) && defined(ADDRESS_SANITIZER))
2685 // Checks that prerenderers will terminate when the RenderView crashes.
2686 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderRendererCrash) {
2687 scoped_ptr<TestPrerender> prerender =
2688 PrerenderTestURL("files/prerender/prerender_page.html",
2689 FINAL_STATUS_RENDERER_CRASHED,
2692 // Navigate to about:crash and then wait for the renderer to crash.
2693 ASSERT_TRUE(prerender->contents());
2694 ASSERT_TRUE(prerender->contents()->prerender_contents());
2695 prerender->contents()->prerender_contents()->GetController().
2696 LoadURL(
2697 GURL(content::kChromeUICrashURL),
2698 content::Referrer(),
2699 ui::PAGE_TRANSITION_TYPED,
2700 std::string());
2701 prerender->WaitForStop();
2703 #endif
2705 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2706 PrerenderPageWithFragment) {
2707 PrerenderTestURL("files/prerender/prerender_page.html#fragment",
2708 FINAL_STATUS_USED,
2711 ChannelDestructionWatcher channel_close_watcher;
2712 channel_close_watcher.WatchChannel(browser()->tab_strip_model()->
2713 GetActiveWebContents()->GetRenderProcessHost());
2714 NavigateToDestURL();
2715 channel_close_watcher.WaitForChannelClose();
2717 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
2720 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2721 PrerenderPageWithRedirectedFragment) {
2722 PrerenderTestURL(
2723 CreateClientRedirect("files/prerender/prerender_page.html#fragment"),
2724 FINAL_STATUS_USED,
2727 ChannelDestructionWatcher channel_close_watcher;
2728 channel_close_watcher.WatchChannel(browser()->tab_strip_model()->
2729 GetActiveWebContents()->GetRenderProcessHost());
2730 NavigateToDestURL();
2731 channel_close_watcher.WaitForChannelClose();
2733 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
2736 // Checks that we do not use a prerendered page when navigating from
2737 // the main page to a fragment.
2738 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2739 PrerenderPageNavigateFragment) {
2740 PrerenderTestURL("files/prerender/no_prerender_page.html",
2741 FINAL_STATUS_APP_TERMINATING,
2743 NavigateToURLWithDisposition(
2744 "files/prerender/no_prerender_page.html#fragment",
2745 CURRENT_TAB, false);
2748 // Checks that we do not use a prerendered page when we prerender a fragment
2749 // but navigate to the main page.
2750 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2751 PrerenderFragmentNavigatePage) {
2752 PrerenderTestURL("files/prerender/no_prerender_page.html#fragment",
2753 FINAL_STATUS_APP_TERMINATING,
2755 NavigateToURLWithDisposition(
2756 "files/prerender/no_prerender_page.html",
2757 CURRENT_TAB, false);
2760 // Checks that we do not use a prerendered page when we prerender a fragment
2761 // but navigate to a different fragment on the same page.
2762 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2763 PrerenderFragmentNavigateFragment) {
2764 PrerenderTestURL("files/prerender/no_prerender_page.html#other_fragment",
2765 FINAL_STATUS_APP_TERMINATING,
2767 NavigateToURLWithDisposition(
2768 "files/prerender/no_prerender_page.html#fragment",
2769 CURRENT_TAB, false);
2772 // Checks that we do not use a prerendered page when the page uses a client
2773 // redirect to refresh from a fragment on the same page.
2774 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2775 PrerenderClientRedirectFromFragment) {
2776 PrerenderTestURL(
2777 CreateClientRedirect("files/prerender/no_prerender_page.html#fragment"),
2778 FINAL_STATUS_APP_TERMINATING,
2780 NavigateToURLWithDisposition(
2781 "files/prerender/no_prerender_page.html",
2782 CURRENT_TAB, false);
2785 // Checks that we do not use a prerendered page when the page uses a client
2786 // redirect to refresh to a fragment on the same page.
2787 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2788 PrerenderClientRedirectToFragment) {
2789 PrerenderTestURL(
2790 CreateClientRedirect("files/prerender/no_prerender_page.html"),
2791 FINAL_STATUS_APP_TERMINATING,
2793 NavigateToURLWithDisposition(
2794 "files/prerender/no_prerender_page.html#fragment",
2795 CURRENT_TAB, false);
2798 // Checks that we correctly use a prerendered page when the page uses JS to set
2799 // the window.location.hash to a fragment on the same page.
2800 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2801 PrerenderPageChangeFragmentLocationHash) {
2802 PrerenderTestURL("files/prerender/prerender_fragment_location_hash.html",
2803 FINAL_STATUS_USED,
2805 NavigateToURL("files/prerender/prerender_fragment_location_hash.html");
2808 // Checks that prerendering a PNG works correctly.
2809 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderImagePng) {
2810 DisableJavascriptCalls();
2811 PrerenderTestURL("files/prerender/image.png", FINAL_STATUS_USED, 1);
2812 NavigateToDestURL();
2815 // Checks that prerendering a JPG works correctly.
2816 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderImageJpeg) {
2817 DisableJavascriptCalls();
2818 PrerenderTestURL("files/prerender/image.jpeg", FINAL_STATUS_USED, 1);
2819 NavigateToDestURL();
2822 // Checks that a prerender of a CRX will result in a cancellation due to
2823 // download.
2824 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCrx) {
2825 PrerenderTestURL("files/prerender/extension.crx", FINAL_STATUS_DOWNLOAD, 0);
2828 // Checks that xhr GET requests allow prerenders.
2829 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrGet) {
2830 PrerenderTestURL("files/prerender/prerender_xhr_get.html",
2831 FINAL_STATUS_USED,
2833 NavigateToDestURL();
2836 // Checks that xhr HEAD requests allow prerenders.
2837 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrHead) {
2838 PrerenderTestURL("files/prerender/prerender_xhr_head.html",
2839 FINAL_STATUS_USED,
2841 NavigateToDestURL();
2844 // Checks that xhr OPTIONS requests allow prerenders.
2845 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrOptions) {
2846 PrerenderTestURL("files/prerender/prerender_xhr_options.html",
2847 FINAL_STATUS_USED,
2849 NavigateToDestURL();
2852 // Checks that xhr TRACE requests allow prerenders.
2853 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrTrace) {
2854 PrerenderTestURL("files/prerender/prerender_xhr_trace.html",
2855 FINAL_STATUS_USED,
2857 NavigateToDestURL();
2860 // Checks that xhr POST requests allow prerenders.
2861 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrPost) {
2862 PrerenderTestURL("files/prerender/prerender_xhr_post.html",
2863 FINAL_STATUS_USED,
2865 NavigateToDestURL();
2868 // Checks that xhr PUT cancels prerenders.
2869 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrPut) {
2870 PrerenderTestURL("files/prerender/prerender_xhr_put.html",
2871 FINAL_STATUS_INVALID_HTTP_METHOD,
2875 // Checks that xhr DELETE cancels prerenders.
2876 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderXhrDelete) {
2877 PrerenderTestURL("files/prerender/prerender_xhr_delete.html",
2878 FINAL_STATUS_INVALID_HTTP_METHOD,
2882 // Checks that a top-level page which would trigger an SSL error is canceled.
2883 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSSLErrorTopLevel) {
2884 net::SpawnedTestServer::SSLOptions ssl_options;
2885 ssl_options.server_certificate =
2886 net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME;
2887 net::SpawnedTestServer https_server(
2888 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
2889 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
2890 ASSERT_TRUE(https_server.Start());
2891 GURL https_url = https_server.GetURL("files/prerender/prerender_page.html");
2892 PrerenderTestURL(https_url,
2893 FINAL_STATUS_SSL_ERROR,
2897 // Checks that an SSL error that comes from a subresource does not cancel
2898 // the page. Non-main-frame requests are simply cancelled if they run into
2899 // an SSL problem.
2900 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSSLErrorSubresource) {
2901 net::SpawnedTestServer::SSLOptions ssl_options;
2902 ssl_options.server_certificate =
2903 net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME;
2904 net::SpawnedTestServer https_server(
2905 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
2906 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
2907 ASSERT_TRUE(https_server.Start());
2908 GURL https_url = https_server.GetURL("files/prerender/image.jpeg");
2909 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
2910 replacement_text.push_back(
2911 std::make_pair("REPLACE_WITH_IMAGE_URL", https_url.spec()));
2912 std::string replacement_path;
2913 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
2914 "files/prerender/prerender_with_image.html",
2915 replacement_text,
2916 &replacement_path));
2917 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
2918 NavigateToDestURL();
2921 // Checks that an SSL error that comes from an iframe does not cancel
2922 // the page. Non-main-frame requests are simply cancelled if they run into
2923 // an SSL problem.
2924 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSSLErrorIframe) {
2925 net::SpawnedTestServer::SSLOptions ssl_options;
2926 ssl_options.server_certificate =
2927 net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME;
2928 net::SpawnedTestServer https_server(
2929 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
2930 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
2931 ASSERT_TRUE(https_server.Start());
2932 GURL https_url = https_server.GetURL(
2933 "files/prerender/prerender_embedded_content.html");
2934 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
2935 replacement_text.push_back(
2936 std::make_pair("REPLACE_WITH_URL", https_url.spec()));
2937 std::string replacement_path;
2938 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
2939 "files/prerender/prerender_with_iframe.html",
2940 replacement_text,
2941 &replacement_path));
2942 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
2943 NavigateToDestURL();
2946 // Checks that we cancel correctly when window.print() is called.
2947 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPrint) {
2948 DisableLoadEventCheck();
2949 PrerenderTestURL("files/prerender/prerender_print.html",
2950 FINAL_STATUS_WINDOW_PRINT,
2954 // Checks that prerenders do not get swapped into target pages that have opened
2955 // popups; the BrowsingInstance is not empty.
2956 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderTargetHasPopup) {
2957 PrerenderTestURL("files/prerender/prerender_page.html",
2958 FINAL_STATUS_NON_EMPTY_BROWSING_INSTANCE,
2960 OpenURLViaWindowOpen(GURL(url::kAboutBlankURL));
2962 // Switch back to the current tab and attempt to swap it in.
2963 current_browser()->tab_strip_model()->ActivateTabAt(0, true);
2964 NavigateToDestURLWithDisposition(CURRENT_TAB, false);
2967 class TestClientCertStore : public net::ClientCertStore {
2968 public:
2969 TestClientCertStore() {}
2970 ~TestClientCertStore() override {}
2972 // net::ClientCertStore:
2973 void GetClientCerts(const net::SSLCertRequestInfo& cert_request_info,
2974 net::CertificateList* selected_certs,
2975 const base::Closure& callback) override {
2976 *selected_certs = net::CertificateList(
2977 1, scoped_refptr<net::X509Certificate>(
2978 new net::X509Certificate("test", "test", base::Time(), base::Time())));
2979 callback.Run();
2983 scoped_ptr<net::ClientCertStore> CreateCertStore() {
2984 return scoped_ptr<net::ClientCertStore>(new TestClientCertStore);
2987 // Checks that a top-level page which would normally request an SSL client
2988 // certificate will never be seen since it's an https top-level resource.
2989 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
2990 PrerenderSSLClientCertTopLevel) {
2991 ProfileIOData::FromResourceContext(
2992 current_browser()->profile()->GetResourceContext())->
2993 set_client_cert_store_factory_for_testing(
2994 base::Bind(&CreateCertStore));
2995 net::SpawnedTestServer::SSLOptions ssl_options;
2996 ssl_options.request_client_certificate = true;
2997 net::SpawnedTestServer https_server(
2998 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
2999 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3000 ASSERT_TRUE(https_server.Start());
3001 GURL https_url = https_server.GetURL("files/prerender/prerender_page.html");
3002 PrerenderTestURL(https_url, FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED, 0);
3005 // Checks that an SSL Client Certificate request that originates from a
3006 // subresource will cancel the prerendered page.
3007 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3008 PrerenderSSLClientCertSubresource) {
3009 ProfileIOData::FromResourceContext(
3010 current_browser()->profile()->GetResourceContext())->
3011 set_client_cert_store_factory_for_testing(
3012 base::Bind(&CreateCertStore));
3013 net::SpawnedTestServer::SSLOptions ssl_options;
3014 ssl_options.request_client_certificate = true;
3015 net::SpawnedTestServer https_server(
3016 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
3017 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3018 ASSERT_TRUE(https_server.Start());
3019 GURL https_url = https_server.GetURL("files/prerender/image.jpeg");
3020 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3021 replacement_text.push_back(
3022 std::make_pair("REPLACE_WITH_IMAGE_URL", https_url.spec()));
3023 std::string replacement_path;
3024 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3025 "files/prerender/prerender_with_image.html",
3026 replacement_text,
3027 &replacement_path));
3028 PrerenderTestURL(replacement_path,
3029 FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED,
3033 // Checks that an SSL Client Certificate request that originates from an
3034 // iframe will cancel the prerendered page.
3035 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSSLClientCertIframe) {
3036 ProfileIOData::FromResourceContext(
3037 current_browser()->profile()->GetResourceContext())->
3038 set_client_cert_store_factory_for_testing(
3039 base::Bind(&CreateCertStore));
3040 net::SpawnedTestServer::SSLOptions ssl_options;
3041 ssl_options.request_client_certificate = true;
3042 net::SpawnedTestServer https_server(
3043 net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
3044 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3045 ASSERT_TRUE(https_server.Start());
3046 GURL https_url = https_server.GetURL(
3047 "files/prerender/prerender_embedded_content.html");
3048 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3049 replacement_text.push_back(
3050 std::make_pair("REPLACE_WITH_URL", https_url.spec()));
3051 std::string replacement_path;
3052 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3053 "files/prerender/prerender_with_iframe.html",
3054 replacement_text,
3055 &replacement_path));
3056 PrerenderTestURL(replacement_path,
3057 FINAL_STATUS_SSL_CLIENT_CERTIFICATE_REQUESTED,
3061 #if defined(FULL_SAFE_BROWSING)
3062 // Ensures that we do not prerender pages with a safe browsing
3063 // interstitial.
3064 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSafeBrowsingTopLevel) {
3065 GURL url = test_server()->GetURL("files/prerender/prerender_page.html");
3066 GetFakeSafeBrowsingDatabaseManager()->SetThreatTypeForUrl(
3067 url, SB_THREAT_TYPE_URL_MALWARE);
3068 PrerenderTestURL("files/prerender/prerender_page.html",
3069 FINAL_STATUS_SAFE_BROWSING, 0);
3072 // Ensures that server redirects to a malware page will cancel prerenders.
3073 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3074 PrerenderSafeBrowsingServerRedirect) {
3075 GURL url = test_server()->GetURL("files/prerender/prerender_page.html");
3076 GetFakeSafeBrowsingDatabaseManager()->SetThreatTypeForUrl(
3077 url, SB_THREAT_TYPE_URL_MALWARE);
3078 PrerenderTestURL(CreateServerRedirect("files/prerender/prerender_page.html"),
3079 FINAL_STATUS_SAFE_BROWSING,
3083 // Ensures that client redirects to a malware page will cancel prerenders.
3084 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3085 PrerenderSafeBrowsingClientRedirect) {
3086 GURL url = test_server()->GetURL("files/prerender/prerender_page.html");
3087 GetFakeSafeBrowsingDatabaseManager()->SetThreatTypeForUrl(
3088 url, SB_THREAT_TYPE_URL_MALWARE);
3089 PrerenderTestURL(CreateClientRedirect("files/prerender/prerender_page.html"),
3090 FINAL_STATUS_SAFE_BROWSING,
3094 // Ensures that we do not prerender pages which have a malware subresource.
3095 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSafeBrowsingSubresource) {
3096 GURL image_url = test_server()->GetURL("files/prerender/image.jpeg");
3097 GetFakeSafeBrowsingDatabaseManager()->SetThreatTypeForUrl(
3098 image_url, SB_THREAT_TYPE_URL_MALWARE);
3099 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3100 replacement_text.push_back(
3101 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3102 std::string replacement_path;
3103 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3104 "files/prerender/prerender_with_image.html",
3105 replacement_text,
3106 &replacement_path));
3107 PrerenderTestURL(replacement_path,
3108 FINAL_STATUS_SAFE_BROWSING,
3112 // Ensures that we do not prerender pages which have a malware iframe.
3113 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSafeBrowsingIframe) {
3114 GURL iframe_url = test_server()->GetURL(
3115 "files/prerender/prerender_embedded_content.html");
3116 GetFakeSafeBrowsingDatabaseManager()->SetThreatTypeForUrl(
3117 iframe_url, SB_THREAT_TYPE_URL_MALWARE);
3118 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3119 replacement_text.push_back(
3120 std::make_pair("REPLACE_WITH_URL", iframe_url.spec()));
3121 std::string replacement_path;
3122 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3123 "files/prerender/prerender_with_iframe.html",
3124 replacement_text,
3125 &replacement_path));
3126 PrerenderTestURL(replacement_path,
3127 FINAL_STATUS_SAFE_BROWSING,
3131 #endif
3133 // Checks that a local storage read will not cause prerender to fail.
3134 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderLocalStorageRead) {
3135 PrerenderTestURL("files/prerender/prerender_localstorage_read.html",
3136 FINAL_STATUS_USED,
3138 NavigateToDestURL();
3141 // Checks that a local storage write will not cause prerender to fail.
3142 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderLocalStorageWrite) {
3143 PrerenderTestURL("files/prerender/prerender_localstorage_write.html",
3144 FINAL_STATUS_USED,
3146 NavigateToDestURL();
3149 // Checks that the favicon is properly loaded on prerender.
3150 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderFavicon) {
3151 scoped_ptr<TestPrerender> prerender =
3152 PrerenderTestURL("files/prerender/prerender_favicon.html",
3153 FINAL_STATUS_USED,
3155 NavigateToDestURL();
3157 if (!FaviconTabHelper::FromWebContents(
3158 GetActiveWebContents())->FaviconIsValid()) {
3159 // If the favicon has not been set yet, wait for it to be.
3160 content::WindowedNotificationObserver favicon_update_watcher(
3161 chrome::NOTIFICATION_FAVICON_UPDATED,
3162 content::Source<WebContents>(GetActiveWebContents()));
3163 favicon_update_watcher.Wait();
3165 EXPECT_TRUE(FaviconTabHelper::FromWebContents(
3166 GetActiveWebContents())->FaviconIsValid());
3169 // Checks that when a prerendered page is swapped in to a referring page, the
3170 // unload handlers on the referring page are executed.
3171 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderUnload) {
3172 // Matches URL in prerender_loader_with_unload.html.
3173 const GURL unload_url("http://unload-url.test");
3174 base::FilePath empty_file = ui_test_utils::GetTestFilePath(
3175 base::FilePath(), base::FilePath(FILE_PATH_LITERAL("empty.html")));
3176 RequestCounter unload_counter;
3177 BrowserThread::PostTask(
3178 BrowserThread::IO, FROM_HERE,
3179 base::Bind(&CreateCountingInterceptorOnIO,
3180 unload_url, empty_file, unload_counter.AsWeakPtr()));
3182 set_loader_path("files/prerender/prerender_loader_with_unload.html");
3183 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3184 NavigateToDestURL();
3185 unload_counter.WaitForCount(1);
3188 // Checks that a hanging unload on the referring page of a prerender swap does
3189 // not crash the browser on exit.
3190 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHangingUnload) {
3191 // Matches URL in prerender_loader_with_unload.html.
3192 const GURL hang_url("http://unload-url.test");
3193 base::FilePath empty_file = ui_test_utils::GetTestFilePath(
3194 base::FilePath(), base::FilePath(FILE_PATH_LITERAL("empty.html")));
3195 BrowserThread::PostTask(
3196 BrowserThread::IO, FROM_HERE,
3197 base::Bind(&CreateHangingFirstRequestInterceptorOnIO,
3198 hang_url, empty_file,
3199 base::Closure()));
3201 set_loader_path("files/prerender/prerender_loader_with_unload.html");
3202 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3203 NavigateToDestURL();
3207 // Checks that when the history is cleared, prerendering is cancelled and
3208 // prerendering history is cleared.
3209 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClearHistory) {
3210 scoped_ptr<TestPrerender> prerender =
3211 PrerenderTestURL("files/prerender/prerender_page.html",
3212 FINAL_STATUS_CACHE_OR_HISTORY_CLEARED,
3215 ClearBrowsingData(current_browser(), BrowsingDataRemover::REMOVE_HISTORY);
3216 prerender->WaitForStop();
3218 // Make sure prerender history was cleared.
3219 EXPECT_EQ(0, GetHistoryLength());
3222 // Checks that when the cache is cleared, prerenders are cancelled but
3223 // prerendering history is not cleared.
3224 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClearCache) {
3225 scoped_ptr<TestPrerender> prerender =
3226 PrerenderTestURL("files/prerender/prerender_page.html",
3227 FINAL_STATUS_CACHE_OR_HISTORY_CLEARED,
3230 ClearBrowsingData(current_browser(), BrowsingDataRemover::REMOVE_CACHE);
3231 prerender->WaitForStop();
3233 // Make sure prerender history was not cleared. Not a vital behavior, but
3234 // used to compare with PrerenderClearHistory test.
3235 EXPECT_EQ(1, GetHistoryLength());
3238 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelAll) {
3239 scoped_ptr<TestPrerender> prerender =
3240 PrerenderTestURL("files/prerender/prerender_page.html",
3241 FINAL_STATUS_CANCELLED,
3244 GetPrerenderManager()->CancelAllPrerenders();
3245 prerender->WaitForStop();
3247 EXPECT_FALSE(prerender->contents());
3250 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderEvents) {
3251 scoped_ptr<TestPrerender> prerender =
3252 PrerenderTestURL("files/prerender/prerender_page.html",
3253 FINAL_STATUS_CANCELLED, 1);
3255 GetPrerenderManager()->CancelAllPrerenders();
3256 prerender->WaitForStop();
3258 EXPECT_TRUE(DidReceivePrerenderStartEventForLinkNumber(0));
3259 EXPECT_TRUE(DidReceivePrerenderStopEventForLinkNumber(0));
3260 EXPECT_FALSE(HadPrerenderEventErrors());
3263 // Cancels the prerender of a page with its own prerender. The second prerender
3264 // should never be started.
3265 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3266 PrerenderCancelPrerenderWithPrerender) {
3267 scoped_ptr<TestPrerender> prerender =
3268 PrerenderTestURL("files/prerender/prerender_infinite_a.html",
3269 FINAL_STATUS_CANCELLED,
3272 GetPrerenderManager()->CancelAllPrerenders();
3273 prerender->WaitForStop();
3275 EXPECT_FALSE(prerender->contents());
3278 // Prerendering and history tests.
3279 // The prerendered page is navigated to in several ways [navigate via
3280 // omnibox, click on link, key-modified click to open in background tab, etc],
3281 // followed by a navigation to another page from the prerendered page, followed
3282 // by a back navigation.
3284 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNavigateClickGoBack) {
3285 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3286 FINAL_STATUS_USED,
3288 NavigateToDestURL();
3289 ClickToNextPageAfterPrerender();
3290 GoBackToPrerender();
3293 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNavigateNavigateGoBack) {
3294 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3295 FINAL_STATUS_USED,
3297 NavigateToDestURL();
3298 NavigateToNextPageAfterPrerender();
3299 GoBackToPrerender();
3302 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClickClickGoBack) {
3303 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3304 FINAL_STATUS_USED,
3306 OpenDestURLViaClick();
3307 ClickToNextPageAfterPrerender();
3308 GoBackToPrerender();
3311 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClickNavigateGoBack) {
3312 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3313 FINAL_STATUS_USED,
3315 OpenDestURLViaClick();
3316 NavigateToNextPageAfterPrerender();
3317 GoBackToPrerender();
3320 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClickNewWindow) {
3321 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3322 FINAL_STATUS_APP_TERMINATING, 1);
3323 OpenDestURLViaClickNewWindow();
3326 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderClickNewForegroundTab) {
3327 PrerenderTestURL("files/prerender/prerender_page_with_link.html",
3328 FINAL_STATUS_APP_TERMINATING, 1);
3329 OpenDestURLViaClickNewForegroundTab();
3332 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3333 NavigateToPrerenderedPageWhenDevToolsAttached) {
3334 DisableJavascriptCalls();
3335 WebContents* web_contents =
3336 current_browser()->tab_strip_model()->GetActiveWebContents();
3337 scoped_refptr<DevToolsAgentHost> agent(
3338 DevToolsAgentHost::GetOrCreateFor(web_contents));
3339 FakeDevToolsClient client;
3340 agent->AttachClient(&client);
3341 const char* url = "files/prerender/prerender_page.html";
3342 PrerenderTestURL(url, FINAL_STATUS_DEVTOOLS_ATTACHED, 1);
3343 NavigateToURLWithDisposition(url, CURRENT_TAB, false);
3344 agent->DetachClient();
3347 // Validate that the sessionStorage namespace remains the same when swapping
3348 // in a prerendered page.
3349 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderSessionStorage) {
3350 set_loader_path("files/prerender/prerender_loader_with_session_storage.html");
3351 PrerenderTestURL(GetCrossDomainTestUrl("files/prerender/prerender_page.html"),
3352 FINAL_STATUS_USED,
3354 NavigateToDestURL();
3355 GoBackToPageBeforePrerender();
3358 // Checks that the control group works. An XHR PUT cannot be detected in the
3359 // control group.
3360 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ControlGroup) {
3361 RestorePrerenderMode restore_prerender_mode;
3362 PrerenderManager::SetMode(
3363 PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
3364 DisableJavascriptCalls();
3365 PrerenderTestURL("files/prerender/prerender_xhr_put.html",
3366 FINAL_STATUS_WOULD_HAVE_BEEN_USED, 0);
3367 NavigateToDestURL();
3370 // Checks that the control group correctly hits WOULD_HAVE_BEEN_USED
3371 // renderer-initiated navigations. (This verifies that the ShouldFork logic
3372 // behaves correctly.)
3373 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ControlGroupRendererInitiated) {
3374 RestorePrerenderMode restore_prerender_mode;
3375 PrerenderManager::SetMode(
3376 PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
3377 DisableJavascriptCalls();
3378 PrerenderTestURL("files/prerender/prerender_xhr_put.html",
3379 FINAL_STATUS_WOULD_HAVE_BEEN_USED, 0);
3380 OpenDestURLViaClick();
3383 // Make sure that the MatchComplete dummy works in the normal case. Once
3384 // a prerender is cancelled because of a script, a dummy must be created to
3385 // account for the MatchComplete case, and it must have a final status of
3386 // FINAL_STATUS_WOULD_HAVE_BEEN_USED.
3387 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MatchCompleteDummy) {
3388 RestorePrerenderMode restore_prerender_mode;
3389 PrerenderManager::SetMode(
3390 PrerenderManager::PRERENDER_MODE_EXPERIMENT_MATCH_COMPLETE_GROUP);
3392 std::vector<FinalStatus> expected_final_status_queue;
3393 expected_final_status_queue.push_back(FINAL_STATUS_INVALID_HTTP_METHOD);
3394 expected_final_status_queue.push_back(FINAL_STATUS_WOULD_HAVE_BEEN_USED);
3395 PrerenderTestURL("files/prerender/prerender_xhr_put.html",
3396 expected_final_status_queue, 1);
3397 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
3398 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
3399 histogram_tester().ExpectTotalCount(
3400 "Prerender.none_PerceivedPLTMatchedComplete", 0);
3401 histogram_tester().ExpectTotalCount(
3402 "Prerender.websame_PrerenderNotSwappedInPLT", 1);
3404 NavigateToDestURL();
3405 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLT", 1);
3406 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLTMatched",
3408 histogram_tester().ExpectTotalCount(
3409 "Prerender.websame_PerceivedPLTMatchedComplete", 1);
3412 class PrerenderBrowserTestWithNaCl : public PrerenderBrowserTest {
3413 public:
3414 PrerenderBrowserTestWithNaCl() {}
3415 ~PrerenderBrowserTestWithNaCl() override {}
3417 void SetUpCommandLine(base::CommandLine* command_line) override {
3418 PrerenderBrowserTest::SetUpCommandLine(command_line);
3419 command_line->AppendSwitch(switches::kEnableNaCl);
3423 // Check that NaCl plugins work when enabled, with prerendering.
3424 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTestWithNaCl,
3425 PrerenderNaClPluginEnabled) {
3426 #if defined(OS_WIN) && defined(USE_ASH)
3427 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3428 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3429 switches::kAshBrowserTests))
3430 return;
3431 #endif
3433 PrerenderTestURL("files/prerender/prerender_plugin_nacl_enabled.html",
3434 FINAL_STATUS_USED,
3436 NavigateToDestURL();
3438 // To avoid any chance of a race, we have to let the script send its response
3439 // asynchronously.
3440 WebContents* web_contents =
3441 browser()->tab_strip_model()->GetActiveWebContents();
3442 bool display_test_result = false;
3443 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(web_contents,
3444 "DidDisplayReallyPass()",
3445 &display_test_result));
3446 ASSERT_TRUE(display_test_result);
3449 // Checks that the referrer policy is used when prerendering.
3450 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderReferrerPolicy) {
3451 set_loader_path("files/prerender/prerender_loader_with_referrer_policy.html");
3452 PrerenderTestURL("files/prerender/prerender_referrer_policy.html",
3453 FINAL_STATUS_USED,
3455 NavigateToDestURL();
3458 // Checks that the referrer policy is used when prerendering on HTTPS.
3459 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3460 PrerenderSSLReferrerPolicy) {
3461 UseHttpsSrcServer();
3462 set_loader_path("files/prerender/prerender_loader_with_referrer_policy.html");
3463 PrerenderTestURL("files/prerender/prerender_referrer_policy.html",
3464 FINAL_STATUS_USED,
3466 NavigateToDestURL();
3469 // Checks that the referrer policy is used when prerendering is cancelled.
3470 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCancelReferrerPolicy) {
3471 scoped_ptr<TestContentBrowserClient> test_content_browser_client(
3472 new TestContentBrowserClient);
3473 content::ContentBrowserClient* original_browser_client =
3474 content::SetBrowserClientForTesting(test_content_browser_client.get());
3476 set_loader_path("files/prerender/prerender_loader_with_referrer_policy.html");
3477 PrerenderTestURL("files/prerender/prerender_referrer_policy.html",
3478 FINAL_STATUS_CANCELLED,
3480 OpenDestURLViaClick();
3482 bool display_test_result = false;
3483 WebContents* web_contents =
3484 browser()->tab_strip_model()->GetActiveWebContents();
3485 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
3486 web_contents,
3487 "window.domAutomationController.send(DidDisplayPass())",
3488 &display_test_result));
3489 EXPECT_TRUE(display_test_result);
3491 content::SetBrowserClientForTesting(original_browser_client);
3494 // Test interaction of the webNavigation and tabs API with prerender.
3495 class PrerenderBrowserTestWithExtensions : public PrerenderBrowserTest,
3496 public ExtensionApiTest {
3497 public:
3498 PrerenderBrowserTestWithExtensions() {
3499 // The individual tests start the test server through ExtensionApiTest, so
3500 // the port number can be passed through to the extension.
3501 autostart_test_server_ = false;
3504 void SetUp() override { PrerenderBrowserTest::SetUp(); }
3506 void SetUpCommandLine(base::CommandLine* command_line) override {
3507 PrerenderBrowserTest::SetUpCommandLine(command_line);
3508 ExtensionApiTest::SetUpCommandLine(command_line);
3511 void SetUpInProcessBrowserTestFixture() override {
3512 PrerenderBrowserTest::SetUpInProcessBrowserTestFixture();
3513 ExtensionApiTest::SetUpInProcessBrowserTestFixture();
3516 void TearDownInProcessBrowserTestFixture() override {
3517 PrerenderBrowserTest::TearDownInProcessBrowserTestFixture();
3518 ExtensionApiTest::TearDownInProcessBrowserTestFixture();
3521 void SetUpOnMainThread() override {
3522 PrerenderBrowserTest::SetUpOnMainThread();
3526 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTestWithExtensions, WebNavigation) {
3527 ASSERT_TRUE(StartSpawnedTestServer());
3528 extensions::FrameNavigationState::set_allow_extension_scheme(true);
3530 // Wait for the extension to set itself up and return control to us.
3531 ASSERT_TRUE(RunExtensionTest("webnavigation/prerender")) << message_;
3533 extensions::ResultCatcher catcher;
3535 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3537 ChannelDestructionWatcher channel_close_watcher;
3538 channel_close_watcher.WatchChannel(browser()->tab_strip_model()->
3539 GetActiveWebContents()->GetRenderProcessHost());
3540 NavigateToDestURL();
3541 channel_close_watcher.WaitForChannelClose();
3543 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
3544 ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
3547 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTestWithExtensions, TabsApi) {
3548 ASSERT_TRUE(StartSpawnedTestServer());
3549 extensions::FrameNavigationState::set_allow_extension_scheme(true);
3551 // Wait for the extension to set itself up and return control to us.
3552 ASSERT_TRUE(RunExtensionTest("tabs/on_replaced")) << message_;
3554 extensions::ResultCatcher catcher;
3556 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3558 ChannelDestructionWatcher channel_close_watcher;
3559 channel_close_watcher.WatchChannel(browser()->tab_strip_model()->
3560 GetActiveWebContents()->GetRenderProcessHost());
3561 NavigateToDestURL();
3562 channel_close_watcher.WaitForChannelClose();
3564 ASSERT_TRUE(IsEmptyPrerenderLinkManager());
3565 ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
3568 // Test that prerenders abort when navigating to a stream.
3569 // See chrome/browser/extensions/api/streams_private/streams_private_apitest.cc
3570 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTestWithExtensions, StreamsTest) {
3571 RestorePrerenderMode restore_prerender_mode;
3572 PrerenderManager::SetMode(
3573 PrerenderManager::PRERENDER_MODE_EXPERIMENT_MATCH_COMPLETE_GROUP);
3575 ASSERT_TRUE(StartSpawnedTestServer());
3577 const extensions::Extension* extension = LoadExtension(
3578 test_data_dir_.AppendASCII("streams_private/handle_mime_type"));
3579 ASSERT_TRUE(extension);
3580 EXPECT_EQ(std::string(extension_misc::kMimeHandlerPrivateTestExtensionId),
3581 extension->id());
3582 MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
3583 ASSERT_TRUE(handler);
3584 EXPECT_TRUE(handler->CanHandleMIMEType("application/msword"));
3586 PrerenderTestURL("files/prerender/document.doc", FINAL_STATUS_DOWNLOAD, 0);
3588 // Sanity-check that the extension would have picked up the stream in a normal
3589 // navigation had prerender not intercepted it.
3590 // streams_private/handle_mime_type reports success if it has handled the
3591 // application/msword type.
3592 extensions::ResultCatcher catcher;
3593 NavigateToDestURL();
3594 EXPECT_TRUE(catcher.GetNextResult());
3597 // Checks that non-http/https/chrome-extension subresource cancels the
3598 // prerender.
3599 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3600 PrerenderCancelSubresourceUnsupportedScheme) {
3601 GURL image_url = GURL("invalidscheme://www.google.com/test.jpg");
3602 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3603 replacement_text.push_back(
3604 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3605 std::string replacement_path;
3606 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3607 "files/prerender/prerender_with_image.html",
3608 replacement_text,
3609 &replacement_path));
3610 PrerenderTestURL(replacement_path, FINAL_STATUS_UNSUPPORTED_SCHEME, 0);
3613 // Ensure that about:blank is permitted for any subresource.
3614 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3615 PrerenderAllowAboutBlankSubresource) {
3616 GURL image_url = GURL("about:blank");
3617 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3618 replacement_text.push_back(
3619 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3620 std::string replacement_path;
3621 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3622 "files/prerender/prerender_with_image.html",
3623 replacement_text,
3624 &replacement_path));
3625 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
3626 NavigateToDestURL();
3629 // Checks that non-http/https/chrome-extension subresource cancels the prerender
3630 // on redirect.
3631 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3632 PrerenderCancelSubresourceRedirectUnsupportedScheme) {
3633 GURL image_url = test_server()->GetURL(
3634 CreateServerRedirect("invalidscheme://www.google.com/test.jpg"));
3635 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3636 replacement_text.push_back(
3637 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3638 std::string replacement_path;
3639 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3640 "files/prerender/prerender_with_image.html",
3641 replacement_text,
3642 &replacement_path));
3643 PrerenderTestURL(replacement_path, FINAL_STATUS_UNSUPPORTED_SCHEME, 0);
3646 // Checks that chrome-extension subresource does not cancel the prerender.
3647 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3648 PrerenderKeepSubresourceExtensionScheme) {
3649 GURL image_url = GURL("chrome-extension://abcdefg/test.jpg");
3650 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3651 replacement_text.push_back(
3652 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3653 std::string replacement_path;
3654 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3655 "files/prerender/prerender_with_image.html",
3656 replacement_text,
3657 &replacement_path));
3658 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
3659 NavigateToDestURL();
3662 // Checks that redirect to chrome-extension subresource does not cancel the
3663 // prerender.
3664 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3665 PrerenderKeepSubresourceRedirectExtensionScheme) {
3666 GURL image_url = test_server()->GetURL(
3667 CreateServerRedirect("chrome-extension://abcdefg/test.jpg"));
3668 std::vector<net::SpawnedTestServer::StringPair> replacement_text;
3669 replacement_text.push_back(
3670 std::make_pair("REPLACE_WITH_IMAGE_URL", image_url.spec()));
3671 std::string replacement_path;
3672 ASSERT_TRUE(net::SpawnedTestServer::GetFilePathWithReplacements(
3673 "files/prerender/prerender_with_image.html",
3674 replacement_text,
3675 &replacement_path));
3676 PrerenderTestURL(replacement_path, FINAL_STATUS_USED, 1);
3677 NavigateToDestURL();
3680 // Checks that non-http/https main page redirects cancel the prerender.
3681 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3682 PrerenderCancelMainFrameRedirectUnsupportedScheme) {
3683 GURL url = test_server()->GetURL(
3684 CreateServerRedirect("invalidscheme://www.google.com/test.html"));
3685 PrerenderTestURL(url, FINAL_STATUS_UNSUPPORTED_SCHEME, 0);
3688 // Checks that media source video loads are deferred on prerendering.
3689 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderHTML5MediaSourceVideo) {
3690 PrerenderTestURL("files/prerender/prerender_html5_video_media_source.html",
3691 FINAL_STATUS_USED,
3693 NavigateToDestURL();
3694 WaitForASCIITitle(GetActiveWebContents(), kPassTitle);
3697 // Checks that a prerender that creates an audio stream (via a WebAudioDevice)
3698 // is cancelled.
3699 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderWebAudioDevice) {
3700 DisableLoadEventCheck();
3701 PrerenderTestURL("files/prerender/prerender_web_audio_device.html",
3702 FINAL_STATUS_CREATING_AUDIO_STREAM, 0);
3705 // Checks that prerenders do not swap in to WebContents being captured.
3706 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCapturedWebContents) {
3707 PrerenderTestURL("files/prerender/prerender_page.html",
3708 FINAL_STATUS_PAGE_BEING_CAPTURED, 1);
3709 WebContents* web_contents = GetActiveWebContents();
3710 web_contents->IncrementCapturerCount(gfx::Size());
3711 NavigateToDestURLWithDisposition(CURRENT_TAB, false);
3712 web_contents->DecrementCapturerCount();
3715 // Checks that prerenders are aborted on cross-process navigation from
3716 // a server redirect.
3717 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3718 PrerenderCrossProcessServerRedirect) {
3719 // Force everything to be a process swap.
3720 SwapProcessesContentBrowserClient test_browser_client;
3721 content::ContentBrowserClient* original_browser_client =
3722 content::SetBrowserClientForTesting(&test_browser_client);
3724 PrerenderTestURL(
3725 CreateServerRedirect("files/prerender/prerender_page.html"),
3726 FINAL_STATUS_OPEN_URL, 0);
3728 content::SetBrowserClientForTesting(original_browser_client);
3731 // Checks that URLRequests for prerenders being aborted on cross-process
3732 // navigation from a server redirect are cleaned up, so they don't keep cache
3733 // entries locked.
3734 // See http://crbug.com/341134
3735 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3736 PrerenderCrossProcessServerRedirectNoHang) {
3737 const char kDestPath[] = "files/prerender/prerender_page.html";
3738 // Force everything to be a process swap.
3739 SwapProcessesContentBrowserClient test_browser_client;
3740 content::ContentBrowserClient* original_browser_client =
3741 content::SetBrowserClientForTesting(&test_browser_client);
3743 PrerenderTestURL(CreateServerRedirect(kDestPath), FINAL_STATUS_OPEN_URL, 0);
3745 ui_test_utils::NavigateToURL(
3746 browser(),
3747 test_server()->GetURL(kDestPath));
3749 content::SetBrowserClientForTesting(original_browser_client);
3752 // Checks that prerenders are aborted on cross-process navigation from
3753 // a client redirect.
3754 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3755 PrerenderCrossProcessClientRedirect) {
3756 // Cross-process navigation logic for renderer-initiated navigations
3757 // is partially controlled by the renderer, namely
3758 // ChromeContentRendererClient. This test instead relies on the Web
3759 // Store triggering such navigations.
3760 std::string webstore_url = extension_urls::GetWebstoreLaunchURL();
3762 // Mock out requests to the Web Store.
3763 base::FilePath file(GetTestPath("prerender_page.html"));
3764 BrowserThread::PostTask(
3765 BrowserThread::IO, FROM_HERE,
3766 base::Bind(&CreateMockInterceptorOnIO, GURL(webstore_url), file));
3768 PrerenderTestURL(CreateClientRedirect(webstore_url),
3769 FINAL_STATUS_OPEN_URL, 1);
3772 // Checks that canceling a MatchComplete dummy doesn't result in two
3773 // stop events.
3774 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CancelMatchCompleteDummy) {
3775 RestorePrerenderMode restore_prerender_mode;
3776 PrerenderManager::SetMode(
3777 PrerenderManager::PRERENDER_MODE_EXPERIMENT_MATCH_COMPLETE_GROUP);
3779 std::vector<FinalStatus> expected_final_status_queue;
3780 expected_final_status_queue.push_back(FINAL_STATUS_JAVASCRIPT_ALERT);
3781 expected_final_status_queue.push_back(FINAL_STATUS_CANCELLED);
3782 ScopedVector<TestPrerender> prerenders =
3783 PrerenderTestURL("files/prerender/prerender_alert_before_onload.html",
3784 expected_final_status_queue, 0);
3786 // Cancel the MatchComplete dummy.
3787 GetPrerenderManager()->CancelAllPrerenders();
3788 prerenders[1]->WaitForStop();
3790 // Check the referring page only got one copy of the event.
3791 EXPECT_FALSE(HadPrerenderEventErrors());
3794 // Checks that a deferred redirect to an image is not loaded until the page is
3795 // visible. Also test the right histogram events are emitted in this case.
3796 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDeferredImage) {
3797 DisableJavascriptCalls();
3799 // The prerender will not completely load until after the swap, so wait for a
3800 // title change before calling DidPrerenderPass.
3801 scoped_ptr<TestPrerender> prerender =
3802 PrerenderTestURL(
3803 "files/prerender/prerender_deferred_image.html",
3804 FINAL_STATUS_USED, 0);
3805 WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle);
3806 EXPECT_EQ(1, GetPrerenderDomContentLoadedEventCountForLinkNumber(0));
3807 EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents()));
3808 EXPECT_EQ(0, prerender->number_of_loads());
3809 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
3810 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
3811 histogram_tester().ExpectTotalCount(
3812 "Prerender.none_PerceivedPLTMatchedComplete", 0);
3813 histogram_tester().ExpectTotalCount(
3814 "Prerender.websame_PrerenderNotSwappedInPLT", 0);
3816 // Swap.
3817 NavigationOrSwapObserver swap_observer(current_browser()->tab_strip_model(),
3818 GetActiveWebContents());
3819 ui_test_utils::NavigateToURLWithDisposition(
3820 current_browser(), dest_url(), CURRENT_TAB,
3821 ui_test_utils::BROWSER_TEST_NONE);
3822 swap_observer.Wait();
3824 // The prerender never observes the final load.
3825 EXPECT_EQ(0, prerender->number_of_loads());
3827 // Now check DidDisplayPass.
3828 EXPECT_TRUE(DidDisplayPass(GetActiveWebContents()));
3830 histogram_tester().ExpectTotalCount(
3831 "Prerender.websame_PrerenderNotSwappedInPLT", 0);
3832 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLT", 1);
3833 histogram_tester().ExpectTotalCount("Prerender.websame_PerceivedPLTMatched",
3835 histogram_tester().ExpectTotalCount(
3836 "Prerender.websame_PerceivedPLTMatchedComplete", 1);
3839 // Checks that a deferred redirect to an image is not loaded until the
3840 // page is visible, even after another redirect.
3841 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3842 PrerenderDeferredImageAfterRedirect) {
3843 DisableJavascriptCalls();
3845 // The prerender will not completely load until after the swap, so wait for a
3846 // title change before calling DidPrerenderPass.
3847 scoped_ptr<TestPrerender> prerender =
3848 PrerenderTestURL(
3849 "files/prerender/prerender_deferred_image.html",
3850 FINAL_STATUS_USED, 0);
3851 WaitForASCIITitle(prerender->contents()->prerender_contents(), kReadyTitle);
3852 EXPECT_TRUE(DidPrerenderPass(prerender->contents()->prerender_contents()));
3853 EXPECT_EQ(0, prerender->number_of_loads());
3855 // Swap.
3856 NavigationOrSwapObserver swap_observer(current_browser()->tab_strip_model(),
3857 GetActiveWebContents());
3858 ui_test_utils::NavigateToURLWithDisposition(
3859 current_browser(), dest_url(), CURRENT_TAB,
3860 ui_test_utils::BROWSER_TEST_NONE);
3861 swap_observer.Wait();
3863 // The prerender never observes the final load.
3864 EXPECT_EQ(0, prerender->number_of_loads());
3866 // Now check DidDisplayPass.
3867 EXPECT_TRUE(DidDisplayPass(GetActiveWebContents()));
3870 // Checks that deferred redirects in the main frame are followed.
3871 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDeferredMainFrame) {
3872 DisableJavascriptCalls();
3873 PrerenderTestURL(
3874 "files/prerender/image-deferred.png",
3875 FINAL_STATUS_USED, 1);
3876 NavigateToDestURL();
3879 // Checks that deferred redirects in the main frame are followed, even
3880 // with a double-redirect.
3881 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3882 PrerenderDeferredMainFrameAfterRedirect) {
3883 DisableJavascriptCalls();
3884 PrerenderTestURL(
3885 CreateServerRedirect("files/prerender/image-deferred.png"),
3886 FINAL_STATUS_USED, 1);
3887 NavigateToDestURL();
3890 // Checks that deferred redirects in a synchronous XHR abort the
3891 // prerender.
3892 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderDeferredSynchronousXHR) {
3893 RestorePrerenderMode restore_prerender_mode;
3894 PrerenderManager::SetMode(
3895 PrerenderManager::PRERENDER_MODE_EXPERIMENT_MATCH_COMPLETE_GROUP);
3896 PrerenderTestURL("files/prerender/prerender_deferred_sync_xhr.html",
3897 FINAL_STATUS_BAD_DEFERRED_REDIRECT, 0);
3898 NavigateToDestURL();
3901 // Checks that prerenders are not swapped for navigations with extra headers.
3902 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderExtraHeadersNoSwap) {
3903 PrerenderTestURL("files/prerender/prerender_page.html",
3904 FINAL_STATUS_APP_TERMINATING, 1);
3906 content::OpenURLParams params(dest_url(), Referrer(), CURRENT_TAB,
3907 ui::PAGE_TRANSITION_TYPED, false);
3908 params.extra_headers = "X-Custom-Header: 42\r\n";
3909 NavigateToURLWithParams(params, false);
3912 // Checks that prerenders are not swapped for navigations with browser-initiated
3913 // POST data.
3914 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
3915 PrerenderBrowserInitiatedPostNoSwap) {
3916 PrerenderTestURL("files/prerender/prerender_page.html",
3917 FINAL_STATUS_APP_TERMINATING, 1);
3919 std::string post_data = "DATA";
3920 content::OpenURLParams params(dest_url(), Referrer(), CURRENT_TAB,
3921 ui::PAGE_TRANSITION_TYPED, false);
3922 params.uses_post = true;
3923 params.browser_initiated_post_data =
3924 base::RefCountedString::TakeString(&post_data);
3925 NavigateToURLWithParams(params, false);
3928 // Checks that the prerendering of a page is canceled correctly when the
3929 // prerendered page tries to make a second navigation entry.
3930 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderNewNavigationEntry) {
3931 PrerenderTestURL("files/prerender/prerender_new_entry.html",
3932 FINAL_STATUS_NEW_NAVIGATION_ENTRY,
3936 // Attempt a swap-in in a new tab. The session storage doesn't match, so it
3937 // should not swap.
3938 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPageNewTab) {
3939 PrerenderTestURL("files/prerender/prerender_page.html",
3940 FINAL_STATUS_APP_TERMINATING, 1);
3942 // Open a new tab to navigate in.
3943 ui_test_utils::NavigateToURLWithDisposition(
3944 current_browser(), GURL(url::kAboutBlankURL), NEW_FOREGROUND_TAB,
3945 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
3947 // Now navigate in the new tab.
3948 NavigateToDestURLWithDisposition(CURRENT_TAB, false);
3951 // Checks that prerenders honor |should_replace_current_entry|.
3952 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderReplaceCurrentEntry) {
3953 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3955 content::OpenURLParams params(dest_url(), Referrer(), CURRENT_TAB,
3956 ui::PAGE_TRANSITION_TYPED, false);
3957 params.should_replace_current_entry = true;
3958 NavigateToURLWithParams(params, false);
3960 const NavigationController& controller =
3961 GetActiveWebContents()->GetController();
3962 // First entry is about:blank, second is prerender_page.html.
3963 EXPECT_TRUE(controller.GetPendingEntry() == NULL);
3964 EXPECT_EQ(2, controller.GetEntryCount());
3965 EXPECT_EQ(GURL(url::kAboutBlankURL), controller.GetEntryAtIndex(0)->GetURL());
3966 EXPECT_EQ(dest_url(), controller.GetEntryAtIndex(1)->GetURL());
3969 // Checks that <a ping> requests are not dropped in prerender.
3970 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPing) {
3971 // Count hits to a certain URL.
3972 const GURL kPingURL("http://prerender.test/ping");
3973 base::FilePath empty_file = ui_test_utils::GetTestFilePath(
3974 base::FilePath(), base::FilePath(FILE_PATH_LITERAL("empty.html")));
3975 RequestCounter ping_counter;
3976 BrowserThread::PostTask(
3977 BrowserThread::IO, FROM_HERE,
3978 base::Bind(&CreateCountingInterceptorOnIO,
3979 kPingURL, empty_file, ping_counter.AsWeakPtr()));
3981 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
3982 OpenDestURLViaClickPing(kPingURL);
3984 ping_counter.WaitForCount(1);
3987 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderPPLTNormalNavigation) {
3988 GURL url = test_server()->GetURL("files/prerender/prerender_page.html");
3989 ui_test_utils::NavigateToURL(current_browser(), url);
3990 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLT", 1);
3991 histogram_tester().ExpectTotalCount("Prerender.none_PerceivedPLTMatched", 0);
3992 histogram_tester().ExpectTotalCount(
3993 "Prerender.none_PerceivedPLTMatchedComplete", 0);
3996 // Checks that a prerender which calls window.close() on itself is aborted.
3997 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderWindowClose) {
3998 DisableLoadEventCheck();
3999 PrerenderTestURL("files/prerender/prerender_window_close.html",
4000 FINAL_STATUS_CLOSED, 0);
4003 class PrerenderIncognitoBrowserTest : public PrerenderBrowserTest {
4004 public:
4005 void SetUpOnMainThread() override {
4006 Profile* normal_profile = current_browser()->profile();
4007 set_browser(ui_test_utils::OpenURLOffTheRecord(
4008 normal_profile, GURL("about:blank")));
4009 PrerenderBrowserTest::SetUpOnMainThread();
4013 // Checks that prerendering works in incognito mode.
4014 IN_PROC_BROWSER_TEST_F(PrerenderIncognitoBrowserTest, PrerenderIncognito) {
4015 PrerenderTestURL("files/prerender/prerender_page.html", FINAL_STATUS_USED, 1);
4016 NavigateToDestURL();
4019 // Checks that prerenders are aborted when an incognito profile is closed.
4020 IN_PROC_BROWSER_TEST_F(PrerenderIncognitoBrowserTest,
4021 PrerenderIncognitoClosed) {
4022 scoped_ptr<TestPrerender> prerender =
4023 PrerenderTestURL("files/prerender/prerender_page.html",
4024 FINAL_STATUS_PROFILE_DESTROYED, 1);
4025 current_browser()->window()->Close();
4026 prerender->WaitForStop();
4029 class PrerenderOmniboxBrowserTest : public PrerenderBrowserTest {
4030 public:
4031 LocationBar* GetLocationBar() {
4032 return current_browser()->window()->GetLocationBar();
4035 OmniboxView* GetOmniboxView() {
4036 return GetLocationBar()->GetOmniboxView();
4039 void WaitForAutocompleteDone(OmniboxView* omnibox_view) {
4040 AutocompleteController* controller =
4041 omnibox_view->model()->popup_model()->autocomplete_controller();
4042 while (!controller->done()) {
4043 content::WindowedNotificationObserver ready_observer(
4044 chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
4045 content::Source<AutocompleteController>(controller));
4046 ready_observer.Wait();
4050 predictors::AutocompleteActionPredictor* GetAutocompleteActionPredictor() {
4051 Profile* profile = current_browser()->profile();
4052 return predictors::AutocompleteActionPredictorFactory::GetForProfile(
4053 profile);
4056 scoped_ptr<TestPrerender> StartOmniboxPrerender(
4057 const GURL& url,
4058 FinalStatus expected_final_status) {
4059 scoped_ptr<TestPrerender> prerender =
4060 ExpectPrerender(expected_final_status);
4061 WebContents* web_contents = GetActiveWebContents();
4062 GetAutocompleteActionPredictor()->StartPrerendering(
4063 url,
4064 web_contents->GetController().GetDefaultSessionStorageNamespace(),
4065 gfx::Size(50, 50));
4066 prerender->WaitForStart();
4067 return prerender.Pass();
4071 // Checks that closing the omnibox popup cancels an omnibox prerender.
4072 // http://crbug.com/395152
4073 IN_PROC_BROWSER_TEST_F(PrerenderOmniboxBrowserTest,
4074 DISABLED_PrerenderOmniboxCancel) {
4075 // Fake an omnibox prerender.
4076 scoped_ptr<TestPrerender> prerender = StartOmniboxPrerender(
4077 test_server()->GetURL("files/empty.html"),
4078 FINAL_STATUS_CANCELLED);
4080 // Revert the location bar. This should cancel the prerender.
4081 GetLocationBar()->Revert();
4082 prerender->WaitForStop();
4085 // Checks that accepting omnibox input abandons an omnibox prerender.
4086 // http://crbug.com/394592
4087 IN_PROC_BROWSER_TEST_F(PrerenderOmniboxBrowserTest,
4088 DISABLED_PrerenderOmniboxAbandon) {
4089 // Set the abandon timeout to something high so it does not introduce
4090 // flakiness if the prerender times out before the test completes.
4091 GetPrerenderManager()->mutable_config().abandon_time_to_live =
4092 base::TimeDelta::FromDays(999);
4094 // Enter a URL into the Omnibox.
4095 OmniboxView* omnibox_view = GetOmniboxView();
4096 omnibox_view->OnBeforePossibleChange();
4097 omnibox_view->SetUserText(
4098 base::UTF8ToUTF16(test_server()->GetURL("files/empty.html?1").spec()));
4099 omnibox_view->OnAfterPossibleChange();
4100 WaitForAutocompleteDone(omnibox_view);
4102 // Fake an omnibox prerender for a different URL.
4103 scoped_ptr<TestPrerender> prerender = StartOmniboxPrerender(
4104 test_server()->GetURL("files/empty.html?2"),
4105 FINAL_STATUS_APP_TERMINATING);
4107 // The final status may be either FINAL_STATUS_APP_TERMINATING or
4108 // FINAL_STATUS_CANCELLED. Although closing the omnibox will not cancel an
4109 // abandoned prerender, the AutocompleteActionPredictor will cancel the
4110 // predictor on destruction.
4111 prerender->contents()->set_skip_final_checks(true);
4113 // Navigate to the URL entered.
4114 omnibox_view->model()->AcceptInput(CURRENT_TAB, false);
4116 // Prerender should be running, but abandoned.
4117 EXPECT_TRUE(
4118 GetAutocompleteActionPredictor()->IsPrerenderAbandonedForTesting());
4121 // Prefetch should be allowed depending on preference and network type.
4122 // This test is for the bsae case: no Finch overrides should never disable.
4123 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
4124 LocalPredictorDisableWorksBaseCase) {
4125 TestShouldDisableLocalPredictorPreferenceNetworkMatrix(
4126 false /*preference_wifi_network_wifi*/,
4127 false /*preference_wifi_network_4g*/,
4128 false /*preference_always_network_wifi*/,
4129 false /*preference_always_network_4g*/,
4130 false /*preference_never_network_wifi*/,
4131 false /*preference_never_network_4g*/);
4134 // Prefetch should be allowed depending on preference and network type.
4135 // LocalPredictorOnCellularOnly should disable all wifi cases.
4136 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
4137 LocalPredictorDisableWorksCellularOnly) {
4138 CreateTestFieldTrial("PrerenderLocalPredictorSpec",
4139 "LocalPredictorOnCellularOnly=Enabled");
4140 TestShouldDisableLocalPredictorPreferenceNetworkMatrix(
4141 true /*preference_wifi_network_wifi*/,
4142 false /*preference_wifi_network_4g*/,
4143 true /*preference_always_network_wifi*/,
4144 false /*preference_always_network_4g*/,
4145 true /*preference_never_network_wifi*/,
4146 false /*preference_never_network_4g*/);
4149 // Prefetch should be allowed depending on preference and network type.
4150 // LocalPredictorNetworkPredictionEnabledOnly should disable whenever
4151 // network predictions will not be exercised.
4152 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
4153 LocalPredictorDisableWorksNetworkPredictionEnableOnly) {
4154 CreateTestFieldTrial("PrerenderLocalPredictorSpec",
4155 "LocalPredictorNetworkPredictionEnabledOnly=Enabled");
4156 TestShouldDisableLocalPredictorPreferenceNetworkMatrix(
4157 false /*preference_wifi_network_wifi*/,
4158 true /*preference_wifi_network_4g*/,
4159 false /*preference_always_network_wifi*/,
4160 false /*preference_always_network_4g*/,
4161 true /*preference_never_network_wifi*/,
4162 true /*preference_never_network_4g*/);
4165 // Prefetch should be allowed depending on preference and network type.
4166 // If LocalPredictorNetworkPredictionEnabledOnly and
4167 // LocalPredictorOnCellularOnly are both selected, we must disable whenever
4168 // network predictions are not exercised, or when we are on wifi.
4169 IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
4170 LocalPredictorDisableWorksBothOptions) {
4171 CreateTestFieldTrial("PrerenderLocalPredictorSpec",
4172 "LocalPredictorOnCellularOnly=Enabled:"
4173 "LocalPredictorNetworkPredictionEnabledOnly=Enabled");
4174 TestShouldDisableLocalPredictorPreferenceNetworkMatrix(
4175 true /*preference_wifi_network_wifi*/,
4176 true /*preference_wifi_network_4g*/,
4177 true /*preference_always_network_wifi*/,
4178 false /*preference_always_network_4g*/,
4179 true /*preference_never_network_wifi*/,
4180 true /*preference_never_network_4g*/);
4183 } // namespace prerender