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"
9 #include "base/location.h"
10 #include "base/run_loop.h"
11 #include "base/single_thread_task_runner.h"
12 #include "components/scheduler/renderer/renderer_scheduler.h"
13 #include "content/app/mojo/mojo_init.h"
14 #include "content/common/dom_storage/dom_storage_types.h"
15 #include "content/common/frame_messages.h"
16 #include "content/common/input_messages.h"
17 #include "content/common/view_messages.h"
18 #include "content/public/browser/content_browser_client.h"
19 #include "content/public/browser/native_web_keyboard_event.h"
20 #include "content/public/common/content_client.h"
21 #include "content/public/common/renderer_preferences.h"
22 #include "content/public/renderer/content_renderer_client.h"
23 #include "content/public/test/frame_load_waiter.h"
24 #include "content/renderer/history_controller.h"
25 #include "content/renderer/history_serialization.h"
26 #include "content/renderer/render_thread_impl.h"
27 #include "content/renderer/render_view_impl.h"
28 #include "content/renderer/renderer_blink_platform_impl.h"
29 #include "content/renderer/renderer_main_platform_delegate.h"
30 #include "content/test/fake_compositor_dependencies.h"
31 #include "content/test/mock_render_process.h"
32 #include "content/test/test_content_client.h"
33 #include "content/test/test_render_frame.h"
34 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
35 #include "third_party/WebKit/public/platform/WebURLRequest.h"
36 #include "third_party/WebKit/public/web/WebDocument.h"
37 #include "third_party/WebKit/public/web/WebHistoryItem.h"
38 #include "third_party/WebKit/public/web/WebInputElement.h"
39 #include "third_party/WebKit/public/web/WebInputEvent.h"
40 #include "third_party/WebKit/public/web/WebKit.h"
41 #include "third_party/WebKit/public/web/WebLocalFrame.h"
42 #include "third_party/WebKit/public/web/WebScriptSource.h"
43 #include "third_party/WebKit/public/web/WebView.h"
44 #include "ui/base/resource/resource_bundle.h"
45 #include "ui/events/keycodes/keyboard_codes.h"
46 #include "v8/include/v8.h"
48 #if defined(OS_MACOSX)
49 #include "base/mac/scoped_nsautorelease_pool.h"
52 using blink::WebGestureEvent
;
53 using blink::WebInputEvent
;
54 using blink::WebLocalFrame
;
55 using blink::WebMouseEvent
;
56 using blink::WebScriptSource
;
57 using blink::WebString
;
58 using blink::WebURLRequest
;
62 const int32 kRouteId
= 5;
63 const int32 kMainFrameRouteId
= 6;
64 const int32 kNewWindowRouteId
= 7;
65 const int32 kNewFrameRouteId
= 10;
66 const int32 kSurfaceId
= 42;
68 // Converts |ascii_character| into |key_code| and returns true on success.
69 // Handles only the characters needed by tests.
70 bool GetWindowsKeyCode(char ascii_character
, int* key_code
) {
71 if (isalnum(ascii_character
)) {
72 *key_code
= base::ToUpperASCII(ascii_character
);
76 switch (ascii_character
) {
81 *key_code
= ui::VKEY_OEM_MINUS
;
84 *key_code
= ui::VKEY_OEM_PERIOD
;
87 *key_code
= ui::VKEY_BACK
;
98 class RendererBlinkPlatformImplNoSandboxImpl
99 : public RendererBlinkPlatformImpl
{
101 RendererBlinkPlatformImplNoSandboxImpl(
102 scheduler::RendererScheduler
* scheduler
)
103 : RendererBlinkPlatformImpl(scheduler
) {}
105 virtual blink::WebSandboxSupport
* sandboxSupport() {
110 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
111 RendererBlinkPlatformImplNoSandbox() {
112 renderer_scheduler_
= scheduler::RendererScheduler::Create();
113 blink_platform_impl_
.reset(
114 new RendererBlinkPlatformImplNoSandboxImpl(renderer_scheduler_
.get()));
117 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
118 ~RendererBlinkPlatformImplNoSandbox() {
122 RenderViewTest::RendererBlinkPlatformImplNoSandbox::Get() const {
123 return blink_platform_impl_
.get();
126 scheduler::RendererScheduler
*
127 RenderViewTest::RendererBlinkPlatformImplNoSandbox::Scheduler() const {
128 return renderer_scheduler_
.get();
131 RenderViewTest::RenderViewTest()
133 RenderFrameImpl::InstallCreateHook(&TestRenderFrame::CreateTestRenderFrame
);
136 RenderViewTest::~RenderViewTest() {
139 void RenderViewTest::ProcessPendingMessages() {
140 msg_loop_
.task_runner()->PostTask(FROM_HERE
,
141 base::MessageLoop::QuitClosure());
145 WebLocalFrame
* RenderViewTest::GetMainFrame() {
146 return view_
->GetWebView()->mainFrame()->toWebLocalFrame();
149 void RenderViewTest::ExecuteJavaScriptForTests(const char* js
) {
150 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js
)));
153 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
154 const base::string16
& script
,
156 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
157 v8::Local
<v8::Value
> result
=
158 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script
));
159 if (result
.IsEmpty() || !result
->IsInt32())
163 *int_result
= result
->Int32Value();
168 void RenderViewTest::LoadHTML(const char* html
) {
169 std::string url_str
= "data:text/html;charset=utf-8,";
170 url_str
.append(html
);
172 WebURLRequest
request(url
);
173 request
.setCheckForBrowserSideNavigation(false);
174 GetMainFrame()->loadRequest(request
);
175 // The load actually happens asynchronously, so we pump messages to process
176 // the pending continuation.
177 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
180 PageState
RenderViewTest::GetCurrentPageState() {
181 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
182 return HistoryEntryToPageState(impl
->history_controller()->GetCurrentEntry());
185 void RenderViewTest::GoBack(const PageState
& state
) {
186 GoToOffset(-1, state
);
189 void RenderViewTest::GoForward(const PageState
& state
) {
190 GoToOffset(1, state
);
193 void RenderViewTest::SetUp() {
194 // Blink needs to be initialized before calling CreateContentRendererClient()
195 // because it uses blink internally.
196 blink::initialize(blink_platform_impl_
.Get());
198 content_client_
.reset(CreateContentClient());
199 content_browser_client_
.reset(CreateContentBrowserClient());
200 content_renderer_client_
.reset(CreateContentRendererClient());
201 SetContentClient(content_client_
.get());
202 SetBrowserClientForTesting(content_browser_client_
.get());
203 SetRendererClientForTesting(content_renderer_client_
.get());
205 // Subclasses can set render_thread_ with their own implementation before
206 // calling RenderViewTest::SetUp().
208 render_thread_
.reset(new MockRenderThread());
209 render_thread_
->set_routing_id(kRouteId
);
210 render_thread_
->set_surface_id(kSurfaceId
);
211 render_thread_
->set_new_window_routing_id(kNewWindowRouteId
);
212 render_thread_
->set_new_frame_routing_id(kNewFrameRouteId
);
214 #if defined(OS_MACOSX)
215 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
217 command_line_
.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM
));
218 params_
.reset(new MainFunctionParams(*command_line_
));
219 platform_
.reset(new RendererMainPlatformDelegate(*params_
));
220 platform_
->PlatformInitialize();
222 // Setting flags and really doing anything with WebKit is fairly fragile and
223 // hacky, but this is the world we live in...
224 std::string
flags("--expose-gc");
225 v8::V8::SetFlagsFromString(flags
.c_str(), static_cast<int>(flags
.size()));
227 // Ensure that we register any necessary schemes when initializing WebKit,
228 // since we are using a MockRenderThread.
229 RenderThreadImpl::RegisterSchemes();
231 // This check is needed because when run under content_browsertests,
232 // ResourceBundle isn't initialized (since we have to use a diferent test
233 // suite implementation than for content_unittests). For browser_tests, this
234 // is already initialized.
235 if (!ui::ResourceBundle::HasSharedInstance())
236 ui::ResourceBundle::InitSharedInstanceWithLocale(
237 "en-US", NULL
, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES
);
239 compositor_deps_
.reset(new FakeCompositorDependencies
);
240 mock_process_
.reset(new MockRenderProcess
);
242 ViewMsg_New_Params view_params
;
243 view_params
.opener_frame_route_id
= MSG_ROUTING_NONE
;
244 view_params
.window_was_created_with_opener
= false;
245 view_params
.renderer_preferences
= RendererPreferences();
246 view_params
.web_preferences
= WebPreferences();
247 view_params
.view_id
= kRouteId
;
248 view_params
.main_frame_routing_id
= kMainFrameRouteId
;
249 view_params
.surface_id
= kSurfaceId
;
250 view_params
.session_storage_namespace_id
= kInvalidSessionStorageNamespaceId
;
251 view_params
.swapped_out
= false;
252 view_params
.replicated_frame_state
= FrameReplicationState();
253 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
254 view_params
.hidden
= false;
255 view_params
.never_visible
= false;
256 view_params
.next_page_id
= 1;
257 view_params
.initial_size
= *InitialSizeParams();
258 view_params
.enable_auto_resize
= false;
259 view_params
.min_size
= gfx::Size();
260 view_params
.max_size
= gfx::Size();
266 // This needs to pass the mock render thread to the view.
267 RenderViewImpl
* view
=
268 RenderViewImpl::Create(compositor_deps_
.get(), view_params
, false);
272 void RenderViewTest::TearDown() {
273 // Try very hard to collect garbage before shutting down.
274 // "5" was chosen following http://crbug.com/46571#c9
275 const int kGCIterations
= 5;
276 for (int i
= 0; i
< kGCIterations
; i
++)
277 GetMainFrame()->collectGarbage();
279 // Run the loop so the release task from the renderwidget executes.
280 ProcessPendingMessages();
282 for (int i
= 0; i
< kGCIterations
; i
++)
283 GetMainFrame()->collectGarbage();
285 render_thread_
->SendCloseMessage();
287 mock_process_
.reset();
289 // After telling the view to close and resetting mock_process_ we may get
290 // some new tasks which need to be processed before shutting down WebKit
291 // (http://crbug.com/21508).
292 base::RunLoop().RunUntilIdle();
294 #if defined(OS_MACOSX)
295 // Needs to run before blink::shutdown().
296 autorelease_pool_
.reset(NULL
);
299 blink_platform_impl_
.Scheduler()->Shutdown();
302 platform_
->PlatformUninitialize();
305 command_line_
.reset();
308 void RenderViewTest::SendNativeKeyEvent(
309 const NativeWebKeyboardEvent
& key_event
) {
310 SendWebKeyboardEvent(key_event
);
313 void RenderViewTest::SendWebKeyboardEvent(
314 const blink::WebKeyboardEvent
& key_event
) {
315 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
316 impl
->OnMessageReceived(
317 InputMsg_HandleInputEvent(0, &key_event
, ui::LatencyInfo(), false));
320 void RenderViewTest::SendWebMouseEvent(
321 const blink::WebMouseEvent
& mouse_event
) {
322 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
323 impl
->OnMessageReceived(
324 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
327 const char* const kGetCoordinatesScript
=
329 " function GetCoordinates(elem) {"
332 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
333 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
334 " coordinates[0] += parent_coordinates[0];"
335 " coordinates[1] += parent_coordinates[1];"
336 " return [ Math.round(coordinates[0]),"
337 " Math.round(coordinates[1])];"
339 " var elem = document.getElementById('$1');"
342 " var bounds = GetCoordinates(elem);"
343 " bounds[2] = Math.round(elem.offsetWidth);"
344 " bounds[3] = Math.round(elem.offsetHeight);"
347 gfx::Rect
RenderViewTest::GetElementBounds(const std::string
& element_id
) {
348 std::vector
<std::string
> params
;
349 params
.push_back(element_id
);
351 base::ReplaceStringPlaceholders(kGetCoordinatesScript
, params
, NULL
);
353 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
354 v8::HandleScope
handle_scope(isolate
);
355 v8::Local
<v8::Value
> value
= GetMainFrame()->executeScriptAndReturnValue(
356 WebScriptSource(WebString::fromUTF8(script
)));
357 if (value
.IsEmpty() || !value
->IsArray())
360 v8::Local
<v8::Array
> array
= value
.As
<v8::Array
>();
361 if (array
->Length() != 4)
363 std::vector
<int> coords
;
364 for (int i
= 0; i
< 4; ++i
) {
365 v8::Local
<v8::Number
> index
= v8::Number::New(isolate
, i
);
366 v8::Local
<v8::Value
> value
= array
->Get(index
);
367 if (value
.IsEmpty() || !value
->IsInt32())
369 coords
.push_back(value
->Int32Value());
371 return gfx::Rect(coords
[0], coords
[1], coords
[2], coords
[3]);
374 bool RenderViewTest::SimulateElementClick(const std::string
& element_id
) {
375 gfx::Rect bounds
= GetElementBounds(element_id
);
376 if (bounds
.IsEmpty())
378 SimulatePointClick(bounds
.CenterPoint());
382 void RenderViewTest::SimulatePointClick(const gfx::Point
& point
) {
383 WebMouseEvent mouse_event
;
384 mouse_event
.type
= WebInputEvent::MouseDown
;
385 mouse_event
.button
= WebMouseEvent::ButtonLeft
;
386 mouse_event
.x
= point
.x();
387 mouse_event
.y
= point
.y();
388 mouse_event
.clickCount
= 1;
389 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
390 impl
->OnMessageReceived(
391 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
392 mouse_event
.type
= WebInputEvent::MouseUp
;
393 impl
->OnMessageReceived(
394 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
398 bool RenderViewTest::SimulateElementRightClick(const std::string
& element_id
) {
399 gfx::Rect bounds
= GetElementBounds(element_id
);
400 if (bounds
.IsEmpty())
402 SimulatePointRightClick(bounds
.CenterPoint());
406 void RenderViewTest::SimulatePointRightClick(const gfx::Point
& point
) {
407 WebMouseEvent mouse_event
;
408 mouse_event
.type
= WebInputEvent::MouseDown
;
409 mouse_event
.button
= WebMouseEvent::ButtonRight
;
410 mouse_event
.x
= point
.x();
411 mouse_event
.y
= point
.y();
412 mouse_event
.clickCount
= 1;
413 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
414 impl
->OnMessageReceived(
415 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
416 mouse_event
.type
= WebInputEvent::MouseUp
;
417 impl
->OnMessageReceived(
418 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
421 void RenderViewTest::SimulateRectTap(const gfx::Rect
& rect
) {
422 WebGestureEvent gesture_event
;
423 gesture_event
.x
= rect
.CenterPoint().x();
424 gesture_event
.y
= rect
.CenterPoint().y();
425 gesture_event
.data
.tap
.tapCount
= 1;
426 gesture_event
.data
.tap
.width
= rect
.width();
427 gesture_event
.data
.tap
.height
= rect
.height();
428 gesture_event
.type
= WebInputEvent::GestureTap
;
429 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
430 impl
->OnMessageReceived(
431 InputMsg_HandleInputEvent(0, &gesture_event
, ui::LatencyInfo(), false));
432 impl
->FocusChangeComplete();
435 void RenderViewTest::SetFocused(const blink::WebNode
& node
) {
436 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
437 impl
->focusedNodeChanged(blink::WebNode(), node
);
440 void RenderViewTest::Reload(const GURL
& url
) {
441 CommonNavigationParams
common_params(
442 url
, Referrer(), ui::PAGE_TRANSITION_LINK
, FrameMsg_Navigate_Type::RELOAD
,
443 true, false, base::TimeTicks(),
444 FrameMsg_UILoadMetricsReportType::NO_REPORT
, GURL(), GURL());
445 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
446 TestRenderFrame
* frame
=
447 static_cast<TestRenderFrame
*>(impl
->GetMainRenderFrame());
448 frame
->Navigate(common_params
, StartNavigationParams(),
449 RequestNavigationParams());
450 FrameLoadWaiter(frame
).Wait();
453 uint32
RenderViewTest::GetNavigationIPCType() {
454 return FrameHostMsg_DidCommitProvisionalLoad::ID
;
457 void RenderViewTest::Resize(gfx::Size new_size
,
458 gfx::Rect resizer_rect
,
459 bool is_fullscreen_granted
) {
460 ViewMsg_Resize_Params params
;
461 params
.screen_info
= blink::WebScreenInfo();
462 params
.new_size
= new_size
;
463 params
.physical_backing_size
= new_size
;
464 params
.top_controls_height
= 0.f
;
465 params
.top_controls_shrink_blink_size
= false;
466 params
.resizer_rect
= resizer_rect
;
467 params
.is_fullscreen_granted
= is_fullscreen_granted
;
468 params
.display_mode
= blink::WebDisplayModeBrowser
;
469 scoped_ptr
<IPC::Message
> resize_message(new ViewMsg_Resize(0, params
));
470 OnMessageReceived(*resize_message
);
473 void RenderViewTest::SimulateUserTypingASCIICharacter(char ascii_character
,
474 bool flush_message_loop
) {
475 blink::WebKeyboardEvent event
;
476 event
.text
[0] = ascii_character
;
477 ASSERT_TRUE(GetWindowsKeyCode(ascii_character
, &event
.windowsKeyCode
));
478 if (isupper(ascii_character
) || ascii_character
== '@' ||
479 ascii_character
== '_') {
480 event
.modifiers
= blink::WebKeyboardEvent::ShiftKey
;
483 event
.type
= blink::WebKeyboardEvent::RawKeyDown
;
484 SendWebKeyboardEvent(event
);
486 event
.type
= blink::WebKeyboardEvent::Char
;
487 SendWebKeyboardEvent(event
);
489 event
.type
= blink::WebKeyboardEvent::KeyUp
;
490 SendWebKeyboardEvent(event
);
492 if (flush_message_loop
) {
493 // Processing is delayed because of a Blink bug:
494 // https://bugs.webkit.org/show_bug.cgi?id=16976 See
495 // PasswordAutofillAgent::TextDidChangeInTextField() for details.
496 base::MessageLoop::current()->RunUntilIdle();
500 void RenderViewTest::SimulateUserInputChangeForElement(
501 blink::WebInputElement
* input
,
502 const std::string
& new_value
) {
503 ASSERT_TRUE(base::IsStringASCII(new_value
));
504 while (!input
->focused())
505 input
->document().frame()->view()->advanceFocus(false);
507 size_t previous_length
= input
->value().length();
508 for (size_t i
= 0; i
< previous_length
; ++i
)
509 SimulateUserTypingASCIICharacter(ui::VKEY_BACK
, false);
511 EXPECT_TRUE(input
->value().utf8().empty());
512 for (size_t i
= 0; i
< new_value
.size(); ++i
)
513 SimulateUserTypingASCIICharacter(new_value
[i
], false);
515 // Compare only beginning, because autocomplete may have filled out the
517 EXPECT_EQ(new_value
, input
->value().utf8().substr(0, new_value
.length()));
519 base::MessageLoop::current()->RunUntilIdle();
522 bool RenderViewTest::OnMessageReceived(const IPC::Message
& msg
) {
523 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
524 return impl
->OnMessageReceived(msg
);
527 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame
* frame
,
528 bool is_new_navigation
) {
529 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
530 blink::WebHistoryItem item
;
532 impl
->GetMainRenderFrame()->didNavigateWithinPage(
535 is_new_navigation
? blink::WebStandardCommit
536 : blink::WebHistoryInertCommit
);
539 void RenderViewTest::SendContentStateImmediately() {
540 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
541 impl
->set_send_content_state_immediately(true);
544 blink::WebWidget
* RenderViewTest::GetWebWidget() {
545 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
546 return impl
->webwidget();
550 ContentClient
* RenderViewTest::CreateContentClient() {
551 return new TestContentClient
;
554 ContentBrowserClient
* RenderViewTest::CreateContentBrowserClient() {
555 return new ContentBrowserClient
;
558 ContentRendererClient
* RenderViewTest::CreateContentRendererClient() {
559 return new ContentRendererClient
;
562 scoped_ptr
<ViewMsg_Resize_Params
> RenderViewTest::InitialSizeParams() {
563 return make_scoped_ptr(new ViewMsg_Resize_Params());
566 void RenderViewTest::GoToOffset(int offset
, const PageState
& state
) {
567 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
569 int history_list_length
= impl
->historyBackListCount() +
570 impl
->historyForwardListCount() + 1;
571 int pending_offset
= offset
+ impl
->history_list_offset_
;
573 CommonNavigationParams
common_params(
574 GURL(), Referrer(), ui::PAGE_TRANSITION_FORWARD_BACK
,
575 FrameMsg_Navigate_Type::NORMAL
, true, false, base::TimeTicks(),
576 FrameMsg_UILoadMetricsReportType::NO_REPORT
, GURL(), GURL());
577 RequestNavigationParams request_params
;
578 request_params
.page_state
= state
;
579 request_params
.page_id
= impl
->page_id_
+ offset
;
580 request_params
.nav_entry_id
= pending_offset
+ 1;
581 request_params
.pending_history_list_offset
= pending_offset
;
582 request_params
.current_history_list_offset
= impl
->history_list_offset_
;
583 request_params
.current_history_list_length
= history_list_length
;
585 TestRenderFrame
* frame
=
586 static_cast<TestRenderFrame
*>(impl
->GetMainRenderFrame());
587 frame
->Navigate(common_params
, StartNavigationParams(), request_params
);
589 // The load actually happens asynchronously, so we pump messages to process
590 // the pending continuation.
591 FrameLoadWaiter(frame
).Wait();
594 } // namespace content