Make sure the win_chromium_gn_x64_dbg bot is using symbol_level=1
[chromium-blink-merge.git] / chrome / browser / geolocation / geolocation_browsertest.cc
blob4d33d0bc3e44764e1787d95d03d58c95c8df539f
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/profiles/profile.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/browser_commands.h"
19 #include "chrome/browser/ui/tabs/tab_strip_model.h"
20 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
21 #include "chrome/common/chrome_paths.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/test/base/in_process_browser_test.h"
24 #include "chrome/test/base/ui_test_utils.h"
25 #include "components/content_settings/core/browser/content_settings_usages_state.h"
26 #include "components/content_settings/core/browser/host_content_settings_map.h"
27 #include "components/content_settings/core/common/content_settings_pattern.h"
28 #include "content/public/browser/dom_operation_notification_details.h"
29 #include "content/public/browser/navigation_controller.h"
30 #include "content/public/browser/notification_details.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/render_frame_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "content/public/test/browser_test_utils.h"
35 #include "net/base/net_util.h"
36 #include "net/test/embedded_test_server/embedded_test_server.h"
38 using content::DomOperationNotificationDetails;
39 using content::NavigationController;
40 using content::WebContents;
42 namespace {
44 // IFrameLoader ---------------------------------------------------------------
46 // Used to block until an iframe is loaded via a javascript call.
47 // Note: NavigateToURLBlockUntilNavigationsComplete doesn't seem to work for
48 // multiple embedded iframes, as notifications seem to be 'batched'. Instead, we
49 // load and wait one single frame here by calling a javascript function.
50 class IFrameLoader : public content::NotificationObserver {
51 public:
52 IFrameLoader(Browser* browser, int iframe_id, const GURL& url);
53 ~IFrameLoader() override;
55 // content::NotificationObserver:
56 void Observe(int type,
57 const content::NotificationSource& source,
58 const content::NotificationDetails& details) override;
60 const GURL& iframe_url() const { return iframe_url_; }
62 private:
63 content::NotificationRegistrar registrar_;
65 // If true the navigation has completed.
66 bool navigation_completed_;
68 // If true the javascript call has completed.
69 bool javascript_completed_;
71 std::string javascript_response_;
73 // The URL for the iframe we just loaded.
74 GURL iframe_url_;
76 DISALLOW_COPY_AND_ASSIGN(IFrameLoader);
79 IFrameLoader::IFrameLoader(Browser* browser, int iframe_id, const GURL& url)
80 : navigation_completed_(false),
81 javascript_completed_(false) {
82 WebContents* web_contents =
83 browser->tab_strip_model()->GetActiveWebContents();
84 NavigationController* controller = &web_contents->GetController();
85 registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
86 content::Source<NavigationController>(controller));
87 registrar_.Add(this, content::NOTIFICATION_DOM_OPERATION_RESPONSE,
88 content::NotificationService::AllSources());
89 std::string script(base::StringPrintf(
90 "window.domAutomationController.setAutomationId(0);"
91 "window.domAutomationController.send(addIFrame(%d, \"%s\"));",
92 iframe_id, url.spec().c_str()));
93 web_contents->GetMainFrame()->ExecuteJavaScriptForTests(
94 base::UTF8ToUTF16(script));
95 content::RunMessageLoop();
97 EXPECT_EQ(base::StringPrintf("\"%d\"", iframe_id), javascript_response_);
98 registrar_.RemoveAll();
99 // Now that we loaded the iframe, let's fetch its src.
100 script = base::StringPrintf(
101 "window.domAutomationController.send(getIFrameSrc(%d))", iframe_id);
102 std::string iframe_src;
103 EXPECT_TRUE(content::ExecuteScriptAndExtractString(web_contents, script,
104 &iframe_src));
105 iframe_url_ = GURL(iframe_src);
108 IFrameLoader::~IFrameLoader() {
111 void IFrameLoader::Observe(int type,
112 const content::NotificationSource& source,
113 const content::NotificationDetails& details) {
114 if (type == content::NOTIFICATION_LOAD_STOP) {
115 navigation_completed_ = true;
116 } else if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) {
117 content::Details<DomOperationNotificationDetails> dom_op_details(details);
118 javascript_response_ = dom_op_details->json;
119 javascript_completed_ = true;
121 if (javascript_completed_ && navigation_completed_)
122 base::MessageLoopForUI::current()->Quit();
125 // PermissionRequestObserver ---------------------------------------------------
127 // Used to observe the creation of permission prompt without responding.
128 class PermissionRequestObserver : public PermissionBubbleManager::Observer {
129 public:
130 explicit PermissionRequestObserver(content::WebContents* web_contents)
131 : bubble_manager_(PermissionBubbleManager::FromWebContents(web_contents)),
132 request_shown_(false),
133 message_loop_runner_(new content::MessageLoopRunner) {
134 bubble_manager_->AddObserver(this);
136 ~PermissionRequestObserver() override {
137 // Safe to remove twice if it happens.
138 bubble_manager_->RemoveObserver(this);
141 void Wait() { message_loop_runner_->Run(); }
143 bool request_shown() { return request_shown_; }
145 private:
146 // PermissionBubbleManager::Observer
147 void OnBubbleAdded() override {
148 request_shown_ = true;
149 bubble_manager_->RemoveObserver(this);
150 message_loop_runner_->Quit();
153 PermissionBubbleManager* bubble_manager_;
154 bool request_shown_;
155 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
157 DISALLOW_COPY_AND_ASSIGN(PermissionRequestObserver);
160 } // namespace
163 // GeolocationBrowserTest -----------------------------------------------------
165 // This is a browser test for Geolocation.
166 // It exercises various integration points from javascript <-> browser:
167 // 1. Prompt is displayed when a geolocation is requested from an unauthorized
168 // origin.
169 // 2. Denying the request triggers the correct error callback.
170 // 3. Allowing the request does not trigger an error, and allow a geoposition to
171 // be passed to javascript.
172 // 4. Permissions persisted in disk are respected.
173 // 5. Incognito profiles don't use saved permissions.
174 class GeolocationBrowserTest : public InProcessBrowserTest {
175 public:
176 enum InitializationOptions {
177 INITIALIZATION_NONE,
178 INITIALIZATION_OFFTHERECORD,
179 INITIALIZATION_NEWTAB,
180 INITIALIZATION_IFRAMES,
183 GeolocationBrowserTest();
184 ~GeolocationBrowserTest() override;
186 // InProcessBrowserTest:
187 void SetUpOnMainThread() override;
188 void TearDownInProcessBrowserTestFixture() override;
190 Browser* current_browser() { return current_browser_; }
191 void set_html_for_tests(const std::string& html_for_tests) {
192 html_for_tests_ = html_for_tests;
194 content::RenderFrameHost* frame_host() const { return render_frame_host_; }
195 const GURL& current_url() const { return current_url_; }
196 const GURL& iframe_url(size_t i) const { return iframe_urls_[i]; }
197 double fake_latitude() const { return fake_latitude_; }
198 double fake_longitude() const { return fake_longitude_; }
200 // Initializes the test server and navigates to the initial url.
201 bool Initialize(InitializationOptions options) WARN_UNUSED_RESULT;
203 // Loads the specified number of iframes.
204 void LoadIFrames(int number_iframes);
206 // Specifies which frame is to be used for JavaScript calls.
207 void SetFrameHost(const std::string& frame_name);
209 // Check geolocation and accept or deny the resulting permission bubble.
210 // Returns |true| if the expected behavior happened.
211 bool RequestAndAcceptPermission() WARN_UNUSED_RESULT;
212 bool RequestAndDenyPermission() WARN_UNUSED_RESULT;
214 // Check geolocation and observe whether the permission bubble was shown.
215 // Callers should set |bubble_should_display| to |true| if they expect a
216 // bubble to display.
217 void RequestPermissionAndObserve(bool bubble_should_display);
219 // Checks that no errors have been received in javascript, and checks that the
220 // position most recently received in javascript matches |latitude| and
221 // |longitude|.
222 void CheckGeoposition(double latitude, double longitude);
224 // Checks whether a coordinate change has been registered yet (and waits if
225 // it hasn't). After sending new geoposition coordinates, call this before
226 // CheckGeoposition to avoid a race condition.
227 bool CheckGeopositionUpdated() WARN_UNUSED_RESULT;
229 // Executes |function| in |render_frame_host| and checks that the return value
230 // matches |expected|.
231 void CheckStringValueFromJavascriptForFrame(
232 const std::string& expected,
233 const std::string& function,
234 content::RenderFrameHost* render_frame_host);
236 // Executes |function| and checks that the return value matches |expected|.
237 void CheckStringValueFromJavascript(const std::string& expected,
238 const std::string& function);
240 // Sets a new position and sends a notification with the new position. Call
241 // CheckGeopositionReadyCallback after this to make sure that the value has
242 // been received by the JavaScript.
243 void NotifyGeoposition(double latitude, double longitude);
245 // Convenience method to look up the number of queued permission bubbles.
246 int GetBubblesQueueSize(PermissionBubbleManager* mgr);
248 private:
249 std::string RequestAndRespondToPermission(
250 PermissionBubbleManager::AutoResponseType bubble_response);
252 Browser* current_browser_;
253 // path element of a URL referencing the html content for this test.
254 std::string html_for_tests_;
255 // This member defines the frame where the JavaScript calls will run.
256 content::RenderFrameHost* render_frame_host_;
257 // The current url for the top level page.
258 GURL current_url_;
259 // If not empty, the GURLs for the iframes loaded by LoadIFrames().
260 std::vector<GURL> iframe_urls_;
261 double fake_latitude_;
262 double fake_longitude_;
264 DISALLOW_COPY_AND_ASSIGN(GeolocationBrowserTest);
267 GeolocationBrowserTest::GeolocationBrowserTest()
268 : current_browser_(nullptr),
269 html_for_tests_("/geolocation/simple.html"),
270 render_frame_host_(nullptr),
271 fake_latitude_(1.23),
272 fake_longitude_(4.56) {
275 GeolocationBrowserTest::~GeolocationBrowserTest() {
278 void GeolocationBrowserTest::SetUpOnMainThread() {
279 ui_test_utils::OverrideGeolocation(fake_latitude_, fake_longitude_);
282 void GeolocationBrowserTest::TearDownInProcessBrowserTestFixture() {
283 LOG(WARNING) << "TearDownInProcessBrowserTestFixture. Test Finished.";
286 bool GeolocationBrowserTest::Initialize(InitializationOptions options) {
287 if (!embedded_test_server()->Started() &&
288 !embedded_test_server()->InitializeAndWaitUntilReady()) {
289 ADD_FAILURE() << "Test server failed to start.";
290 return false;
293 current_url_ = embedded_test_server()->GetURL(html_for_tests_);
294 if (options == INITIALIZATION_OFFTHERECORD) {
295 current_browser_ = OpenURLOffTheRecord(browser()->profile(), current_url_);
296 } else {
297 current_browser_ = browser();
298 if (options == INITIALIZATION_NEWTAB)
299 chrome::NewTab(current_browser_);
301 if (options != INITIALIZATION_OFFTHERECORD)
302 ui_test_utils::NavigateToURL(current_browser_, current_url_);
304 EXPECT_TRUE(current_browser_);
305 return !!current_browser_;
308 void GeolocationBrowserTest::LoadIFrames(int number_iframes) {
309 // Limit to 3 iframes.
310 DCHECK_LT(0, number_iframes);
311 DCHECK_LE(number_iframes, 3);
312 iframe_urls_.resize(number_iframes);
313 for (int i = 0; i < number_iframes; ++i) {
314 IFrameLoader loader(current_browser_, i, GURL());
315 iframe_urls_[i] = loader.iframe_url();
319 void GeolocationBrowserTest::SetFrameHost(const std::string& frame_name) {
320 WebContents* web_contents =
321 current_browser_->tab_strip_model()->GetActiveWebContents();
322 render_frame_host_ = nullptr;
324 if (frame_name.empty()) {
325 render_frame_host_ = web_contents->GetMainFrame();
326 } else {
327 render_frame_host_ = content::FrameMatchingPredicate(
328 web_contents, base::Bind(&content::FrameMatchesName, frame_name));
330 DCHECK(render_frame_host_);
333 bool GeolocationBrowserTest::RequestAndAcceptPermission() {
334 std::string result =
335 RequestAndRespondToPermission(PermissionBubbleManager::ACCEPT_ALL);
336 return "request-callback-success" == result;
339 bool GeolocationBrowserTest::RequestAndDenyPermission() {
340 std::string result =
341 RequestAndRespondToPermission(PermissionBubbleManager::DENY_ALL);
342 return "request-callback-error" == result;
345 std::string GeolocationBrowserTest::RequestAndRespondToPermission(
346 PermissionBubbleManager::AutoResponseType bubble_response) {
347 std::string result;
348 PermissionBubbleManager::FromWebContents(
349 current_browser_->tab_strip_model()->GetActiveWebContents())
350 ->set_auto_response_for_test(bubble_response);
351 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
352 render_frame_host_, "geoStartWithAsyncResponse();", &result));
353 return result;
356 void GeolocationBrowserTest::RequestPermissionAndObserve(
357 bool bubble_should_display) {
358 std::string result;
359 PermissionRequestObserver observer(
360 current_browser_->tab_strip_model()->GetActiveWebContents());
361 if (bubble_should_display) {
362 // Control will return as soon as the API call is made, and then the
363 // observer will wait for the bubble to display.
364 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
365 render_frame_host_, "geoStartWithSyncResponse()", &result));
366 observer.Wait();
367 } else {
368 // Control will return once one of the callbacks fires.
369 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
370 render_frame_host_, "geoStartWithAsyncResponse()", &result));
372 EXPECT_EQ(bubble_should_display, observer.request_shown());
375 void GeolocationBrowserTest::CheckGeoposition(double latitude,
376 double longitude) {
377 // Checks we have no error.
378 CheckStringValueFromJavascript("0", "geoGetLastError()");
379 CheckStringValueFromJavascript(base::DoubleToString(latitude),
380 "geoGetLastPositionLatitude()");
381 CheckStringValueFromJavascript(base::DoubleToString(longitude),
382 "geoGetLastPositionLongitude()");
385 bool GeolocationBrowserTest::CheckGeopositionUpdated() {
386 // Control will return (a) if the update has already been received, or (b)
387 // when the update is received. This will hang if the geolocation is never
388 // updated. Currently this expects geoposition to be updated once; if your
389 // test updates geoposition repeatedly, |position_updated| (JS) needs to
390 // change to an int to count how often it's been updated.
391 std::string result;
392 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
393 render_frame_host_, "checkIfGeopositionUpdated();", &result));
394 return result == "geoposition-updated";
397 void GeolocationBrowserTest::CheckStringValueFromJavascriptForFrame(
398 const std::string& expected,
399 const std::string& function,
400 content::RenderFrameHost* render_frame_host) {
401 std::string script(base::StringPrintf(
402 "window.domAutomationController.send(%s)", function.c_str()));
403 std::string result;
404 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
405 render_frame_host, script, &result));
406 EXPECT_EQ(expected, result);
409 void GeolocationBrowserTest::CheckStringValueFromJavascript(
410 const std::string& expected,
411 const std::string& function) {
412 CheckStringValueFromJavascriptForFrame(
413 expected, function, render_frame_host_);
416 void GeolocationBrowserTest::NotifyGeoposition(double latitude,
417 double longitude) {
418 fake_latitude_ = latitude;
419 fake_longitude_ = longitude;
420 ui_test_utils::OverrideGeolocation(latitude, longitude);
423 int GeolocationBrowserTest::GetBubblesQueueSize(PermissionBubbleManager* mgr) {
424 return static_cast<int>(mgr->requests_.size());
427 // Tests ----------------------------------------------------------------------
429 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, DisplaysPrompt) {
430 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
431 SetFrameHost("");
432 ASSERT_TRUE(RequestAndAcceptPermission());
435 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, Geoposition) {
436 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
437 SetFrameHost("");
438 ASSERT_TRUE(RequestAndAcceptPermission());
439 CheckGeoposition(fake_latitude(), fake_longitude());
442 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, ErrorOnPermissionDenied) {
443 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
444 SetFrameHost("");
445 EXPECT_TRUE(RequestAndDenyPermission());
446 CheckStringValueFromJavascript("1", "geoGetLastError()");
449 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, NoPromptForSecondTab) {
450 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
451 SetFrameHost("");
452 ASSERT_TRUE(RequestAndAcceptPermission());
454 // Checks bubble is not needed in a second tab.
455 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB));
456 SetFrameHost("");
457 RequestPermissionAndObserve(false);
458 CheckGeoposition(fake_latitude(), fake_longitude());
461 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, NoPromptForDeniedOrigin) {
462 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
463 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
464 ContentSettingsPattern::FromURLNoWildcard(current_url()),
465 ContentSettingsPattern::FromURLNoWildcard(current_url()),
466 CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), CONTENT_SETTING_BLOCK);
468 // Check that the bubble wasn't shown but we get an error for this origin.
469 SetFrameHost("");
470 RequestPermissionAndObserve(false);
471 CheckStringValueFromJavascript("1", "geoGetLastError()");
473 // Checks prompt will not be created a second tab.
474 ASSERT_TRUE(Initialize(INITIALIZATION_NEWTAB));
475 SetFrameHost("");
476 RequestPermissionAndObserve(false);
477 CheckStringValueFromJavascript("1", "geoGetLastError()");
480 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, NoPromptForAllowedOrigin) {
481 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
482 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
483 ContentSettingsPattern::FromURLNoWildcard(current_url()),
484 ContentSettingsPattern::FromURLNoWildcard(current_url()),
485 CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string(), CONTENT_SETTING_ALLOW);
486 // Checks no prompt will be created and there's no error callback.
487 SetFrameHost("");
488 RequestPermissionAndObserve(false);
489 CheckGeoposition(fake_latitude(), fake_longitude());
492 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, NoPromptForOffTheRecord) {
493 // Check prompt will be created and persisted for regular profile.
494 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
495 SetFrameHost("");
496 ASSERT_TRUE(RequestAndAcceptPermission());
497 CheckGeoposition(fake_latitude(), fake_longitude());
499 // Go incognito, and check no prompt will be created.
500 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD));
501 SetFrameHost("");
502 RequestPermissionAndObserve(false);
503 CheckGeoposition(fake_latitude(), fake_longitude());
506 // http://crbug.com/523387
507 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest,
508 DISABLED_NoLeakFromOffTheRecord) {
509 // Check prompt will be created for incognito profile.
510 ASSERT_TRUE(Initialize(INITIALIZATION_OFFTHERECORD));
511 SetFrameHost("");
512 ASSERT_TRUE(RequestAndAcceptPermission());
513 CheckGeoposition(fake_latitude(), fake_longitude());
515 // Check prompt will be created for the regular profile.
516 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
517 SetFrameHost("");
518 ASSERT_TRUE(RequestAndAcceptPermission());
519 CheckGeoposition(fake_latitude(), fake_longitude());
522 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, IFramesWithFreshPosition) {
523 set_html_for_tests("/geolocation/two_iframes.html");
524 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
525 LoadIFrames(2);
527 // Request permission from the first frame.
528 SetFrameHost("iframe_0");
529 ASSERT_TRUE(RequestAndAcceptPermission());
530 CheckGeoposition(fake_latitude(), fake_longitude());
532 // Test second iframe from a different origin with a cached geoposition will
533 // create the prompt.
534 SetFrameHost("iframe_1");
535 RequestPermissionAndObserve(true);
537 // Back to the first frame, enable navigation and refresh geoposition.
538 SetFrameHost("iframe_0");
539 double fresh_position_latitude = 3.17;
540 double fresh_position_longitude = 4.23;
541 NotifyGeoposition(fresh_position_latitude, fresh_position_longitude);
542 ASSERT_TRUE(CheckGeopositionUpdated());
543 CheckGeoposition(fresh_position_latitude, fresh_position_longitude);
545 // Authorize the second frame and check it works.
546 SetFrameHost("iframe_1");
547 ASSERT_TRUE(RequestAndAcceptPermission());
548 CheckGeoposition(fake_latitude(), fake_longitude());
551 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, IFramesWithCachedPosition) {
552 set_html_for_tests("/geolocation/two_iframes.html");
553 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
554 LoadIFrames(2);
556 // Request permission from the first frame.
557 SetFrameHost("iframe_0");
558 ASSERT_TRUE(RequestAndAcceptPermission());
559 CheckGeoposition(fake_latitude(), fake_longitude());
561 // Refresh geoposition, but let's not yet create the watch on the second frame
562 // so that it'll fetch from cache.
563 double cached_position_latitude = 5.67;
564 double cached_position_lognitude = 8.09;
565 NotifyGeoposition(cached_position_latitude, cached_position_lognitude);
566 ASSERT_TRUE(CheckGeopositionUpdated());
567 CheckGeoposition(cached_position_latitude, cached_position_lognitude);
569 // Now check the second frame gets cached values as well.
570 SetFrameHost("iframe_1");
571 ASSERT_TRUE(RequestAndAcceptPermission());
572 CheckGeoposition(cached_position_latitude, cached_position_lognitude);
575 // http://crbug.com/523387
576 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest,
577 DISABLED_CancelPermissionForFrame) {
578 set_html_for_tests("/geolocation/two_iframes.html");
579 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
580 LoadIFrames(2);
582 SetFrameHost("iframe_0");
583 ASSERT_TRUE(RequestAndAcceptPermission());
584 CheckGeoposition(fake_latitude(), fake_longitude());
586 // Test second iframe from a different origin with a cached geoposition will
587 // create the prompt.
588 SetFrameHost("iframe_1");
589 RequestPermissionAndObserve(true);
591 // Navigate the iframe, and ensure the prompt is gone.
592 WebContents* web_contents =
593 current_browser()->tab_strip_model()->GetActiveWebContents();
594 IFrameLoader change_iframe_1(current_browser(), 1, current_url());
595 int num_bubbles_after_cancel = GetBubblesQueueSize(
596 PermissionBubbleManager::FromWebContents(web_contents));
597 EXPECT_EQ(0, num_bubbles_after_cancel);
600 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, InvalidUrlRequest) {
601 // Tests that an invalid URL (e.g. from a popup window) is rejected
602 // correctly. Also acts as a regression test for http://crbug.com/40478
603 set_html_for_tests("/geolocation/invalid_request_url.html");
604 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
606 SetFrameHost("");
607 WebContents* original_tab =
608 current_browser()->tab_strip_model()->GetActiveWebContents();
609 CheckStringValueFromJavascript("1", "requestGeolocationFromInvalidUrl()");
610 CheckStringValueFromJavascriptForFrame("1", "isAlive()",
611 original_tab->GetMainFrame());
614 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, NoPromptBeforeStart) {
615 // See http://crbug.com/42789
616 set_html_for_tests("/geolocation/two_iframes.html");
617 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
618 LoadIFrames(2);
620 // Access navigator.geolocation, but ensure it won't request permission.
621 SetFrameHost("iframe_1");
622 CheckStringValueFromJavascript("object", "geoAccessNavigatorGeolocation()");
624 SetFrameHost("iframe_0");
625 ASSERT_TRUE(RequestAndAcceptPermission());
626 CheckGeoposition(fake_latitude(), fake_longitude());
628 // Permission should be requested after adding a watch.
629 SetFrameHost("iframe_1");
630 ASSERT_TRUE(RequestAndAcceptPermission());
631 CheckGeoposition(fake_latitude(), fake_longitude());
634 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, TwoWatchesInOneFrame) {
635 set_html_for_tests("/geolocation/two_watches.html");
636 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
637 SetFrameHost("");
639 // Tell the JS what to expect as the final coordinates.
640 double final_position_latitude = 3.17;
641 double final_position_longitude = 4.23;
642 std::string script =
643 base::StringPrintf("geoSetFinalPosition(%f, %f)", final_position_latitude,
644 final_position_longitude);
645 CheckStringValueFromJavascript("ok", script);
647 // Request permission and set two watches for the initial success callback.
648 ASSERT_TRUE(RequestAndAcceptPermission());
649 CheckGeoposition(fake_latitude(), fake_longitude());
651 // The second watch will now have cancelled. Ensure an update still makes
652 // its way through to the first watcher.
653 NotifyGeoposition(final_position_latitude, final_position_longitude);
654 ASSERT_TRUE(CheckGeopositionUpdated());
655 CheckGeoposition(final_position_latitude, final_position_longitude);
658 // TODO(felt): Disabled because the second permission request hangs.
659 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, DISABLED_PendingChildFrames) {
660 set_html_for_tests("/geolocation/two_iframes.html");
661 ASSERT_TRUE(Initialize(INITIALIZATION_IFRAMES));
662 LoadIFrames(2);
664 SetFrameHost("iframe_0");
665 RequestPermissionAndObserve(true);
667 SetFrameHost("iframe_1");
668 RequestPermissionAndObserve(true);
671 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, TabDestroyed) {
672 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
673 SetFrameHost("");
674 RequestPermissionAndObserve(true);
676 std::string script =
677 "window.domAutomationController.send(window.close());";
678 bool result = content::ExecuteScript(
679 current_browser()->tab_strip_model()->GetActiveWebContents(), script);
680 EXPECT_EQ(result, true);
683 IN_PROC_BROWSER_TEST_F(GeolocationBrowserTest, LastUsageUpdated) {
684 ASSERT_TRUE(Initialize(INITIALIZATION_NONE));
685 base::SimpleTestClock* clock_ = new base::SimpleTestClock();
686 current_browser()
687 ->profile()
688 ->GetHostContentSettingsMap()
689 ->SetPrefClockForTesting(scoped_ptr<base::Clock>(clock_));
690 clock_->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10));
692 // Setting the permission should trigger the last usage.
693 current_browser()->profile()->GetHostContentSettingsMap()->SetContentSetting(
694 ContentSettingsPattern::FromURLNoWildcard(current_url()),
695 ContentSettingsPattern::FromURLNoWildcard(current_url()),
696 CONTENT_SETTINGS_TYPE_GEOLOCATION,
697 std::string(),
698 CONTENT_SETTING_ALLOW);
700 // Permission has been used at the starting time.
701 EXPECT_EQ(current_browser()
702 ->profile()
703 ->GetHostContentSettingsMap()
704 ->GetLastUsage(current_url().GetOrigin(),
705 current_url().GetOrigin(),
706 CONTENT_SETTINGS_TYPE_GEOLOCATION)
707 .ToDoubleT(),
708 10);
710 clock_->Advance(base::TimeDelta::FromSeconds(3));
712 // Watching should trigger the last usage update.
713 SetFrameHost("");
714 RequestPermissionAndObserve(false);
715 CheckGeoposition(fake_latitude(), fake_longitude());
717 // Last usage has been updated.
718 EXPECT_EQ(current_browser()
719 ->profile()
720 ->GetHostContentSettingsMap()
721 ->GetLastUsage(current_url().GetOrigin(),
722 current_url().GetOrigin(),
723 CONTENT_SETTINGS_TYPE_GEOLOCATION)
724 .ToDoubleT(),
725 13);