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