ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / public / test / browser_test_utils.h
bloba55ad06c2260fb0dd0f9a340810e4786af9c8574
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 base {
32 class RunLoop;
35 namespace gfx {
36 class Point;
39 namespace net {
40 namespace test_server {
41 class EmbeddedTestServer;
45 // A collections of functions designed for use with content_browsertests and
46 // browser_tests.
47 // TO BE CLEAR: any function here must work against both binaries. If it only
48 // works with browser_tests, it should be in chrome\test\base\ui_test_utils.h.
49 // If it only works with content_browsertests, it should be in
50 // content\test\content_browser_test_utils.h.
52 namespace content {
54 class BrowserContext;
55 class MessageLoopRunner;
56 class RenderViewHost;
57 class WebContents;
59 // Navigate a frame with ID |iframe_id| to |url|, blocking until the navigation
60 // finishes. Uses a renderer-initiated navigation from script code in the
61 // main frame.
62 bool NavigateIframeToURL(WebContents* web_contents,
63 std::string iframe_id,
64 const GURL& url);
66 // Generate a URL for a file path including a query string.
67 GURL GetFileUrlWithQuery(const base::FilePath& path,
68 const std::string& query_string);
70 // Checks whether the page type of the last committed navigation entry matches
71 // |page_type|.
72 bool IsLastCommittedEntryOfPageType(WebContents* web_contents,
73 content::PageType page_type);
75 // Waits for a load stop for the specified |web_contents|'s controller, if the
76 // tab is currently web_contents. Otherwise returns immediately. Tests should
77 // use WaitForLoadStop instead and check that last navigation succeeds, and
78 // this function should only be used if the navigation leads to web_contents
79 // being destroyed.
80 void WaitForLoadStopWithoutSuccessCheck(WebContents* web_contents);
82 // Waits for a load stop for the specified |web_contents|'s controller, if the
83 // tab is currently web_contents. Otherwise returns immediately. Returns true
84 // if the last navigation succeeded (resulted in a committed navigation entry
85 // of type PAGE_TYPE_NORMAL).
86 // TODO(alexmos): tests that use this function to wait for successful
87 // navigations should be refactored to do EXPECT_TRUE(WaitForLoadStop()).
88 bool WaitForLoadStop(WebContents* web_contents);
90 #if defined(USE_AURA)
91 // If WebContent's view is currently being resized, this will wait for the ack
92 // from the renderer that the resize is complete and for the
93 // WindowEventDispatcher to release the pointer moves. If there's no resize in
94 // progress, the method will return right away.
95 void WaitForResizeComplete(WebContents* web_contents);
96 #endif // USE_AURA
98 // Causes the specified web_contents to crash. Blocks until it is crashed.
99 void CrashTab(WebContents* web_contents);
101 // Simulates clicking at the center of the given tab asynchronously; modifiers
102 // may contain bits from WebInputEvent::Modifiers.
103 void SimulateMouseClick(WebContents* web_contents,
104 int modifiers,
105 blink::WebMouseEvent::Button button);
107 // Simulates clicking at the point |point| of the given tab asynchronously;
108 // modifiers may contain bits from WebInputEvent::Modifiers.
109 void SimulateMouseClickAt(WebContents* web_contents,
110 int modifiers,
111 blink::WebMouseEvent::Button button,
112 const gfx::Point& point);
114 // Simulates asynchronously a mouse enter/move/leave event.
115 void SimulateMouseEvent(WebContents* web_contents,
116 blink::WebInputEvent::Type type,
117 const gfx::Point& point);
119 // Taps the screen at |point|.
120 void SimulateTapAt(WebContents* web_contents, const gfx::Point& point);
122 // Sends a key press asynchronously.
123 // The native code of the key event will be set to InvalidNativeKeycode().
124 // |key_code| alone is good enough for scenarios that only need the char
125 // value represented by a key event and not the physical key on the keyboard
126 // or the keyboard layout.
127 // For scenarios such as chromoting that need the native code,
128 // SimulateKeyPressWithCode should be used.
129 void SimulateKeyPress(WebContents* web_contents,
130 ui::KeyboardCode key_code,
131 bool control,
132 bool shift,
133 bool alt,
134 bool command);
136 // Sends a key press asynchronously.
137 // |code| specifies the UIEvents (aka: DOM4Events) value of the key:
138 // https://dvcs.w3.org/hg/d4e/raw-file/tip/source_respec.htm
139 // The native code of the key event will be set based on |code|.
140 // See ui/base/keycodes/vi usb_keycode_map.h for mappings between |code|
141 // and the native code.
142 // Examples of the various codes:
143 // key_code: VKEY_A
144 // code: "KeyA"
145 // native key code: 0x001e (for Windows).
146 // native key code: 0x0026 (for Linux).
147 void SimulateKeyPressWithCode(WebContents* web_contents,
148 ui::KeyboardCode key_code,
149 const char* code,
150 bool control,
151 bool shift,
152 bool alt,
153 bool command);
155 namespace internal {
156 // Allow ExecuteScript* methods to target either a WebContents or a
157 // RenderFrameHost. Targetting a WebContents means executing the script in the
158 // RenderFrameHost returned by WebContents::GetMainFrame(), which is the
159 // main frame. Pass a specific RenderFrameHost to target it.
160 class ToRenderFrameHost {
161 public:
162 ToRenderFrameHost(WebContents* web_contents);
163 ToRenderFrameHost(RenderViewHost* render_view_host);
164 ToRenderFrameHost(RenderFrameHost* render_frame_host);
166 RenderFrameHost* render_frame_host() const { return render_frame_host_; }
168 private:
169 RenderFrameHost* render_frame_host_;
171 } // namespace internal
173 // Executes the passed |script| in the specified frame. The |script| should not
174 // invoke domAutomationController.send(); otherwise, your test will hang or be
175 // flaky. If you want to extract a result, use one of the below functions.
176 // Returns true on success.
177 bool ExecuteScript(const internal::ToRenderFrameHost& adapter,
178 const std::string& script) WARN_UNUSED_RESULT;
180 // The following methods executes the passed |script| in the specified frame and
181 // sets |result| to the value passed to "window.domAutomationController.send" by
182 // the executed script. They return true on success, false if the script
183 // execution failed or did not evaluate to the expected type.
184 bool ExecuteScriptAndExtractInt(const internal::ToRenderFrameHost& adapter,
185 const std::string& script,
186 int* result) WARN_UNUSED_RESULT;
187 bool ExecuteScriptAndExtractBool(const internal::ToRenderFrameHost& adapter,
188 const std::string& script,
189 bool* result) WARN_UNUSED_RESULT;
190 bool ExecuteScriptAndExtractString(const internal::ToRenderFrameHost& adapter,
191 const std::string& script,
192 std::string* result) WARN_UNUSED_RESULT;
194 // Walks the frame tree of the specified WebContents and returns the sole frame
195 // that matches the specified predicate function. This function will DCHECK if
196 // no frames match the specified predicate, or if more than one frame matches.
197 RenderFrameHost* FrameMatchingPredicate(
198 WebContents* web_contents,
199 const base::Callback<bool(RenderFrameHost*)>& predicate);
201 // Predicates for use with FrameMatchingPredicate.
202 bool FrameMatchesName(const std::string& name, RenderFrameHost* frame);
203 bool FrameIsChildOfMainFrame(RenderFrameHost* frame);
204 bool FrameHasSourceUrl(const GURL& url, RenderFrameHost* frame);
206 // Executes the WebUI resource test runner injecting each resource ID in
207 // |js_resource_ids| prior to executing the tests.
209 // Returns true if tests ran successfully, false otherwise.
210 bool ExecuteWebUIResourceTest(WebContents* web_contents,
211 const std::vector<int>& js_resource_ids);
213 // Returns the cookies for the given url.
214 std::string GetCookies(BrowserContext* browser_context, const GURL& url);
216 // Sets a cookie for the given url. Returns true on success.
217 bool SetCookie(BrowserContext* browser_context,
218 const GURL& url,
219 const std::string& value);
221 // Fetch the histograms data from other processes. This should be called after
222 // the test code has been executed but before performing assertions.
223 void FetchHistogramsFromChildProcesses();
225 // Registers a request handler which redirects to a different host, based
226 // on the request path. The format of the path should be
227 // "/cross-site/hostname/rest/of/path" to redirect the request to
228 // "<scheme>://hostname:<port>/rest/of/path", where <scheme> and <port>
229 // are the values for the instance of EmbeddedTestServer.
230 void SetupCrossSiteRedirector(
231 net::test_server::EmbeddedTestServer* embedded_test_server);
233 // Waits for an interstitial page to attach to given web contents.
234 void WaitForInterstitialAttach(content::WebContents* web_contents);
236 // Waits for an interstitial page to detach from given web contents.
237 void WaitForInterstitialDetach(content::WebContents* web_contents);
239 // Runs task and waits for an interstitial page to detach from given web
240 // contents. Prefer this over WaitForInterstitialDetach if web_contents may be
241 // destroyed by the time WaitForInterstitialDetach is called (e.g. when waiting
242 // for an interstitial detach after closing a tab).
243 void RunTaskAndWaitForInterstitialDetach(content::WebContents* web_contents,
244 const base::Closure& task);
246 // Waits until all resources have loaded in the given RenderFrameHost.
247 // When the load completes, this function sends a "pageLoadComplete" message
248 // via domAutomationController. The caller should make sure this extra
249 // message is handled properly.
250 bool WaitForRenderFrameReady(RenderFrameHost* rfh) WARN_UNUSED_RESULT;
252 // Watches title changes on a WebContents, blocking until an expected title is
253 // set.
254 class TitleWatcher : public WebContentsObserver {
255 public:
256 // |web_contents| must be non-NULL and needs to stay alive for the
257 // entire lifetime of |this|. |expected_title| is the title that |this|
258 // will wait for.
259 TitleWatcher(WebContents* web_contents,
260 const base::string16& expected_title);
261 ~TitleWatcher() override;
263 // Adds another title to watch for.
264 void AlsoWaitForTitle(const base::string16& expected_title);
266 // Waits until the title matches either expected_title or one of the titles
267 // added with AlsoWaitForTitle. Returns the value of the most recently
268 // observed matching title.
269 const base::string16& WaitAndGetTitle() WARN_UNUSED_RESULT;
271 private:
272 // Overridden WebContentsObserver methods.
273 void DidStopLoading(RenderViewHost* render_view_host) override;
274 void TitleWasSet(NavigationEntry* entry, bool explicit_set) override;
276 void TestTitle();
278 std::vector<base::string16> expected_titles_;
279 scoped_refptr<MessageLoopRunner> message_loop_runner_;
281 // The most recently observed expected title, if any.
282 base::string16 observed_title_;
284 DISALLOW_COPY_AND_ASSIGN(TitleWatcher);
287 // Watches a WebContents and blocks until it is destroyed.
288 class WebContentsDestroyedWatcher : public WebContentsObserver {
289 public:
290 explicit WebContentsDestroyedWatcher(WebContents* web_contents);
291 ~WebContentsDestroyedWatcher() override;
293 // Waits until the WebContents is destroyed.
294 void Wait();
296 private:
297 // Overridden WebContentsObserver methods.
298 void WebContentsDestroyed() override;
300 scoped_refptr<MessageLoopRunner> message_loop_runner_;
302 DISALLOW_COPY_AND_ASSIGN(WebContentsDestroyedWatcher);
305 // Watches a RenderProcessHost and waits for specified destruction events.
306 class RenderProcessHostWatcher : public RenderProcessHostObserver {
307 public:
308 enum WatchType {
309 WATCH_FOR_PROCESS_EXIT,
310 WATCH_FOR_HOST_DESTRUCTION
313 RenderProcessHostWatcher(RenderProcessHost* render_process_host,
314 WatchType type);
315 // Waits for the render process that contains the specified web contents.
316 RenderProcessHostWatcher(WebContents* web_contents, WatchType type);
317 ~RenderProcessHostWatcher() override;
319 // Waits until the renderer process exits.
320 void Wait();
322 private:
323 // Overridden RenderProcessHost::LifecycleObserver methods.
324 void RenderProcessExited(RenderProcessHost* host,
325 base::TerminationStatus status,
326 int exit_code) override;
327 void RenderProcessHostDestroyed(RenderProcessHost* host) override;
329 RenderProcessHost* render_process_host_;
330 WatchType type_;
332 scoped_refptr<MessageLoopRunner> message_loop_runner_;
334 DISALLOW_COPY_AND_ASSIGN(RenderProcessHostWatcher);
337 // Watches for responses from the DOMAutomationController and keeps them in a
338 // queue. Useful for waiting for a message to be received.
339 class DOMMessageQueue : public NotificationObserver {
340 public:
341 // Constructs a DOMMessageQueue and begins listening for messages from the
342 // DOMAutomationController. Do not construct this until the browser has
343 // started.
344 DOMMessageQueue();
345 ~DOMMessageQueue() override;
347 // Removes all messages in the message queue.
348 void ClearQueue();
350 // Wait for the next message to arrive. |message| will be set to the next
351 // message. Returns true on success.
352 bool WaitForMessage(std::string* message) WARN_UNUSED_RESULT;
354 // Overridden NotificationObserver methods.
355 void Observe(int type,
356 const NotificationSource& source,
357 const NotificationDetails& details) override;
359 private:
360 NotificationRegistrar registrar_;
361 std::queue<std::string> message_queue_;
362 scoped_refptr<MessageLoopRunner> message_loop_runner_;
364 DISALLOW_COPY_AND_ASSIGN(DOMMessageQueue);
367 // Used to wait for a new WebContents to be created. Instantiate this object
368 // before the operation that will create the window.
369 class WebContentsAddedObserver {
370 public:
371 WebContentsAddedObserver();
372 ~WebContentsAddedObserver();
374 // Will run a message loop to wait for the new window if it hasn't been
375 // created since the constructor
376 WebContents* GetWebContents();
378 // Will tell whether RenderViewCreated Callback has invoked
379 bool RenderViewCreatedCalled();
381 private:
382 class RenderViewCreatedObserver;
384 void WebContentsCreated(WebContents* web_contents);
386 // Callback to WebContentCreated(). Cached so that we can unregister it.
387 base::Callback<void(WebContents*)> web_contents_created_callback_;
389 WebContents* web_contents_;
390 scoped_ptr<RenderViewCreatedObserver> child_observer_;
391 scoped_refptr<MessageLoopRunner> runner_;
393 DISALLOW_COPY_AND_ASSIGN(WebContentsAddedObserver);
396 } // namespace content
398 #endif // CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_