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/common/dom_storage/dom_storage_types.h"
14 #include "content/common/frame_messages.h"
15 #include "content/common/input_messages.h"
16 #include "content/common/view_messages.h"
17 #include "content/public/browser/content_browser_client.h"
18 #include "content/public/browser/native_web_keyboard_event.h"
19 #include "content/public/common/content_client.h"
20 #include "content/public/common/renderer_preferences.h"
21 #include "content/public/renderer/content_renderer_client.h"
22 #include "content/public/test/frame_load_waiter.h"
23 #include "content/renderer/history_controller.h"
24 #include "content/renderer/history_serialization.h"
25 #include "content/renderer/render_thread_impl.h"
26 #include "content/renderer/render_view_impl.h"
27 #include "content/renderer/renderer_blink_platform_impl.h"
28 #include "content/renderer/renderer_main_platform_delegate.h"
29 #include "content/test/fake_compositor_dependencies.h"
30 #include "content/test/mock_render_process.h"
31 #include "content/test/test_content_client.h"
32 #include "content/test/test_render_frame.h"
33 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
34 #include "third_party/WebKit/public/platform/WebURLRequest.h"
35 #include "third_party/WebKit/public/web/WebDocument.h"
36 #include "third_party/WebKit/public/web/WebHistoryItem.h"
37 #include "third_party/WebKit/public/web/WebInputElement.h"
38 #include "third_party/WebKit/public/web/WebInputEvent.h"
39 #include "third_party/WebKit/public/web/WebKit.h"
40 #include "third_party/WebKit/public/web/WebLocalFrame.h"
41 #include "third_party/WebKit/public/web/WebScriptSource.h"
42 #include "third_party/WebKit/public/web/WebView.h"
43 #include "ui/base/resource/resource_bundle.h"
44 #include "ui/events/keycodes/keyboard_codes.h"
45 #include "v8/include/v8.h"
47 #if defined(OS_MACOSX)
48 #include "base/mac/scoped_nsautorelease_pool.h"
51 using blink::WebGestureEvent
;
52 using blink::WebInputEvent
;
53 using blink::WebLocalFrame
;
54 using blink::WebMouseEvent
;
55 using blink::WebScriptSource
;
56 using blink::WebString
;
57 using blink::WebURLRequest
;
61 const int32 kRouteId
= 5;
62 const int32 kMainFrameRouteId
= 6;
63 const int32 kNewWindowRouteId
= 7;
64 const int32 kNewFrameRouteId
= 10;
65 const int32 kSurfaceId
= 42;
67 // Converts |ascii_character| into |key_code| and returns true on success.
68 // Handles only the characters needed by tests.
69 bool GetWindowsKeyCode(char ascii_character
, int* key_code
) {
70 if (isalnum(ascii_character
)) {
71 *key_code
= base::ToUpperASCII(ascii_character
);
75 switch (ascii_character
) {
80 *key_code
= ui::VKEY_OEM_MINUS
;
83 *key_code
= ui::VKEY_OEM_PERIOD
;
86 *key_code
= ui::VKEY_BACK
;
97 class RendererBlinkPlatformImplNoSandboxImpl
98 : public RendererBlinkPlatformImpl
{
100 RendererBlinkPlatformImplNoSandboxImpl(
101 scheduler::RendererScheduler
* scheduler
)
102 : RendererBlinkPlatformImpl(scheduler
) {}
104 virtual blink::WebSandboxSupport
* sandboxSupport() {
109 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
110 RendererBlinkPlatformImplNoSandbox() {
111 renderer_scheduler_
= scheduler::RendererScheduler::Create();
112 blink_platform_impl_
.reset(
113 new RendererBlinkPlatformImplNoSandboxImpl(renderer_scheduler_
.get()));
116 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
117 ~RendererBlinkPlatformImplNoSandbox() {
121 RenderViewTest::RendererBlinkPlatformImplNoSandbox::Get() const {
122 return blink_platform_impl_
.get();
125 scheduler::RendererScheduler
*
126 RenderViewTest::RendererBlinkPlatformImplNoSandbox::Scheduler() const {
127 return renderer_scheduler_
.get();
130 RenderViewTest::RenderViewTest()
132 RenderFrameImpl::InstallCreateHook(&TestRenderFrame::CreateTestRenderFrame
);
135 RenderViewTest::~RenderViewTest() {
138 void RenderViewTest::ProcessPendingMessages() {
139 msg_loop_
.task_runner()->PostTask(FROM_HERE
,
140 base::MessageLoop::QuitClosure());
144 WebLocalFrame
* RenderViewTest::GetMainFrame() {
145 return view_
->GetWebView()->mainFrame()->toWebLocalFrame();
148 void RenderViewTest::ExecuteJavaScriptForTests(const char* js
) {
149 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js
)));
152 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
153 const base::string16
& script
,
155 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
156 v8::Local
<v8::Value
> result
=
157 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script
));
158 if (result
.IsEmpty() || !result
->IsInt32())
162 *int_result
= result
->Int32Value();
167 void RenderViewTest::LoadHTML(const char* html
) {
168 std::string url_str
= "data:text/html;charset=utf-8,";
169 url_str
.append(html
);
171 WebURLRequest
request(url
);
172 request
.setCheckForBrowserSideNavigation(false);
173 GetMainFrame()->loadRequest(request
);
174 // The load actually happens asynchronously, so we pump messages to process
175 // the pending continuation.
176 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
179 PageState
RenderViewTest::GetCurrentPageState() {
180 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
181 return HistoryEntryToPageState(impl
->history_controller()->GetCurrentEntry());
184 void RenderViewTest::GoBack(const PageState
& state
) {
185 GoToOffset(-1, state
);
188 void RenderViewTest::GoForward(const PageState
& state
) {
189 GoToOffset(1, state
);
192 void RenderViewTest::SetUp() {
193 content_client_
.reset(CreateContentClient());
194 content_browser_client_
.reset(CreateContentBrowserClient());
195 content_renderer_client_
.reset(CreateContentRendererClient());
196 SetContentClient(content_client_
.get());
197 SetBrowserClientForTesting(content_browser_client_
.get());
198 SetRendererClientForTesting(content_renderer_client_
.get());
200 // Subclasses can set render_thread_ with their own implementation before
201 // calling RenderViewTest::SetUp().
203 render_thread_
.reset(new MockRenderThread());
204 render_thread_
->set_routing_id(kRouteId
);
205 render_thread_
->set_surface_id(kSurfaceId
);
206 render_thread_
->set_new_window_routing_id(kNewWindowRouteId
);
207 render_thread_
->set_new_frame_routing_id(kNewFrameRouteId
);
209 #if defined(OS_MACOSX)
210 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
212 command_line_
.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM
));
213 params_
.reset(new MainFunctionParams(*command_line_
));
214 platform_
.reset(new RendererMainPlatformDelegate(*params_
));
215 platform_
->PlatformInitialize();
217 // Setting flags and really doing anything with WebKit is fairly fragile and
218 // hacky, but this is the world we live in...
219 std::string
flags("--expose-gc");
220 v8::V8::SetFlagsFromString(flags
.c_str(), static_cast<int>(flags
.size()));
221 blink::initialize(blink_platform_impl_
.Get());
223 // Ensure that we register any necessary schemes when initializing WebKit,
224 // since we are using a MockRenderThread.
225 RenderThreadImpl::RegisterSchemes();
227 // This check is needed because when run under content_browsertests,
228 // ResourceBundle isn't initialized (since we have to use a diferent test
229 // suite implementation than for content_unittests). For browser_tests, this
230 // is already initialized.
231 if (!ui::ResourceBundle::HasSharedInstance())
232 ui::ResourceBundle::InitSharedInstanceWithLocale(
233 "en-US", NULL
, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES
);
235 compositor_deps_
.reset(new FakeCompositorDependencies
);
236 mock_process_
.reset(new MockRenderProcess
);
238 ViewMsg_New_Params view_params
;
239 view_params
.opener_frame_route_id
= MSG_ROUTING_NONE
;
240 view_params
.window_was_created_with_opener
= false;
241 view_params
.renderer_preferences
= RendererPreferences();
242 view_params
.web_preferences
= WebPreferences();
243 view_params
.view_id
= kRouteId
;
244 view_params
.main_frame_routing_id
= kMainFrameRouteId
;
245 view_params
.surface_id
= kSurfaceId
;
246 view_params
.session_storage_namespace_id
= kInvalidSessionStorageNamespaceId
;
247 view_params
.swapped_out
= false;
248 view_params
.replicated_frame_state
= FrameReplicationState();
249 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
250 view_params
.hidden
= false;
251 view_params
.never_visible
= false;
252 view_params
.next_page_id
= 1;
253 view_params
.initial_size
= *InitialSizeParams();
254 view_params
.enable_auto_resize
= false;
255 view_params
.min_size
= gfx::Size();
256 view_params
.max_size
= gfx::Size();
258 // This needs to pass the mock render thread to the view.
259 RenderViewImpl
* view
=
260 RenderViewImpl::Create(compositor_deps_
.get(), view_params
, false);
264 void RenderViewTest::TearDown() {
265 // Try very hard to collect garbage before shutting down.
266 // "5" was chosen following http://crbug.com/46571#c9
267 const int kGCIterations
= 5;
268 for (int i
= 0; i
< kGCIterations
; i
++)
269 GetMainFrame()->collectGarbage();
271 // Run the loop so the release task from the renderwidget executes.
272 ProcessPendingMessages();
274 for (int i
= 0; i
< kGCIterations
; i
++)
275 GetMainFrame()->collectGarbage();
277 render_thread_
->SendCloseMessage();
279 mock_process_
.reset();
281 // After telling the view to close and resetting mock_process_ we may get
282 // some new tasks which need to be processed before shutting down WebKit
283 // (http://crbug.com/21508).
284 base::RunLoop().RunUntilIdle();
286 #if defined(OS_MACOSX)
287 // Needs to run before blink::shutdown().
288 autorelease_pool_
.reset(NULL
);
291 blink_platform_impl_
.Scheduler()->Shutdown();
294 platform_
->PlatformUninitialize();
297 command_line_
.reset();
300 void RenderViewTest::SendNativeKeyEvent(
301 const NativeWebKeyboardEvent
& key_event
) {
302 SendWebKeyboardEvent(key_event
);
305 void RenderViewTest::SendWebKeyboardEvent(
306 const blink::WebKeyboardEvent
& key_event
) {
307 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
308 impl
->OnMessageReceived(
309 InputMsg_HandleInputEvent(0, &key_event
, ui::LatencyInfo(), false));
312 void RenderViewTest::SendWebMouseEvent(
313 const blink::WebMouseEvent
& mouse_event
) {
314 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
315 impl
->OnMessageReceived(
316 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
319 const char* const kGetCoordinatesScript
=
321 " function GetCoordinates(elem) {"
324 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
325 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
326 " coordinates[0] += parent_coordinates[0];"
327 " coordinates[1] += parent_coordinates[1];"
328 " return [ Math.round(coordinates[0]),"
329 " Math.round(coordinates[1])];"
331 " var elem = document.getElementById('$1');"
334 " var bounds = GetCoordinates(elem);"
335 " bounds[2] = Math.round(elem.offsetWidth);"
336 " bounds[3] = Math.round(elem.offsetHeight);"
339 gfx::Rect
RenderViewTest::GetElementBounds(const std::string
& element_id
) {
340 std::vector
<std::string
> params
;
341 params
.push_back(element_id
);
343 base::ReplaceStringPlaceholders(kGetCoordinatesScript
, params
, NULL
);
345 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
346 v8::HandleScope
handle_scope(isolate
);
347 v8::Local
<v8::Value
> value
= GetMainFrame()->executeScriptAndReturnValue(
348 WebScriptSource(WebString::fromUTF8(script
)));
349 if (value
.IsEmpty() || !value
->IsArray())
352 v8::Local
<v8::Array
> array
= value
.As
<v8::Array
>();
353 if (array
->Length() != 4)
355 std::vector
<int> coords
;
356 for (int i
= 0; i
< 4; ++i
) {
357 v8::Local
<v8::Number
> index
= v8::Number::New(isolate
, i
);
358 v8::Local
<v8::Value
> value
= array
->Get(index
);
359 if (value
.IsEmpty() || !value
->IsInt32())
361 coords
.push_back(value
->Int32Value());
363 return gfx::Rect(coords
[0], coords
[1], coords
[2], coords
[3]);
366 bool RenderViewTest::SimulateElementClick(const std::string
& element_id
) {
367 gfx::Rect bounds
= GetElementBounds(element_id
);
368 if (bounds
.IsEmpty())
370 SimulatePointClick(bounds
.CenterPoint());
374 void RenderViewTest::SimulatePointClick(const gfx::Point
& point
) {
375 WebMouseEvent mouse_event
;
376 mouse_event
.type
= WebInputEvent::MouseDown
;
377 mouse_event
.button
= WebMouseEvent::ButtonLeft
;
378 mouse_event
.x
= point
.x();
379 mouse_event
.y
= point
.y();
380 mouse_event
.clickCount
= 1;
381 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
382 impl
->OnMessageReceived(
383 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
384 mouse_event
.type
= WebInputEvent::MouseUp
;
385 impl
->OnMessageReceived(
386 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
390 bool RenderViewTest::SimulateElementRightClick(const std::string
& element_id
) {
391 gfx::Rect bounds
= GetElementBounds(element_id
);
392 if (bounds
.IsEmpty())
394 SimulatePointRightClick(bounds
.CenterPoint());
398 void RenderViewTest::SimulatePointRightClick(const gfx::Point
& point
) {
399 WebMouseEvent mouse_event
;
400 mouse_event
.type
= WebInputEvent::MouseDown
;
401 mouse_event
.button
= WebMouseEvent::ButtonRight
;
402 mouse_event
.x
= point
.x();
403 mouse_event
.y
= point
.y();
404 mouse_event
.clickCount
= 1;
405 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
406 impl
->OnMessageReceived(
407 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
408 mouse_event
.type
= WebInputEvent::MouseUp
;
409 impl
->OnMessageReceived(
410 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
413 void RenderViewTest::SimulateRectTap(const gfx::Rect
& rect
) {
414 WebGestureEvent gesture_event
;
415 gesture_event
.x
= rect
.CenterPoint().x();
416 gesture_event
.y
= rect
.CenterPoint().y();
417 gesture_event
.data
.tap
.tapCount
= 1;
418 gesture_event
.data
.tap
.width
= rect
.width();
419 gesture_event
.data
.tap
.height
= rect
.height();
420 gesture_event
.type
= WebInputEvent::GestureTap
;
421 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
422 impl
->OnMessageReceived(
423 InputMsg_HandleInputEvent(0, &gesture_event
, ui::LatencyInfo(), false));
424 impl
->FocusChangeComplete();
427 void RenderViewTest::SetFocused(const blink::WebNode
& node
) {
428 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
429 impl
->focusedNodeChanged(blink::WebNode(), node
);
432 void RenderViewTest::Reload(const GURL
& url
) {
433 CommonNavigationParams
common_params(
434 url
, Referrer(), ui::PAGE_TRANSITION_LINK
, FrameMsg_Navigate_Type::RELOAD
,
435 true, false, base::TimeTicks(),
436 FrameMsg_UILoadMetricsReportType::NO_REPORT
, GURL(), GURL());
437 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
438 TestRenderFrame
* frame
=
439 static_cast<TestRenderFrame
*>(impl
->GetMainRenderFrame());
440 frame
->Navigate(common_params
, StartNavigationParams(),
441 RequestNavigationParams());
442 FrameLoadWaiter(frame
).Wait();
445 uint32
RenderViewTest::GetNavigationIPCType() {
446 return FrameHostMsg_DidCommitProvisionalLoad::ID
;
449 void RenderViewTest::Resize(gfx::Size new_size
,
450 gfx::Rect resizer_rect
,
451 bool is_fullscreen_granted
) {
452 ViewMsg_Resize_Params params
;
453 params
.screen_info
= blink::WebScreenInfo();
454 params
.new_size
= new_size
;
455 params
.physical_backing_size
= new_size
;
456 params
.top_controls_height
= 0.f
;
457 params
.top_controls_shrink_blink_size
= false;
458 params
.resizer_rect
= resizer_rect
;
459 params
.is_fullscreen_granted
= is_fullscreen_granted
;
460 params
.display_mode
= blink::WebDisplayModeBrowser
;
461 scoped_ptr
<IPC::Message
> resize_message(new ViewMsg_Resize(0, params
));
462 OnMessageReceived(*resize_message
);
465 void RenderViewTest::SimulateUserTypingASCIICharacter(char ascii_character
,
466 bool flush_message_loop
) {
467 blink::WebKeyboardEvent event
;
468 event
.text
[0] = ascii_character
;
469 ASSERT_TRUE(GetWindowsKeyCode(ascii_character
, &event
.windowsKeyCode
));
470 if (isupper(ascii_character
) || ascii_character
== '@' ||
471 ascii_character
== '_') {
472 event
.modifiers
= blink::WebKeyboardEvent::ShiftKey
;
475 event
.type
= blink::WebKeyboardEvent::RawKeyDown
;
476 SendWebKeyboardEvent(event
);
478 event
.type
= blink::WebKeyboardEvent::Char
;
479 SendWebKeyboardEvent(event
);
481 event
.type
= blink::WebKeyboardEvent::KeyUp
;
482 SendWebKeyboardEvent(event
);
484 if (flush_message_loop
) {
485 // Processing is delayed because of a Blink bug:
486 // https://bugs.webkit.org/show_bug.cgi?id=16976 See
487 // PasswordAutofillAgent::TextDidChangeInTextField() for details.
488 base::MessageLoop::current()->RunUntilIdle();
492 void RenderViewTest::SimulateUserInputChangeForElement(
493 blink::WebInputElement
* input
,
494 const std::string
& new_value
) {
495 ASSERT_TRUE(base::IsStringASCII(new_value
));
496 while (!input
->focused())
497 input
->document().frame()->view()->advanceFocus(false);
499 size_t previous_length
= input
->value().length();
500 for (size_t i
= 0; i
< previous_length
; ++i
)
501 SimulateUserTypingASCIICharacter(ui::VKEY_BACK
, false);
503 EXPECT_TRUE(input
->value().utf8().empty());
504 for (size_t i
= 0; i
< new_value
.size(); ++i
)
505 SimulateUserTypingASCIICharacter(new_value
[i
], false);
507 // Compare only beginning, because autocomplete may have filled out the
509 EXPECT_EQ(new_value
, input
->value().utf8().substr(0, new_value
.length()));
511 base::MessageLoop::current()->RunUntilIdle();
514 bool RenderViewTest::OnMessageReceived(const IPC::Message
& msg
) {
515 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
516 return impl
->OnMessageReceived(msg
);
519 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame
* frame
,
520 bool is_new_navigation
) {
521 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
522 blink::WebHistoryItem item
;
524 impl
->GetMainRenderFrame()->didNavigateWithinPage(
527 is_new_navigation
? blink::WebStandardCommit
528 : blink::WebHistoryInertCommit
);
531 void RenderViewTest::SendContentStateImmediately() {
532 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
533 impl
->set_send_content_state_immediately(true);
536 blink::WebWidget
* RenderViewTest::GetWebWidget() {
537 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
538 return impl
->webwidget();
542 ContentClient
* RenderViewTest::CreateContentClient() {
543 return new TestContentClient
;
546 ContentBrowserClient
* RenderViewTest::CreateContentBrowserClient() {
547 return new ContentBrowserClient
;
550 ContentRendererClient
* RenderViewTest::CreateContentRendererClient() {
551 return new ContentRendererClient
;
554 scoped_ptr
<ViewMsg_Resize_Params
> RenderViewTest::InitialSizeParams() {
555 return make_scoped_ptr(new ViewMsg_Resize_Params());
558 void RenderViewTest::GoToOffset(int offset
, const PageState
& state
) {
559 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
561 int history_list_length
= impl
->historyBackListCount() +
562 impl
->historyForwardListCount() + 1;
563 int pending_offset
= offset
+ impl
->history_list_offset_
;
565 CommonNavigationParams
common_params(
566 GURL(), Referrer(), ui::PAGE_TRANSITION_FORWARD_BACK
,
567 FrameMsg_Navigate_Type::NORMAL
, true, false, base::TimeTicks(),
568 FrameMsg_UILoadMetricsReportType::NO_REPORT
, GURL(), GURL());
569 RequestNavigationParams request_params
;
570 request_params
.page_state
= state
;
571 request_params
.page_id
= impl
->page_id_
+ offset
;
572 request_params
.nav_entry_id
= pending_offset
+ 1;
573 request_params
.pending_history_list_offset
= pending_offset
;
574 request_params
.current_history_list_offset
= impl
->history_list_offset_
;
575 request_params
.current_history_list_length
= history_list_length
;
577 TestRenderFrame
* frame
=
578 static_cast<TestRenderFrame
*>(impl
->GetMainRenderFrame());
579 frame
->Navigate(common_params
, StartNavigationParams(), request_params
);
581 // The load actually happens asynchronously, so we pump messages to process
582 // the pending continuation.
583 FrameLoadWaiter(frame
).Wait();
586 } // namespace content