Revert of Remove OneClickSigninHelper since it is no longer used. (patchset #5 id...
[chromium-blink-merge.git] / chrome / browser / geolocation / geolocation_browsertest.cc
blob6e215a0953d604952c9f83459a816073e3dc3874
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 <string>
7 #include "base/command_line.h"
8 #include "base/compiler_specific.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/test/simple_test_clock.h"
13 #include "base/time/clock.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
16 #include "chrome/browser/infobars/infobar_service.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/ui/browser.h"
19 #include "chrome/browser/ui/browser_commands.h"
20 #include "chrome/browser/ui/tabs/tab_strip_model.h"
21 #include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h"
22 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "chrome/test/base/in_process_browser_test.h"
26 #include "chrome/test/base/ui_test_utils.h"
27 #include "components/content_settings/core/browser/content_settings_usages_state.h"
28 #include "components/content_settings/core/browser/host_content_settings_map.h"
29 #include "components/content_settings/core/common/content_settings_pattern.h"
30 #include "components/infobars/core/confirm_infobar_delegate.h"
31 #include "components/infobars/core/infobar.h"
32 #include "content/public/browser/dom_operation_notification_details.h"
33 #include "content/public/browser/navigation_controller.h"
34 #include "content/public/browser/notification_details.h"
35 #include "content/public/browser/notification_service.h"
36 #include "content/public/browser/render_frame_host.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/test/browser_test_utils.h"
39 #include "net/base/net_util.h"
40 #include "net/test/embedded_test_server/embedded_test_server.h"
42 using content::DomOperationNotificationDetails;
43 using content::NavigationController;
44 using content::WebContents;
46 namespace {
48 // IFrameLoader ---------------------------------------------------------------
50 // Used to block until an iframe is loaded via a javascript call.
51 // Note: NavigateToURLBlockUntilNavigationsComplete doesn't seem to work for
52 // multiple embedded iframes, as notifications seem to be 'batched'. Instead, we
53 // load and wait one single frame here by calling a javascript function.
54 class IFrameLoader : public content::NotificationObserver {
55 public:
56 IFrameLoader(Browser* browser, int iframe_id, const GURL& url);
57 ~IFrameLoader() override;
59 // content::NotificationObserver:
60 void Observe(int type,
61 const content::NotificationSource& source,
62 const content::NotificationDetails& details) override;
64 const GURL& iframe_url() const { return iframe_url_; }
66 private:
67 content::NotificationRegistrar registrar_;
69 // If true the navigation has completed.
70 bool navigation_completed_;
72 // If true the javascript call has completed.
73 bool javascript_completed_;
75 std::string javascript_response_;
77 // The URL for the iframe we just loaded.
78 GURL iframe_url_;
80 DISALLOW_COPY_AND_ASSIGN(IFrameLoader);
83 IFrameLoader::IFrameLoader(Browser* browser, int iframe_id, const GURL& url)
84 : navigation_completed_(false),
85 javascript_completed_(false) {
86 WebContents* web_contents =
87 browser->tab_strip_model()->GetActiveWebContents();
88 NavigationController* controller = &web_contents->GetController();
89 registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
90 content::Source<NavigationController>(controller));
91 registrar_.Add(this, content::NOTIFICATION_DOM_OPERATION_RESPONSE,
92 content::NotificationService::AllSources());
93 std::string script(base::StringPrintf(
94 "window.domAutomationController.setAutomationId(0);"
95 "window.domAutomationController.send(addIFrame(%d, \"%s\"));",
96 iframe_id, url.spec().c_str()));
97 web_contents->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(script));
98 content::RunMessageLoop();
100 EXPECT_EQ(base::StringPrintf("\"%d\"", iframe_id), javascript_response_);
101 registrar_.RemoveAll();
102 // Now that we loaded the iframe, let's fetch its src.
103 script = base::StringPrintf(
104 "window.domAutomationController.send(getIFrameSrc(%d))", iframe_id);
105 std::string iframe_src;
106 EXPECT_TRUE(content::ExecuteScriptAndExtractString(web_contents, script,
107 &iframe_src));
108 iframe_url_ = GURL(iframe_src);
111 IFrameLoader::~IFrameLoader() {
114 void IFrameLoader::Observe(int type,
115 const content::NotificationSource& source,
116 const content::NotificationDetails& details) {
117 if (type == content::NOTIFICATION_LOAD_STOP) {
118 navigation_completed_ = true;
119 } else if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) {
120 content::Details<DomOperationNotificationDetails> dom_op_details(details);
121 javascript_response_ = dom_op_details->json;
122 javascript_completed_ = true;
124 if (javascript_completed_ && navigation_completed_)
125 base::MessageLoopForUI::current()->Quit();
128 // GeolocationNotificationObserver --------------------------------------------
130 class GeolocationNotificationObserver : public content::NotificationObserver {
131 public:
132 // If |wait_for_prompt| is true, AddWatchAndWaitForNotification will block
133 // until the prompt has been displayed; otherwise it will block until the
134 // navigation is completed. Does not take ownership of |view|.
135 GeolocationNotificationObserver(
136 bool wait_for_prompt, MockPermissionBubbleView* view);
137 ~GeolocationNotificationObserver() override;
139 // content::NotificationObserver:
140 void Observe(int type,
141 const content::NotificationSource& source,
142 const content::NotificationDetails& details) override;
144 // Note: also runs the 'geoStart' method in the test JS script.
145 void AddWatchAndWaitForNotification(
146 content::RenderFrameHost* render_frame_host);
148 bool has_infobar() const { return !!infobar_; }
149 infobars::InfoBar* infobar() { return infobar_; }
151 private:
152 content::NotificationRegistrar registrar_;
153 bool wait_for_prompt_;
154 infobars::InfoBar* infobar_;
155 bool navigation_started_;
156 bool navigation_completed_;
157 std::string javascript_response_;
158 MockPermissionBubbleView* mock_view_;
160 DISALLOW_COPY_AND_ASSIGN(GeolocationNotificationObserver);
163 GeolocationNotificationObserver::GeolocationNotificationObserver(
164 bool wait_for_prompt,
165 MockPermissionBubbleView* view)
166 : wait_for_prompt_(wait_for_prompt),
167 infobar_(nullptr),
168 navigation_started_(false),
169 navigation_completed_(false),
170 mock_view_(view) {
171 registrar_.Add(this, content::NOTIFICATION_DOM_OPERATION_RESPONSE,
172 content::NotificationService::AllSources());
173 if (wait_for_prompt && !PermissionBubbleManager::Enabled()) {
174 registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
175 content::NotificationService::AllSources());
176 } else if (!wait_for_prompt) {
177 registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
178 content::NotificationService::AllSources());
179 registrar_.Add(this, content::NOTIFICATION_LOAD_START,
180 content::NotificationService::AllSources());
181 registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
182 content::NotificationService::AllSources());
184 mock_view_->SetBrowserTest(true);
187 GeolocationNotificationObserver::~GeolocationNotificationObserver() {
190 void GeolocationNotificationObserver::Observe(
191 int type,
192 const content::NotificationSource& source,
193 const content::NotificationDetails& details) {
194 if (type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED) {
195 infobar_ = content::Details<infobars::InfoBar::AddedDetails>(details).ptr();
196 ASSERT_FALSE(infobar_->delegate()->GetIcon().IsEmpty());
197 ASSERT_TRUE(infobar_->delegate()->AsConfirmInfoBarDelegate());
198 } else if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) {
199 content::Details<DomOperationNotificationDetails> dom_op_details(details);
200 javascript_response_ = dom_op_details->json;
201 LOG(WARNING) << "javascript_response " << javascript_response_;
202 if (wait_for_prompt_ && PermissionBubbleManager::Enabled())
203 base::MessageLoopForUI::current()->Quit();
204 } else if ((type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) ||
205 (type == content::NOTIFICATION_LOAD_START)) {
206 navigation_started_ = true;
207 } else if ((type == content::NOTIFICATION_LOAD_STOP) && navigation_started_) {
208 navigation_started_ = false;
209 navigation_completed_ = true;
212 // We're either waiting for just the infobar, or for both a javascript
213 // prompt and response.
214 if ((wait_for_prompt_ && infobar_ && !PermissionBubbleManager::Enabled()) ||
215 (navigation_completed_ && !javascript_response_.empty()))
216 base::MessageLoopForUI::current()->Quit();
219 void GeolocationNotificationObserver::AddWatchAndWaitForNotification(
220 content::RenderFrameHost* render_frame_host) {
221 if (!PermissionBubbleManager::Enabled()) {
222 LOG(WARNING) << "will add geolocation watch";
223 std::string script(
224 "window.domAutomationController.setAutomationId(0);"
225 "window.domAutomationController.send(geoStart());");
226 render_frame_host->ExecuteJavaScript(base::UTF8ToUTF16(script));
227 content::RunMessageLoop();
228 registrar_.RemoveAll();
229 LOG(WARNING) << "got geolocation watch" << javascript_response_;
230 EXPECT_NE("\"0\"", javascript_response_);
231 EXPECT_TRUE(
232 wait_for_prompt_ ? (infobar_ != nullptr) : navigation_completed_);
233 } else {
234 LOG(WARNING) << "will add geolocation watch for bubble";
235 std::string script(
236 "window.domAutomationController.setAutomationId(0);"
237 "window.domAutomationController.send(geoStart());");
238 render_frame_host->ExecuteJavaScript(base::UTF8ToUTF16(script));
239 content::RunMessageLoop();
240 while (wait_for_prompt_ && !mock_view_->IsVisible())
241 content::RunMessageLoop();
245 } // namespace
248 // GeolocationBrowserTest -----------------------------------------------------
250 // This is a browser test for Geolocation.
251 // It exercises various integration points from javascript <-> browser:
252 // 1. Prompt is displayed when a geolocation is requested from an unauthorized
253 // origin.
254 // 2. Denying the request triggers the correct error callback.
255 // 3. Allowing the request does not trigger an error, and allow a geoposition to
256 // be passed to javascript.
257 // 4. Permissions persisted in disk are respected.
258 // 5. Incognito profiles don't use saved permissions.
259 class GeolocationBrowserTest : public InProcessBrowserTest,
260 public testing::WithParamInterface<bool> {
261 public:
262 enum InitializationOptions {
263 INITIALIZATION_NONE,
264 INITIALIZATION_OFFTHERECORD,
265 INITIALIZATION_NEWTAB,
266 INITIALIZATION_IFRAMES,
269 GeolocationBrowserTest();
270 ~GeolocationBrowserTest() override;
272 // InProcessBrowserTest:
273 void SetUpOnMainThread() override;
274 void TearDownInProcessBrowserTestFixture() override;
276 Browser* current_browser() { return current_browser_; }
277 void set_html_for_tests(const std::string& html_for_tests) {
278 html_for_tests_ = html_for_tests;
280 content::RenderFrameHost* frame_host() const { return render_frame_host_; }
281 const GURL& current_url() const { return current_url_; }
282 const GURL& iframe_url(size_t i) const { return iframe_urls_[i]; }
283 double fake_latitude() const { return fake_latitude_; }
284 double fake_longitude() const { return fake_longitude_; }
286 // Initializes the test server and navigates to the initial url.
287 bool Initialize(InitializationOptions options) WARN_UNUSED_RESULT;
289 // Loads the specified number of iframes.
290 void LoadIFrames(int number_iframes);
292 // Specifies which frame is to be used for JavaScript calls.
293 void SetFrameHost(const std::string& frame_name);
295 // Start watching for geolocation notifications. If |wait_for_prompt| is
296 // true, wait for the prompt (infobar or bubble) to be displayed. Otherwise
297 // wait for a javascript response.
298 void AddGeolocationWatch(bool wait_for_prompt);
300 // Checks that no errors have been received in javascript, and checks that the
301 // position most recently received in javascript matches |latitude| and
302 // |longitude|.
303 void CheckGeoposition(double latitude, double longitude);
305 // For |requesting_url| if |allowed| is true accept the prompt. Otherwise
306 // cancel it.
307 void SetPromptResponse(const GURL& requesting_url, bool allowed);
309 // Executes |function| in |render_frame_host| and checks that the return value
310 // matches |expected|.
311 void CheckStringValueFromJavascriptForFrame(
312 const std::string& expected,
313 const std::string& function,
314 content::RenderFrameHost* render_frame_host);
316 // Executes |function| and checks that the return value matches |expected|.
317 void CheckStringValueFromJavascript(const std::string& expected,
318 const std::string& function);
320 // Sets a new position and sends a notification with the new position.
321 void NotifyGeoposition(double latitude, double longitude);
323 // Convenience method to look up the number of queued permission bubbles.
324 int GetBubblesQueueSize(PermissionBubbleManager* mgr);
326 private:
327 infobars::InfoBar* infobar_;
328 Browser* current_browser_;
329 // path element of a URL referencing the html content for this test.
330 std::string html_for_tests_;
331 // This member defines the frame where the JavaScript calls will run.
332 content::RenderFrameHost* render_frame_host_;
333 // The current url for the top level page.
334 GURL current_url_;
335 // If not empty, the GURLs for the iframes loaded by LoadIFrames().
336 std::vector<GURL> iframe_urls_;
337 double fake_latitude_;
338 double fake_longitude_;
339 MockPermissionBubbleView mock_bubble_view_;
341 DISALLOW_COPY_AND_ASSIGN(GeolocationBrowserTest);
344 GeolocationBrowserTest::GeolocationBrowserTest()
345 : infobar_(nullptr),
346 current_browser_(nullptr),
347 html_for_tests_("/geolocation/simple.html"),
348 render_frame_host_(nullptr),
349 fake_latitude_(1.23),
350 fake_longitude_(4.56) {
353 GeolocationBrowserTest::~GeolocationBrowserTest() {
356 void GeolocationBrowserTest::SetUpOnMainThread() {
357 ui_test_utils::OverrideGeolocation(fake_latitude_, fake_longitude_);
358 #if !defined(OS_ANDROID)
359 if (GetParam()) {
360 base::CommandLine::ForCurrentProcess()->AppendSwitch(
361 switches::kEnablePermissionsBubbles);
362 EXPECT_TRUE(PermissionBubbleManager::Enabled());
363 } else {
364 base::CommandLine::ForCurrentProcess()->AppendSwitch(
365 switches::kDisablePermissionsBubbles);
366 EXPECT_FALSE(PermissionBubbleManager::Enabled());
368 #endif
371 void GeolocationBrowserTest::TearDownInProcessBrowserTestFixture() {
372 LOG(WARNING) << "TearDownInProcessBrowserTestFixture. Test Finished.";
375 bool GeolocationBrowserTest::Initialize(InitializationOptions options) {
376 if (!embedded_test_server()->Started() &&
377 !embedded_test_server()->InitializeAndWaitUntilReady()) {
378 ADD_FAILURE() << "Test server failed to start.";
379 return false;
382 current_url_ = embedded_test_server()->GetURL(html_for_tests_);
383 LOG(WARNING) << "before navigate";
384 if (options == INITIALIZATION_OFFTHERECORD) {
385 current_browser_ = ui_test_utils::OpenURLOffTheRecord(
386 browser()->profile(), current_url_);
387 } else {
388 current_browser_ = browser();
389 if (options == INITIALIZATION_NEWTAB)
390 chrome::NewTab(current_browser_);
392 WebContents* web_contents =
393 current_browser_->tab_strip_model()->GetActiveWebContents();
394 PermissionBubbleManager::FromWebContents(web_contents)->SetView(
395 &mock_bubble_view_);
396 if (options != INITIALIZATION_OFFTHERECORD)
397 ui_test_utils::NavigateToURL(current_browser_, current_url_);
398 LOG(WARNING) << "after navigate";
400 EXPECT_TRUE(current_browser_);
401 return !!current_browser_;
404 void GeolocationBrowserTest::LoadIFrames(int number_iframes) {
405 // Limit to 3 iframes.
406 DCHECK_LT(0, number_iframes);
407 DCHECK_LE(number_iframes, 3);
408 iframe_urls_.resize(number_iframes);
409 for (int i = 0; i < number_iframes; ++i) {
410 IFrameLoader loader(current_browser_, i, GURL());
411 iframe_urls_[i] = loader.iframe_url();
415 void GeolocationBrowserTest::SetFrameHost(const std::string& frame_name) {
416 WebContents* web_contents =
417 current_browser_->tab_strip_model()->GetActiveWebContents();
418 render_frame_host_ = nullptr;
420 if (frame_name.empty()) {
421 render_frame_host_ = web_contents->GetMainFrame();
422 } else {
423 render_frame_host_ = content::FrameMatchingPredicate(
424 web_contents, base::Bind(&content::FrameMatchesName, frame_name));
426 DCHECK(render_frame_host_);
429 void GeolocationBrowserTest::AddGeolocationWatch(bool wait_for_prompt) {
430 GeolocationNotificationObserver notification_observer(
431 wait_for_prompt, &mock_bubble_view_);
432 notification_observer.AddWatchAndWaitForNotification(render_frame_host_);
433 if (wait_for_prompt && !PermissionBubbleManager::Enabled()) {
434 EXPECT_TRUE(notification_observer.has_infobar());
435 infobar_ = notification_observer.infobar();
439 void GeolocationBrowserTest::CheckGeoposition(double latitude,
440 double longitude) {
441 // Checks we have no error.
442 CheckStringValueFromJavascript("0", "geoGetLastError()");
443 CheckStringValueFromJavascript(base::DoubleToString(latitude),
444 "geoGetLastPositionLatitude()");
445 CheckStringValueFromJavascript(base::DoubleToString(longitude),
446 "geoGetLastPositionLongitude()");
449 void GeolocationBrowserTest::SetPromptResponse(const GURL& requesting_url,
450 bool allowed) {
451 WebContents* web_contents =
452 current_browser_->tab_strip_model()->GetActiveWebContents();
453 TabSpecificContentSettings* content_settings =
454 TabSpecificContentSettings::FromWebContents(web_contents);
455 const ContentSettingsUsagesState& usages_state =
456 content_settings->geolocation_usages_state();
457 size_t state_map_size = usages_state.state_map().size();
459 if (PermissionBubbleManager::Enabled()) {
460 if (allowed)
461 mock_bubble_view_.Accept();
462 else
463 mock_bubble_view_.Deny();
465 EXPECT_GT(usages_state.state_map().size(), state_map_size);
466 GURL requesting_origin(requesting_url.GetOrigin());
467 EXPECT_EQ(1U, usages_state.state_map().count(requesting_origin));
468 ContentSetting expected_setting =
469 allowed ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK;
470 EXPECT_EQ(expected_setting,
471 usages_state.state_map().find(requesting_origin)->second);
472 content::RunAllPendingInMessageLoop();
473 LOG(WARNING) << "set permission bubble response";
474 } else {
475 ASSERT_TRUE(infobar_);
476 LOG(WARNING) << "will set infobar response";
478 content::WindowedNotificationObserver observer(
479 content::NOTIFICATION_LOAD_STOP,
480 content::Source<NavigationController>(
481 &web_contents->GetController()));
482 if (allowed)
483 infobar_->delegate()->AsConfirmInfoBarDelegate()->Accept();
484 else
485 infobar_->delegate()->AsConfirmInfoBarDelegate()->Cancel();
486 observer.Wait();
489 InfoBarService* infobar_service =
490 InfoBarService::FromWebContents(web_contents);
491 infobar_service->RemoveInfoBar(infobar_);
492 LOG(WARNING) << "infobar response set";
493 infobar_ = nullptr;
494 EXPECT_GT(usages_state.state_map().size(), state_map_size);
495 GURL requesting_origin(requesting_url.GetOrigin());
496 EXPECT_EQ(1U, usages_state.state_map().count(requesting_origin));
497 ContentSetting expected_setting =
498 allowed ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK;
499 EXPECT_EQ(expected_setting,
500 usages_state.state_map().find(requesting_origin)->second);
504 void GeolocationBrowserTest::CheckStringValueFromJavascriptForFrame(
505 const std::string& expected,
506 const std::string& function,
507 content::RenderFrameHost* render_frame_host) {
508 std::string script(base::StringPrintf(
509 "window.domAutomationController.send(%s)", function.c_str()));
510 std::string result;
511 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
512 render_frame_host, script, &result));
513 EXPECT_EQ(expected, result);
516 void GeolocationBrowserTest::CheckStringValueFromJavascript(
517 const std::string& expected,
518 const std::string& function) {
519 CheckStringValueFromJavascriptForFrame(
520 expected, function, render_frame_host_);
523 void GeolocationBrowserTest::NotifyGeoposition(double latitude,
524 double longitude) {
525 fake_latitude_ = latitude;
526 fake_longitude_ = longitude;
527 ui_test_utils::OverrideGeolocation(latitude, longitude);
528 LOG(WARNING) << "MockLocationProvider listeners updated";
531 int GeolocationBrowserTest::GetBubblesQueueSize(PermissionBubbleManager* mgr) {
532 return static_cast<int>(mgr->requests_.size());
535 // Tests ----------------------------------------------------------------------
537 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, DisplaysPrompt) {
538 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
539 SetFrameHost("");
540 AddGeolocationWatch(true);
543 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, Geoposition) {
544 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
545 SetFrameHost("");
546 AddGeolocationWatch(true);
547 SetPromptResponse(current_url(), true);
548 CheckGeoposition(fake_latitude(), fake_longitude());
551 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest,
552 ErrorOnPermissionDenied) {
553 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
554 SetFrameHost("");
555 AddGeolocationWatch(true);
556 // Prompt was displayed, deny access and check for error code.
557 SetPromptResponse(current_url(), false);
558 CheckStringValueFromJavascript("1", "geoGetLastError()");
561 // See http://crbug.com/308358
562 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, DISABLED_NoPromptForSecondTab) {
563 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
564 SetFrameHost("");
565 AddGeolocationWatch(true);
566 SetPromptResponse(current_url(), true);
567 // Disables further prompts from this tab.
568 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
570 // Checks infobar will not be created in a second tab.
571 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB));
572 SetFrameHost("");
573 AddGeolocationWatch(false);
574 CheckGeoposition(fake_latitude(), fake_longitude());
577 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, NoPromptForDeniedOrigin) {
578 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
579 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
580 ContentSettingsPattern::FromURLNoWildcard(current_url()),
581 ContentSettingsPattern::FromURLNoWildcard(current_url()),
582 CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), CONTENT_SETTING_BLOCK);
583 SetFrameHost("");
584 AddGeolocationWatch(false);
585 // Checks we have an error for this denied origin.
586 CheckStringValueFromJavascript("1", "geoGetLastError()");
587 // Checks prompt will not be created a second tab.
588 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB));
589 SetFrameHost("");
590 AddGeolocationWatch(false);
591 CheckStringValueFromJavascript("1", "geoGetLastError()");
594 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, NoPromptForAllowedOrigin) {
595 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
596 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
597 ContentSettingsPattern::FromURLNoWildcard(current_url()),
598 ContentSettingsPattern::FromURLNoWildcard(current_url()),
599 CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), CONTENT_SETTING_ALLOW);
600 // Checks no prompt will be created and there's no error callback.
601 SetFrameHost("");
602 AddGeolocationWatch(false);
603 CheckGeoposition(fake_latitude(), fake_longitude());
606 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, NoPromptForOffTheRecord) {
607 // First, check prompt will be created for regular profile
608 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
609 SetFrameHost("");
610 AddGeolocationWatch(true);
611 // Response will be persisted.
612 SetPromptResponse(current_url(), true);
613 CheckGeoposition(fake_latitude(), fake_longitude());
614 // Disables further prompts from this tab.
615 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
616 // Go incognito, and checks no prompt will be created.
617 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD));
618 SetFrameHost("");
619 AddGeolocationWatch(false);
620 CheckGeoposition(fake_latitude(), fake_longitude());
623 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, NoLeakFromOffTheRecord) {
624 // First, check prompt will be created for incognito profile.
625 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD));
626 SetFrameHost("");
627 AddGeolocationWatch(true);
628 // Response won't be persisted.
629 SetPromptResponse(current_url(), true);
630 CheckGeoposition(fake_latitude(), fake_longitude());
631 // Disables further prompts from this tab.
632 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
633 // Go to the regular profile, prompt will be created.
634 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
635 SetFrameHost("");
636 AddGeolocationWatch(true);
637 SetPromptResponse(current_url(), false);
638 CheckStringValueFromJavascript("1", "geoGetLastError()");
641 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, IFramesWithFreshPosition) {
642 set_html_for_tests("/geolocation/iframes_different_origin.html");
643 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
644 LoadIFrames(2);
645 LOG(WARNING) << "frames loaded";
647 SetFrameHost("iframe_0");
648 AddGeolocationWatch(true);
649 SetPromptResponse(iframe_url(0), true);
650 CheckGeoposition(fake_latitude(), fake_longitude());
651 // Disables further prompts from this iframe.
652 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
654 // Test second iframe from a different origin with a cached geoposition will
655 // create the prompt.
656 SetFrameHost("iframe_1");
657 AddGeolocationWatch(true);
659 // Back to the first frame, enable navigation and refresh geoposition.
660 SetFrameHost("iframe_0");
661 CheckStringValueFromJavascript("1", "geoSetMaxNavigateCount(1)");
662 double fresh_position_latitude = 3.17;
663 double fresh_position_longitude = 4.23;
664 content::WindowedNotificationObserver observer(
665 content::NOTIFICATION_LOAD_STOP,
666 content::Source<NavigationController>(
667 &current_browser()->tab_strip_model()->GetActiveWebContents()->
668 GetController()));
669 NotifyGeoposition(fresh_position_latitude, fresh_position_longitude);
670 observer.Wait();
671 CheckGeoposition(fresh_position_latitude, fresh_position_longitude);
673 // Disable navigation for this frame.
674 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
676 // Now go ahead an authorize the second frame.
677 SetFrameHost("iframe_1");
678 // Infobar was displayed, allow access and check there's no error code.
679 SetPromptResponse(iframe_url(1), true);
680 LOG(WARNING) << "Checking position...";
681 CheckGeoposition(fresh_position_latitude, fresh_position_longitude);
682 LOG(WARNING) << "...done.";
685 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest,
686 IFramesWithCachedPosition) {
687 set_html_for_tests("/geolocation/iframes_different_origin.html");
688 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
689 LoadIFrames(2);
691 SetFrameHost("iframe_0");
692 AddGeolocationWatch(true);
693 SetPromptResponse(iframe_url(0), true);
694 CheckGeoposition(fake_latitude(), fake_longitude());
696 // Refresh geoposition, but let's not yet create the watch on the second frame
697 // so that it'll fetch from cache.
698 double cached_position_latitude = 5.67;
699 double cached_position_lognitude = 8.09;
700 content::WindowedNotificationObserver observer(
701 content::NOTIFICATION_LOAD_STOP,
702 content::Source<NavigationController>(
703 &current_browser()->tab_strip_model()->GetActiveWebContents()->
704 GetController()));
705 NotifyGeoposition(cached_position_latitude, cached_position_lognitude);
706 observer.Wait();
707 CheckGeoposition(cached_position_latitude, cached_position_lognitude);
709 // Disable navigation for this frame.
710 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
712 // Now go ahead and authorize the second frame.
713 SetFrameHost("iframe_1");
714 AddGeolocationWatch(true);
715 // WebKit will use its cache, but we also broadcast a position shortly
716 // afterwards. We're only interested in the first navigation for the success
717 // callback from the cached position.
718 CheckStringValueFromJavascript("1", "geoSetMaxNavigateCount(1)");
719 SetPromptResponse(iframe_url(1), true);
720 CheckGeoposition(cached_position_latitude, cached_position_lognitude);
723 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, CancelPermissionForFrame) {
724 set_html_for_tests("/geolocation/iframes_different_origin.html");
725 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
726 LoadIFrames(2);
727 LOG(WARNING) << "frames loaded";
729 SetFrameHost("iframe_0");
730 AddGeolocationWatch(true);
731 SetPromptResponse(iframe_url(0), true);
732 CheckGeoposition(fake_latitude(), fake_longitude());
733 // Disables further prompts from this iframe.
734 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
736 // Test second iframe from a different origin with a cached geoposition will
737 // create the prompt.
738 SetFrameHost("iframe_1");
739 AddGeolocationWatch(true);
741 // Change the iframe, and ensure the prompt is gone.
742 if (PermissionBubbleManager::Enabled()) {
743 WebContents* web_contents =
744 current_browser()->tab_strip_model()->GetActiveWebContents();
745 int num_bubbles_before_cancel = GetBubblesQueueSize(
746 PermissionBubbleManager::FromWebContents(web_contents));
747 IFrameLoader change_iframe_1(current_browser(), 1, current_url());
748 int num_bubbles_after_cancel = GetBubblesQueueSize(
749 PermissionBubbleManager::FromWebContents(web_contents));
750 EXPECT_EQ(num_bubbles_before_cancel, num_bubbles_after_cancel + 1);
751 } else {
752 InfoBarService* infobar_service = InfoBarService::FromWebContents(
753 current_browser()->tab_strip_model()->GetActiveWebContents());
754 size_t num_infobars_before_cancel = infobar_service->infobar_count();
755 IFrameLoader change_iframe_1(current_browser(), 1, current_url());
756 size_t num_infobars_after_cancel = infobar_service->infobar_count();
757 EXPECT_EQ(num_infobars_before_cancel, num_infobars_after_cancel + 1);
761 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, InvalidUrlRequest) {
762 // Tests that an invalid URL (e.g. from a popup window) is rejected
763 // correctly. Also acts as a regression test for http://crbug.com/40478
764 set_html_for_tests("/geolocation/invalid_request_url.html");
765 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
767 SetFrameHost("");
768 WebContents* original_tab =
769 current_browser()->tab_strip_model()->GetActiveWebContents();
770 CheckStringValueFromJavascript("1", "requestGeolocationFromInvalidUrl()");
771 CheckStringValueFromJavascriptForFrame("1", "isAlive()",
772 original_tab->GetMainFrame());
775 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, NoPromptBeforeStart) {
776 // See http://crbug.com/42789
777 set_html_for_tests("/geolocation/iframes_different_origin.html");
778 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
779 LoadIFrames(2);
780 LOG(WARNING) << "frames loaded";
782 // Access navigator.geolocation, but ensure it won't request permission.
783 SetFrameHost("iframe_1");
784 CheckStringValueFromJavascript("object", "geoAccessNavigatorGeolocation()");
786 SetFrameHost("iframe_0");
787 AddGeolocationWatch(true);
788 SetPromptResponse(iframe_url(0), true);
789 CheckGeoposition(fake_latitude(), fake_longitude());
790 CheckStringValueFromJavascript("0", "geoSetMaxNavigateCount(0)");
792 // Permission should be requested after adding a watch.
793 SetFrameHost("iframe_1");
794 AddGeolocationWatch(true);
795 SetPromptResponse(iframe_url(1), true);
796 CheckGeoposition(fake_latitude(), fake_longitude());
799 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, TwoWatchesInOneFrame) {
800 set_html_for_tests("/geolocation/two_watches.html");
801 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
803 // First, set the JavaScript to navigate when it receives |final_position|.
804 double final_position_latitude = 3.17;
805 double final_position_longitude = 4.23;
806 std::string script = base::StringPrintf(
807 "window.domAutomationController.send(geoSetFinalPosition(%f, %f))",
808 final_position_latitude, final_position_longitude);
809 std::string js_result;
810 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
811 current_browser()->tab_strip_model()->GetActiveWebContents(), script,
812 &js_result));
813 EXPECT_EQ(js_result, "ok");
815 // Send a position which both geolocation watches will receive.
816 SetFrameHost("");
817 AddGeolocationWatch(true);
818 SetPromptResponse(current_url(), true);
819 CheckGeoposition(fake_latitude(), fake_longitude());
821 // The second watch will now have cancelled. Ensure an update still makes
822 // its way through to the first watcher.
823 content::WindowedNotificationObserver observer(
824 content::NOTIFICATION_LOAD_STOP,
825 content::Source<NavigationController>(
826 &current_browser()->tab_strip_model()->GetActiveWebContents()->
827 GetController()));
828 NotifyGeoposition(final_position_latitude, final_position_longitude);
829 observer.Wait();
830 CheckGeoposition(final_position_latitude, final_position_longitude);
833 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, TabDestroyed) {
834 // This test triggers crbug.com/433877.
835 // TODO(felt): Reenable this test for permission bubbles once that's fixed.
836 if (PermissionBubbleManager::Enabled()) return;
838 set_html_for_tests("/geolocation/tab_destroyed.html");
839 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
840 LoadIFrames(3);
842 SetFrameHost("iframe_0");
843 AddGeolocationWatch(true);
845 SetFrameHost("iframe_1");
846 AddGeolocationWatch(false);
848 SetFrameHost("iframe_2");
849 AddGeolocationWatch(false);
851 std::string script =
852 "window.domAutomationController.send(window.close());";
853 bool result = content::ExecuteScript(
854 current_browser()->tab_strip_model()->GetActiveWebContents(), script);
855 EXPECT_EQ(result, true);
858 IN_PROC_BROWSER_TEST_P(GeolocationBrowserTest, LastUsageUpdated) {
859 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
860 base::SimpleTestClock* clock_ = new base::SimpleTestClock();
861 current_browser()
862 ->profile()
863 ->GetHostContentSettingsMap()
864 ->SetPrefClockForTesting(scoped_ptr<base::Clock>(clock_));
865 clock_->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10));
867 // Setting the permission should trigger the last usage.
868 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
869 ContentSettingsPattern::FromURLNoWildcard(current_url()),
870 ContentSettingsPattern::FromURLNoWildcard(current_url()),
871 CONTENT_SETTINGS_TYPE_GEOLOCATION,
872 std::string(),
873 CONTENT_SETTING_ALLOW);
875 // Permission has been used at the starting time.
876 EXPECT_EQ(current_browser()
877 ->profile()
878 ->GetHostContentSettingsMap()
879 ->GetLastUsage(current_url().GetOrigin(),
880 current_url().GetOrigin(),
881 CONTENT_SETTINGS_TYPE_GEOLOCATION)
882 .ToDoubleT(),
883 10);
885 clock_->Advance(base::TimeDelta::FromSeconds(3));
887 // Watching should trigger the last usage update.
888 SetFrameHost("");
889 AddGeolocationWatch(false);
890 CheckGeoposition(fake_latitude(), fake_longitude());
892 // Last usage has been updated.
893 EXPECT_EQ(current_browser()
894 ->profile()
895 ->GetHostContentSettingsMap()
896 ->GetLastUsage(current_url().GetOrigin(),
897 current_url().GetOrigin(),
898 CONTENT_SETTINGS_TYPE_GEOLOCATION)
899 .ToDoubleT(),
900 13);
903 INSTANTIATE_TEST_CASE_P(GeolocationBrowserTestWithParams,
904 GeolocationBrowserTest,
905 testing::Values(false));