[Android WebView] Fix webview perf bot switchover to use org.chromium.webview_shell...
[chromium-blink-merge.git] / content / public / test / browser_test_utils.h
blob7faff1928793d72ff97a991afacd7dcbca63d314
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 #ifndef CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_
6 #define CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_
8 #include <queue>
9 #include <string>
10 #include <vector>
12 #include "base/callback.h"
13 #include "base/compiler_specific.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/process/process.h"
17 #include "base/strings/string16.h"
18 #include "content/public/browser/notification_observer.h"
19 #include "content/public/browser/notification_registrar.h"
20 #include "content/public/browser/render_process_host_observer.h"
21 #include "content/public/browser/web_contents_observer.h"
22 #include "content/public/common/page_type.h"
23 #include "third_party/WebKit/public/web/WebInputEvent.h"
24 #include "ui/events/keycodes/keyboard_codes.h"
25 #include "url/gurl.h"
27 #if defined(OS_WIN)
28 #include "base/win/scoped_handle.h"
29 #endif
31 namespace gfx {
32 class Point;
35 namespace net {
36 namespace test_server {
37 class EmbeddedTestServer;
41 // A collections of functions designed for use with content_browsertests and
42 // browser_tests.
43 // TO BE CLEAR: any function here must work against both binaries. If it only
44 // works with browser_tests, it should be in chrome\test\base\ui_test_utils.h.
45 // If it only works with content_browsertests, it should be in
46 // content\test\content_browser_test_utils.h.
48 namespace content {
50 class BrowserContext;
51 class MessageLoopRunner;
52 class RenderViewHost;
53 class WebContents;
55 // Navigate a frame with ID |iframe_id| to |url|, blocking until the navigation
56 // finishes. Uses a renderer-initiated navigation from script code in the
57 // main frame.
58 bool NavigateIframeToURL(WebContents* web_contents,
59 std::string iframe_id,
60 const GURL& url);
62 // Generate a URL for a file path including a query string.
63 GURL GetFileUrlWithQuery(const base::FilePath& path,
64 const std::string& query_string);
66 // Checks whether the page type of the last committed navigation entry matches
67 // |page_type|.
68 bool IsLastCommittedEntryOfPageType(WebContents* web_contents,
69 content::PageType page_type);
71 // Waits for a load stop for the specified |web_contents|'s controller, if the
72 // tab is currently web_contents. Otherwise returns immediately. Tests should
73 // use WaitForLoadStop instead and check that last navigation succeeds, and
74 // this function should only be used if the navigation leads to web_contents
75 // being destroyed.
76 void WaitForLoadStopWithoutSuccessCheck(WebContents* web_contents);
78 // Waits for a load stop for the specified |web_contents|'s controller, if the
79 // tab is currently web_contents. Otherwise returns immediately. Returns true
80 // if the last navigation succeeded (resulted in a committed navigation entry
81 // of type PAGE_TYPE_NORMAL).
82 // TODO(alexmos): tests that use this function to wait for successful
83 // navigations should be refactored to do EXPECT_TRUE(WaitForLoadStop()).
84 bool WaitForLoadStop(WebContents* web_contents);
86 #if defined(USE_AURA) || defined(OS_ANDROID)
87 // If WebContent's view is currently being resized, this will wait for the ack
88 // from the renderer that the resize is complete and for the
89 // WindowEventDispatcher to release the pointer moves. If there's no resize in
90 // progress, the method will return right away.
91 void WaitForResizeComplete(WebContents* web_contents);
92 #endif // defined(USE_AURA) || defined(OS_ANDROID)
94 // Causes the specified web_contents to crash. Blocks until it is crashed.
95 void CrashTab(WebContents* web_contents);
97 // Simulates clicking at the center of the given tab asynchronously; modifiers
98 // may contain bits from WebInputEvent::Modifiers.
99 void SimulateMouseClick(WebContents* web_contents,
100 int modifiers,
101 blink::WebMouseEvent::Button button);
103 // Simulates clicking at the point |point| of the given tab asynchronously;
104 // modifiers may contain bits from WebInputEvent::Modifiers.
105 void SimulateMouseClickAt(WebContents* web_contents,
106 int modifiers,
107 blink::WebMouseEvent::Button button,
108 const gfx::Point& point);
110 // Simulates asynchronously a mouse enter/move/leave event.
111 void SimulateMouseEvent(WebContents* web_contents,
112 blink::WebInputEvent::Type type,
113 const gfx::Point& point);
115 // Taps the screen at |point|.
116 void SimulateTapAt(WebContents* web_contents, const gfx::Point& point);
118 // Taps the screen with modifires at |point|.
119 void SimulateTapWithModifiersAt(WebContents* web_contents,
120 unsigned Modifiers,
121 const gfx::Point& point);
123 // Sends a key press asynchronously.
124 // The native code of the key event will be set to InvalidNativeKeycode().
125 // |key_code| alone is good enough for scenarios that only need the char
126 // value represented by a key event and not the physical key on the keyboard
127 // or the keyboard layout.
128 // For scenarios such as chromoting that need the native code,
129 // SimulateKeyPressWithCode should be used.
130 void SimulateKeyPress(WebContents* web_contents,
131 ui::KeyboardCode key_code,
132 bool control,
133 bool shift,
134 bool alt,
135 bool command);
137 // Sends a key press asynchronously.
138 // |code| specifies the UIEvents (aka: DOM4Events) value of the key:
139 // https://dvcs.w3.org/hg/d4e/raw-file/tip/source_respec.htm
140 // The native code of the key event will be set based on |code|.
141 // See ui/base/keycodes/vi usb_keycode_map.h for mappings between |code|
142 // and the native code.
143 // Examples of the various codes:
144 // key_code: VKEY_A
145 // code: "KeyA"
146 // native key code: 0x001e (for Windows).
147 // native key code: 0x0026 (for Linux).
148 void SimulateKeyPressWithCode(WebContents* web_contents,
149 ui::KeyboardCode key_code,
150 const char* code,
151 bool control,
152 bool shift,
153 bool alt,
154 bool command);
156 namespace internal {
157 // Allow ExecuteScript* methods to target either a WebContents or a
158 // RenderFrameHost. Targetting a WebContents means executing the script in the
159 // RenderFrameHost returned by WebContents::GetMainFrame(), which is the
160 // main frame. Pass a specific RenderFrameHost to target it.
161 class ToRenderFrameHost {
162 public:
163 ToRenderFrameHost(WebContents* web_contents);
164 ToRenderFrameHost(RenderViewHost* render_view_host);
165 ToRenderFrameHost(RenderFrameHost* render_frame_host);
167 RenderFrameHost* render_frame_host() const { return render_frame_host_; }
169 private:
170 RenderFrameHost* render_frame_host_;
172 } // namespace internal
174 // Executes the passed |script| in the specified frame. The |script| should not
175 // invoke domAutomationController.send(); otherwise, your test will hang or be
176 // flaky. If you want to extract a result, use one of the below functions.
177 // Returns true on success.
178 bool ExecuteScript(const internal::ToRenderFrameHost& adapter,
179 const std::string& script) WARN_UNUSED_RESULT;
181 // The following methods executes the passed |script| in the specified frame and
182 // sets |result| to the value passed to "window.domAutomationController.send" by
183 // the executed script. They return true on success, false if the script
184 // execution failed or did not evaluate to the expected type.
185 bool ExecuteScriptAndExtractInt(const internal::ToRenderFrameHost& adapter,
186 const std::string& script,
187 int* result) WARN_UNUSED_RESULT;
188 bool ExecuteScriptAndExtractBool(const internal::ToRenderFrameHost& adapter,
189 const std::string& script,
190 bool* result) WARN_UNUSED_RESULT;
191 bool ExecuteScriptAndExtractString(const internal::ToRenderFrameHost& adapter,
192 const std::string& script,
193 std::string* result) WARN_UNUSED_RESULT;
195 // Walks the frame tree of the specified WebContents and returns the sole frame
196 // that matches the specified predicate function. This function will DCHECK if
197 // no frames match the specified predicate, or if more than one frame matches.
198 RenderFrameHost* FrameMatchingPredicate(
199 WebContents* web_contents,
200 const base::Callback<bool(RenderFrameHost*)>& predicate);
202 // Predicates for use with FrameMatchingPredicate.
203 bool FrameMatchesName(const std::string& name, RenderFrameHost* frame);
204 bool FrameIsChildOfMainFrame(RenderFrameHost* frame);
205 bool FrameHasSourceUrl(const GURL& url, RenderFrameHost* frame);
207 // Executes the WebUI resource test runner injecting each resource ID in
208 // |js_resource_ids| prior to executing the tests.
210 // Returns true if tests ran successfully, false otherwise.
211 bool ExecuteWebUIResourceTest(WebContents* web_contents,
212 const std::vector<int>& js_resource_ids);
214 // Returns the cookies for the given url.
215 std::string GetCookies(BrowserContext* browser_context, const GURL& url);
217 // Sets a cookie for the given url. Returns true on success.
218 bool SetCookie(BrowserContext* browser_context,
219 const GURL& url,
220 const std::string& value);
222 // Fetch the histograms data from other processes. This should be called after
223 // the test code has been executed but before performing assertions.
224 void FetchHistogramsFromChildProcesses();
226 // Registers a request handler which redirects to a different host, based
227 // on the request path. The format of the path should be
228 // "/cross-site/hostname/rest/of/path" to redirect the request to
229 // "<scheme>://hostname:<port>/rest/of/path", where <scheme> and <port>
230 // are the values for the instance of EmbeddedTestServer.
231 void SetupCrossSiteRedirector(
232 net::test_server::EmbeddedTestServer* embedded_test_server);
234 // Waits for an interstitial page to attach to given web contents.
235 void WaitForInterstitialAttach(content::WebContents* web_contents);
237 // Waits for an interstitial page to detach from given web contents.
238 void WaitForInterstitialDetach(content::WebContents* web_contents);
240 // Runs task and waits for an interstitial page to detach from given web
241 // contents. Prefer this over WaitForInterstitialDetach if web_contents may be
242 // destroyed by the time WaitForInterstitialDetach is called (e.g. when waiting
243 // for an interstitial detach after closing a tab).
244 void RunTaskAndWaitForInterstitialDetach(content::WebContents* web_contents,
245 const base::Closure& task);
247 // Waits until all resources have loaded in the given RenderFrameHost.
248 // When the load completes, this function sends a "pageLoadComplete" message
249 // via domAutomationController. The caller should make sure this extra
250 // message is handled properly.
251 bool WaitForRenderFrameReady(RenderFrameHost* rfh) WARN_UNUSED_RESULT;
253 // Watches title changes on a WebContents, blocking until an expected title is
254 // set.
255 class TitleWatcher : public WebContentsObserver {
256 public:
257 // |web_contents| must be non-NULL and needs to stay alive for the
258 // entire lifetime of |this|. |expected_title| is the title that |this|
259 // will wait for.
260 TitleWatcher(WebContents* web_contents,
261 const base::string16& expected_title);
262 ~TitleWatcher() override;
264 // Adds another title to watch for.
265 void AlsoWaitForTitle(const base::string16& expected_title);
267 // Waits until the title matches either expected_title or one of the titles
268 // added with AlsoWaitForTitle. Returns the value of the most recently
269 // observed matching title.
270 const base::string16& WaitAndGetTitle() WARN_UNUSED_RESULT;
272 private:
273 // Overridden WebContentsObserver methods.
274 void DidStopLoading() override;
275 void TitleWasSet(NavigationEntry* entry, bool explicit_set) override;
277 void TestTitle();
279 std::vector<base::string16> expected_titles_;
280 scoped_refptr<MessageLoopRunner> message_loop_runner_;
282 // The most recently observed expected title, if any.
283 base::string16 observed_title_;
285 DISALLOW_COPY_AND_ASSIGN(TitleWatcher);
288 // Watches a WebContents and blocks until it is destroyed.
289 class WebContentsDestroyedWatcher : public WebContentsObserver {
290 public:
291 explicit WebContentsDestroyedWatcher(WebContents* web_contents);
292 ~WebContentsDestroyedWatcher() override;
294 // Waits until the WebContents is destroyed.
295 void Wait();
297 private:
298 // Overridden WebContentsObserver methods.
299 void WebContentsDestroyed() override;
301 scoped_refptr<MessageLoopRunner> message_loop_runner_;
303 DISALLOW_COPY_AND_ASSIGN(WebContentsDestroyedWatcher);
306 // Watches a RenderProcessHost and waits for specified destruction events.
307 class RenderProcessHostWatcher : public RenderProcessHostObserver {
308 public:
309 enum WatchType {
310 WATCH_FOR_PROCESS_EXIT,
311 WATCH_FOR_HOST_DESTRUCTION
314 RenderProcessHostWatcher(RenderProcessHost* render_process_host,
315 WatchType type);
316 // Waits for the render process that contains the specified web contents.
317 RenderProcessHostWatcher(WebContents* web_contents, WatchType type);
318 ~RenderProcessHostWatcher() override;
320 // Waits until the renderer process exits.
321 void Wait();
323 // Returns true if a renderer process exited cleanly (without hitting
324 // RenderProcessExited with an abnormal TerminationStatus). This should be
325 // called after Wait().
326 bool did_exit_normally() { return did_exit_normally_; }
328 private:
329 // Overridden RenderProcessHost::LifecycleObserver methods.
330 void RenderProcessExited(RenderProcessHost* host,
331 base::TerminationStatus status,
332 int exit_code) override;
333 void RenderProcessHostDestroyed(RenderProcessHost* host) override;
335 RenderProcessHost* render_process_host_;
336 WatchType type_;
337 bool did_exit_normally_;
339 scoped_refptr<MessageLoopRunner> message_loop_runner_;
341 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostWatcher);
344 // Watches for responses from the DOMAutomationController and keeps them in a
345 // queue. Useful for waiting for a message to be received.
346 class DOMMessageQueue : public NotificationObserver {
347 public:
348 // Constructs a DOMMessageQueue and begins listening for messages from the
349 // DOMAutomationController. Do not construct this until the browser has
350 // started.
351 DOMMessageQueue();
352 ~DOMMessageQueue() override;
354 // Removes all messages in the message queue.
355 void ClearQueue();
357 // Wait for the next message to arrive. |message| will be set to the next
358 // message. Returns true on success.
359 bool WaitForMessage(std::string* message) WARN_UNUSED_RESULT;
361 // Overridden NotificationObserver methods.
362 void Observe(int type,
363 const NotificationSource& source,
364 const NotificationDetails& details) override;
366 private:
367 NotificationRegistrar registrar_;
368 std::queue<std::string> message_queue_;
369 scoped_refptr<MessageLoopRunner> message_loop_runner_;
371 DISALLOW_COPY_AND_ASSIGN(DOMMessageQueue);
374 // Used to wait for a new WebContents to be created. Instantiate this object
375 // before the operation that will create the window.
376 class WebContentsAddedObserver {
377 public:
378 WebContentsAddedObserver();
379 ~WebContentsAddedObserver();
381 // Will run a message loop to wait for the new window if it hasn't been
382 // created since the constructor
383 WebContents* GetWebContents();
385 // Will tell whether RenderViewCreated Callback has invoked
386 bool RenderViewCreatedCalled();
388 private:
389 class RenderViewCreatedObserver;
391 void WebContentsCreated(WebContents* web_contents);
393 // Callback to WebContentCreated(). Cached so that we can unregister it.
394 base::Callback<void(WebContents*)> web_contents_created_callback_;
396 WebContents* web_contents_;
397 scoped_ptr<RenderViewCreatedObserver> child_observer_;
398 scoped_refptr<MessageLoopRunner> runner_;
400 DISALLOW_COPY_AND_ASSIGN(WebContentsAddedObserver);
403 } // namespace content
405 #endif // CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_