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.
5 #include "content/public/test/render_view_test.h"
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"
37 #if defined(OS_MACOSX)
38 #include "base/mac/scoped_nsautorelease_pool.h"
41 using blink::WebInputEvent
;
42 using blink::WebLocalFrame
;
43 using blink::WebMouseEvent
;
44 using blink::WebScriptSource
;
45 using blink::WebString
;
46 using blink::WebURLRequest
;
49 const int32 kOpenerId
= -2;
50 const int32 kRouteId
= 5;
51 const int32 kMainFrameRouteId
= 6;
52 const int32 kNewWindowRouteId
= 7;
53 const int32 kNewFrameRouteId
= 10;
54 const int32 kSurfaceId
= 42;
60 class RendererWebKitPlatformSupportImplNoSandboxImpl
61 : public RendererWebKitPlatformSupportImpl
{
63 virtual blink::WebSandboxSupport
* sandboxSupport() {
68 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
69 RendererWebKitPlatformSupportImplNoSandbox() {
70 webkit_platform_support_
.reset(
71 new RendererWebKitPlatformSupportImplNoSandboxImpl());
74 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
75 ~RendererWebKitPlatformSupportImplNoSandbox() {
79 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
80 return webkit_platform_support_
.get();
83 RenderViewTest::RenderViewTest()
87 RenderViewTest::~RenderViewTest() {
90 void RenderViewTest::ProcessPendingMessages() {
91 msg_loop_
.PostTask(FROM_HERE
, base::MessageLoop::QuitClosure());
95 WebLocalFrame
* RenderViewTest::GetMainFrame() {
96 return view_
->GetWebView()->mainFrame()->toWebLocalFrame();
99 void RenderViewTest::ExecuteJavaScript(const char* js
) {
100 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js
)));
103 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
104 const base::string16
& script
,
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())
113 *int_result
= result
->Int32Value();
118 void RenderViewTest::LoadHTML(const char* html
) {
119 std::string url_str
= "data:text/html;charset=utf-8,";
120 url_str
.append(html
);
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();
128 PageState
RenderViewTest::GetCurrentPageState() {
129 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
130 return HistoryEntryToPageState(impl
->history_controller()->GetCurrentEntry());
133 void RenderViewTest::GoBack(const PageState
& state
) {
134 GoToOffset(-1, state
);
137 void RenderViewTest::GoForward(const PageState
& state
) {
138 GoToOffset(1, state
);
141 void 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());
149 // Subclasses can set render_thread_ with their own implementation before
150 // calling RenderViewTest::SetUp().
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
);
158 #if defined(OS_MACOSX)
159 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
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();
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());
172 // Ensure that we register any necessary schemes when initializing WebKit,
173 // since we are using a MockRenderThread.
174 RenderThreadImpl::RegisterSchemes();
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
);
184 mock_process_
.reset(new MockRenderProcess
);
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(),
195 kInvalidSessionStorageNamespaceId
,
197 false, // is_renderer_created
198 false, // swapped_out
199 MSG_ROUTING_NONE
, // proxy_routing_id
201 false, // never_visible
203 blink::WebScreenInfo());
208 void 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();
215 // Run the loop so the release task from the renderwidget executes.
216 ProcessPendingMessages();
218 for (int i
= 0; i
< kGCIterations
; i
++)
219 GetMainFrame()->collectGarbage();
221 render_thread_
->SendCloseMessage();
223 mock_process_
.reset();
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();
230 #if defined(OS_MACOSX)
231 // Needs to run before blink::shutdown().
232 autorelease_pool_
.reset(NULL
);
237 platform_
->PlatformUninitialize();
240 command_line_
.reset();
243 void RenderViewTest::SendNativeKeyEvent(
244 const NativeWebKeyboardEvent
& key_event
) {
245 SendWebKeyboardEvent(key_event
);
248 void 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));
255 void 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));
262 const char* const kGetCoordinatesScript
=
264 " function GetCoordinates(elem) {"
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])];"
274 " var elem = document.getElementById('$1');"
277 " var bounds = GetCoordinates(elem);"
278 " bounds[2] = Math.round(elem.offsetWidth);"
279 " bounds[3] = Math.round(elem.offsetHeight);"
282 gfx::Rect
RenderViewTest::GetElementBounds(const std::string
& element_id
) {
283 std::vector
<std::string
> params
;
284 params
.push_back(element_id
);
286 ReplaceStringPlaceholders(kGetCoordinatesScript
, params
, NULL
);
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())
295 v8::Handle
<v8::Array
> array
= value
.As
<v8::Array
>();
296 if (array
->Length() != 4)
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())
304 coords
.push_back(value
->Int32Value());
306 return gfx::Rect(coords
[0], coords
[1], coords
[2], coords
[3]);
309 bool RenderViewTest::SimulateElementClick(const std::string
& element_id
) {
310 gfx::Rect bounds
= GetElementBounds(element_id
);
311 if (bounds
.IsEmpty())
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
);
326 void RenderViewTest::SetFocused(const blink::WebNode
& node
) {
327 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
328 impl
->focusedNodeChanged(node
);
331 void RenderViewTest::ClearHistory() {
332 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
334 impl
->history_list_offset_
= -1;
335 impl
->history_list_length_
= 0;
336 impl
->history_page_ids_
.clear();
339 void RenderViewTest::Reload(const GURL
& url
) {
340 FrameMsg_Navigate_Params params
;
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();
348 uint32
RenderViewTest::GetNavigationIPCType() {
349 return FrameHostMsg_DidCommitProvisionalLoad::ID
;
352 void 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
);
366 bool RenderViewTest::OnMessageReceived(const IPC::Message
& msg
) {
367 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
368 return impl
->OnMessageReceived(msg
);
371 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame
* frame
,
372 bool is_new_navigation
) {
373 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
374 blink::WebHistoryItem item
;
376 impl
->GetMainRenderFrame()->didNavigateWithinPage(
379 is_new_navigation
? blink::WebStandardCommit
380 : blink::WebHistoryInertCommit
);
383 void RenderViewTest::SendContentStateImmediately() {
384 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
385 impl
->set_send_content_state_immediately(true);
388 blink::WebWidget
* RenderViewTest::GetWebWidget() {
389 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
390 return impl
->webwidget();
394 ContentClient
* RenderViewTest::CreateContentClient() {
395 return new TestContentClient
;
398 ContentBrowserClient
* RenderViewTest::CreateContentBrowserClient() {
399 return new ContentBrowserClient
;
402 ContentRendererClient
* RenderViewTest::CreateContentRendererClient() {
403 return new ContentRendererClient
;
406 void RenderViewTest::GoToOffset(int offset
, const PageState
& state
) {
407 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
409 int history_list_length
= impl
->historyBackListCount() +
410 impl
->historyForwardListCount() + 1;
411 int pending_offset
= offset
+ impl
->history_list_offset();
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();
423 FrameMsg_Navigate
navigate_message(impl
->GetMainRenderFrame()->GetRoutingID(),
425 impl
->GetMainRenderFrame()->OnMessageReceived(navigate_message
);
427 // The load actually happens asynchronously, so we pump messages to process
428 // the pending continuation.
429 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
432 } // namespace content