Do not announce robot account token before account ID is available
[chromium-blink-merge.git] / chrome / test / base / ui_test_utils.cc
blob8b686afdf2aefc5a82b5b68aa7e6e04779e0c19c
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 "chrome/test/base/ui_test_utils.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #endif
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/path_service.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/test/test_timeouts.h"
24 #include "base/time/time.h"
25 #include "chrome/browser/autocomplete/autocomplete_controller.h"
26 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/history/history_service_factory.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/ui/browser.h"
31 #include "chrome/browser/ui/browser_commands.h"
32 #include "chrome/browser/ui/browser_finder.h"
33 #include "chrome/browser/ui/browser_iterator.h"
34 #include "chrome/browser/ui/browser_list.h"
35 #include "chrome/browser/ui/browser_navigator.h"
36 #include "chrome/browser/ui/browser_window.h"
37 #include "chrome/browser/ui/find_bar/find_notification_details.h"
38 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
39 #include "chrome/browser/ui/host_desktop.h"
40 #include "chrome/browser/ui/location_bar/location_bar.h"
41 #include "chrome/browser/ui/omnibox/omnibox_view.h"
42 #include "chrome/browser/ui/tabs/tab_strip_model.h"
43 #include "chrome/common/chrome_paths.h"
44 #include "chrome/common/pref_names.h"
45 #include "chrome/test/base/find_in_page_observer.h"
46 #include "components/app_modal/app_modal_dialog.h"
47 #include "components/app_modal/app_modal_dialog_queue.h"
48 #include "components/bookmarks/browser/bookmark_model.h"
49 #include "components/history/core/browser/history_service_observer.h"
50 #include "components/search_engines/template_url_service.h"
51 #include "content/public/browser/dom_operation_notification_details.h"
52 #include "content/public/browser/download_item.h"
53 #include "content/public/browser/download_manager.h"
54 #include "content/public/browser/geolocation_provider.h"
55 #include "content/public/browser/navigation_controller.h"
56 #include "content/public/browser/navigation_entry.h"
57 #include "content/public/browser/notification_service.h"
58 #include "content/public/browser/render_process_host.h"
59 #include "content/public/browser/web_contents.h"
60 #include "content/public/browser/web_contents_observer.h"
61 #include "content/public/common/geoposition.h"
62 #include "content/public/test/browser_test_utils.h"
63 #include "content/public/test/download_test_observer.h"
64 #include "content/public/test/test_navigation_observer.h"
65 #include "content/public/test/test_utils.h"
66 #include "net/base/filename_util.h"
67 #include "net/cookies/cookie_constants.h"
68 #include "net/cookies/cookie_monster.h"
69 #include "net/cookies/cookie_store.h"
70 #include "net/test/python_utils.h"
71 #include "net/url_request/url_request_context.h"
72 #include "net/url_request/url_request_context_getter.h"
73 #include "ui/gfx/geometry/rect.h"
75 #if defined(USE_AURA)
76 #include "ash/shell.h"
77 #include "ui/aura/window_event_dispatcher.h"
78 #endif
80 using content::DomOperationNotificationDetails;
81 using content::NativeWebKeyboardEvent;
82 using content::NavigationController;
83 using content::NavigationEntry;
84 using content::OpenURLParams;
85 using content::Referrer;
86 using content::WebContents;
88 namespace ui_test_utils {
90 namespace {
92 Browser* WaitForBrowserNotInSet(std::set<Browser*> excluded_browsers) {
93 Browser* new_browser = GetBrowserNotInSet(excluded_browsers);
94 if (new_browser == NULL) {
95 BrowserAddedObserver observer;
96 new_browser = observer.WaitForSingleNewBrowser();
97 // The new browser should never be in |excluded_browsers|.
98 DCHECK(!ContainsKey(excluded_browsers, new_browser));
100 return new_browser;
103 class AppModalDialogWaiter : public app_modal::AppModalDialogObserver {
104 public:
105 AppModalDialogWaiter()
106 : dialog_(NULL) {
108 ~AppModalDialogWaiter() override {
111 app_modal::AppModalDialog* Wait() {
112 if (dialog_)
113 return dialog_;
114 message_loop_runner_ = new content::MessageLoopRunner;
115 message_loop_runner_->Run();
116 EXPECT_TRUE(dialog_);
117 return dialog_;
120 // AppModalDialogWaiter:
121 void Notify(app_modal::AppModalDialog* dialog) override {
122 DCHECK(!dialog_);
123 dialog_ = dialog;
124 if (message_loop_runner_.get() && message_loop_runner_->loop_running())
125 message_loop_runner_->Quit();
128 private:
129 app_modal::AppModalDialog* dialog_;
130 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
132 DISALLOW_COPY_AND_ASSIGN(AppModalDialogWaiter);
135 } // namespace
137 bool GetCurrentTabTitle(const Browser* browser, base::string16* title) {
138 WebContents* web_contents =
139 browser->tab_strip_model()->GetActiveWebContents();
140 if (!web_contents)
141 return false;
142 NavigationEntry* last_entry = web_contents->GetController().GetActiveEntry();
143 if (!last_entry)
144 return false;
145 title->assign(last_entry->GetTitleForDisplay(std::string()));
146 return true;
149 Browser* OpenURLOffTheRecord(Profile* profile, const GURL& url) {
150 chrome::HostDesktopType active_desktop = chrome::GetActiveDesktop();
151 chrome::OpenURLOffTheRecord(profile, url, active_desktop);
152 Browser* browser = chrome::FindTabbedBrowser(
153 profile->GetOffTheRecordProfile(), false, active_desktop);
154 content::TestNavigationObserver observer(
155 browser->tab_strip_model()->GetActiveWebContents());
156 observer.Wait();
157 return browser;
160 void NavigateToURL(chrome::NavigateParams* params) {
161 chrome::Navigate(params);
162 content::WaitForLoadStop(params->target_contents);
166 void NavigateToURLWithPost(Browser* browser, const GURL& url) {
167 chrome::NavigateParams params(browser, url,
168 ui::PAGE_TRANSITION_FORM_SUBMIT);
169 params.uses_post = true;
170 NavigateToURL(&params);
173 void NavigateToURL(Browser* browser, const GURL& url) {
174 NavigateToURLWithDisposition(browser, url, CURRENT_TAB,
175 BROWSER_TEST_WAIT_FOR_NAVIGATION);
178 void NavigateToURLWithDispositionBlockUntilNavigationsComplete(
179 Browser* browser,
180 const GURL& url,
181 int number_of_navigations,
182 WindowOpenDisposition disposition,
183 int browser_test_flags) {
184 TabStripModel* tab_strip = browser->tab_strip_model();
185 if (disposition == CURRENT_TAB && tab_strip->GetActiveWebContents())
186 content::WaitForLoadStop(tab_strip->GetActiveWebContents());
187 content::TestNavigationObserver same_tab_observer(
188 tab_strip->GetActiveWebContents(),
189 number_of_navigations);
191 std::set<Browser*> initial_browsers;
192 for (chrome::BrowserIterator it; !it.done(); it.Next())
193 initial_browsers.insert(*it);
195 content::WindowedNotificationObserver tab_added_observer(
196 chrome::NOTIFICATION_TAB_ADDED,
197 content::NotificationService::AllSources());
199 browser->OpenURL(OpenURLParams(
200 url, Referrer(), disposition, ui::PAGE_TRANSITION_TYPED, false));
201 if (browser_test_flags & BROWSER_TEST_WAIT_FOR_BROWSER)
202 browser = WaitForBrowserNotInSet(initial_browsers);
203 if (browser_test_flags & BROWSER_TEST_WAIT_FOR_TAB)
204 tab_added_observer.Wait();
205 if (!(browser_test_flags & BROWSER_TEST_WAIT_FOR_NAVIGATION)) {
206 // Some other flag caused the wait prior to this.
207 return;
209 WebContents* web_contents = NULL;
210 if (disposition == NEW_BACKGROUND_TAB) {
211 // We've opened up a new tab, but not selected it.
212 TabStripModel* tab_strip = browser->tab_strip_model();
213 web_contents = tab_strip->GetWebContentsAt(tab_strip->active_index() + 1);
214 EXPECT_TRUE(web_contents != NULL)
215 << " Unable to wait for navigation to \"" << url.spec()
216 << "\" because the new tab is not available yet";
217 if (!web_contents)
218 return;
219 } else if ((disposition == CURRENT_TAB) ||
220 (disposition == NEW_FOREGROUND_TAB) ||
221 (disposition == SINGLETON_TAB)) {
222 // The currently selected tab is the right one.
223 web_contents = browser->tab_strip_model()->GetActiveWebContents();
225 if (disposition == CURRENT_TAB) {
226 same_tab_observer.Wait();
227 return;
228 } else if (web_contents) {
229 content::TestNavigationObserver observer(web_contents,
230 number_of_navigations);
231 observer.Wait();
232 return;
234 EXPECT_TRUE(NULL != web_contents) << " Unable to wait for navigation to \""
235 << url.spec() << "\""
236 << " because we can't get the tab contents";
239 void NavigateToURLWithDisposition(Browser* browser,
240 const GURL& url,
241 WindowOpenDisposition disposition,
242 int browser_test_flags) {
243 NavigateToURLWithDispositionBlockUntilNavigationsComplete(
244 browser,
245 url,
247 disposition,
248 browser_test_flags);
251 void NavigateToURLBlockUntilNavigationsComplete(Browser* browser,
252 const GURL& url,
253 int number_of_navigations) {
254 NavigateToURLWithDispositionBlockUntilNavigationsComplete(
255 browser,
256 url,
257 number_of_navigations,
258 CURRENT_TAB,
259 BROWSER_TEST_WAIT_FOR_NAVIGATION);
262 base::FilePath GetTestFilePath(const base::FilePath& dir,
263 const base::FilePath& file) {
264 base::FilePath path;
265 PathService::Get(chrome::DIR_TEST_DATA, &path);
266 return path.Append(dir).Append(file);
269 GURL GetTestUrl(const base::FilePath& dir, const base::FilePath& file) {
270 return net::FilePathToFileURL(GetTestFilePath(dir, file));
273 bool GetRelativeBuildDirectory(base::FilePath* build_dir) {
274 // This function is used to find the build directory so TestServer can serve
275 // built files (nexes, etc). TestServer expects a path relative to the source
276 // root.
277 base::FilePath exe_dir =
278 base::CommandLine::ForCurrentProcess()->GetProgram().DirName();
279 base::FilePath src_dir;
280 if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_dir))
281 return false;
283 // We must first generate absolute paths to SRC and EXE and from there
284 // generate a relative path.
285 if (!exe_dir.IsAbsolute())
286 exe_dir = base::MakeAbsoluteFilePath(exe_dir);
287 if (!src_dir.IsAbsolute())
288 src_dir = base::MakeAbsoluteFilePath(src_dir);
289 if (!exe_dir.IsAbsolute())
290 return false;
291 if (!src_dir.IsAbsolute())
292 return false;
294 size_t match, exe_size, src_size;
295 std::vector<base::FilePath::StringType> src_parts, exe_parts;
297 // Determine point at which src and exe diverge.
298 exe_dir.GetComponents(&exe_parts);
299 src_dir.GetComponents(&src_parts);
300 exe_size = exe_parts.size();
301 src_size = src_parts.size();
302 for (match = 0; match < exe_size && match < src_size; ++match) {
303 if (exe_parts[match] != src_parts[match])
304 break;
307 // Create a relative path.
308 *build_dir = base::FilePath();
309 for (size_t tmp_itr = match; tmp_itr < src_size; ++tmp_itr)
310 *build_dir = build_dir->Append(FILE_PATH_LITERAL(".."));
311 for (; match < exe_size; ++match)
312 *build_dir = build_dir->Append(exe_parts[match]);
313 return true;
316 app_modal::AppModalDialog* WaitForAppModalDialog() {
317 app_modal::AppModalDialogQueue* dialog_queue =
318 app_modal::AppModalDialogQueue::GetInstance();
319 if (dialog_queue->HasActiveDialog())
320 return dialog_queue->active_dialog();
321 AppModalDialogWaiter waiter;
322 return waiter.Wait();
325 int FindInPage(WebContents* tab,
326 const base::string16& search_string,
327 bool forward,
328 bool match_case,
329 int* ordinal,
330 gfx::Rect* selection_rect) {
331 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(tab);
332 find_tab_helper->StartFinding(search_string, forward, match_case);
333 FindInPageNotificationObserver observer(tab);
334 observer.Wait();
335 if (ordinal)
336 *ordinal = observer.active_match_ordinal();
337 if (selection_rect)
338 *selection_rect = observer.selection_rect();
339 return observer.number_of_matches();
342 void WaitForTemplateURLServiceToLoad(TemplateURLService* service) {
343 if (service->loaded())
344 return;
345 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
346 new content::MessageLoopRunner;
347 scoped_ptr<TemplateURLService::Subscription> subscription =
348 service->RegisterOnLoadedCallback(
349 message_loop_runner->QuitClosure());
350 service->Load();
351 message_loop_runner->Run();
353 ASSERT_TRUE(service->loaded());
356 void DownloadURL(Browser* browser, const GURL& download_url) {
357 base::ScopedTempDir downloads_directory;
358 ASSERT_TRUE(downloads_directory.CreateUniqueTempDir());
359 browser->profile()->GetPrefs()->SetFilePath(
360 prefs::kDownloadDefaultDirectory, downloads_directory.path());
362 content::DownloadManager* download_manager =
363 content::BrowserContext::GetDownloadManager(browser->profile());
364 scoped_ptr<content::DownloadTestObserver> observer(
365 new content::DownloadTestObserverTerminal(
366 download_manager, 1,
367 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
369 ui_test_utils::NavigateToURL(browser, download_url);
370 observer->WaitForFinished();
373 void SendToOmniboxAndSubmit(LocationBar* location_bar,
374 const std::string& input) {
375 OmniboxView* omnibox = location_bar->GetOmniboxView();
376 omnibox->model()->OnSetFocus(false);
377 omnibox->SetUserText(base::ASCIIToUTF16(input));
378 location_bar->AcceptInput();
379 while (!omnibox->model()->autocomplete_controller()->done()) {
380 content::WindowedNotificationObserver observer(
381 chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
382 content::NotificationService::AllSources());
383 observer.Wait();
387 Browser* GetBrowserNotInSet(std::set<Browser*> excluded_browsers) {
388 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
389 if (excluded_browsers.find(*it) == excluded_browsers.end())
390 return *it;
392 return NULL;
395 namespace {
397 void GetCookiesCallback(base::WaitableEvent* event,
398 std::string* cookies,
399 const std::string& cookie_line) {
400 *cookies = cookie_line;
401 event->Signal();
404 void GetCookiesOnIOThread(
405 const GURL& url,
406 const scoped_refptr<net::URLRequestContextGetter>& context_getter,
407 base::WaitableEvent* event,
408 std::string* cookies) {
409 context_getter->GetURLRequestContext()->cookie_store()->
410 GetCookiesWithOptionsAsync(
411 url, net::CookieOptions(),
412 base::Bind(&GetCookiesCallback, event, cookies));
415 } // namespace
417 void GetCookies(const GURL& url,
418 WebContents* contents,
419 int* value_size,
420 std::string* value) {
421 *value_size = -1;
422 if (url.is_valid() && contents) {
423 scoped_refptr<net::URLRequestContextGetter> context_getter =
424 contents->GetBrowserContext()->GetRequestContextForRenderProcess(
425 contents->GetRenderProcessHost()->GetID());
426 base::WaitableEvent event(true /* manual reset */,
427 false /* not initially signaled */);
428 CHECK(content::BrowserThread::PostTask(
429 content::BrowserThread::IO, FROM_HERE,
430 base::Bind(&GetCookiesOnIOThread, url, context_getter, &event, value)));
431 event.Wait();
433 *value_size = static_cast<int>(value->size());
437 WindowedTabAddedNotificationObserver::WindowedTabAddedNotificationObserver(
438 const content::NotificationSource& source)
439 : WindowedNotificationObserver(chrome::NOTIFICATION_TAB_ADDED, source),
440 added_tab_(NULL) {
443 void WindowedTabAddedNotificationObserver::Observe(
444 int type,
445 const content::NotificationSource& source,
446 const content::NotificationDetails& details) {
447 added_tab_ = content::Details<WebContents>(details).ptr();
448 content::WindowedNotificationObserver::Observe(type, source, details);
451 UrlLoadObserver::UrlLoadObserver(const GURL& url,
452 const content::NotificationSource& source)
453 : WindowedNotificationObserver(content::NOTIFICATION_LOAD_STOP, source),
454 url_(url) {
457 UrlLoadObserver::~UrlLoadObserver() {}
459 void UrlLoadObserver::Observe(
460 int type,
461 const content::NotificationSource& source,
462 const content::NotificationDetails& details) {
463 NavigationController* controller =
464 content::Source<NavigationController>(source).ptr();
465 if (controller->GetWebContents()->GetURL() != url_)
466 return;
468 WindowedNotificationObserver::Observe(type, source, details);
471 BrowserAddedObserver::BrowserAddedObserver()
472 : notification_observer_(
473 chrome::NOTIFICATION_BROWSER_OPENED,
474 content::NotificationService::AllSources()) {
475 for (chrome::BrowserIterator it; !it.done(); it.Next())
476 original_browsers_.insert(*it);
479 BrowserAddedObserver::~BrowserAddedObserver() {
482 Browser* BrowserAddedObserver::WaitForSingleNewBrowser() {
483 notification_observer_.Wait();
484 // Ensure that only a single new browser has appeared.
485 EXPECT_EQ(original_browsers_.size() + 1, chrome::GetTotalBrowserCount());
486 return GetBrowserNotInSet(original_browsers_);
489 void OverrideGeolocation(double latitude, double longitude) {
490 content::Geoposition position;
491 position.latitude = latitude;
492 position.longitude = longitude;
493 position.altitude = 0.;
494 position.accuracy = 0.;
495 position.timestamp = base::Time::Now();
496 content::GeolocationProvider::GetInstance()->OverrideLocationForTesting(
497 position);
500 HistoryEnumerator::HistoryEnumerator(Profile* profile) {
501 scoped_refptr<content::MessageLoopRunner> message_loop_runner =
502 new content::MessageLoopRunner;
504 HistoryService* hs = HistoryServiceFactory::GetForProfile(
505 profile, ServiceAccessType::EXPLICIT_ACCESS);
506 hs->QueryHistory(base::string16(),
507 history::QueryOptions(),
508 base::Bind(&HistoryEnumerator::HistoryQueryComplete,
509 base::Unretained(this),
510 message_loop_runner->QuitClosure()),
511 &tracker_);
512 message_loop_runner->Run();
515 HistoryEnumerator::~HistoryEnumerator() {}
517 void HistoryEnumerator::HistoryQueryComplete(
518 const base::Closure& quit_task,
519 history::QueryResults* results) {
520 for (size_t i = 0; i < results->size(); ++i)
521 urls_.push_back((*results)[i].url());
522 quit_task.Run();
525 // Wait for HistoryService to load.
526 class WaitHistoryLoadedObserver : public history::HistoryServiceObserver {
527 public:
528 explicit WaitHistoryLoadedObserver(content::MessageLoopRunner* runner);
529 ~WaitHistoryLoadedObserver() override;
531 // history::HistoryServiceObserver:
532 void OnHistoryServiceLoaded(HistoryService* service) override;
534 private:
535 // weak
536 content::MessageLoopRunner* runner_;
539 WaitHistoryLoadedObserver::WaitHistoryLoadedObserver(
540 content::MessageLoopRunner* runner)
541 : runner_(runner) {
544 WaitHistoryLoadedObserver::~WaitHistoryLoadedObserver() {
547 void WaitHistoryLoadedObserver::OnHistoryServiceLoaded(
548 HistoryService* service) {
549 runner_->Quit();
552 void WaitForHistoryToLoad(HistoryService* history_service) {
553 if (!history_service->BackendLoaded()) {
554 scoped_refptr<content::MessageLoopRunner> runner =
555 new content::MessageLoopRunner;
556 WaitHistoryLoadedObserver observer(runner.get());
557 ScopedObserver<HistoryService, history::HistoryServiceObserver>
558 scoped_observer(&observer);
559 scoped_observer.Add(history_service);
560 runner->Run();
564 } // namespace ui_test_utils