Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / content / public / test / render_view_test.cc
blob1e1a0485beeac68c59707ceffe6f62c9cb2a94f6
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 "components/scheduler/renderer/renderer_scheduler.h"
9 #include "content/common/dom_storage/dom_storage_types.h"
10 #include "content/common/frame_messages.h"
11 #include "content/common/input_messages.h"
12 #include "content/common/view_messages.h"
13 #include "content/public/browser/content_browser_client.h"
14 #include "content/public/browser/native_web_keyboard_event.h"
15 #include "content/public/common/content_client.h"
16 #include "content/public/common/renderer_preferences.h"
17 #include "content/public/renderer/content_renderer_client.h"
18 #include "content/public/test/frame_load_waiter.h"
19 #include "content/renderer/history_controller.h"
20 #include "content/renderer/history_serialization.h"
21 #include "content/renderer/render_thread_impl.h"
22 #include "content/renderer/render_view_impl.h"
23 #include "content/renderer/renderer_blink_platform_impl.h"
24 #include "content/renderer/renderer_main_platform_delegate.h"
25 #include "content/test/fake_compositor_dependencies.h"
26 #include "content/test/mock_render_process.h"
27 #include "content/test/test_content_client.h"
28 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
29 #include "third_party/WebKit/public/platform/WebURLRequest.h"
30 #include "third_party/WebKit/public/web/WebHistoryItem.h"
31 #include "third_party/WebKit/public/web/WebInputEvent.h"
32 #include "third_party/WebKit/public/web/WebKit.h"
33 #include "third_party/WebKit/public/web/WebLocalFrame.h"
34 #include "third_party/WebKit/public/web/WebScriptSource.h"
35 #include "third_party/WebKit/public/web/WebView.h"
36 #include "ui/base/resource/resource_bundle.h"
37 #include "v8/include/v8.h"
39 #if defined(OS_MACOSX)
40 #include "base/mac/scoped_nsautorelease_pool.h"
41 #endif
43 using blink::WebGestureEvent;
44 using blink::WebInputEvent;
45 using blink::WebLocalFrame;
46 using blink::WebMouseEvent;
47 using blink::WebScriptSource;
48 using blink::WebString;
49 using blink::WebURLRequest;
51 namespace {
52 const int32 kOpenerId = -2;
53 const int32 kRouteId = 5;
54 const int32 kMainFrameRouteId = 6;
55 const int32 kNewWindowRouteId = 7;
56 const int32 kNewFrameRouteId = 10;
57 const int32 kSurfaceId = 42;
59 } // namespace
61 namespace content {
63 class RendererBlinkPlatformImplNoSandboxImpl
64 : public RendererBlinkPlatformImpl {
65 public:
66 RendererBlinkPlatformImplNoSandboxImpl(
67 scheduler::RendererScheduler* scheduler)
68 : RendererBlinkPlatformImpl(scheduler) {}
70 virtual blink::WebSandboxSupport* sandboxSupport() {
71 return NULL;
75 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
76 RendererBlinkPlatformImplNoSandbox() {
77 renderer_scheduler_ = scheduler::RendererScheduler::Create();
78 blink_platform_impl_.reset(
79 new RendererBlinkPlatformImplNoSandboxImpl(renderer_scheduler_.get()));
82 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
83 ~RendererBlinkPlatformImplNoSandbox() {
86 blink::Platform* RenderViewTest::RendererBlinkPlatformImplNoSandbox::Get() {
87 return blink_platform_impl_.get();
90 RenderViewTest::RenderViewTest()
91 : view_(NULL) {
94 RenderViewTest::~RenderViewTest() {
97 void RenderViewTest::ProcessPendingMessages() {
98 msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
99 msg_loop_.Run();
102 WebLocalFrame* RenderViewTest::GetMainFrame() {
103 return view_->GetWebView()->mainFrame()->toWebLocalFrame();
106 void RenderViewTest::ExecuteJavaScript(const char* js) {
107 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
110 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
111 const base::string16& script,
112 int* int_result) {
113 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
114 v8::Handle<v8::Value> result =
115 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script));
116 if (result.IsEmpty() || !result->IsInt32())
117 return false;
119 if (int_result)
120 *int_result = result->Int32Value();
122 return true;
125 void RenderViewTest::LoadHTML(const char* html) {
126 std::string url_str = "data:text/html;charset=utf-8,";
127 url_str.append(html);
128 GURL url(url_str);
129 WebURLRequest request(url);
130 request.setCheckForBrowserSideNavigation(false);
131 GetMainFrame()->loadRequest(request);
132 // The load actually happens asynchronously, so we pump messages to process
133 // the pending continuation.
134 FrameLoadWaiter(view_->GetMainRenderFrame()).Wait();
137 PageState RenderViewTest::GetCurrentPageState() {
138 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
139 return HistoryEntryToPageState(impl->history_controller()->GetCurrentEntry());
142 void RenderViewTest::GoBack(const PageState& state) {
143 GoToOffset(-1, state);
146 void RenderViewTest::GoForward(const PageState& state) {
147 GoToOffset(1, state);
150 void RenderViewTest::SetUp() {
151 content_client_.reset(CreateContentClient());
152 content_browser_client_.reset(CreateContentBrowserClient());
153 content_renderer_client_.reset(CreateContentRendererClient());
154 SetContentClient(content_client_.get());
155 SetBrowserClientForTesting(content_browser_client_.get());
156 SetRendererClientForTesting(content_renderer_client_.get());
158 // Subclasses can set render_thread_ with their own implementation before
159 // calling RenderViewTest::SetUp().
160 if (!render_thread_)
161 render_thread_.reset(new MockRenderThread());
162 render_thread_->set_routing_id(kRouteId);
163 render_thread_->set_surface_id(kSurfaceId);
164 render_thread_->set_new_window_routing_id(kNewWindowRouteId);
165 render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
167 #if defined(OS_MACOSX)
168 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
169 #endif
170 command_line_.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
171 params_.reset(new MainFunctionParams(*command_line_));
172 platform_.reset(new RendererMainPlatformDelegate(*params_));
173 platform_->PlatformInitialize();
175 // Setting flags and really doing anything with WebKit is fairly fragile and
176 // hacky, but this is the world we live in...
177 std::string flags("--expose-gc");
178 v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
179 blink::initialize(blink_platform_impl_.Get());
181 // Ensure that we register any necessary schemes when initializing WebKit,
182 // since we are using a MockRenderThread.
183 RenderThreadImpl::RegisterSchemes();
185 // This check is needed because when run under content_browsertests,
186 // ResourceBundle isn't initialized (since we have to use a diferent test
187 // suite implementation than for content_unittests). For browser_tests, this
188 // is already initialized.
189 if (!ui::ResourceBundle::HasSharedInstance())
190 ui::ResourceBundle::InitSharedInstanceWithLocale(
191 "en-US", NULL, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
193 compositor_deps_.reset(new FakeCompositorDependencies);
194 mock_process_.reset(new MockRenderProcess);
196 ViewMsg_New_Params view_params;
197 view_params.opener_route_id = kOpenerId;
198 view_params.window_was_created_with_opener = false;
199 view_params.renderer_preferences = RendererPreferences();
200 view_params.web_preferences = WebPreferences();
201 view_params.view_id = kRouteId;
202 view_params.main_frame_routing_id = kMainFrameRouteId;
203 view_params.surface_id = kSurfaceId;
204 view_params.session_storage_namespace_id = kInvalidSessionStorageNamespaceId;
205 view_params.frame_name = base::string16();
206 view_params.swapped_out = false;
207 view_params.replicated_frame_state = FrameReplicationState();
208 view_params.proxy_routing_id = MSG_ROUTING_NONE;
209 view_params.hidden = false;
210 view_params.never_visible = false;
211 view_params.next_page_id = 1;
212 view_params.initial_size = *InitialSizeParams();
213 view_params.enable_auto_resize = false;
214 view_params.min_size = gfx::Size();
215 view_params.max_size = gfx::Size();
217 // This needs to pass the mock render thread to the view.
218 RenderViewImpl* view =
219 RenderViewImpl::Create(view_params, compositor_deps_.get(), false);
220 view->AddRef();
221 view_ = view;
224 void RenderViewTest::TearDown() {
225 // Try very hard to collect garbage before shutting down.
226 // "5" was chosen following http://crbug.com/46571#c9
227 const int kGCIterations = 5;
228 for (int i = 0; i < kGCIterations; i++)
229 GetMainFrame()->collectGarbage();
231 // Run the loop so the release task from the renderwidget executes.
232 ProcessPendingMessages();
234 for (int i = 0; i < kGCIterations; i++)
235 GetMainFrame()->collectGarbage();
237 render_thread_->SendCloseMessage();
238 view_ = NULL;
239 mock_process_.reset();
241 // After telling the view to close and resetting mock_process_ we may get
242 // some new tasks which need to be processed before shutting down WebKit
243 // (http://crbug.com/21508).
244 base::RunLoop().RunUntilIdle();
246 #if defined(OS_MACOSX)
247 // Needs to run before blink::shutdown().
248 autorelease_pool_.reset(NULL);
249 #endif
251 blink::shutdown();
253 platform_->PlatformUninitialize();
254 platform_.reset();
255 params_.reset();
256 command_line_.reset();
259 void RenderViewTest::SendNativeKeyEvent(
260 const NativeWebKeyboardEvent& key_event) {
261 SendWebKeyboardEvent(key_event);
264 void RenderViewTest::SendWebKeyboardEvent(
265 const blink::WebKeyboardEvent& key_event) {
266 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
267 impl->OnMessageReceived(
268 InputMsg_HandleInputEvent(0, &key_event, ui::LatencyInfo(), false));
271 void RenderViewTest::SendWebMouseEvent(
272 const blink::WebMouseEvent& mouse_event) {
273 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
274 impl->OnMessageReceived(
275 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
278 const char* const kGetCoordinatesScript =
279 "(function() {"
280 " function GetCoordinates(elem) {"
281 " if (!elem)"
282 " return [ 0, 0];"
283 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
284 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
285 " coordinates[0] += parent_coordinates[0];"
286 " coordinates[1] += parent_coordinates[1];"
287 " return [ Math.round(coordinates[0]),"
288 " Math.round(coordinates[1])];"
289 " };"
290 " var elem = document.getElementById('$1');"
291 " if (!elem)"
292 " return null;"
293 " var bounds = GetCoordinates(elem);"
294 " bounds[2] = Math.round(elem.offsetWidth);"
295 " bounds[3] = Math.round(elem.offsetHeight);"
296 " return bounds;"
297 "})();";
298 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
299 std::vector<std::string> params;
300 params.push_back(element_id);
301 std::string script =
302 ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
304 v8::Isolate* isolate = v8::Isolate::GetCurrent();
305 v8::HandleScope handle_scope(isolate);
306 v8::Handle<v8::Value> value = GetMainFrame()->executeScriptAndReturnValue(
307 WebScriptSource(WebString::fromUTF8(script)));
308 if (value.IsEmpty() || !value->IsArray())
309 return gfx::Rect();
311 v8::Handle<v8::Array> array = value.As<v8::Array>();
312 if (array->Length() != 4)
313 return gfx::Rect();
314 std::vector<int> coords;
315 for (int i = 0; i < 4; ++i) {
316 v8::Handle<v8::Number> index = v8::Number::New(isolate, i);
317 v8::Local<v8::Value> value = array->Get(index);
318 if (value.IsEmpty() || !value->IsInt32())
319 return gfx::Rect();
320 coords.push_back(value->Int32Value());
322 return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
325 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
326 gfx::Rect bounds = GetElementBounds(element_id);
327 if (bounds.IsEmpty())
328 return false;
329 SimulatePointClick(bounds.CenterPoint());
330 return true;
333 void RenderViewTest::SimulatePointClick(const gfx::Point& point) {
334 WebMouseEvent mouse_event;
335 mouse_event.type = WebInputEvent::MouseDown;
336 mouse_event.button = WebMouseEvent::ButtonLeft;
337 mouse_event.x = point.x();
338 mouse_event.y = point.y();
339 mouse_event.clickCount = 1;
340 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
341 impl->OnMessageReceived(
342 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
343 mouse_event.type = WebInputEvent::MouseUp;
344 impl->OnMessageReceived(
345 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
348 void RenderViewTest::SimulateRectTap(const gfx::Rect& rect) {
349 WebGestureEvent gesture_event;
350 gesture_event.x = rect.CenterPoint().x();
351 gesture_event.y = rect.CenterPoint().y();
352 gesture_event.data.tap.tapCount = 1;
353 gesture_event.data.tap.width = rect.width();
354 gesture_event.data.tap.height = rect.height();
355 gesture_event.type = WebInputEvent::GestureTap;
356 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
357 impl->OnMessageReceived(
358 InputMsg_HandleInputEvent(0, &gesture_event, ui::LatencyInfo(), false));
359 impl->FocusChangeComplete();
362 void RenderViewTest::SetFocused(const blink::WebNode& node) {
363 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
364 impl->focusedNodeChanged(blink::WebNode(), node);
367 void RenderViewTest::Reload(const GURL& url) {
368 CommonNavigationParams common_params(
369 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::RELOAD,
370 true, base::TimeTicks(), FrameMsg_UILoadMetricsReportType::NO_REPORT,
371 GURL(), GURL());
372 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
373 impl->GetMainRenderFrame()->OnNavigate(common_params, StartNavigationParams(),
374 RequestNavigationParams());
375 FrameLoadWaiter(impl->GetMainRenderFrame()).Wait();
378 uint32 RenderViewTest::GetNavigationIPCType() {
379 return FrameHostMsg_DidCommitProvisionalLoad::ID;
382 void RenderViewTest::Resize(gfx::Size new_size,
383 gfx::Rect resizer_rect,
384 bool is_fullscreen_granted) {
385 ViewMsg_Resize_Params params;
386 params.screen_info = blink::WebScreenInfo();
387 params.new_size = new_size;
388 params.physical_backing_size = new_size;
389 params.top_controls_height = 0.f;
390 params.top_controls_shrink_blink_size = false;
391 params.resizer_rect = resizer_rect;
392 params.is_fullscreen_granted = is_fullscreen_granted;
393 params.display_mode = blink::WebDisplayModeBrowser;
394 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
395 OnMessageReceived(*resize_message);
398 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
399 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
400 return impl->OnMessageReceived(msg);
403 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame* frame,
404 bool is_new_navigation) {
405 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
406 blink::WebHistoryItem item;
407 item.initialize();
408 impl->GetMainRenderFrame()->didNavigateWithinPage(
409 frame,
410 item,
411 is_new_navigation ? blink::WebStandardCommit
412 : blink::WebHistoryInertCommit);
415 void RenderViewTest::SendContentStateImmediately() {
416 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
417 impl->set_send_content_state_immediately(true);
420 blink::WebWidget* RenderViewTest::GetWebWidget() {
421 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
422 return impl->webwidget();
426 ContentClient* RenderViewTest::CreateContentClient() {
427 return new TestContentClient;
430 ContentBrowserClient* RenderViewTest::CreateContentBrowserClient() {
431 return new ContentBrowserClient;
434 ContentRendererClient* RenderViewTest::CreateContentRendererClient() {
435 return new ContentRendererClient;
438 scoped_ptr<ViewMsg_Resize_Params> RenderViewTest::InitialSizeParams() {
439 return make_scoped_ptr(new ViewMsg_Resize_Params());
442 void RenderViewTest::GoToOffset(int offset, const PageState& state) {
443 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
445 int history_list_length = impl->historyBackListCount() +
446 impl->historyForwardListCount() + 1;
447 int pending_offset = offset + impl->history_list_offset_;
449 CommonNavigationParams common_params(
450 GURL(), Referrer(), ui::PAGE_TRANSITION_FORWARD_BACK,
451 FrameMsg_Navigate_Type::NORMAL, true, base::TimeTicks(),
452 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
453 RequestNavigationParams request_params;
454 request_params.page_state = state;
455 request_params.page_id = impl->page_id_ + offset;
456 request_params.pending_history_list_offset = pending_offset;
457 request_params.current_history_list_offset = impl->history_list_offset_;
458 request_params.current_history_list_length = history_list_length;
460 impl->GetMainRenderFrame()->OnNavigate(common_params, StartNavigationParams(),
461 request_params);
463 // The load actually happens asynchronously, so we pump messages to process
464 // the pending continuation.
465 FrameLoadWaiter(view_->GetMainRenderFrame()).Wait();
468 } // namespace content