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