ServiceWorkerVersion: remove unused parameter in DispatchInstallEvent
[chromium-blink-merge.git] / content / public / test / browser_test_utils.cc
blob5de8137fae17df19ad4697870ec5cd22409c0464
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 "content/public/test/browser_test_utils.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/json/json_reader.h"
10 #include "base/process/kill.h"
11 #include "base/rand_util.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/test/test_timeouts.h"
17 #include "base/values.h"
18 #include "content/browser/renderer_host/render_widget_host_impl.h"
19 #include "content/browser/web_contents/web_contents_impl.h"
20 #include "content/browser/web_contents/web_contents_view.h"
21 #include "content/common/input/synthetic_web_input_event_builders.h"
22 #include "content/public/browser/browser_context.h"
23 #include "content/public/browser/dom_operation_notification_details.h"
24 #include "content/public/browser/histogram_fetcher.h"
25 #include "content/public/browser/navigation_entry.h"
26 #include "content/public/browser/notification_service.h"
27 #include "content/public/browser/notification_types.h"
28 #include "content/public/browser/render_frame_host.h"
29 #include "content/public/browser/render_process_host.h"
30 #include "content/public/browser/render_view_host.h"
31 #include "content/public/browser/web_contents.h"
32 #include "content/public/browser/web_contents_observer.h"
33 #include "content/public/test/test_utils.h"
34 #include "net/base/filename_util.h"
35 #include "net/cookies/cookie_store.h"
36 #include "net/test/embedded_test_server/embedded_test_server.h"
37 #include "net/test/embedded_test_server/http_request.h"
38 #include "net/test/embedded_test_server/http_response.h"
39 #include "net/test/python_utils.h"
40 #include "net/url_request/url_request_context.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "testing/gtest/include/gtest/gtest.h"
43 #include "ui/base/resource/resource_bundle.h"
44 #include "ui/compositor/test/draw_waiter_for_test.h"
45 #include "ui/events/gesture_detection/gesture_configuration.h"
46 #include "ui/events/keycodes/dom4/keycode_converter.h"
47 #include "ui/resources/grit/webui_resources.h"
49 #if defined(USE_AURA)
50 #include "ui/aura/test/window_event_dispatcher_test_api.h"
51 #include "ui/aura/window.h"
52 #include "ui/aura/window_event_dispatcher.h"
53 #include "ui/aura/window_tree_host.h"
54 #endif // USE_AURA
56 namespace content {
57 namespace {
59 class DOMOperationObserver : public NotificationObserver,
60 public WebContentsObserver {
61 public:
62 explicit DOMOperationObserver(RenderViewHost* rvh)
63 : WebContentsObserver(WebContents::FromRenderViewHost(rvh)),
64 did_respond_(false) {
65 registrar_.Add(this, NOTIFICATION_DOM_OPERATION_RESPONSE,
66 Source<WebContents>(web_contents()));
67 message_loop_runner_ = new MessageLoopRunner;
70 void Observe(int type,
71 const NotificationSource& source,
72 const NotificationDetails& details) override {
73 DCHECK(type == NOTIFICATION_DOM_OPERATION_RESPONSE);
74 Details<DomOperationNotificationDetails> dom_op_details(details);
75 response_ = dom_op_details->json;
76 did_respond_ = true;
77 message_loop_runner_->Quit();
80 // Overridden from WebContentsObserver:
81 void RenderProcessGone(base::TerminationStatus status) override {
82 message_loop_runner_->Quit();
85 bool WaitAndGetResponse(std::string* response) WARN_UNUSED_RESULT {
86 message_loop_runner_->Run();
87 *response = response_;
88 return did_respond_;
91 private:
92 NotificationRegistrar registrar_;
93 std::string response_;
94 bool did_respond_;
95 scoped_refptr<MessageLoopRunner> message_loop_runner_;
97 DISALLOW_COPY_AND_ASSIGN(DOMOperationObserver);
100 class InterstitialObserver : public content::WebContentsObserver {
101 public:
102 InterstitialObserver(content::WebContents* web_contents,
103 const base::Closure& attach_callback,
104 const base::Closure& detach_callback)
105 : WebContentsObserver(web_contents),
106 attach_callback_(attach_callback),
107 detach_callback_(detach_callback) {
109 ~InterstitialObserver() override {}
111 // WebContentsObserver methods:
112 void DidAttachInterstitialPage() override { attach_callback_.Run(); }
113 void DidDetachInterstitialPage() override { detach_callback_.Run(); }
115 private:
116 base::Closure attach_callback_;
117 base::Closure detach_callback_;
119 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
122 // Specifying a prototype so that we can add the WARN_UNUSED_RESULT attribute.
123 bool ExecuteScriptHelper(
124 RenderFrameHost* render_frame_host,
125 const std::string& original_script,
126 scoped_ptr<base::Value>* result) WARN_UNUSED_RESULT;
128 // Executes the passed |original_script| in the frame specified by
129 // |render_frame_host|. If |result| is not NULL, stores the value that the
130 // evaluation of the script in |result|. Returns true on success.
131 bool ExecuteScriptHelper(RenderFrameHost* render_frame_host,
132 const std::string& original_script,
133 scoped_ptr<base::Value>* result) {
134 // TODO(jcampan): we should make the domAutomationController not require an
135 // automation id.
136 std::string script =
137 "window.domAutomationController.setAutomationId(0);" + original_script;
138 DOMOperationObserver dom_op_observer(render_frame_host->GetRenderViewHost());
139 render_frame_host->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script));
140 std::string json;
141 if (!dom_op_observer.WaitAndGetResponse(&json)) {
142 DLOG(ERROR) << "Cannot communicate with DOMOperationObserver.";
143 return false;
146 // Nothing more to do for callers that ignore the returned JS value.
147 if (!result)
148 return true;
150 base::JSONReader reader(base::JSON_ALLOW_TRAILING_COMMAS);
151 result->reset(reader.ReadToValue(json));
152 if (!result->get()) {
153 DLOG(ERROR) << reader.GetErrorMessage();
154 return false;
157 return true;
160 void BuildSimpleWebKeyEvent(blink::WebInputEvent::Type type,
161 ui::KeyboardCode key_code,
162 int native_key_code,
163 int modifiers,
164 NativeWebKeyboardEvent* event) {
165 event->nativeKeyCode = native_key_code;
166 event->windowsKeyCode = key_code;
167 event->setKeyIdentifierFromWindowsKeyCode();
168 event->type = type;
169 event->modifiers = modifiers;
170 event->isSystemKey = false;
171 event->timeStampSeconds = base::Time::Now().ToDoubleT();
172 event->skip_in_browser = true;
174 if (type == blink::WebInputEvent::Char ||
175 type == blink::WebInputEvent::RawKeyDown) {
176 event->text[0] = key_code;
177 event->unmodifiedText[0] = key_code;
181 void InjectRawKeyEvent(WebContents* web_contents,
182 blink::WebInputEvent::Type type,
183 ui::KeyboardCode key_code,
184 int native_key_code,
185 int modifiers) {
186 NativeWebKeyboardEvent event;
187 BuildSimpleWebKeyEvent(type, key_code, native_key_code, modifiers, &event);
188 web_contents->GetRenderViewHost()->ForwardKeyboardEvent(event);
191 void GetCookiesCallback(std::string* cookies_out,
192 base::WaitableEvent* event,
193 const std::string& cookies) {
194 *cookies_out = cookies;
195 event->Signal();
198 void GetCookiesOnIOThread(const GURL& url,
199 net::URLRequestContextGetter* context_getter,
200 base::WaitableEvent* event,
201 std::string* cookies) {
202 net::CookieStore* cookie_store =
203 context_getter->GetURLRequestContext()->cookie_store();
204 cookie_store->GetCookiesWithOptionsAsync(
205 url, net::CookieOptions(),
206 base::Bind(&GetCookiesCallback, cookies, event));
209 void SetCookieCallback(bool* result,
210 base::WaitableEvent* event,
211 bool success) {
212 *result = success;
213 event->Signal();
216 void SetCookieOnIOThread(const GURL& url,
217 const std::string& value,
218 net::URLRequestContextGetter* context_getter,
219 base::WaitableEvent* event,
220 bool* result) {
221 net::CookieStore* cookie_store =
222 context_getter->GetURLRequestContext()->cookie_store();
223 cookie_store->SetCookieWithOptionsAsync(
224 url, value, net::CookieOptions(),
225 base::Bind(&SetCookieCallback, result, event));
228 scoped_ptr<net::test_server::HttpResponse> CrossSiteRedirectResponseHandler(
229 const GURL& server_base_url,
230 const net::test_server::HttpRequest& request) {
231 std::string prefix("/cross-site/");
232 if (!StartsWithASCII(request.relative_url, prefix, true))
233 return scoped_ptr<net::test_server::HttpResponse>();
235 std::string params = request.relative_url.substr(prefix.length());
237 // A hostname to redirect to must be included in the URL, therefore at least
238 // one '/' character is expected.
239 size_t slash = params.find('/');
240 if (slash == std::string::npos)
241 return scoped_ptr<net::test_server::HttpResponse>();
243 // Replace the host of the URL with the one passed in the URL.
244 GURL::Replacements replace_host;
245 replace_host.SetHostStr(base::StringPiece(params).substr(0, slash));
246 GURL redirect_server = server_base_url.ReplaceComponents(replace_host);
248 // Append the real part of the path to the new URL.
249 std::string path = params.substr(slash + 1);
250 GURL redirect_target(redirect_server.Resolve(path));
251 DCHECK(redirect_target.is_valid());
253 scoped_ptr<net::test_server::BasicHttpResponse> http_response(
254 new net::test_server::BasicHttpResponse);
255 http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
256 http_response->AddCustomHeader("Location", redirect_target.spec());
257 return http_response.Pass();
260 } // namespace
262 bool NavigateIframeToURL(WebContents* web_contents,
263 std::string iframe_id,
264 const GURL& url) {
265 // TODO(creis): This should wait for LOAD_STOP, but cross-site subframe
266 // navigations generate extra DidStartLoading and DidStopLoading messages.
267 // Until we replace swappedout:// with frame proxies, we need to listen for
268 // something else. For now, we trigger NEW_SUBFRAME navigations and listen
269 // for commit. See https://crbug.com/436250.
270 std::string script = base::StringPrintf(
271 "setTimeout(\""
272 "var iframes = document.getElementById('%s');iframes.src='%s';"
273 "\",0)",
274 iframe_id.c_str(), url.spec().c_str());
275 WindowedNotificationObserver load_observer(
276 NOTIFICATION_NAV_ENTRY_COMMITTED,
277 Source<NavigationController>(&web_contents->GetController()));
278 bool result = ExecuteScript(web_contents, script);
279 load_observer.Wait();
280 return result;
283 GURL GetFileUrlWithQuery(const base::FilePath& path,
284 const std::string& query_string) {
285 GURL url = net::FilePathToFileURL(path);
286 if (!query_string.empty()) {
287 GURL::Replacements replacements;
288 replacements.SetQueryStr(query_string);
289 return url.ReplaceComponents(replacements);
291 return url;
294 void WaitForLoadStopWithoutSuccessCheck(WebContents* web_contents) {
295 // In many cases, the load may have finished before we get here. Only wait if
296 // the tab still has a pending navigation.
297 if (web_contents->IsLoading()) {
298 WindowedNotificationObserver load_stop_observer(
299 NOTIFICATION_LOAD_STOP,
300 Source<NavigationController>(&web_contents->GetController()));
301 load_stop_observer.Wait();
305 bool WaitForLoadStop(WebContents* web_contents) {
306 WaitForLoadStopWithoutSuccessCheck(web_contents);
307 return IsLastCommittedEntryOfPageType(web_contents, PAGE_TYPE_NORMAL);
310 bool IsLastCommittedEntryOfPageType(WebContents* web_contents,
311 content::PageType page_type) {
312 NavigationEntry* last_entry =
313 web_contents->GetController().GetLastCommittedEntry();
314 if (!last_entry)
315 return false;
316 return last_entry->GetPageType() == page_type;
319 void CrashTab(WebContents* web_contents) {
320 RenderProcessHost* rph = web_contents->GetRenderProcessHost();
321 RenderProcessHostWatcher watcher(
322 rph, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
323 rph->Shutdown(0, false);
324 watcher.Wait();
327 #if defined(USE_AURA)
328 bool IsResizeComplete(aura::test::WindowEventDispatcherTestApi* dispatcher_test,
329 RenderWidgetHostImpl* widget_host) {
330 return !dispatcher_test->HoldingPointerMoves() &&
331 !widget_host->resize_ack_pending_for_testing();
334 void WaitForResizeComplete(WebContents* web_contents) {
335 aura::Window* content = web_contents->GetContentNativeView();
336 if (!content)
337 return;
339 aura::WindowTreeHost* window_host = content->GetHost();
340 aura::WindowEventDispatcher* dispatcher = window_host->dispatcher();
341 aura::test::WindowEventDispatcherTestApi dispatcher_test(dispatcher);
342 RenderWidgetHostImpl* widget_host =
343 RenderWidgetHostImpl::From(web_contents->GetRenderViewHost());
344 if (!IsResizeComplete(&dispatcher_test, widget_host)) {
345 WindowedNotificationObserver resize_observer(
346 NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
347 base::Bind(IsResizeComplete, &dispatcher_test, widget_host));
348 resize_observer.Wait();
351 #endif // USE_AURA
353 void SimulateMouseClick(WebContents* web_contents,
354 int modifiers,
355 blink::WebMouseEvent::Button button) {
356 int x = web_contents->GetContainerBounds().width() / 2;
357 int y = web_contents->GetContainerBounds().height() / 2;
358 SimulateMouseClickAt(web_contents, modifiers, button, gfx::Point(x, y));
361 void SimulateMouseClickAt(WebContents* web_contents,
362 int modifiers,
363 blink::WebMouseEvent::Button button,
364 const gfx::Point& point) {
365 blink::WebMouseEvent mouse_event;
366 mouse_event.type = blink::WebInputEvent::MouseDown;
367 mouse_event.button = button;
368 mouse_event.x = point.x();
369 mouse_event.y = point.y();
370 mouse_event.modifiers = modifiers;
371 // Mac needs globalX/globalY for events to plugins.
372 gfx::Rect offset = web_contents->GetContainerBounds();
373 mouse_event.globalX = point.x() + offset.x();
374 mouse_event.globalY = point.y() + offset.y();
375 mouse_event.clickCount = 1;
376 web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
377 mouse_event.type = blink::WebInputEvent::MouseUp;
378 web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
381 void SimulateMouseEvent(WebContents* web_contents,
382 blink::WebInputEvent::Type type,
383 const gfx::Point& point) {
384 blink::WebMouseEvent mouse_event;
385 mouse_event.type = type;
386 mouse_event.x = point.x();
387 mouse_event.y = point.y();
388 web_contents->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
391 void SimulateTapAt(WebContents* web_contents, const gfx::Point& point) {
392 blink::WebGestureEvent tap;
393 tap.type = blink::WebGestureEvent::GestureTap;
394 tap.x = point.x();
395 tap.y = point.y();
396 RenderWidgetHostImpl* widget_host =
397 RenderWidgetHostImpl::From(web_contents->GetRenderViewHost());
398 widget_host->ForwardGestureEvent(tap);
401 void SimulateKeyPress(WebContents* web_contents,
402 ui::KeyboardCode key_code,
403 bool control,
404 bool shift,
405 bool alt,
406 bool command) {
407 SimulateKeyPressWithCode(
408 web_contents, key_code, NULL, control, shift, alt, command);
411 void SimulateKeyPressWithCode(WebContents* web_contents,
412 ui::KeyboardCode key_code,
413 const char* code,
414 bool control,
415 bool shift,
416 bool alt,
417 bool command) {
418 int native_key_code = ui::KeycodeConverter::CodeToNativeKeycode(code);
420 int modifiers = 0;
422 // The order of these key down events shouldn't matter for our simulation.
423 // For our simulation we can use either the left keys or the right keys.
424 if (control) {
425 modifiers |= blink::WebInputEvent::ControlKey;
426 InjectRawKeyEvent(web_contents,
427 blink::WebInputEvent::RawKeyDown,
428 ui::VKEY_CONTROL,
429 ui::KeycodeConverter::CodeToNativeKeycode("ControlLeft"),
430 modifiers);
433 if (shift) {
434 modifiers |= blink::WebInputEvent::ShiftKey;
435 InjectRawKeyEvent(web_contents,
436 blink::WebInputEvent::RawKeyDown,
437 ui::VKEY_SHIFT,
438 ui::KeycodeConverter::CodeToNativeKeycode("ShiftLeft"),
439 modifiers);
442 if (alt) {
443 modifiers |= blink::WebInputEvent::AltKey;
444 InjectRawKeyEvent(web_contents,
445 blink::WebInputEvent::RawKeyDown,
446 ui::VKEY_MENU,
447 ui::KeycodeConverter::CodeToNativeKeycode("AltLeft"),
448 modifiers);
451 if (command) {
452 modifiers |= blink::WebInputEvent::MetaKey;
453 InjectRawKeyEvent(web_contents,
454 blink::WebInputEvent::RawKeyDown,
455 ui::VKEY_COMMAND,
456 ui::KeycodeConverter::CodeToNativeKeycode("OSLeft"),
457 modifiers);
460 InjectRawKeyEvent(
461 web_contents,
462 blink::WebInputEvent::RawKeyDown,
463 key_code,
464 native_key_code,
465 modifiers);
467 InjectRawKeyEvent(
468 web_contents,
469 blink::WebInputEvent::Char,
470 key_code,
471 native_key_code,
472 modifiers);
474 InjectRawKeyEvent(
475 web_contents,
476 blink::WebInputEvent::KeyUp,
477 key_code,
478 native_key_code,
479 modifiers);
481 // The order of these key releases shouldn't matter for our simulation.
482 if (control) {
483 modifiers &= ~blink::WebInputEvent::ControlKey;
484 InjectRawKeyEvent(web_contents,
485 blink::WebInputEvent::KeyUp,
486 ui::VKEY_CONTROL,
487 ui::KeycodeConverter::CodeToNativeKeycode("ControlLeft"),
488 modifiers);
491 if (shift) {
492 modifiers &= ~blink::WebInputEvent::ShiftKey;
493 InjectRawKeyEvent(web_contents,
494 blink::WebInputEvent::KeyUp,
495 ui::VKEY_SHIFT,
496 ui::KeycodeConverter::CodeToNativeKeycode("ShiftLeft"),
497 modifiers);
500 if (alt) {
501 modifiers &= ~blink::WebInputEvent::AltKey;
502 InjectRawKeyEvent(web_contents,
503 blink::WebInputEvent::KeyUp,
504 ui::VKEY_MENU,
505 ui::KeycodeConverter::CodeToNativeKeycode("AltLeft"),
506 modifiers);
509 if (command) {
510 modifiers &= ~blink::WebInputEvent::MetaKey;
511 InjectRawKeyEvent(web_contents,
512 blink::WebInputEvent::KeyUp,
513 ui::VKEY_COMMAND,
514 ui::KeycodeConverter::CodeToNativeKeycode("OSLeft"),
515 modifiers);
518 ASSERT_EQ(modifiers, 0);
521 namespace internal {
523 ToRenderFrameHost::ToRenderFrameHost(WebContents* web_contents)
524 : render_frame_host_(web_contents->GetMainFrame()) {
527 ToRenderFrameHost::ToRenderFrameHost(RenderViewHost* render_view_host)
528 : render_frame_host_(render_view_host->GetMainFrame()) {
531 ToRenderFrameHost::ToRenderFrameHost(RenderFrameHost* render_frame_host)
532 : render_frame_host_(render_frame_host) {
535 } // namespace internal
537 bool ExecuteScript(const internal::ToRenderFrameHost& adapter,
538 const std::string& script) {
539 std::string new_script =
540 script + ";window.domAutomationController.send(0);";
541 return ExecuteScriptHelper(adapter.render_frame_host(), new_script, NULL);
544 bool ExecuteScriptAndExtractInt(const internal::ToRenderFrameHost& adapter,
545 const std::string& script, int* result) {
546 DCHECK(result);
547 scoped_ptr<base::Value> value;
548 if (!ExecuteScriptHelper(adapter.render_frame_host(), script, &value) ||
549 !value.get()) {
550 return false;
553 return value->GetAsInteger(result);
556 bool ExecuteScriptAndExtractBool(const internal::ToRenderFrameHost& adapter,
557 const std::string& script, bool* result) {
558 DCHECK(result);
559 scoped_ptr<base::Value> value;
560 if (!ExecuteScriptHelper(adapter.render_frame_host(), script, &value) ||
561 !value.get()) {
562 return false;
565 return value->GetAsBoolean(result);
568 bool ExecuteScriptAndExtractString(const internal::ToRenderFrameHost& adapter,
569 const std::string& script,
570 std::string* result) {
571 DCHECK(result);
572 scoped_ptr<base::Value> value;
573 if (!ExecuteScriptHelper(adapter.render_frame_host(), script, &value) ||
574 !value.get()) {
575 return false;
578 return value->GetAsString(result);
581 namespace {
582 void AddToSetIfFrameMatchesPredicate(
583 std::set<RenderFrameHost*>* frame_set,
584 const base::Callback<bool(RenderFrameHost*)>& predicate,
585 RenderFrameHost* host) {
586 if (predicate.Run(host))
587 frame_set->insert(host);
591 RenderFrameHost* FrameMatchingPredicate(
592 WebContents* web_contents,
593 const base::Callback<bool(RenderFrameHost*)>& predicate) {
594 std::set<RenderFrameHost*> frame_set;
595 web_contents->ForEachFrame(
596 base::Bind(&AddToSetIfFrameMatchesPredicate, &frame_set, predicate));
597 DCHECK_EQ(1U, frame_set.size());
598 return *frame_set.begin();
601 bool FrameMatchesName(const std::string& name, RenderFrameHost* frame) {
602 return frame->GetFrameName() == name;
605 bool FrameIsChildOfMainFrame(RenderFrameHost* frame) {
606 return frame->GetParent() && !frame->GetParent()->GetParent();
609 bool FrameHasSourceUrl(const GURL& url, RenderFrameHost* frame) {
610 return frame->GetLastCommittedURL() == url;
613 bool ExecuteWebUIResourceTest(WebContents* web_contents,
614 const std::vector<int>& js_resource_ids) {
615 // Inject WebUI test runner script first prior to other scripts required to
616 // run the test as scripts may depend on it being declared.
617 std::vector<int> ids;
618 ids.push_back(IDR_WEBUI_JS_WEBUI_RESOURCE_TEST);
619 ids.insert(ids.end(), js_resource_ids.begin(), js_resource_ids.end());
621 std::string script;
622 for (std::vector<int>::iterator iter = ids.begin();
623 iter != ids.end();
624 ++iter) {
625 ResourceBundle::GetSharedInstance().GetRawDataResource(*iter)
626 .AppendToString(&script);
627 script.append("\n");
629 if (!ExecuteScript(web_contents, script))
630 return false;
632 DOMMessageQueue message_queue;
633 if (!ExecuteScript(web_contents, "runTests()"))
634 return false;
636 std::string message;
637 do {
638 if (!message_queue.WaitForMessage(&message))
639 return false;
640 } while (message.compare("\"PENDING\"") == 0);
642 return message.compare("\"SUCCESS\"") == 0;
645 std::string GetCookies(BrowserContext* browser_context, const GURL& url) {
646 std::string cookies;
647 base::WaitableEvent event(true, false);
648 net::URLRequestContextGetter* context_getter =
649 browser_context->GetRequestContext();
651 BrowserThread::PostTask(
652 BrowserThread::IO, FROM_HERE,
653 base::Bind(&GetCookiesOnIOThread, url,
654 make_scoped_refptr(context_getter), &event, &cookies));
655 event.Wait();
656 return cookies;
659 bool SetCookie(BrowserContext* browser_context,
660 const GURL& url,
661 const std::string& value) {
662 bool result = false;
663 base::WaitableEvent event(true, false);
664 net::URLRequestContextGetter* context_getter =
665 browser_context->GetRequestContext();
667 BrowserThread::PostTask(
668 BrowserThread::IO, FROM_HERE,
669 base::Bind(&SetCookieOnIOThread, url, value,
670 make_scoped_refptr(context_getter), &event, &result));
671 event.Wait();
672 return result;
675 void FetchHistogramsFromChildProcesses() {
676 scoped_refptr<content::MessageLoopRunner> runner = new MessageLoopRunner;
678 FetchHistogramsAsynchronously(
679 base::MessageLoop::current(),
680 runner->QuitClosure(),
681 // If this call times out, it means that a child process is not
682 // responding, which is something we should not ignore. The timeout is
683 // set to be longer than the normal browser test timeout so that it will
684 // be prempted by the normal timeout.
685 TestTimeouts::action_max_timeout());
686 runner->Run();
689 void SetupCrossSiteRedirector(
690 net::test_server::EmbeddedTestServer* embedded_test_server) {
691 embedded_test_server->RegisterRequestHandler(
692 base::Bind(&CrossSiteRedirectResponseHandler,
693 embedded_test_server->base_url()));
696 void WaitForInterstitialAttach(content::WebContents* web_contents) {
697 if (web_contents->ShowingInterstitialPage())
698 return;
699 scoped_refptr<content::MessageLoopRunner> loop_runner(
700 new content::MessageLoopRunner);
701 InterstitialObserver observer(web_contents,
702 loop_runner->QuitClosure(),
703 base::Closure());
704 loop_runner->Run();
707 void WaitForInterstitialDetach(content::WebContents* web_contents) {
708 RunTaskAndWaitForInterstitialDetach(web_contents, base::Closure());
711 void RunTaskAndWaitForInterstitialDetach(content::WebContents* web_contents,
712 const base::Closure& task) {
713 if (!web_contents || !web_contents->ShowingInterstitialPage())
714 return;
715 scoped_refptr<content::MessageLoopRunner> loop_runner(
716 new content::MessageLoopRunner);
717 InterstitialObserver observer(web_contents,
718 base::Closure(),
719 loop_runner->QuitClosure());
720 if (!task.is_null())
721 task.Run();
722 // At this point, web_contents may have been deleted.
723 loop_runner->Run();
726 bool WaitForRenderFrameReady(RenderFrameHost* rfh) {
727 if (!rfh)
728 return false;
729 std::string result;
730 EXPECT_TRUE(
731 content::ExecuteScriptAndExtractString(
732 rfh,
733 "(function() {"
734 " var done = false;"
735 " function checkState() {"
736 " if (!done && document.readyState == 'complete') {"
737 " done = true;"
738 " window.domAutomationController.send('pageLoadComplete');"
739 " }"
740 " }"
741 " checkState();"
742 " document.addEventListener('readystatechange', checkState);"
743 "})();",
744 &result));
745 return result == "pageLoadComplete";
748 TitleWatcher::TitleWatcher(WebContents* web_contents,
749 const base::string16& expected_title)
750 : WebContentsObserver(web_contents),
751 message_loop_runner_(new MessageLoopRunner) {
752 EXPECT_TRUE(web_contents != NULL);
753 expected_titles_.push_back(expected_title);
756 void TitleWatcher::AlsoWaitForTitle(const base::string16& expected_title) {
757 expected_titles_.push_back(expected_title);
760 TitleWatcher::~TitleWatcher() {
763 const base::string16& TitleWatcher::WaitAndGetTitle() {
764 TestTitle();
765 message_loop_runner_->Run();
766 return observed_title_;
769 void TitleWatcher::DidStopLoading(RenderViewHost* render_view_host) {
770 // When navigating through the history, the restored NavigationEntry's title
771 // will be used. If the entry ends up having the same title after we return
772 // to it, as will usually be the case, then WebContentsObserver::TitleSet
773 // will then be suppressed, since the NavigationEntry's title hasn't changed.
774 TestTitle();
777 void TitleWatcher::TitleWasSet(NavigationEntry* entry, bool explicit_set) {
778 TestTitle();
781 void TitleWatcher::TestTitle() {
782 std::vector<base::string16>::const_iterator it =
783 std::find(expected_titles_.begin(),
784 expected_titles_.end(),
785 web_contents()->GetTitle());
786 if (it == expected_titles_.end())
787 return;
789 observed_title_ = *it;
790 message_loop_runner_->Quit();
793 WebContentsDestroyedWatcher::WebContentsDestroyedWatcher(
794 WebContents* web_contents)
795 : WebContentsObserver(web_contents),
796 message_loop_runner_(new MessageLoopRunner) {
797 EXPECT_TRUE(web_contents != NULL);
800 WebContentsDestroyedWatcher::~WebContentsDestroyedWatcher() {
803 void WebContentsDestroyedWatcher::Wait() {
804 message_loop_runner_->Run();
807 void WebContentsDestroyedWatcher::WebContentsDestroyed() {
808 message_loop_runner_->Quit();
811 RenderProcessHostWatcher::RenderProcessHostWatcher(
812 RenderProcessHost* render_process_host, WatchType type)
813 : render_process_host_(render_process_host),
814 type_(type),
815 message_loop_runner_(new MessageLoopRunner) {
816 render_process_host_->AddObserver(this);
819 RenderProcessHostWatcher::RenderProcessHostWatcher(
820 WebContents* web_contents, WatchType type)
821 : render_process_host_(web_contents->GetRenderProcessHost()),
822 type_(type),
823 message_loop_runner_(new MessageLoopRunner) {
824 render_process_host_->AddObserver(this);
827 RenderProcessHostWatcher::~RenderProcessHostWatcher() {
828 if (render_process_host_)
829 render_process_host_->RemoveObserver(this);
832 void RenderProcessHostWatcher::Wait() {
833 message_loop_runner_->Run();
836 void RenderProcessHostWatcher::RenderProcessExited(
837 RenderProcessHost* host,
838 base::TerminationStatus status,
839 int exit_code) {
840 if (type_ == WATCH_FOR_PROCESS_EXIT)
841 message_loop_runner_->Quit();
844 void RenderProcessHostWatcher::RenderProcessHostDestroyed(
845 RenderProcessHost* host) {
846 render_process_host_ = NULL;
847 if (type_ == WATCH_FOR_HOST_DESTRUCTION)
848 message_loop_runner_->Quit();
851 DOMMessageQueue::DOMMessageQueue() {
852 registrar_.Add(this, NOTIFICATION_DOM_OPERATION_RESPONSE,
853 NotificationService::AllSources());
856 DOMMessageQueue::~DOMMessageQueue() {}
858 void DOMMessageQueue::Observe(int type,
859 const NotificationSource& source,
860 const NotificationDetails& details) {
861 Details<DomOperationNotificationDetails> dom_op_details(details);
862 message_queue_.push(dom_op_details->json);
863 if (message_loop_runner_.get())
864 message_loop_runner_->Quit();
867 void DOMMessageQueue::ClearQueue() {
868 message_queue_ = std::queue<std::string>();
871 bool DOMMessageQueue::WaitForMessage(std::string* message) {
872 DCHECK(message);
873 if (message_queue_.empty()) {
874 // This will be quit when a new message comes in.
875 message_loop_runner_ = new MessageLoopRunner;
876 message_loop_runner_->Run();
878 // The queue should not be empty, unless we were quit because of a timeout.
879 if (message_queue_.empty())
880 return false;
881 *message = message_queue_.front();
882 message_queue_.pop();
883 return true;
886 class WebContentsAddedObserver::RenderViewCreatedObserver
887 : public WebContentsObserver {
888 public:
889 explicit RenderViewCreatedObserver(WebContents* web_contents)
890 : WebContentsObserver(web_contents),
891 render_view_created_called_(false),
892 main_frame_created_called_(false) {}
894 // WebContentsObserver:
895 void RenderViewCreated(RenderViewHost* rvh) override {
896 render_view_created_called_ = true;
899 void RenderFrameCreated(RenderFrameHost* rfh) override {
900 if (rfh == web_contents()->GetMainFrame())
901 main_frame_created_called_ = true;
904 bool render_view_created_called_;
905 bool main_frame_created_called_;
908 WebContentsAddedObserver::WebContentsAddedObserver()
909 : web_contents_created_callback_(
910 base::Bind(&WebContentsAddedObserver::WebContentsCreated,
911 base::Unretained(this))),
912 web_contents_(NULL) {
913 WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
914 web_contents_created_callback_);
917 WebContentsAddedObserver::~WebContentsAddedObserver() {
918 WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
919 web_contents_created_callback_);
922 void WebContentsAddedObserver::WebContentsCreated(WebContents* web_contents) {
923 DCHECK(!web_contents_);
924 web_contents_ = web_contents;
925 child_observer_.reset(new RenderViewCreatedObserver(web_contents));
927 if (runner_.get())
928 runner_->QuitClosure().Run();
931 WebContents* WebContentsAddedObserver::GetWebContents() {
932 if (web_contents_)
933 return web_contents_;
935 runner_ = new MessageLoopRunner();
936 runner_->Run();
937 return web_contents_;
940 bool WebContentsAddedObserver::RenderViewCreatedCalled() {
941 if (child_observer_) {
942 return child_observer_->render_view_created_called_ &&
943 child_observer_->main_frame_created_called_;
945 return false;
948 } // namespace content