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