browser_test_utils.h revision effb81e5f8246d0db0270817048dc992db66e9fb
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.
4
5#ifndef CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_
6#define CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_
7
8#include <queue>
9#include <string>
10#include <vector>
11
12#include "base/callback_forward.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 "third_party/WebKit/public/web/WebInputEvent.h"
23#include "ui/events/keycodes/keyboard_codes.h"
24#include "url/gurl.h"
25
26#if defined(OS_WIN)
27#include "base/win/scoped_handle.h"
28#endif
29
30namespace base {
31class RunLoop;
32}
33
34namespace gfx {
35class Point;
36}
37
38// A collections of functions designed for use with content_browsertests and
39// browser_tests.
40// TO BE CLEAR: any function here must work against both binaries. If it only
41// works with browser_tests, it should be in chrome\test\base\ui_test_utils.h.
42// If it only works with content_browsertests, it should be in
43// content\test\content_browser_test_utils.h.
44
45namespace content {
46
47class BrowserContext;
48class MessageLoopRunner;
49class RenderViewHost;
50class WebContents;
51
52// Generate a URL for a file path including a query string.
53GURL GetFileUrlWithQuery(const base::FilePath& path,
54                         const std::string& query_string);
55
56// Waits for a load stop for the specified |web_contents|'s controller, if the
57// tab is currently web_contents.  Otherwise returns immediately.
58void WaitForLoadStop(WebContents* web_contents);
59
60// Causes the specified web_contents to crash. Blocks until it is crashed.
61void CrashTab(WebContents* web_contents);
62
63// Simulates clicking at the center of the given tab asynchronously; modifiers
64// may contain bits from WebInputEvent::Modifiers.
65void SimulateMouseClick(WebContents* web_contents,
66                        int modifiers,
67                        blink::WebMouseEvent::Button button);
68
69// Simulates clicking at the point |point| of the given tab asynchronously;
70// modifiers may contain bits from WebInputEvent::Modifiers.
71void SimulateMouseClickAt(WebContents* web_contents,
72                          int modifiers,
73                          blink::WebMouseEvent::Button button,
74                          const gfx::Point& point);
75
76// Simulates asynchronously a mouse enter/move/leave event.
77void SimulateMouseEvent(WebContents* web_contents,
78                        blink::WebInputEvent::Type type,
79                        const gfx::Point& point);
80
81// Sends a key press asynchronously.
82// The native code of the key event will be set to InvalidNativeKeycode().
83// |key_code| alone is good enough for scenarios that only need the char
84// value represented by a key event and not the physical key on the keyboard
85// or the keyboard layout.
86// For scenarios such as chromoting that need the native code,
87// SimulateKeyPressWithCode should be used.
88void SimulateKeyPress(WebContents* web_contents,
89                      ui::KeyboardCode key_code,
90                      bool control,
91                      bool shift,
92                      bool alt,
93                      bool command);
94
95// Sends a key press asynchronously.
96// |code| specifies the UIEvents (aka: DOM4Events) value of the key:
97// https://dvcs.w3.org/hg/d4e/raw-file/tip/source_respec.htm
98// The native code of the key event will be set based on |code|.
99// See ui/base/keycodes/vi usb_keycode_map.h for mappings between |code|
100// and the native code.
101// Examples of the various codes:
102//   key_code: VKEY_A
103//   code: "KeyA"
104//   native key code: 0x001e (for Windows).
105//   native key code: 0x0026 (for Linux).
106void SimulateKeyPressWithCode(WebContents* web_contents,
107                              ui::KeyboardCode key_code,
108                              const char* code,
109                              bool control,
110                              bool shift,
111                              bool alt,
112                              bool command);
113
114namespace internal {
115// Allow ExecuteScript* methods to target either a WebContents or a
116// RenderFrameHost.  Targetting a WebContents means executing the script in the
117// RenderFrameHost returned by WebContents::GetMainFrame(), which is the
118// main frame.  Pass a specific RenderFrameHost to target it.
119class ToRenderFrameHost {
120 public:
121  ToRenderFrameHost(WebContents* web_contents);
122  ToRenderFrameHost(RenderViewHost* render_view_host);
123  ToRenderFrameHost(RenderFrameHost* render_frame_host);
124
125  RenderFrameHost* render_frame_host() const { return render_frame_host_; }
126
127 private:
128  RenderFrameHost* render_frame_host_;
129};
130}  // namespace internal
131
132// Executes the passed |script| in the specified frame. The |script| should not
133// invoke domAutomationController.send(); otherwise, your test will hang or be
134// flaky. If you want to extract a result, use one of the below functions.
135// Returns true on success.
136bool ExecuteScript(const internal::ToRenderFrameHost& adapter,
137                   const std::string& script) WARN_UNUSED_RESULT;
138
139// The following methods executes the passed |script| in the specified frame and
140// sets |result| to the value passed to "window.domAutomationController.send" by
141// the executed script. They return true on success, false if the script
142// execution failed or did not evaluate to the expected type.
143bool ExecuteScriptAndExtractInt(const internal::ToRenderFrameHost& adapter,
144                                const std::string& script,
145                                int* result) WARN_UNUSED_RESULT;
146bool ExecuteScriptAndExtractBool(const internal::ToRenderFrameHost& adapter,
147                                 const std::string& script,
148                                 bool* result) WARN_UNUSED_RESULT;
149bool ExecuteScriptAndExtractString(const internal::ToRenderFrameHost& adapter,
150                                   const std::string& script,
151                                   std::string* result) WARN_UNUSED_RESULT;
152
153// Walks the frame tree of the specified WebContents and returns the sole frame
154// that matches the specified predicate function. This function will DCHECK if
155// no frames match the specified predicate, or if more than one frame matches.
156RenderFrameHost* FrameMatchingPredicate(
157    WebContents* web_contents,
158    const base::Callback<bool(RenderFrameHost*)>& predicate);
159
160// Predicates for use with FrameMatchingPredicate.
161bool FrameMatchesName(const std::string& name, RenderFrameHost* frame);
162bool FrameIsChildOfMainFrame(RenderFrameHost* frame);
163bool FrameHasSourceUrl(const GURL& url, RenderFrameHost* frame);
164
165// Executes the WebUI resource test runner injecting each resource ID in
166// |js_resource_ids| prior to executing the tests.
167//
168// Returns true if tests ran successfully, false otherwise.
169bool ExecuteWebUIResourceTest(WebContents* web_contents,
170                              const std::vector<int>& js_resource_ids);
171
172// Returns the cookies for the given url.
173std::string GetCookies(BrowserContext* browser_context, const GURL& url);
174
175// Sets a cookie for the given url. Returns true on success.
176bool SetCookie(BrowserContext* browser_context,
177               const GURL& url,
178               const std::string& value);
179
180// Watches title changes on a WebContents, blocking until an expected title is
181// set.
182class TitleWatcher : public WebContentsObserver {
183 public:
184  // |web_contents| must be non-NULL and needs to stay alive for the
185  // entire lifetime of |this|. |expected_title| is the title that |this|
186  // will wait for.
187  TitleWatcher(WebContents* web_contents,
188               const base::string16& expected_title);
189  virtual ~TitleWatcher();
190
191  // Adds another title to watch for.
192  void AlsoWaitForTitle(const base::string16& expected_title);
193
194  // Waits until the title matches either expected_title or one of the titles
195  // added with AlsoWaitForTitle. Returns the value of the most recently
196  // observed matching title.
197  const base::string16& WaitAndGetTitle() WARN_UNUSED_RESULT;
198
199 private:
200  // Overridden WebContentsObserver methods.
201  virtual void DidStopLoading(RenderViewHost* render_view_host) OVERRIDE;
202  virtual void TitleWasSet(NavigationEntry* entry, bool explicit_set) OVERRIDE;
203
204  void TestTitle();
205
206  std::vector<base::string16> expected_titles_;
207  scoped_refptr<MessageLoopRunner> message_loop_runner_;
208
209  // The most recently observed expected title, if any.
210  base::string16 observed_title_;
211
212  DISALLOW_COPY_AND_ASSIGN(TitleWatcher);
213};
214
215// Watches a WebContents and blocks until it is destroyed.
216class WebContentsDestroyedWatcher : public WebContentsObserver {
217 public:
218  explicit WebContentsDestroyedWatcher(WebContents* web_contents);
219  virtual ~WebContentsDestroyedWatcher();
220
221  // Waits until the WebContents is destroyed.
222  void Wait();
223
224 private:
225  // Overridden WebContentsObserver methods.
226  virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE;
227
228  scoped_refptr<MessageLoopRunner> message_loop_runner_;
229
230  DISALLOW_COPY_AND_ASSIGN(WebContentsDestroyedWatcher);
231};
232
233// Watches a RenderProcessHost and waits for specified destruction events.
234class RenderProcessHostWatcher : public RenderProcessHostObserver {
235 public:
236  enum WatchType {
237    WATCH_FOR_PROCESS_EXIT,
238    WATCH_FOR_HOST_DESTRUCTION
239  };
240
241  RenderProcessHostWatcher(RenderProcessHost* render_process_host,
242                           WatchType type);
243  // Waits for the render process that contains the specified web contents.
244  RenderProcessHostWatcher(WebContents* web_contents, WatchType type);
245  virtual ~RenderProcessHostWatcher();
246
247  // Waits until the renderer process exits.
248  void Wait();
249
250 private:
251  // Overridden RenderProcessHost::LifecycleObserver methods.
252  virtual void RenderProcessExited(RenderProcessHost* host,
253                                   base::ProcessHandle handle,
254                                   base::TerminationStatus status,
255                                   int exit_code) OVERRIDE;
256  virtual void RenderProcessHostDestroyed(RenderProcessHost* host) OVERRIDE;
257
258  RenderProcessHost* render_process_host_;
259  WatchType type_;
260
261  scoped_refptr<MessageLoopRunner> message_loop_runner_;
262
263  DISALLOW_COPY_AND_ASSIGN(RenderProcessHostWatcher);
264};
265
266// Watches for responses from the DOMAutomationController and keeps them in a
267// queue. Useful for waiting for a message to be received.
268class DOMMessageQueue : public NotificationObserver {
269 public:
270  // Constructs a DOMMessageQueue and begins listening for messages from the
271  // DOMAutomationController. Do not construct this until the browser has
272  // started.
273  DOMMessageQueue();
274  virtual ~DOMMessageQueue();
275
276  // Removes all messages in the message queue.
277  void ClearQueue();
278
279  // Wait for the next message to arrive. |message| will be set to the next
280  // message. Returns true on success.
281  bool WaitForMessage(std::string* message) WARN_UNUSED_RESULT;
282
283  // Overridden NotificationObserver methods.
284  virtual void Observe(int type,
285                       const NotificationSource& source,
286                       const NotificationDetails& details) OVERRIDE;
287
288 private:
289  NotificationRegistrar registrar_;
290  std::queue<std::string> message_queue_;
291  scoped_refptr<MessageLoopRunner> message_loop_runner_;
292
293  DISALLOW_COPY_AND_ASSIGN(DOMMessageQueue);
294};
295
296}  // namespace content
297
298#endif  // CONTENT_PUBLIC_TEST_BROWSER_TEST_UTILS_H_
299