render_view_test.cc revision 58537e28ecd584eab876aee8be7156509866d23a
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#include "content/public/test/render_view_test.h"
6
7#include "base/run_loop.h"
8#include "content/common/dom_storage/dom_storage_types.h"
9#include "content/common/input_messages.h"
10#include "content/common/view_messages.h"
11#include "content/public/browser/native_web_keyboard_event.h"
12#include "content/public/common/renderer_preferences.h"
13#include "content/public/renderer/history_item_serialization.h"
14#include "content/renderer/render_thread_impl.h"
15#include "content/renderer/render_view_impl.h"
16#include "content/renderer/renderer_main_platform_delegate.h"
17#include "content/renderer/renderer_webkitplatformsupport_impl.h"
18#include "content/test/mock_render_process.h"
19#include "third_party/WebKit/public/platform/WebURLRequest.h"
20#include "third_party/WebKit/public/web/WebFrame.h"
21#include "third_party/WebKit/public/web/WebHistoryItem.h"
22#include "third_party/WebKit/public/web/WebInputEvent.h"
23#include "third_party/WebKit/public/web/WebKit.h"
24#include "third_party/WebKit/public/web/WebScreenInfo.h"
25#include "third_party/WebKit/public/web/WebScriptController.h"
26#include "third_party/WebKit/public/web/WebScriptSource.h"
27#include "third_party/WebKit/public/web/WebView.h"
28#include "ui/base/resource/resource_bundle.h"
29#include "webkit/glue/webkit_glue.h"
30
31using WebKit::WebFrame;
32using WebKit::WebInputEvent;
33using WebKit::WebMouseEvent;
34using WebKit::WebScriptController;
35using WebKit::WebScriptSource;
36using WebKit::WebString;
37using WebKit::WebURLRequest;
38
39namespace {
40const int32 kOpenerId = -2;
41const int32 kRouteId = 5;
42const int32 kMainFrameRouteId = 6;
43const int32 kNewWindowRouteId = 7;
44const int32 kSurfaceId = 42;
45
46}  // namespace
47
48namespace content {
49
50class RendererWebKitPlatformSupportImplNoSandboxImpl
51    : public RendererWebKitPlatformSupportImpl {
52 public:
53  virtual WebKit::WebSandboxSupport* sandboxSupport() {
54    return NULL;
55  }
56};
57
58RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
59    RendererWebKitPlatformSupportImplNoSandbox() {
60  webkit_platform_support_.reset(
61      new RendererWebKitPlatformSupportImplNoSandboxImpl());
62}
63
64RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
65    ~RendererWebKitPlatformSupportImplNoSandbox() {
66}
67
68WebKit::Platform*
69    RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
70  return webkit_platform_support_.get();
71}
72
73RenderViewTest::RenderViewTest()
74    : view_(NULL) {
75}
76
77RenderViewTest::~RenderViewTest() {
78}
79
80void RenderViewTest::ProcessPendingMessages() {
81  msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
82  msg_loop_.Run();
83}
84
85WebFrame* RenderViewTest::GetMainFrame() {
86  return view_->GetWebView()->mainFrame();
87}
88
89void RenderViewTest::ExecuteJavaScript(const char* js) {
90  GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
91}
92
93bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
94    const string16& script,
95    int* int_result) {
96  v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
97  v8::Handle<v8::Value> result =
98      GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script));
99  if (result.IsEmpty() || !result->IsInt32())
100    return false;
101
102  if (int_result)
103    *int_result = result->Int32Value();
104
105  return true;
106}
107
108void RenderViewTest::LoadHTML(const char* html) {
109  std::string url_str = "data:text/html;charset=utf-8,";
110  url_str.append(html);
111  GURL url(url_str);
112
113  GetMainFrame()->loadRequest(WebURLRequest(url));
114
115  // The load actually happens asynchronously, so we pump messages to process
116  // the pending continuation.
117  ProcessPendingMessages();
118}
119
120void RenderViewTest::GoBack(const WebKit::WebHistoryItem& item) {
121  GoToOffset(-1, item);
122}
123
124void RenderViewTest::GoForward(const WebKit::WebHistoryItem& item) {
125  GoToOffset(1, item);
126}
127
128void RenderViewTest::SetUp() {
129  // Subclasses can set the ContentClient's renderer before calling
130  // RenderViewTest::SetUp().
131  ContentRendererClient* old_client =
132      SetRendererClientForTesting(&content_renderer_client_);
133  if (old_client)
134    SetRendererClientForTesting(old_client);
135
136  // Subclasses can set render_thread_ with their own implementation before
137  // calling RenderViewTest::SetUp().
138  if (!render_thread_)
139    render_thread_.reset(new MockRenderThread());
140  render_thread_->set_routing_id(kRouteId);
141  render_thread_->set_surface_id(kSurfaceId);
142  render_thread_->set_new_window_routing_id(kNewWindowRouteId);
143
144  command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));
145  params_.reset(new MainFunctionParams(*command_line_));
146  platform_.reset(new RendererMainPlatformDelegate(*params_));
147  platform_->PlatformInitialize();
148
149  // Setting flags and really doing anything with WebKit is fairly fragile and
150  // hacky, but this is the world we live in...
151  webkit_glue::SetJavaScriptFlags(" --expose-gc");
152  WebKit::initialize(webkit_platform_support_.Get());
153
154  // Ensure that we register any necessary schemes when initializing WebKit,
155  // since we are using a MockRenderThread.
156  RenderThreadImpl::RegisterSchemes();
157
158  // This check is needed because when run under content_browsertests,
159  // ResourceBundle isn't initialized (since we have to use a diferent test
160  // suite implementation than for content_unittests). For browser_tests, this
161  // is already initialized.
162  if (!ResourceBundle::HasSharedInstance())
163    ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL);
164
165  mock_process_.reset(new MockRenderProcess);
166
167  // This needs to pass the mock render thread to the view.
168  RenderViewImpl* view = RenderViewImpl::Create(
169      kOpenerId,
170      RendererPreferences(),
171      WebPreferences(),
172      new SharedRenderViewCounter(0),
173      kRouteId,
174      kMainFrameRouteId,
175      kSurfaceId,
176      kInvalidSessionStorageNamespaceId,
177      string16(),
178      false, // is_renderer_created
179      false, // swapped_out
180      false, // hidden
181      1, // next_page_id
182      WebKit::WebScreenInfo(),
183      AccessibilityModeOff,
184      true);
185  view->AddRef();
186  view_ = view;
187}
188
189void RenderViewTest::TearDown() {
190  // Try very hard to collect garbage before shutting down.
191  GetMainFrame()->collectGarbage();
192  GetMainFrame()->collectGarbage();
193
194  // Run the loop so the release task from the renderwidget executes.
195  ProcessPendingMessages();
196
197  render_thread_->SendCloseMessage();
198  view_ = NULL;
199  mock_process_.reset();
200
201  // After telling the view to close and resetting mock_process_ we may get
202  // some new tasks which need to be processed before shutting down WebKit
203  // (http://crbug.com/21508).
204  base::RunLoop().RunUntilIdle();
205
206  WebKit::shutdown();
207
208  platform_->PlatformUninitialize();
209  platform_.reset();
210  params_.reset();
211  command_line_.reset();
212}
213
214void RenderViewTest::SendNativeKeyEvent(
215    const NativeWebKeyboardEvent& key_event) {
216  SendWebKeyboardEvent(key_event);
217}
218
219void RenderViewTest::SendWebKeyboardEvent(
220    const WebKit::WebKeyboardEvent& key_event) {
221  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
222  impl->OnMessageReceived(
223      InputMsg_HandleInputEvent(0, &key_event, ui::LatencyInfo(), false));
224}
225
226void RenderViewTest::SendWebMouseEvent(
227    const WebKit::WebMouseEvent& mouse_event) {
228  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
229  impl->OnMessageReceived(
230      InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
231}
232
233const char* const kGetCoordinatesScript =
234    "(function() {"
235    "  function GetCoordinates(elem) {"
236    "    if (!elem)"
237    "      return [ 0, 0];"
238    "    var coordinates = [ elem.offsetLeft, elem.offsetTop];"
239    "    var parent_coordinates = GetCoordinates(elem.offsetParent);"
240    "    coordinates[0] += parent_coordinates[0];"
241    "    coordinates[1] += parent_coordinates[1];"
242    "    return coordinates;"
243    "  };"
244    "  var elem = document.getElementById('$1');"
245    "  if (!elem)"
246    "    return null;"
247    "  var bounds = GetCoordinates(elem);"
248    "  bounds[2] = elem.offsetWidth;"
249    "  bounds[3] = elem.offsetHeight;"
250    "  return bounds;"
251    "})();";
252gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
253  std::vector<std::string> params;
254  params.push_back(element_id);
255  std::string script =
256      ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
257
258  v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
259  v8::Handle<v8::Value>  value = GetMainFrame()->executeScriptAndReturnValue(
260      WebScriptSource(WebString::fromUTF8(script)));
261  if (value.IsEmpty() || !value->IsArray())
262    return gfx::Rect();
263
264  v8::Handle<v8::Array> array = value.As<v8::Array>();
265  if (array->Length() != 4)
266    return gfx::Rect();
267  std::vector<int> coords;
268  for (int i = 0; i < 4; ++i) {
269    v8::Handle<v8::Number> index = v8::Number::New(i);
270    v8::Local<v8::Value> value = array->Get(index);
271    if (value.IsEmpty() || !value->IsInt32())
272      return gfx::Rect();
273    coords.push_back(value->Int32Value());
274  }
275  return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
276}
277
278bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
279  gfx::Rect bounds = GetElementBounds(element_id);
280  if (bounds.IsEmpty())
281    return false;
282  WebMouseEvent mouse_event;
283  mouse_event.type = WebInputEvent::MouseDown;
284  mouse_event.button = WebMouseEvent::ButtonLeft;
285  mouse_event.x = bounds.CenterPoint().x();
286  mouse_event.y = bounds.CenterPoint().y();
287  mouse_event.clickCount = 1;
288  scoped_ptr<IPC::Message> input_message(
289      new InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
290  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
291  impl->OnMessageReceived(*input_message);
292  return true;
293}
294
295void RenderViewTest::SetFocused(const WebKit::WebNode& node) {
296  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
297  impl->focusedNodeChanged(node);
298}
299
300void RenderViewTest::ClearHistory() {
301  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
302  impl->page_id_ = -1;
303  impl->history_list_offset_ = -1;
304  impl->history_list_length_ = 0;
305  impl->history_page_ids_.clear();
306}
307
308void RenderViewTest::Reload(const GURL& url) {
309  ViewMsg_Navigate_Params params;
310  params.url = url;
311  params.navigation_type = ViewMsg_Navigate_Type::RELOAD;
312  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
313  impl->OnNavigate(params);
314}
315
316uint32 RenderViewTest::GetNavigationIPCType() {
317  return ViewHostMsg_FrameNavigate::ID;
318}
319
320void RenderViewTest::Resize(gfx::Size new_size,
321                            gfx::Rect resizer_rect,
322                            bool is_fullscreen) {
323  ViewMsg_Resize_Params params;
324  params.screen_info = WebKit::WebScreenInfo();
325  params.new_size = new_size;
326  params.physical_backing_size = new_size;
327  params.overdraw_bottom_height = 0.f;
328  params.resizer_rect = resizer_rect;
329  params.is_fullscreen = is_fullscreen;
330  scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
331  OnMessageReceived(*resize_message);
332}
333
334bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
335  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
336  return impl->OnMessageReceived(msg);
337}
338
339void RenderViewTest::DidNavigateWithinPage(WebKit::WebFrame* frame,
340                                           bool is_new_navigation) {
341  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
342  impl->didNavigateWithinPage(frame, is_new_navigation);
343}
344
345void RenderViewTest::SendContentStateImmediately() {
346  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
347  impl->set_send_content_state_immediately(true);
348}
349
350WebKit::WebWidget* RenderViewTest::GetWebWidget() {
351  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
352  return impl->webwidget();
353}
354
355void RenderViewTest::GoToOffset(int offset,
356                                const WebKit::WebHistoryItem& history_item) {
357  RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
358
359  int history_list_length = impl->historyBackListCount() +
360                            impl->historyForwardListCount() + 1;
361  int pending_offset = offset + impl->history_list_offset();
362
363  ViewMsg_Navigate_Params navigate_params;
364  navigate_params.navigation_type = ViewMsg_Navigate_Type::NORMAL;
365  navigate_params.transition = PAGE_TRANSITION_FORWARD_BACK;
366  navigate_params.current_history_list_length = history_list_length;
367  navigate_params.current_history_list_offset = impl->history_list_offset();
368  navigate_params.pending_history_list_offset = pending_offset;
369  navigate_params.page_id = impl->GetPageId() + offset;
370  navigate_params.page_state = HistoryItemToPageState(history_item);
371  navigate_params.request_time = base::Time::Now();
372
373  ViewMsg_Navigate navigate_message(impl->GetRoutingID(), navigate_params);
374  OnMessageReceived(navigate_message);
375
376  // The load actually happens asynchronously, so we pump messages to process
377  // the pending continuation.
378  ProcessPendingMessages();
379}
380
381}  // namespace content
382