Update broken references to image assets
[chromium-blink-merge.git] / content / public / test / render_view_test.cc
blobacec861fda04fefd3958b59f5a966388168b5767
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 <cctype>
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"
49 #endif
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;
59 namespace {
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);
72 return true;
75 switch (ascii_character) {
76 case '@':
77 *key_code = '2';
78 return true;
79 case '_':
80 *key_code = ui::VKEY_OEM_MINUS;
81 return true;
82 case '.':
83 *key_code = ui::VKEY_OEM_PERIOD;
84 return true;
85 case ui::VKEY_BACK:
86 *key_code = ui::VKEY_BACK;
87 return true;
88 default:
89 return false;
93 } // namespace
95 namespace content {
97 class RendererBlinkPlatformImplNoSandboxImpl
98 : public RendererBlinkPlatformImpl {
99 public:
100 RendererBlinkPlatformImplNoSandboxImpl(
101 scheduler::RendererScheduler* scheduler)
102 : RendererBlinkPlatformImpl(scheduler) {}
104 virtual blink::WebSandboxSupport* sandboxSupport() {
105 return NULL;
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() {
120 blink::Platform*
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()
131 : view_(NULL) {
132 RenderFrameImpl::InstallCreateHook(&TestRenderFrame::CreateTestRenderFrame);
135 RenderViewTest::~RenderViewTest() {
138 void RenderViewTest::ProcessPendingMessages() {
139 msg_loop_.task_runner()->PostTask(FROM_HERE,
140 base::MessageLoop::QuitClosure());
141 msg_loop_.Run();
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,
154 int* int_result) {
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())
159 return false;
161 if (int_result)
162 *int_result = result->Int32Value();
164 return true;
167 void RenderViewTest::LoadHTML(const char* html) {
168 std::string url_str = "data:text/html;charset=utf-8,";
169 url_str.append(html);
170 GURL url(url_str);
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 // Blink needs to be initialized before calling CreateContentRendererClient()
194 // because it uses blink internally.
195 blink::initialize(blink_platform_impl_.Get());
197 content_client_.reset(CreateContentClient());
198 content_browser_client_.reset(CreateContentBrowserClient());
199 content_renderer_client_.reset(CreateContentRendererClient());
200 SetContentClient(content_client_.get());
201 SetBrowserClientForTesting(content_browser_client_.get());
202 SetRendererClientForTesting(content_renderer_client_.get());
204 // Subclasses can set render_thread_ with their own implementation before
205 // calling RenderViewTest::SetUp().
206 if (!render_thread_)
207 render_thread_.reset(new MockRenderThread());
208 render_thread_->set_routing_id(kRouteId);
209 render_thread_->set_surface_id(kSurfaceId);
210 render_thread_->set_new_window_routing_id(kNewWindowRouteId);
211 render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
213 #if defined(OS_MACOSX)
214 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
215 #endif
216 command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
217 params_.reset(new MainFunctionParams(*command_line_));
218 platform_.reset(new RendererMainPlatformDelegate(*params_));
219 platform_->PlatformInitialize();
221 // Setting flags and really doing anything with WebKit is fairly fragile and
222 // hacky, but this is the world we live in...
223 std::string flags("--expose-gc");
224 v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
226 // Ensure that we register any necessary schemes when initializing WebKit,
227 // since we are using a MockRenderThread.
228 RenderThreadImpl::RegisterSchemes();
230 // This check is needed because when run under content_browsertests,
231 // ResourceBundle isn't initialized (since we have to use a diferent test
232 // suite implementation than for content_unittests). For browser_tests, this
233 // is already initialized.
234 if (!ui::ResourceBundle::HasSharedInstance())
235 ui::ResourceBundle::InitSharedInstanceWithLocale(
236 "en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
238 compositor_deps_.reset(new FakeCompositorDependencies);
239 mock_process_.reset(new MockRenderProcess);
241 ViewMsg_New_Params view_params;
242 view_params.opener_frame_route_id = MSG_ROUTING_NONE;
243 view_params.window_was_created_with_opener = false;
244 view_params.renderer_preferences = RendererPreferences();
245 view_params.web_preferences = WebPreferences();
246 view_params.view_id = kRouteId;
247 view_params.main_frame_routing_id = kMainFrameRouteId;
248 view_params.surface_id = kSurfaceId;
249 view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
250 view_params.swapped_out = false;
251 view_params.replicated_frame_state = FrameReplicationState();
252 view_params.proxy_routing_id = MSG_ROUTING_NONE;
253 view_params.hidden = false;
254 view_params.never_visible = false;
255 view_params.next_page_id = 1;
256 view_params.initial_size = *InitialSizeParams();
257 view_params.enable_auto_resize = false;
258 view_params.min_size = gfx::Size();
259 view_params.max_size = gfx::Size();
261 // This needs to pass the mock render thread to the view.
262 RenderViewImpl* view =
263 RenderViewImpl::Create(compositor_deps_.get(), view_params, false);
264 view_ = view;
267 void RenderViewTest::TearDown() {
268 // Try very hard to collect garbage before shutting down.
269 // "5" was chosen following http://crbug.com/46571#c9
270 const int kGCIterations = 5;
271 for (int i = 0; i < kGCIterations; i++)
272 GetMainFrame()->collectGarbage();
274 // Run the loop so the release task from the renderwidget executes.
275 ProcessPendingMessages();
277 for (int i = 0; i < kGCIterations; i++)
278 GetMainFrame()->collectGarbage();
280 render_thread_->SendCloseMessage();
281 view_ = NULL;
282 mock_process_.reset();
284 // After telling the view to close and resetting mock_process_ we may get
285 // some new tasks which need to be processed before shutting down WebKit
286 // (http://crbug.com/21508).
287 base::RunLoop().RunUntilIdle();
289 #if defined(OS_MACOSX)
290 // Needs to run before blink::shutdown().
291 autorelease_pool_.reset(NULL);
292 #endif
294 blink_platform_impl_.Scheduler()->Shutdown();
295 blink::shutdown();
297 platform_->PlatformUninitialize();
298 platform_.reset();
299 params_.reset();
300 command_line_.reset();
303 void RenderViewTest::SendNativeKeyEvent(
304 const NativeWebKeyboardEvent& key_event) {
305 SendWebKeyboardEvent(key_event);
308 void RenderViewTest::SendWebKeyboardEvent(
309 const blink::WebKeyboardEvent& key_event) {
310 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
311 impl->OnMessageReceived(
312 InputMsg_HandleInputEvent(0, &key_event, ui::LatencyInfo(), false));
315 void RenderViewTest::SendWebMouseEvent(
316 const blink::WebMouseEvent& mouse_event) {
317 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
318 impl->OnMessageReceived(
319 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
322 const char* const kGetCoordinatesScript =
323 "(function() {"
324 " function GetCoordinates(elem) {"
325 " if (!elem)"
326 " return [ 0, 0];"
327 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
328 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
329 " coordinates[0] += parent_coordinates[0];"
330 " coordinates[1] += parent_coordinates[1];"
331 " return [ Math.round(coordinates[0]),"
332 " Math.round(coordinates[1])];"
333 " };"
334 " var elem = document.getElementById('$1');"
335 " if (!elem)"
336 " return null;"
337 " var bounds = GetCoordinates(elem);"
338 " bounds[2] = Math.round(elem.offsetWidth);"
339 " bounds[3] = Math.round(elem.offsetHeight);"
340 " return bounds;"
341 "})();";
342 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
343 std::vector<std::string> params;
344 params.push_back(element_id);
345 std::string script =
346 base::ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
348 v8::Isolate* isolate = v8::Isolate::GetCurrent();
349 v8::HandleScope handle_scope(isolate);
350 v8::Local<v8::Value> value = GetMainFrame()->executeScriptAndReturnValue(
351 WebScriptSource(WebString::fromUTF8(script)));
352 if (value.IsEmpty() || !value->IsArray())
353 return gfx::Rect();
355 v8::Local<v8::Array> array = value.As<v8::Array>();
356 if (array->Length() != 4)
357 return gfx::Rect();
358 std::vector<int> coords;
359 for (int i = 0; i < 4; ++i) {
360 v8::Local<v8::Number> index = v8::Number::New(isolate, i);
361 v8::Local<v8::Value> value = array->Get(index);
362 if (value.IsEmpty() || !value->IsInt32())
363 return gfx::Rect();
364 coords.push_back(value->Int32Value());
366 return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
369 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
370 gfx::Rect bounds = GetElementBounds(element_id);
371 if (bounds.IsEmpty())
372 return false;
373 SimulatePointClick(bounds.CenterPoint());
374 return true;
377 void RenderViewTest::SimulatePointClick(const gfx::Point& point) {
378 WebMouseEvent mouse_event;
379 mouse_event.type = WebInputEvent::MouseDown;
380 mouse_event.button = WebMouseEvent::ButtonLeft;
381 mouse_event.x = point.x();
382 mouse_event.y = point.y();
383 mouse_event.clickCount = 1;
384 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
385 impl->OnMessageReceived(
386 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
387 mouse_event.type = WebInputEvent::MouseUp;
388 impl->OnMessageReceived(
389 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
393 bool RenderViewTest::SimulateElementRightClick(const std::string& element_id) {
394 gfx::Rect bounds = GetElementBounds(element_id);
395 if (bounds.IsEmpty())
396 return false;
397 SimulatePointRightClick(bounds.CenterPoint());
398 return true;
401 void RenderViewTest::SimulatePointRightClick(const gfx::Point& point) {
402 WebMouseEvent mouse_event;
403 mouse_event.type = WebInputEvent::MouseDown;
404 mouse_event.button = WebMouseEvent::ButtonRight;
405 mouse_event.x = point.x();
406 mouse_event.y = point.y();
407 mouse_event.clickCount = 1;
408 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
409 impl->OnMessageReceived(
410 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
411 mouse_event.type = WebInputEvent::MouseUp;
412 impl->OnMessageReceived(
413 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
416 void RenderViewTest::SimulateRectTap(const gfx::Rect& rect) {
417 WebGestureEvent gesture_event;
418 gesture_event.x = rect.CenterPoint().x();
419 gesture_event.y = rect.CenterPoint().y();
420 gesture_event.data.tap.tapCount = 1;
421 gesture_event.data.tap.width = rect.width();
422 gesture_event.data.tap.height = rect.height();
423 gesture_event.type = WebInputEvent::GestureTap;
424 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
425 impl->OnMessageReceived(
426 InputMsg_HandleInputEvent(0, &gesture_event, ui::LatencyInfo(), false));
427 impl->FocusChangeComplete();
430 void RenderViewTest::SetFocused(const blink::WebNode& node) {
431 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
432 impl->focusedNodeChanged(blink::WebNode(), node);
435 void RenderViewTest::Reload(const GURL& url) {
436 CommonNavigationParams common_params(
437 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::RELOAD,
438 true, false, base::TimeTicks(),
439 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
440 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
441 TestRenderFrame* frame =
442 static_cast<TestRenderFrame*>(impl->GetMainRenderFrame());
443 frame->Navigate(common_params, StartNavigationParams(),
444 RequestNavigationParams());
445 FrameLoadWaiter(frame).Wait();
448 uint32 RenderViewTest::GetNavigationIPCType() {
449 return FrameHostMsg_DidCommitProvisionalLoad::ID;
452 void RenderViewTest::Resize(gfx::Size new_size,
453 gfx::Rect resizer_rect,
454 bool is_fullscreen_granted) {
455 ViewMsg_Resize_Params params;
456 params.screen_info = blink::WebScreenInfo();
457 params.new_size = new_size;
458 params.physical_backing_size = new_size;
459 params.top_controls_height = 0.f;
460 params.top_controls_shrink_blink_size = false;
461 params.resizer_rect = resizer_rect;
462 params.is_fullscreen_granted = is_fullscreen_granted;
463 params.display_mode = blink::WebDisplayModeBrowser;
464 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
465 OnMessageReceived(*resize_message);
468 void RenderViewTest::SimulateUserTypingASCIICharacter(char ascii_character,
469 bool flush_message_loop) {
470 blink::WebKeyboardEvent event;
471 event.text[0] = ascii_character;
472 ASSERT_TRUE(GetWindowsKeyCode(ascii_character, &event.windowsKeyCode));
473 if (isupper(ascii_character) || ascii_character == '@' ||
474 ascii_character == '_') {
475 event.modifiers = blink::WebKeyboardEvent::ShiftKey;
478 event.type = blink::WebKeyboardEvent::RawKeyDown;
479 SendWebKeyboardEvent(event);
481 event.type = blink::WebKeyboardEvent::Char;
482 SendWebKeyboardEvent(event);
484 event.type = blink::WebKeyboardEvent::KeyUp;
485 SendWebKeyboardEvent(event);
487 if (flush_message_loop) {
488 // Processing is delayed because of a Blink bug:
489 // https://bugs.webkit.org/show_bug.cgi?id=16976 See
490 // PasswordAutofillAgent::TextDidChangeInTextField() for details.
491 base::MessageLoop::current()->RunUntilIdle();
495 void RenderViewTest::SimulateUserInputChangeForElement(
496 blink::WebInputElement* input,
497 const std::string& new_value) {
498 ASSERT_TRUE(base::IsStringASCII(new_value));
499 while (!input->focused())
500 input->document().frame()->view()->advanceFocus(false);
502 size_t previous_length = input->value().length();
503 for (size_t i = 0; i < previous_length; ++i)
504 SimulateUserTypingASCIICharacter(ui::VKEY_BACK, false);
506 EXPECT_TRUE(input->value().utf8().empty());
507 for (size_t i = 0; i < new_value.size(); ++i)
508 SimulateUserTypingASCIICharacter(new_value[i], false);
510 // Compare only beginning, because autocomplete may have filled out the
511 // form.
512 EXPECT_EQ(new_value, input->value().utf8().substr(0, new_value.length()));
514 base::MessageLoop::current()->RunUntilIdle();
517 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
518 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
519 return impl->OnMessageReceived(msg);
522 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame* frame,
523 bool is_new_navigation) {
524 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
525 blink::WebHistoryItem item;
526 item.initialize();
527 impl->GetMainRenderFrame()->didNavigateWithinPage(
528 frame,
529 item,
530 is_new_navigation ? blink::WebStandardCommit
531 : blink::WebHistoryInertCommit);
534 void RenderViewTest::SendContentStateImmediately() {
535 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
536 impl->set_send_content_state_immediately(true);
539 blink::WebWidget* RenderViewTest::GetWebWidget() {
540 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
541 return impl->webwidget();
545 ContentClient* RenderViewTest::CreateContentClient() {
546 return new TestContentClient;
549 ContentBrowserClient* RenderViewTest::CreateContentBrowserClient() {
550 return new ContentBrowserClient;
553 ContentRendererClient* RenderViewTest::CreateContentRendererClient() {
554 return new ContentRendererClient;
557 scoped_ptr<ViewMsg_Resize_Params> RenderViewTest::InitialSizeParams() {
558 return make_scoped_ptr(new ViewMsg_Resize_Params());
561 void RenderViewTest::GoToOffset(int offset, const PageState& state) {
562 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
564 int history_list_length = impl->historyBackListCount() +
565 impl->historyForwardListCount() + 1;
566 int pending_offset = offset + impl->history_list_offset_;
568 CommonNavigationParams common_params(
569 GURL(), Referrer(), ui::PAGE_TRANSITION_FORWARD_BACK,
570 FrameMsg_Navigate_Type::NORMAL, true, false, base::TimeTicks(),
571 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
572 RequestNavigationParams request_params;
573 request_params.page_state = state;
574 request_params.page_id = impl->page_id_ + offset;
575 request_params.nav_entry_id = pending_offset + 1;
576 request_params.pending_history_list_offset = pending_offset;
577 request_params.current_history_list_offset = impl->history_list_offset_;
578 request_params.current_history_list_length = history_list_length;
580 TestRenderFrame* frame =
581 static_cast<TestRenderFrame*>(impl->GetMainRenderFrame());
582 frame->Navigate(common_params, StartNavigationParams(), request_params);
584 // The load actually happens asynchronously, so we pump messages to process
585 // the pending continuation.
586 FrameLoadWaiter(frame).Wait();
589 } // namespace content