Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(326)

Side by Side Diff: ios/web/web_state/ui/crw_web_controller_unittest.mm

Issue 1641893003: [ios] Removed WEB_TEST_F from web unit tests. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Self review Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #import "ios/web/web_state/ui/crw_web_controller.h" 5 #import "ios/web/web_state/ui/crw_web_controller.h"
6 6
7 #import <UIKit/UIKit.h>
8 #import <WebKit/WebKit.h> 7 #import <WebKit/WebKit.h>
9 8
10 #include <utility> 9 #include <utility>
11 10
12 #include "base/callback_helpers.h" 11 #include "base/callback_helpers.h"
13 #include "base/ios/ios_util.h" 12 #include "base/ios/ios_util.h"
14 #import "base/mac/bind_objc_block.h" 13 #import "base/mac/bind_objc_block.h"
15 #include "base/mac/scoped_nsobject.h" 14 #include "base/mac/scoped_nsobject.h"
16 #include "base/strings/sys_string_conversions.h" 15 #include "base/strings/sys_string_conversions.h"
17 #include "base/test/histogram_tester.h" 16 #include "base/test/histogram_tester.h"
(...skipping 27 matching lines...) Expand all
45 #include "testing/gtest/include/gtest/gtest.h" 44 #include "testing/gtest/include/gtest/gtest.h"
46 #include "testing/gtest_mac.h" 45 #include "testing/gtest_mac.h"
47 #include "third_party/ocmock/OCMock/OCMock.h" 46 #include "third_party/ocmock/OCMock/OCMock.h"
48 #include "third_party/ocmock/gtest_support.h" 47 #include "third_party/ocmock/gtest_support.h"
49 #include "third_party/ocmock/ocmock_extensions.h" 48 #include "third_party/ocmock/ocmock_extensions.h"
50 #import "ui/base/test/ios/keyboard_appearance_listener.h" 49 #import "ui/base/test/ios/keyboard_appearance_listener.h"
51 #include "ui/base/test/ios/ui_view_test_utils.h" 50 #include "ui/base/test/ios/ui_view_test_utils.h"
52 51
53 using web::NavigationManagerImpl; 52 using web::NavigationManagerImpl;
54 53
55 @interface TestWebController (PrivateTesting)
56 - (void)reloadInternal;
57 @end
58
59 @interface CRWWebController (PrivateAPI) 54 @interface CRWWebController (PrivateAPI)
60 @property(nonatomic, readwrite) web::PageDisplayState pageDisplayState; 55 @property(nonatomic, readwrite) web::PageDisplayState pageDisplayState;
61 @property(nonatomic, readonly) CRWWebControllerContainerView* containerView; 56 @property(nonatomic, readonly) CRWWebControllerContainerView* containerView;
62 - (void)setJsMessageQueueThrottled:(BOOL)throttle; 57 - (void)setJsMessageQueueThrottled:(BOOL)throttle;
63 - (void)removeDocumentLoadCommandsFromQueue; 58 - (void)removeDocumentLoadCommandsFromQueue;
64 - (GURL)URLForHistoryNavigationFromItem:(web::NavigationItem*)fromItem 59 - (GURL)URLForHistoryNavigationFromItem:(web::NavigationItem*)fromItem
65 toItem:(web::NavigationItem*)toItem; 60 toItem:(web::NavigationItem*)toItem;
66 - (BOOL)checkForUnexpectedURLChange;
67 - (void)injectEarlyInjectionScripts;
68 - (void)stopExpectingURLChangeIfNecessary;
69 @end
70
71 @implementation TestWebController (PrivateTesting)
72
73 - (void)reloadInternal {
74 // Empty implementation to prevent the need to mock out a huge number of
75 // calls.
76 }
77
78 @end 61 @end
79 62
80 // Used to mock CRWWebDelegate methods with C++ params. 63 // Used to mock CRWWebDelegate methods with C++ params.
81 @interface MockInteractionLoader : OCMockComplexTypeHelper 64 @interface MockInteractionLoader : OCMockComplexTypeHelper
82 // popupURL passed to webController:shouldBlockPopupWithURL:sourceURL: 65 // popupURL passed to webController:shouldBlockPopupWithURL:sourceURL:
83 // Used for testing. 66 // Used for testing.
84 @property(nonatomic, assign) GURL popupURL; 67 @property(nonatomic, assign) GURL popupURL;
85 // sourceURL passed to webController:shouldBlockPopupWithURL:sourceURL: 68 // sourceURL passed to webController:shouldBlockPopupWithURL:sourceURL:
86 // Used for testing. 69 // Used for testing.
87 @property(nonatomic, assign) GURL sourceURL; 70 @property(nonatomic, assign) GURL sourceURL;
(...skipping 118 matching lines...) Expand 10 before | Expand all | Expand 10 after
206 } 189 }
207 190
208 - (NSString*)commandPrefix { 191 - (NSString*)commandPrefix {
209 return @"wctest"; 192 return @"wctest";
210 } 193 }
211 194
212 @end 195 @end
213 196
214 namespace { 197 namespace {
215 198
216 NSString* const kGetMessageQueueJavaScript =
217 @"window.__gCrWeb === undefined ? '' : __gCrWeb.message.getMessageQueue()";
218
219 NSString* kCheckURLJavaScript =
220 @"try{"
221 "window.__gCrWeb_Verifying = true;"
222 "if(!window.__gCrWeb_CachedRequest||"
223 "!(window.__gCrWeb_CachedRequestDocument===window.document)){"
224 "window.__gCrWeb_CachedRequest = new XMLHttpRequest();"
225 "window.__gCrWeb_CachedRequestDocument = window.document;"
226 "}"
227 "window.__gCrWeb_CachedRequest.open('POST',"
228 "'https://localhost:0/crwebiossecurity',false);"
229 "window.__gCrWeb_CachedRequest.send();"
230 "}catch(e){"
231 "try{"
232 "window.__gCrWeb_CachedRequest.open('POST',"
233 "'/crwebiossecurity/b86b97a1-2ce0-44fd-a074-e2158790c98d',false);"
234 "window.__gCrWeb_CachedRequest.send();"
235 "}catch(e2){}"
236 "}"
237 "delete window.__gCrWeb_Verifying;"
238 "window.location.href";
239
240 NSString* kTestURLString = @"http://www.google.com/"; 199 NSString* kTestURLString = @"http://www.google.com/";
241 200
242 NSMutableURLRequest* requestForCrWebInvokeCommandAndKey(NSString* command,
243 NSString* key) {
244 NSString* fullCommand =
245 [NSString stringWithFormat:@"[{\"command\":\"%@\"}]", command];
246 NSCharacterSet* noCharacters =
247 [NSCharacterSet characterSetWithCharactersInString:@""];
248 NSString* escapedCommand = [fullCommand
249 stringByAddingPercentEncodingWithAllowedCharacters:noCharacters];
250 NSString* urlString =
251 [NSString stringWithFormat:@"crwebinvoke://%@/#%@", key, escapedCommand];
252 return [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
253 }
254
255 // Returns true if the current device is a large iPhone (6 or 6+). 201 // Returns true if the current device is a large iPhone (6 or 6+).
256 bool IsIPhone6Or6Plus() { 202 bool IsIPhone6Or6Plus() {
257 UIUserInterfaceIdiom idiom = [[UIDevice currentDevice] userInterfaceIdiom]; 203 UIUserInterfaceIdiom idiom = [[UIDevice currentDevice] userInterfaceIdiom];
258 return (idiom == UIUserInterfaceIdiomPhone && 204 return (idiom == UIUserInterfaceIdiomPhone &&
259 CGRectGetHeight([[UIScreen mainScreen] nativeBounds]) >= 1334.0); 205 CGRectGetHeight([[UIScreen mainScreen] nativeBounds]) >= 1334.0);
260 } 206 }
261 207
262 // Returns HTML for an optionally zoomable test page with |zoom_state|. 208 // Returns HTML for an optionally zoomable test page with |zoom_state|.
263 enum PageScalabilityType { 209 enum PageScalabilityType {
264 PAGE_SCALABILITY_DISABLED = 0, 210 PAGE_SCALABILITY_DISABLED = 0,
(...skipping 17 matching lines...) Expand all
282 // Forces |webController|'s view to render and waits until |webController|'s 228 // Forces |webController|'s view to render and waits until |webController|'s
283 // PageZoomState matches |zoom_state|. 229 // PageZoomState matches |zoom_state|.
284 void WaitForZoomRendering(CRWWebController* webController, 230 void WaitForZoomRendering(CRWWebController* webController,
285 const web::PageZoomState& zoom_state) { 231 const web::PageZoomState& zoom_state) {
286 ui::test::uiview_utils::ForceViewRendering(webController.view); 232 ui::test::uiview_utils::ForceViewRendering(webController.view);
287 base::test::ios::WaitUntilCondition(^bool() { 233 base::test::ios::WaitUntilCondition(^bool() {
288 return webController.pageDisplayState.zoom_state() == zoom_state; 234 return webController.pageDisplayState.zoom_state() == zoom_state;
289 }); 235 });
290 } 236 }
291 237
292 // A mixin class for testing CRWWKWebViewWebController or 238 // Test fixture for testing CRWWebController. Stubs out web view and
293 // CRWUIWebViewWebController. Stubs out WebView and child CRWWebController. 239 // child CRWWebController.
294 template <typename WebTestT> 240 class CRWWebControllerTest : public web::WebTestWithWKWebViewWebController {
295 class WebControllerTest : public WebTestT {
296 protected: 241 protected:
297 virtual void SetUp() override { 242 void SetUp() override {
298 WebTestT::SetUp(); 243 web::WebTestWithWKWebViewWebController::SetUp();
299 mockWebView_.reset(CreateMockWebView()); 244 mockWebView_.reset(CreateMockWebView());
300 mockScrollView_.reset([[UIScrollView alloc] init]); 245 mockScrollView_.reset([[UIScrollView alloc] init]);
301 [[[mockWebView_ stub] andReturn:mockScrollView_.get()] scrollView]; 246 [[[mockWebView_ stub] andReturn:mockScrollView_.get()] scrollView];
302 247
303 id originalMockDelegate = 248 id originalMockDelegate =
304 [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)]; 249 [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)];
305 mockDelegate_.reset([[MockInteractionLoader alloc] 250 mockDelegate_.reset([[MockInteractionLoader alloc]
306 initWithRepresentedObject:originalMockDelegate]); 251 initWithRepresentedObject:originalMockDelegate]);
307 [WebTestT::webController_ setDelegate:mockDelegate_]; 252 [webController_ setDelegate:mockDelegate_];
308 base::scoped_nsobject<TestWebViewContentView> webViewContentView( 253 base::scoped_nsobject<TestWebViewContentView> webViewContentView(
309 [[TestWebViewContentView alloc] initWithMockWebView:mockWebView_ 254 [[TestWebViewContentView alloc] initWithMockWebView:mockWebView_
310 scrollView:mockScrollView_]); 255 scrollView:mockScrollView_]);
311 [WebTestT::webController_ injectWebViewContentView:webViewContentView]; 256 [webController_ injectWebViewContentView:webViewContentView];
312 257
313 NavigationManagerImpl& navigationManager = 258 NavigationManagerImpl& navigationManager =
314 [WebTestT::webController_ webStateImpl]->GetNavigationManagerImpl(); 259 [webController_ webStateImpl]->GetNavigationManagerImpl();
315 navigationManager.InitializeSession(@"name", nil, NO, 0); 260 navigationManager.InitializeSession(@"name", nil, NO, 0);
316 [navigationManager.GetSessionController() 261 [navigationManager.GetSessionController()
317 addPendingEntry:GURL("http://www.google.com/?q=foo#bar") 262 addPendingEntry:GURL("http://www.google.com/?q=foo#bar")
318 referrer:web::Referrer() 263 referrer:web::Referrer()
319 transition:ui::PAGE_TRANSITION_TYPED 264 transition:ui::PAGE_TRANSITION_TYPED
320 rendererInitiated:NO]; 265 rendererInitiated:NO];
321 // Set up child CRWWebController. 266 // Set up child CRWWebController.
322 mockChildWebController_.reset([[OCMockObject 267 mockChildWebController_.reset([[OCMockObject
323 mockForProtocol:@protocol(CRWWebControllerScripting)] retain]); 268 mockForProtocol:@protocol(CRWWebControllerScripting)] retain]);
324 [[[mockDelegate_ stub] andReturn:mockChildWebController_.get()] 269 [[[mockDelegate_ stub] andReturn:mockChildWebController_.get()]
325 webController:WebTestT::webController_ 270 webController:webController_
326 scriptingInterfaceForWindowNamed:@"http://www.google.com/#newtab"]; 271 scriptingInterfaceForWindowNamed:@"http://www.google.com/#newtab"];
327 } 272 }
328 273
329 virtual void TearDown() override { 274 void TearDown() override {
330 EXPECT_OCMOCK_VERIFY(mockDelegate_); 275 EXPECT_OCMOCK_VERIFY(mockDelegate_);
331 EXPECT_OCMOCK_VERIFY(mockChildWebController_.get()); 276 EXPECT_OCMOCK_VERIFY(mockChildWebController_.get());
332 EXPECT_OCMOCK_VERIFY(mockWebView_); 277 EXPECT_OCMOCK_VERIFY(mockWebView_);
333 [WebTestT::webController_ resetInjectedWebViewContentView]; 278 [webController_ resetInjectedWebViewContentView];
334 [WebTestT::webController_ setDelegate:nil]; 279 [webController_ setDelegate:nil];
335 WebTestT::TearDown(); 280 web::WebTestWithWKWebViewWebController::TearDown();
336 } 281 }
337 282
338 // Creates WebView mock. 283 // Creates WebView mock.
339 virtual UIView* CreateMockWebView() const = 0; 284 UIView* CreateMockWebView() const {
340
341 // Simulates a load request delegate call from the web view.
342 virtual void SimulateLoadRequest(NSURLRequest* request) const = 0;
343
344 base::scoped_nsobject<UIScrollView> mockScrollView_;
345 base::scoped_nsobject<id> mockWebView_;
346 base::scoped_nsobject<id> mockDelegate_;
347 base::scoped_nsobject<id> mockChildWebController_;
348 };
349
350 class CRWUIWebViewWebControllerTest
351 : public WebControllerTest<web::WebTestWithUIWebViewWebController> {
352 protected:
353 UIView* CreateMockWebView() const override {
354 id result = [[OCMockObject mockForClass:[UIWebView class]] retain];
355 [[[result stub] andReturn:nil] request];
356 [[result stub] setDelegate:OCMOCK_ANY]; // Called by resetInjectedWebView
357 // Stub out the injection process.
358 [[[result stub] andReturn:@"object"]
359 stringByEvaluatingJavaScriptFromString:
360 @"try { typeof __gCrWeb; } catch (e) { 'undefined'; }"];
361 [[[result stub] andReturn:@"object"]
362 stringByEvaluatingJavaScriptFromString:@"try { typeof "
363 @"__gCrWeb.windowIdObject; } "
364 @"catch (e) { 'undefined'; }"];
365 return result;
366 }
367 void SimulateLoadRequest(NSURLRequest* request) const override {
368 id<UIWebViewDelegate> delegate =
369 static_cast<id<UIWebViewDelegate>>(webController_.get());
370 [delegate webView:(UIWebView*)mockWebView_
371 shouldStartLoadWithRequest:request
372 navigationType:UIWebViewNavigationTypeLinkClicked];
373 }
374 };
375
376 class CRWWKWebViewWebControllerTest
377 : public WebControllerTest<web::WebTestWithWKWebViewWebController> {
378 protected:
379 void SetUp() override {
380 CR_TEST_REQUIRES_WK_WEB_VIEW();
381 WebControllerTest<web::WebTestWithWKWebViewWebController>::SetUp();
382 }
383 UIView* CreateMockWebView() const override {
384 id result = [[OCMockObject mockForClass:[WKWebView class]] retain]; 285 id result = [[OCMockObject mockForClass:[WKWebView class]] retain];
385 286
386 // Called by resetInjectedWebView 287 // Called by resetInjectedWebView
387 [[result stub] backForwardList]; 288 [[result stub] backForwardList];
388 [[[result stub] andReturn:[NSURL URLWithString:kTestURLString]] URL]; 289 [[[result stub] andReturn:[NSURL URLWithString:kTestURLString]] URL];
389 [[result stub] setNavigationDelegate:OCMOCK_ANY]; 290 [[result stub] setNavigationDelegate:OCMOCK_ANY];
390 [[result stub] setUIDelegate:OCMOCK_ANY]; 291 [[result stub] setUIDelegate:OCMOCK_ANY];
391 [[result stub] addObserver:webController_ 292 [[result stub] addObserver:webController_
392 forKeyPath:OCMOCK_ANY 293 forKeyPath:OCMOCK_ANY
393 options:0 294 options:0
394 context:nullptr]; 295 context:nullptr];
395 [[result stub] addObserver:OCMOCK_ANY 296 [[result stub] addObserver:OCMOCK_ANY
396 forKeyPath:@"scrollView.backgroundColor" 297 forKeyPath:@"scrollView.backgroundColor"
397 options:0 298 options:0
398 context:nullptr]; 299 context:nullptr];
399 300
400 [[result stub] removeObserver:webController_ forKeyPath:OCMOCK_ANY]; 301 [[result stub] removeObserver:webController_ forKeyPath:OCMOCK_ANY];
401 [[result stub] removeObserver:OCMOCK_ANY 302 [[result stub] removeObserver:OCMOCK_ANY
402 forKeyPath:@"scrollView.backgroundColor"]; 303 forKeyPath:@"scrollView.backgroundColor"];
403 304
404 return result; 305 return result;
405 } 306 }
406 void SimulateLoadRequest(NSURLRequest* request) const override {
407 // TODO(eugenebut): implement this method.
408 }
409 };
410 307
411 TEST_F(CRWUIWebViewWebControllerTest, CrWebInvokeWithIncorrectKey) { 308 base::scoped_nsobject<UIScrollView> mockScrollView_;
412 NSURLRequest* request = [NSURLRequest 309 base::scoped_nsobject<id> mockWebView_;
413 requestWithURL:[NSURL URLWithString:@"crwebinvoke:invalidkey#commands"]]; 310 base::scoped_nsobject<id> mockDelegate_;
414 311 base::scoped_nsobject<id> mockChildWebController_;
415 SimulateLoadRequest(request);
416 }
417
418 TEST_F(CRWUIWebViewWebControllerTest, CrWebInvokeWithLargeQueue) {
419 // Pre-define test window id.
420 [webController_ setWindowId:@"12345678901234567890123456789012"];
421 NSString* valid_key = [webController_ windowId];
422 [[[mockWebView_ stub] andReturn:kTestURLString]
423 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
424
425 // Install an observer to handle custom command messages.
426 base::scoped_nsobject<CountingObserver> observer(
427 [[CountingObserver alloc] init]);
428 [webController_ addObserver:observer];
429
430 // Queue a lot of messages.
431 [webController_ setJsMessageQueueThrottled:YES];
432 const int kNumQueuedMessages = 1000;
433 for (int i = 0; i < kNumQueuedMessages; ++i) {
434 NSMutableURLRequest* request =
435 requestForCrWebInvokeCommandAndKey(@"wctest.largequeue", valid_key);
436 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
437 SimulateLoadRequest(request);
438 }
439
440 // Verify the queue still works and all messages are delivered.
441 [webController_ setJsMessageQueueThrottled:NO];
442 EXPECT_EQ(kNumQueuedMessages, [observer messageCount]);
443
444 [webController_ removeObserver:observer];
445 }
446
447 TEST_F(CRWUIWebViewWebControllerTest,
448 CrWebInvokeWithAllMessagesFromCurrentWindow) {
449 // Pre-define test window id.
450 [webController_ setWindowId:@"12345678901234567890123456789012"];
451 NSString* valid_key = [webController_ windowId];
452 [[[mockWebView_ stub] andReturn:kTestURLString]
453 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
454
455 // Install an observer to handle custom command messages.
456 base::scoped_nsobject<CountingObserver> observer(
457 [[CountingObserver alloc] init]);
458 [webController_ addObserver:observer];
459
460 // Queue messages.
461 [webController_ setJsMessageQueueThrottled:YES];
462 NSMutableURLRequest* request =
463 requestForCrWebInvokeCommandAndKey(@"wctest.currentwindow1", valid_key);
464 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
465 SimulateLoadRequest(request);
466 request =
467 requestForCrWebInvokeCommandAndKey(@"wctest.currentwindow2", valid_key);
468 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
469 SimulateLoadRequest(request);
470
471 // Verify the behavior.
472 [webController_ setJsMessageQueueThrottled:NO];
473 EXPECT_EQ(2, [observer messageCount]);
474
475 [webController_ removeObserver:observer];
476 }
477
478 TEST_F(CRWUIWebViewWebControllerTest,
479 CrWebInvokeWithMessagesFromDifferentWindows) {
stuartmorgan 2016/01/28 22:24:46 Shouldn't we be rewriting this (and maybe some of
Eugene But (OOO till 7-30) 2016/02/02 22:55:02 How about I file a bug to write those tests? There
480 // Pre-define test window id.
481 [webController_ setWindowId:@"DEADBEEFDEADBEEFDEADBEEFDEADBEEF"];
482 NSString* valid_key = [webController_ windowId];
483 [[[mockWebView_ stub] andReturn:kTestURLString]
484 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
485
486 // Install an observer to handle custom command messages.
487 base::scoped_nsobject<CountingObserver> observer(
488 [[CountingObserver alloc] init]);
489 [webController_ addObserver:observer];
490
491 // Queue messages.
492 [webController_ setJsMessageQueueThrottled:YES];
493 NSMutableURLRequest* request =
494 requestForCrWebInvokeCommandAndKey(@"wctest.diffwindow1", valid_key);
495 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
496 SimulateLoadRequest(request);
497
498 // Second queued message will come with a new window id.
499 [webController_ setWindowId:@"12345678901234567890123456789012"];
500 valid_key = [webController_ windowId];
501 request =
502 requestForCrWebInvokeCommandAndKey(@"wctest.diffwindow2", valid_key);
503 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
504 SimulateLoadRequest(request);
505
506 [webController_ setJsMessageQueueThrottled:NO];
507 EXPECT_EQ(1, [observer messageCount]);
508
509 [webController_ removeObserver:observer];
510 }
511
512 TEST_F(CRWUIWebViewWebControllerTest, CrWebInvokeWithSameOrigin) {
513 // Pre-define test window id.
514 [webController_ setWindowId:@"12345678901234567890123456789012"];
515 NSString* valid_key = [webController_ windowId];
516 [[[mockWebView_ stub] andReturn:@"http://www.google.com/foo"]
517 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
518
519 // Install an observer to handle custom command messages.
520 base::scoped_nsobject<CountingObserver> observer(
521 [[CountingObserver alloc] init]);
522 [webController_ addObserver:observer];
523
524 // Queue message.
525 [webController_ setJsMessageQueueThrottled:YES];
526 NSMutableURLRequest* request =
527 requestForCrWebInvokeCommandAndKey(@"wctest.sameorigin", valid_key);
528 // Make originURL different from currentURL but keep the origin the same.
529 [request
530 setMainDocumentURL:[NSURL URLWithString:@"http://www.google.com/bar"]];
531 SimulateLoadRequest(request);
532 // Verify the behavior.
533 [webController_ setJsMessageQueueThrottled:NO];
534 EXPECT_EQ(1, [observer messageCount]);
535
536 [webController_ removeObserver:observer];
537 }
538
539 TEST_F(CRWUIWebViewWebControllerTest, CrWebInvokeWithDifferentOrigin) {
540 // Pre-define test window id.
541 [webController_ setWindowId:@"12345678901234567890123456789012"];
542 NSString* valid_key = [webController_ windowId];
543 [[[mockWebView_ stub] andReturn:@"http://www.google.com/"]
544 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
545
546 // Install an observer to handle custom command messages.
547 base::scoped_nsobject<CountingObserver> observer(
548 [[CountingObserver alloc] init]);
549 [webController_ addObserver:observer];
550
551 // Queue message.
552 [webController_ setJsMessageQueueThrottled:YES];
553 NSMutableURLRequest* request =
554 requestForCrWebInvokeCommandAndKey(@"wctest.difforigin", valid_key);
555 // Make originURL have a different scheme from currentURL so that the origin
556 // is different.
557 [request setMainDocumentURL:[NSURL URLWithString:@"https://www.google.com/"]];
558 SimulateLoadRequest(request);
559 // Verify the behavior.
560 [webController_ setJsMessageQueueThrottled:NO];
561 EXPECT_EQ(0, [observer messageCount]);
562
563 [webController_ removeObserver:observer];
564 }
565
566 TEST_F(CRWUIWebViewWebControllerTest, EmptyMessageQueue) {
567 [[[mockWebView_ stub] andReturn:@"[]"]
568 stringByEvaluatingJavaScriptFromString:kGetMessageQueueJavaScript];
569
570 NSURLRequest* request =
571 [NSURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
572
573 SimulateLoadRequest(request);
574 };
575
576 TEST_F(CRWUIWebViewWebControllerTest, WindowOpenBlankURL) {
577 NSString* messageQueueJSON = @"[{"
578 "\"command\" : \"window.open\", "
579 "\"target\" : \"newtab\", "
580 "\"url\" : \"\", "
581 "\"referrerPolicy\" : \"default\" }]";
582
583 SEL selector =
584 @selector(webPageOrderedOpen:referrer:windowName:inBackground:);
585 [mockDelegate_ onSelector:selector
586 callBlockExpectation:^(const GURL& url, const web::Referrer& referrer,
587 NSString* windowName, BOOL inBackground) {
588 EXPECT_EQ(url, GURL("about:blank"));
589 EXPECT_EQ(referrer.url, GURL("http://www.google.com?q=foo#bar"));
590 EXPECT_NSEQ(windowName, @"http://www.google.com/#newtab");
591 EXPECT_FALSE(inBackground);
592 }];
593 [[[mockWebView_ stub] andReturn:messageQueueJSON]
594 stringByEvaluatingJavaScriptFromString:kGetMessageQueueJavaScript];
595 [[[mockWebView_ stub] andReturn:kTestURLString]
596 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
597
598 NSMutableURLRequest* request =
599 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
600 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
601 [webController_ touched:YES];
602 SimulateLoadRequest(request);
603
604 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
605 YES);
606 }
607
608 TEST_F(CRWUIWebViewWebControllerTest, WindowOpenWithInteraction) {
609 NSString* messageQueueJSON = @"[{"
610 "\"command\" : \"window.open\", "
611 "\"target\" : \"newtab\", "
612 "\"url\" : \"http://chromium.org\", "
613 "\"referrerPolicy\" : \"default\" }]";
614
615 SEL selector =
616 @selector(webPageOrderedOpen:referrer:windowName:inBackground:);
617 [mockDelegate_ onSelector:selector
618 callBlockExpectation:^(const GURL& url, const web::Referrer& referrer,
619 NSString* windowName, BOOL inBackground) {
620 EXPECT_EQ(url, GURL("http://chromium.org"));
621 EXPECT_EQ(referrer.url, GURL("http://www.google.com?q=foo#bar"));
622 EXPECT_NSEQ(windowName, @"http://www.google.com/#newtab");
623 EXPECT_FALSE(inBackground);
624 }];
625 [[[mockWebView_ stub] andReturn:messageQueueJSON]
626 stringByEvaluatingJavaScriptFromString:kGetMessageQueueJavaScript];
627 [[[mockWebView_ stub] andReturn:kTestURLString]
628 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
629
630 NSMutableURLRequest* request =
631 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
632 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
633 [webController_ touched:YES];
634 SimulateLoadRequest(request);
635
636 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
637 YES);
638 };
639
640 TEST_F(CRWUIWebViewWebControllerTest, WindowOpenWithFinishingInteraction) {
641 NSString* messageQueueJSON = @"[{"
642 "\"command\" : \"window.open\", "
643 "\"target\" : \"newtab\", "
644 "\"url\" : \"http://chromium.org\", "
645 "\"referrerPolicy\" : \"default\" }]";
646
647 SEL selector =
648 @selector(webPageOrderedOpen:referrer:windowName:inBackground:);
649 [mockDelegate_ onSelector:selector
650 callBlockExpectation:^(const GURL& url, const web::Referrer& referrer,
651 NSString* windowName, BOOL inBackground) {
652 EXPECT_EQ(url, GURL("http://chromium.org"));
653 EXPECT_EQ(referrer.url, GURL("http://www.google.com?q=foo#bar"));
654 EXPECT_NSEQ(windowName, @"http://www.google.com/#newtab");
655 EXPECT_FALSE(inBackground);
656 }];
657 [[[mockWebView_ stub] andReturn:kTestURLString]
658 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
659
660 NSMutableURLRequest* request =
661 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
662 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
663 [webController_ touched:YES];
664 [webController_ touched:NO];
665 SimulateLoadRequest(request);
666
667 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
668 YES);
669 };
670
671 TEST_F(CRWUIWebViewWebControllerTest, WindowOpenWithoutInteraction) {
672 NSString* messageQueueJSON = @"[{"
673 "\"command\" : \"window.open\", "
674 "\"target\" : \"newtab\", "
675 "\"url\" : \"http://chromium.org\", "
676 "\"referrerPolicy\" : \"default\" }]";
677 [[[mockWebView_ stub] andReturn:kTestURLString]
678 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
679
680 NSMutableURLRequest* request =
681 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
682 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
683 SimulateLoadRequest(request);
684
685 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
686 NO);
687
688 MockInteractionLoader* delegate = (MockInteractionLoader*)mockDelegate_;
689 EXPECT_EQ("http://www.google.com/?q=foo#bar", [delegate sourceURL].spec());
690 EXPECT_EQ("http://chromium.org/", [delegate popupURL].spec());
691
692 EXPECT_TRUE([delegate blockedPopupInfo]);
693 };
694
695 TEST_F(CRWUIWebViewWebControllerTest, WindowClose) {
696 NSString* messageQueueJSON = @"[{"
697 "\"command\" : \"window.close\", "
698 "\"target\" : \"newtab\" }]";
699
700 [[mockChildWebController_ expect] orderClose];
701
702 NSMutableURLRequest* request =
703 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
704 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
705 [[[mockWebView_ stub] andReturn:kTestURLString]
706 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
707
708 SimulateLoadRequest(request);
709
710 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
711 YES);
712 };
713
714 TEST_F(CRWUIWebViewWebControllerTest, WindowStop) {
715 NSString* messageQueueJSON = @"[{"
716 "\"command\" : \"window.stop\", "
717 "\"target\" : \"newtab\" }]";
718
719 [[mockChildWebController_ expect] stopLoading];
720
721 NSMutableURLRequest* request =
722 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
723 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
724 [[[mockWebView_ stub] andReturn:kTestURLString]
725 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
726
727 SimulateLoadRequest(request);
728
729 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
730 YES);
731 };
732
733 TEST_F(CRWUIWebViewWebControllerTest, DocumentWrite) {
734 NSString* messageQueueJSON = @"[{"
735 "\"command\" : \"window.document.write\", "
736 "\"target\" : \"newtab\", "
737 "\"html\" : \"<html></html>\" }]";
738
739 [[mockChildWebController_ expect] loadHTML:@"<html></html>"];
740 [[[mockWebView_ stub] andReturn:kTestURLString]
741 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
742
743 NSMutableURLRequest* request =
744 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"chrome:"]];
745 [request setMainDocumentURL:[NSURL URLWithString:kTestURLString]];
746 SimulateLoadRequest(request);
747
748 LoadCommands(messageQueueJSON, net::GURLWithNSURL(request.mainDocumentURL),
749 YES);
750 };
751
752 TEST_F(CRWUIWebViewWebControllerTest, UnicodeEncoding) {
753 base::scoped_nsobject<UIWebView> testWebView(
754 [[UIWebView alloc] initWithFrame:CGRectZero]);
755 NSArray* unicodeArray = @[
756 @"ascii",
757 @"unicode £´∑∂∆˚√˜ß∂",
758 @"˜ǯ˜Â‚·´ÎÔ´„ÅÒ",
759 @"adª™£nÎÍlansdn",
760 @"אבדלמצש",
761 @"صسخبئغفىي",
762 @"ऒतॲहड़६ॼ",
763 ];
764 for (NSString* unicodeString in unicodeArray) {
765 NSString* encodeJS =
766 [NSString stringWithFormat:@"encodeURIComponent('%@');", unicodeString];
767 NSString* encodedString =
768 [testWebView stringByEvaluatingJavaScriptFromString:encodeJS];
769 NSString* decodedString = [encodedString stringByRemovingPercentEncoding];
770 EXPECT_NSEQ(unicodeString, decodedString);
771 }
772 };
773
774 // Tests the removal of document.loaded and document.present commands in the
775 // CRWJSInvokeParameterQueue. Only applicable for UIWebView.
776 TEST_F(CRWUIWebViewWebControllerTest, PageLoadCommandRemoval) {
777 [[[mockWebView_ stub] andReturn:@"[]"]
778 stringByEvaluatingJavaScriptFromString:kGetMessageQueueJavaScript];
779 [[[mockWebView_ stub] andReturn:kTestURLString]
780 stringByEvaluatingJavaScriptFromString:kCheckURLJavaScript];
781
782 // Pre-define test window id.
783 [webController_ setWindowId:@"12345678901234567890123456789012"];
784 NSString* valid_key = [webController_ windowId];
785
786 // Add some commands to the queue.
787 [webController_ setJsMessageQueueThrottled:YES];
788 NSURLRequest* request =
789 requestForCrWebInvokeCommandAndKey(@"document.present", valid_key);
790 SimulateLoadRequest(request);
791 request = requestForCrWebInvokeCommandAndKey(@"document.loaded", valid_key);
792 SimulateLoadRequest(request);
793 request =
794 requestForCrWebInvokeCommandAndKey(@"window.history.forward", valid_key);
795 SimulateLoadRequest(request);
796
797 // Check the queue size before and after removing document load commands.
798 NSUInteger expectedBeforeCount = 3;
799 NSUInteger expectedAfterCount = 1;
800 ASSERT_EQ(expectedBeforeCount,
801 [[static_cast<CRWUIWebViewWebController*>(webController_)
802 jsInvokeParameterQueue] queueLength]);
803 [webController_ removeDocumentLoadCommandsFromQueue];
804 ASSERT_EQ(expectedAfterCount,
805 [[static_cast<CRWUIWebViewWebController*>(webController_)
806 jsInvokeParameterQueue] queueLength]);
807 [webController_ setJsMessageQueueThrottled:NO];
808 }; 312 };
809 313
810 #define MAKE_URL(url_string) GURL([url_string UTF8String]) 314 #define MAKE_URL(url_string) GURL([url_string UTF8String])
811 315
812 WEB_TEST_F(CRWUIWebViewWebControllerTest, 316 TEST_F(CRWWebControllerTest, UrlForHistoryNavigation) {
813 CRWWKWebViewWebControllerTest,
814 URLForHistoryNavigation) {
815 NSArray* urlsNoFragments = @[ 317 NSArray* urlsNoFragments = @[
816 @"http://one.com", 318 @"http://one.com",
817 @"http://two.com/", 319 @"http://two.com/",
818 @"http://three.com/bar", 320 @"http://three.com/bar",
819 @"http://four.com/bar/", 321 @"http://four.com/bar/",
820 @"five", 322 @"five",
821 @"/six", 323 @"/six",
822 @"/seven/", 324 @"/seven/",
823 @"" 325 @""
824 ]; 326 ];
825 327
826 NSArray* fragments = @[ @"#", @"#bar" ]; 328 NSArray* fragments = @[ @"#", @"#bar" ];
827 NSMutableArray* urlsWithFragments = [NSMutableArray array]; 329 NSMutableArray* urlsWithFragments = [NSMutableArray array];
828 for (NSString* url in urlsNoFragments) { 330 for (NSString* url in urlsNoFragments) {
829 for (NSString* fragment in fragments) { 331 for (NSString* fragment in fragments) {
830 [urlsWithFragments addObject:[url stringByAppendingString:fragment]]; 332 [urlsWithFragments addObject:[url stringByAppendingString:fragment]];
831 } 333 }
832 } 334 }
833 web::NavigationItemImpl fromItem; 335 web::NavigationItemImpl fromItem;
834 web::NavigationItemImpl toItem; 336 web::NavigationItemImpl toItem;
835 337
836 // No start fragment: the end url is never changed. 338 // No start fragment: the end url is never changed.
837 for (NSString* start in urlsNoFragments) { 339 for (NSString* start in urlsNoFragments) {
838 for (NSString* end in urlsWithFragments) { 340 for (NSString* end in urlsWithFragments) {
839 fromItem.SetURL(MAKE_URL(start)); 341 fromItem.SetURL(MAKE_URL(start));
840 toItem.SetURL(MAKE_URL(end)); 342 toItem.SetURL(MAKE_URL(end));
841 EXPECT_EQ(MAKE_URL(end), 343 EXPECT_EQ(MAKE_URL(end),
842 [this->webController_ URLForHistoryNavigationFromItem:&fromItem 344 [webController_ URLForHistoryNavigationFromItem:&fromItem
843 toItem:&toItem]); 345 toItem:&toItem]);
844 } 346 }
845 } 347 }
846 // Both contain fragments: the end url is never changed. 348 // Both contain fragments: the end url is never changed.
847 for (NSString* start in urlsWithFragments) { 349 for (NSString* start in urlsWithFragments) {
848 for (NSString* end in urlsWithFragments) { 350 for (NSString* end in urlsWithFragments) {
849 fromItem.SetURL(MAKE_URL(start)); 351 fromItem.SetURL(MAKE_URL(start));
850 toItem.SetURL(MAKE_URL(end)); 352 toItem.SetURL(MAKE_URL(end));
851 EXPECT_EQ(MAKE_URL(end), 353 EXPECT_EQ(MAKE_URL(end),
852 [this->webController_ URLForHistoryNavigationFromItem:&fromItem 354 [webController_ URLForHistoryNavigationFromItem:&fromItem
853 toItem:&toItem]); 355 toItem:&toItem]);
854 } 356 }
855 } 357 }
856 for (unsigned start_index = 0; start_index < [urlsWithFragments count]; 358 for (unsigned start_index = 0; start_index < [urlsWithFragments count];
857 ++start_index) { 359 ++start_index) {
858 NSString* start = urlsWithFragments[start_index]; 360 NSString* start = urlsWithFragments[start_index];
859 for (unsigned end_index = 0; end_index < [urlsNoFragments count]; 361 for (unsigned end_index = 0; end_index < [urlsNoFragments count];
860 ++end_index) { 362 ++end_index) {
861 NSString* end = urlsNoFragments[end_index]; 363 NSString* end = urlsNoFragments[end_index];
862 if (start_index / 2 != end_index) { 364 if (start_index / 2 != end_index) {
863 // The URLs have nothing in common, they are left untouched. 365 // The URLs have nothing in common, they are left untouched.
864 fromItem.SetURL(MAKE_URL(start)); 366 fromItem.SetURL(MAKE_URL(start));
865 toItem.SetURL(MAKE_URL(end)); 367 toItem.SetURL(MAKE_URL(end));
866 EXPECT_EQ(MAKE_URL(end), [this->webController_ 368 EXPECT_EQ(MAKE_URL(end),
867 URLForHistoryNavigationFromItem:&fromItem 369 [webController_ URLForHistoryNavigationFromItem:&fromItem
868 toItem:&toItem]); 370 toItem:&toItem]);
869 } else { 371 } else {
870 // Start contains a fragment and matches end: An empty fragment is 372 // Start contains a fragment and matches end: An empty fragment is
871 // added. 373 // added.
872 fromItem.SetURL(MAKE_URL(start)); 374 fromItem.SetURL(MAKE_URL(start));
873 toItem.SetURL(MAKE_URL(end)); 375 toItem.SetURL(MAKE_URL(end));
874 EXPECT_EQ( 376 EXPECT_EQ(MAKE_URL([end stringByAppendingString:@"#"]),
875 MAKE_URL([end stringByAppendingString:@"#"]), 377 [webController_ URLForHistoryNavigationFromItem:&fromItem
876 [this->webController_ URLForHistoryNavigationFromItem:&fromItem
877 toItem:&toItem]); 378 toItem:&toItem]);
878 } 379 }
879 } 380 }
880 } 381 }
881 } 382 }
882 383
883 // Tests that presentSSLError:forSSLStatus:recoverable:callback: is called with 384 // Tests that presentSSLError:forSSLStatus:recoverable:callback: is called with
884 // correct arguments if WKWebView fails to load a page with bad SSL cert. 385 // correct arguments if WKWebView fails to load a page with bad SSL cert.
885 TEST_F(CRWWKWebViewWebControllerTest, SSLCertError) { 386 TEST_F(CRWWebControllerTest, SslCertError) {
886 CR_TEST_REQUIRES_WK_WEB_VIEW();
887
888 ASSERT_FALSE([mockDelegate_ SSLInfo].is_valid()); 387 ASSERT_FALSE([mockDelegate_ SSLInfo].is_valid());
889 388
890 scoped_refptr<net::X509Certificate> cert = 389 scoped_refptr<net::X509Certificate> cert =
891 net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem"); 390 net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
892 391
893 NSArray* chain = @[ static_cast<id>(cert->os_cert_handle()) ]; 392 NSArray* chain = @[ static_cast<id>(cert->os_cert_handle()) ];
894 NSError* error = 393 NSError* error =
895 [NSError errorWithDomain:NSURLErrorDomain 394 [NSError errorWithDomain:NSURLErrorDomain
896 code:NSURLErrorServerCertificateHasUnknownRoot 395 code:NSURLErrorServerCertificateHasUnknownRoot
897 userInfo:@{ 396 userInfo:@{
(...skipping 12 matching lines...) Expand all
910 // Verify correctness of delegate's method arguments. 409 // Verify correctness of delegate's method arguments.
911 EXPECT_TRUE([mockDelegate_ SSLInfo].is_valid()); 410 EXPECT_TRUE([mockDelegate_ SSLInfo].is_valid());
912 EXPECT_EQ(net::CERT_STATUS_INVALID, [mockDelegate_ SSLInfo].cert_status); 411 EXPECT_EQ(net::CERT_STATUS_INVALID, [mockDelegate_ SSLInfo].cert_status);
913 EXPECT_EQ(net::CERT_STATUS_INVALID, [mockDelegate_ SSLStatus].cert_status); 412 EXPECT_EQ(net::CERT_STATUS_INVALID, [mockDelegate_ SSLStatus].cert_status);
914 EXPECT_EQ(web::SECURITY_STYLE_AUTHENTICATION_BROKEN, 413 EXPECT_EQ(web::SECURITY_STYLE_AUTHENTICATION_BROKEN,
915 [mockDelegate_ SSLStatus].security_style); 414 [mockDelegate_ SSLStatus].security_style);
916 EXPECT_FALSE([mockDelegate_ recoverable]); 415 EXPECT_FALSE([mockDelegate_ recoverable]);
917 EXPECT_TRUE([mockDelegate_ shouldContinueCallback]); 416 EXPECT_TRUE([mockDelegate_ shouldContinueCallback]);
918 } 417 }
919 418
920 // None of the |CRWUIWebViewWebControllerTest| setup is needed;
921 typedef web::WebTestWithUIWebViewWebController
922 CRWUIWebControllerPageDialogsOpenPolicyTest;
923
924 // None of the |CRWWKWebViewWebControllerTest| setup is needed; 419 // None of the |CRWWKWebViewWebControllerTest| setup is needed;
925 typedef web::WebTestWithWKWebViewWebController 420 typedef web::WebTestWithWKWebViewWebController
926 CRWWKWebControllerPageDialogsOpenPolicyTest; 421 CRWWebControllerPageDialogsOpenPolicyTest;
927 422
928 WEB_TEST_F(CRWUIWebControllerPageDialogsOpenPolicyTest, 423 TEST_F(CRWWebControllerPageDialogsOpenPolicyTest, SuppressPolicy) {
929 CRWWKWebControllerPageDialogsOpenPolicyTest, 424 LoadHtml(@"<html><body></body></html>");
930 SuppressPolicy) {
931 this->LoadHtml(@"<html><body></body></html>");
932 id delegate = [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)]; 425 id delegate = [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)];
933 [[delegate expect] webControllerDidSuppressDialog:this->webController_]; 426 [[delegate expect] webControllerDidSuppressDialog:webController_];
934 427
935 [this->webController_ setDelegate:delegate]; 428 [webController_ setDelegate:delegate];
936 [this->webController_ setPageDialogOpenPolicy:web::DIALOG_POLICY_SUPPRESS]; 429 [webController_ setPageDialogOpenPolicy:web::DIALOG_POLICY_SUPPRESS];
937 this->RunJavaScript(@"alert('')"); 430 RunJavaScript(@"alert('')");
938 431
939 this->WaitForBackgroundTasks(); 432 WaitForBackgroundTasks();
940 EXPECT_OCMOCK_VERIFY(delegate); 433 EXPECT_OCMOCK_VERIFY(delegate);
941 [this->webController_ setDelegate:nil]; 434 [webController_ setDelegate:nil];
942 }; 435 };
943 436
944 // A separate test class, as none of the |CRWUIWebViewWebControllerTest| setup 437 // A separate test class, as none of the |CRWWebControllerTest| setup is
945 // is needed; 438 // needed.
946 class CRWUIWebControllerPageScrollStateTest 439 class CRWWebControllerPageScrollStateTest
947 : public web::WebTestWithUIWebViewWebController {
948 protected:
949 // Returns a web::PageDisplayState that will scroll a UIWebView to
950 // |scrollOffset| and zoom the content by |relativeZoomScale|.
951 inline web::PageDisplayState CreateTestPageDisplayState(
952 CGPoint scroll_offset,
953 CGFloat relative_zoom_scale,
954 CGFloat original_minimum_zoom_scale,
955 CGFloat original_maximum_zoom_scale,
956 CGFloat original_zoom_scale) const {
957 return web::PageDisplayState(
958 scroll_offset.x, scroll_offset.y,
959 original_minimum_zoom_scale / relative_zoom_scale,
960 original_maximum_zoom_scale / relative_zoom_scale, 1.0);
961 }
962 };
963
964 // A separate test class, as none of the |CRWUIWebViewWebControllerTest| setup
965 // is needed;
966 class CRWWKWebControllerPageScrollStateTest
967 : public web::WebTestWithWKWebViewWebController { 440 : public web::WebTestWithWKWebViewWebController {
968 protected: 441 protected:
969 // Returns a web::PageDisplayState that will scroll a WKWebView to 442 // Returns a web::PageDisplayState that will scroll a WKWebView to
970 // |scrollOffset| and zoom the content by |relativeZoomScale|. 443 // |scrollOffset| and zoom the content by |relativeZoomScale|.
971 inline web::PageDisplayState CreateTestPageDisplayState( 444 inline web::PageDisplayState CreateTestPageDisplayState(
972 CGPoint scroll_offset, 445 CGPoint scroll_offset,
973 CGFloat relative_zoom_scale, 446 CGFloat relative_zoom_scale,
974 CGFloat original_minimum_zoom_scale, 447 CGFloat original_minimum_zoom_scale,
975 CGFloat original_maximum_zoom_scale, 448 CGFloat original_maximum_zoom_scale,
976 CGFloat original_zoom_scale) const { 449 CGFloat original_zoom_scale) const {
977 return web::PageDisplayState( 450 return web::PageDisplayState(
978 scroll_offset.x, scroll_offset.y, original_minimum_zoom_scale, 451 scroll_offset.x, scroll_offset.y, original_minimum_zoom_scale,
979 original_maximum_zoom_scale, 452 original_maximum_zoom_scale,
980 relative_zoom_scale * original_minimum_zoom_scale); 453 relative_zoom_scale * original_minimum_zoom_scale);
981 } 454 }
982 }; 455 };
983 456
984 // TODO(iOS): Flaky on the bots. crbug/493427 457 // TODO(iOS): Flaky on the bots. crbug/493427
985 WEB_TEST_F(CRWUIWebControllerPageScrollStateTest, 458 TEST_F(CRWWebControllerPageScrollStateTest,
986 CRWWKWebControllerPageScrollStateTest, 459 FLAKY_SetPageDisplayStateWithUserScalableDisabled) {
987 FLAKY_SetPageDisplayStateWithUserScalableDisabled) {
988 #if !TARGET_IPHONE_SIMULATOR 460 #if !TARGET_IPHONE_SIMULATOR
989 // This test fails flakily on device with WKWebView, so skip it there. 461 // TODO(crbug.com/453530): fails flakily on device, so skip it there.
990 // crbug.com/453530 462 return;
991 if ([this->webController_ webViewType] == web::WK_WEB_VIEW_TYPE)
992 return;
993 #endif 463 #endif
994 web::PageZoomState zoom_state(1.0, 5.0, 1.0); 464 web::PageZoomState zoom_state(1.0, 5.0, 1.0);
995 this->LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_DISABLED)); 465 LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_DISABLED));
996 CRWWebController* web_controller = this->webController_.get(); 466 CRWWebController* web_controller = webController_.get();
997 WaitForZoomRendering(web_controller, zoom_state); 467 WaitForZoomRendering(web_controller, zoom_state);
998 web::PageZoomState original_zoom_state = 468 web::PageZoomState original_zoom_state =
999 web_controller.pageDisplayState.zoom_state(); 469 web_controller.pageDisplayState.zoom_state();
1000 470
1001 web::NavigationManager* nagivation_manager = 471 web::NavigationManager* nagivation_manager =
1002 web_controller.webState->GetNavigationManager(); 472 web_controller.webState->GetNavigationManager();
1003 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState( 473 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState(
1004 this->CreateTestPageDisplayState(CGPointMake(1.0, 1.0), // scroll offset 474 CreateTestPageDisplayState(CGPointMake(1.0, 1.0), // scroll offset
1005 3.0, // relative zoom scale 475 3.0, // relative zoom scale
1006 1.0, // original minimum zoom scale 476 1.0, // original minimum zoom scale
1007 5.0, // original maximum zoom scale 477 5.0, // original maximum zoom scale
1008 1.0)); // original zoom scale 478 1.0)); // original zoom scale
1009 [web_controller restoreStateFromHistory]; 479 [web_controller restoreStateFromHistory];
1010 480
1011 // |-restoreStateFromHistory| is async; wait for its completion. 481 // |-restoreStateFromHistory| is async; wait for its completion.
1012 base::test::ios::WaitUntilCondition(^bool() { 482 base::test::ios::WaitUntilCondition(^bool() {
1013 return web_controller.pageDisplayState.scroll_state().offset_x() == 1.0; 483 return web_controller.pageDisplayState.scroll_state().offset_x() == 1.0;
1014 }); 484 });
1015 485
1016 ASSERT_EQ(original_zoom_state, web_controller.pageDisplayState.zoom_state()); 486 ASSERT_EQ(original_zoom_state, web_controller.pageDisplayState.zoom_state());
1017 }; 487 };
1018 488
1019 // TODO(iOS): Flaky on the bots. crbug/493427 489 // TODO(iOS): Flaky on the bots. crbug/493427
1020 WEB_TEST_F(CRWUIWebControllerPageScrollStateTest, 490 TEST_F(CRWWebControllerPageScrollStateTest,
1021 CRWWKWebControllerPageScrollStateTest, 491 FLAKY_SetPageDisplayStateWithUserScalableEnabled) {
1022 FLAKY_SetPageDisplayStateWithUserScalableEnabled) {
1023 web::PageZoomState zoom_state(1.0, 10.0, 1.0); 492 web::PageZoomState zoom_state(1.0, 10.0, 1.0);
1024 this->LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_ENABLED)); 493 LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_ENABLED));
1025 CRWWebController* web_controller = this->webController_.get(); 494 CRWWebController* web_controller = webController_.get();
1026 WaitForZoomRendering(web_controller, zoom_state); 495 WaitForZoomRendering(web_controller, zoom_state);
1027 496
1028 web::NavigationManager* nagivation_manager = 497 web::NavigationManager* nagivation_manager =
1029 web_controller.webState->GetNavigationManager(); 498 web_controller.webState->GetNavigationManager();
1030 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState( 499 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState(
1031 this->CreateTestPageDisplayState(CGPointMake(1.0, 1.0), // scroll offset 500 CreateTestPageDisplayState(CGPointMake(1.0, 1.0), // scroll offset
1032 3.0, // relative zoom scale 501 3.0, // relative zoom scale
1033 1.0, // original minimum zoom scale 502 1.0, // original minimum zoom scale
1034 10.0, // original maximum zoom scale 503 10.0, // original maximum zoom scale
1035 1.0)); // original zoom scale 504 1.0)); // original zoom scale
1036 [web_controller restoreStateFromHistory]; 505 [web_controller restoreStateFromHistory];
1037 506
1038 // |-restoreStateFromHistory| is async; wait for its completion. 507 // |-restoreStateFromHistory| is async; wait for its completion.
1039 base::test::ios::WaitUntilCondition(^bool() { 508 base::test::ios::WaitUntilCondition(^bool() {
1040 return web_controller.pageDisplayState.scroll_state().offset_x() == 1.0; 509 return web_controller.pageDisplayState.scroll_state().offset_x() == 1.0;
1041 }); 510 });
1042 511
1043 web::PageZoomState final_zoom_state = 512 web::PageZoomState final_zoom_state =
1044 web_controller.pageDisplayState.zoom_state(); 513 web_controller.pageDisplayState.zoom_state();
1045 EXPECT_FLOAT_EQ(3, final_zoom_state.zoom_scale() / 514 EXPECT_FLOAT_EQ(3, final_zoom_state.zoom_scale() /
1046 final_zoom_state.minimum_zoom_scale()); 515 final_zoom_state.minimum_zoom_scale());
1047 }; 516 };
1048 517
1049 // TODO(iOS): Flaky on the bots. crbug/493427 518 // TODO(iOS): Flaky on the bots. crbug/493427
1050 WEB_TEST_F(CRWUIWebControllerPageScrollStateTest, 519 TEST_F(CRWWebControllerPageScrollStateTest, FLAKY_AtTop) {
1051 CRWWKWebControllerPageScrollStateTest, 520 // This test fails on iPhone 6/6+; skip until it's fixed. crbug.com/453105
1052 FLAKY_AtTop) { 521 if (IsIPhone6Or6Plus())
1053 // This test fails on iPhone 6/6+ with WKWebView; skip until it's fixed.
1054 // crbug.com/453105
1055 if ([this->webController_ webViewType] == web::WK_WEB_VIEW_TYPE &&
1056 IsIPhone6Or6Plus())
1057 return; 522 return;
1058 523
1059 web::PageZoomState zoom_state = web::PageZoomState(1.0, 5.0, 1.0); 524 web::PageZoomState zoom_state = web::PageZoomState(1.0, 5.0, 1.0);
1060 this->LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_ENABLED)); 525 LoadHtml(GetHTMLForZoomState(zoom_state, PAGE_SCALABILITY_ENABLED));
1061 CRWWebController* web_controller = this->webController_.get(); 526 CRWWebController* web_controller = webController_.get();
1062 WaitForZoomRendering(web_controller, zoom_state); 527 WaitForZoomRendering(web_controller, zoom_state);
1063 ASSERT_TRUE(web_controller.atTop); 528 ASSERT_TRUE(web_controller.atTop);
1064 529
1065 web::NavigationManager* nagivation_manager = 530 web::NavigationManager* nagivation_manager =
1066 web_controller.webState->GetNavigationManager(); 531 web_controller.webState->GetNavigationManager();
1067 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState( 532 nagivation_manager->GetLastCommittedItem()->SetPageDisplayState(
1068 this->CreateTestPageDisplayState(CGPointMake(0.0, 30.0), // scroll offset 533 CreateTestPageDisplayState(CGPointMake(0.0, 30.0), // scroll offset
1069 5.0, // relative zoom scale 534 5.0, // relative zoom scale
1070 1.0, // original minimum zoom scale 535 1.0, // original minimum zoom scale
1071 5.0, // original maximum zoom scale 536 5.0, // original maximum zoom scale
1072 1.0)); // original zoom scale 537 1.0)); // original zoom scale
1073 [web_controller restoreStateFromHistory]; 538 [web_controller restoreStateFromHistory];
1074 539
1075 // |-restoreStateFromHistory| is async; wait for its completion. 540 // |-restoreStateFromHistory| is async; wait for its completion.
1076 base::test::ios::WaitUntilCondition(^bool() { 541 base::test::ios::WaitUntilCondition(^bool() {
1077 return web_controller.pageDisplayState.scroll_state().offset_y() == 30.0; 542 return web_controller.pageDisplayState.scroll_state().offset_y() == 30.0;
1078 }); 543 });
1079 544
1080 ASSERT_FALSE(web_controller.atTop); 545 ASSERT_FALSE(web_controller.atTop);
1081 }; 546 };
1082 547
1083 // Tests that evaluateJavaScript:completionHandler: properly forwards the
1084 // call to UIWebView.
1085 TEST_F(CRWUIWebViewWebControllerTest, JavaScriptEvaluation) {
1086 NSString* kTestScript = @"script";
1087 NSString* kTestResult = @"result";
1088 NSString* scriptWithIDCheck =
1089 [webController_ scriptByAddingWindowIDCheckForScript:kTestScript];
1090 [[[mockWebView_ stub] andReturn:kTestResult]
1091 stringByEvaluatingJavaScriptFromString:scriptWithIDCheck];
1092
1093 __block BOOL completionBlockWasCalled = NO;
1094 [webController_ evaluateJavaScript:kTestScript
1095 stringResultHandler:^(NSString* string, NSError* error) {
1096 completionBlockWasCalled = YES;
1097 EXPECT_NSEQ(kTestResult, string);
1098 EXPECT_EQ(nil, error);
1099 }];
1100
1101 // Wait until JavaScript is evaluated.
1102 base::test::ios::WaitUntilCondition(^bool() {
1103 return completionBlockWasCalled;
1104 });
1105 EXPECT_TRUE(completionBlockWasCalled);
1106 };
1107
1108 TEST_F(CRWUIWebViewWebControllerTest, POSTRequestCache) {
1109 GURL url("http://www.google.fr/");
1110 NSString* mixedCaseCookieHeaderName = @"cOoKiE";
1111 NSString* otherHeaderName = @"Myheader";
1112 NSString* otherHeaderValue = @"A";
1113 NSString* otherHeaderIncorrectValue = @"C";
1114
1115 scoped_ptr<web::NavigationItemImpl> item(new web::NavigationItemImpl());
1116 item->SetURL(url);
1117 item->SetTransitionType(ui::PAGE_TRANSITION_FORM_SUBMIT);
1118 item->set_is_renderer_initiated(true);
1119 base::scoped_nsobject<CRWSessionEntry> currentEntry(
1120 [[CRWSessionEntry alloc] initWithNavigationItem:std::move(item)]);
1121 base::scoped_nsobject<NSMutableURLRequest> request(
1122 [[NSMutableURLRequest alloc] initWithURL:net::NSURLWithGURL(url)]);
1123 [request setHTTPMethod:@"POST"];
1124 [request setValue:otherHeaderValue forHTTPHeaderField:otherHeaderName];
1125 [request setValue:@"B" forHTTPHeaderField:mixedCaseCookieHeaderName];
1126 // No data is cached initially.
1127 EXPECT_EQ(nil, [currentEntry navigationItemImpl]->GetPostData());
1128 EXPECT_EQ(nil, [currentEntry navigationItem]->GetHttpRequestHeaders());
1129 // Streams are not cached.
1130 [request setHTTPBodyStream:[NSInputStream inputStreamWithData:[NSData data]]];
1131 [webController_ cachePOSTDataForRequest:request inSessionEntry:currentEntry];
1132 EXPECT_EQ(nil, [currentEntry navigationItemImpl]->GetPostData());
1133 EXPECT_EQ(nil, [currentEntry navigationItem]->GetHttpRequestHeaders());
1134 [request setHTTPBodyStream:nil];
1135 // POST Data is cached. Cookie headers are stripped, no matter their case.
1136 base::scoped_nsobject<NSData> body([[NSData alloc] init]);
1137 [request setHTTPBody:body];
1138 [webController_ cachePOSTDataForRequest:request inSessionEntry:currentEntry];
1139 EXPECT_EQ(body.get(), [currentEntry navigationItemImpl]->GetPostData());
1140 EXPECT_NSEQ([currentEntry navigationItem]->GetHttpRequestHeaders(),
1141 @{otherHeaderName : otherHeaderValue});
1142 // A new request will not change the cached version.
1143 base::scoped_nsobject<NSData> body2([[NSData alloc] init]);
1144 [request setValue:otherHeaderIncorrectValue
1145 forHTTPHeaderField:otherHeaderName];
1146 [request setHTTPBody:body2];
1147 EXPECT_EQ(body.get(), [currentEntry navigationItemImpl]->GetPostData());
1148 EXPECT_NSEQ([currentEntry navigationItem]->GetHttpRequestHeaders(),
1149 @{otherHeaderName : otherHeaderValue});
1150 }
1151
1152 class WebControllerJSEvaluationTest : public CRWUIWebViewWebControllerTest {
1153 protected:
1154 void SetUp() override {
1155 WebControllerTest::SetUp();
1156
1157 NSString* kTestResult = @"result";
1158 completionBlockWasCalled_ = NO;
1159 NSString* scriptWithIDCheck =
1160 [webController_ scriptByAddingWindowIDCheckForScript:GetTestScript()];
1161 [[[mockWebView_ stub] andReturn:kTestResult]
1162 stringByEvaluatingJavaScriptFromString:scriptWithIDCheck];
1163 completionHandler_.reset([^(NSString* string, NSError* error) {
1164 completionBlockWasCalled_ = YES;
1165 EXPECT_NSEQ(kTestResult, string);
1166 EXPECT_EQ(nil, error);
1167 } copy]);
1168 }
1169 NSString* GetTestScript() const { return @"script"; }
1170 base::scoped_nsprotocol<web::JavaScriptCompletion> completionHandler_;
1171 BOOL completionBlockWasCalled_;
1172 };
1173
1174 // Tests that -evaluateJavaScript:stringResultHandler: properly forwards
1175 // the call to the UIWebView.
1176 TEST_F(WebControllerJSEvaluationTest, JavaScriptEvaluation) {
1177 [webController_ evaluateJavaScript:GetTestScript()
1178 stringResultHandler:completionHandler_];
1179 // Wait until JavaScript is evaluated.
1180 base::test::ios::WaitUntilCondition(^bool() {
1181 return this->completionBlockWasCalled_;
1182 });
1183 EXPECT_TRUE(completionBlockWasCalled_);
1184 }
1185
1186 // Tests that -evaluateUserJavaScript:stringResultHandler: properly
1187 // forwards the call to the UIWebView.
1188 TEST_F(WebControllerJSEvaluationTest, UserJavaScriptEvaluation) {
1189 __block BOOL method_called = NO;
1190 [[[mockWebView_ stub] andDo:^(NSInvocation*) {
1191 method_called = YES;
1192 }]
1193 performSelectorOnMainThread:@selector(
1194 stringByEvaluatingJavaScriptFromString:)
1195 withObject:GetTestScript()
1196 waitUntilDone:NO];
1197 [webController_ evaluateUserJavaScript:GetTestScript()];
1198 EXPECT_TRUE(method_called);
1199 }
1200
1201 // Tests that -evaluateJavaScript:stringResultHandler: does not crash
1202 // on a nil completionHandler.
1203 TEST_F(WebControllerJSEvaluationTest, JavaScriptEvaluationNilHandler) {
1204 [webController_ evaluateJavaScript:GetTestScript() stringResultHandler:nil];
1205 }
1206
1207 // Real UIWebView is required for JSEvaluationTest.
1208 typedef web::WebTestWithUIWebViewWebController
1209 CRWUIWebControllerJSEvaluationTest;
1210
1211 // Real WKWebView is required for JSEvaluationTest. 548 // Real WKWebView is required for JSEvaluationTest.
1212 typedef web::WebTestWithWKWebViewWebController 549 typedef web::WebTestWithWKWebViewWebController CRWWebControllerJSEvaluationTest;
1213 CRWWKWebControllerJSEvaluationTest;
1214 550
1215 // Tests that a script correctly evaluates to string. 551 // Tests that a script correctly evaluates to string.
1216 WEB_TEST_F(CRWUIWebControllerJSEvaluationTest, 552 TEST_F(CRWWebControllerJSEvaluationTest, Evaluation) {
1217 CRWWKWebControllerJSEvaluationTest, 553 LoadHtml(@"<p></p>");
1218 Evaluation) { 554 EXPECT_NSEQ(@"true", EvaluateJavaScriptAsString(@"true"));
1219 this->LoadHtml(@"<p></p>"); 555 EXPECT_NSEQ(@"false", EvaluateJavaScriptAsString(@"false"));
1220 EXPECT_NSEQ(@"true", this->EvaluateJavaScriptAsString(@"true"));
1221 EXPECT_NSEQ(@"false", this->EvaluateJavaScriptAsString(@"false"));
1222 } 556 }
1223 557
1224 // Tests that a script is not evaluated on windowID mismatch. 558 // Tests that a script is not evaluated on windowID mismatch.
1225 WEB_TEST_F(CRWUIWebControllerJSEvaluationTest, 559 TEST_F(CRWWebControllerJSEvaluationTest, WindowIdMissmatch) {
1226 CRWWKWebControllerJSEvaluationTest, 560 LoadHtml(@"<p></p>");
1227 WindowIDMissmatch) {
1228 this->LoadHtml(@"<p></p>");
1229 // Script is evaluated since windowID is matched. 561 // Script is evaluated since windowID is matched.
1230 this->EvaluateJavaScriptAsString(@"window.test1 = '1';"); 562 EvaluateJavaScriptAsString(@"window.test1 = '1';");
1231 EXPECT_NSEQ(@"1", this->EvaluateJavaScriptAsString(@"window.test1")); 563 EXPECT_NSEQ(@"1", EvaluateJavaScriptAsString(@"window.test1"));
1232 564
1233 // Change windowID. 565 // Change windowID.
1234 this->EvaluateJavaScriptAsString(@"__gCrWeb['windowId'] = '';"); 566 EvaluateJavaScriptAsString(@"__gCrWeb['windowId'] = '';");
1235 567
1236 // Script is not evaluated because of windowID mismatch. 568 // Script is not evaluated because of windowID mismatch.
1237 this->EvaluateJavaScriptAsString(@"window.test2 = '2';"); 569 EvaluateJavaScriptAsString(@"window.test2 = '2';");
1238 EXPECT_NSEQ(@"", this->EvaluateJavaScriptAsString(@"window.test2")); 570 EXPECT_NSEQ(@"", EvaluateJavaScriptAsString(@"window.test2"));
1239 } 571 }
1240 572
1241 // A separate test class is used for testing the keyboard dismissal, as none of 573 TEST_F(CRWWebControllerTest, WebUrlWithTrustLevel) {
1242 // the setup in |CRWUIWebViewWebControllerTest| is needed; keyboard appearance
1243 // is tracked by the KeyboardAppearanceListener.
1244 class WebControllerKeyboardTest
1245 : public web::WebTestWithUIWebViewWebController {
1246 protected:
1247 void SetUp() override {
1248 web::WebTestWithUIWebViewWebController::SetUp();
1249 // Close any outstanding alert boxes.
1250 ui::test::uiview_utils::CancelAlerts();
1251
1252 // Sets up the listener for keyboard activation/deactivation notifications.
1253 keyboardListener_.reset([[KeyboardAppearanceListener alloc] init]);
1254 }
1255
1256 base::scoped_nsobject<KeyboardAppearanceListener> keyboardListener_;
1257 };
1258
1259 TEST_F(WebControllerKeyboardTest, DismissKeyboard) {
1260 LoadHtml(@"<html><head></head><body><form><input id=\"textField\" /></form>"
1261 @"</body></html>");
1262
1263 // Get the webview.
1264 UIWebView* webView = static_cast<UIWebView*>(
1265 [webController_ containerView].webViewContentView.webView);
1266 EXPECT_TRUE(webView);
1267
1268 // Due to a bug in iOS ( http://www.openradar.me/22364739 ) the keyWindow
1269 // needs to be manually restored, up to iOS 9.2.
1270 UIWindow* keyWindow = [UIApplication sharedApplication].keyWindow;
1271 base::ScopedClosureRunner runner(base::BindBlock(^{
1272 if (!base::ios::IsRunningOnOrLater(9, 2, 0)) {
1273 [keyWindow makeKeyAndVisible];
1274 }
1275 }));
1276
1277 // Create the window and add the webview.
1278 base::scoped_nsobject<UIWindow> window(
1279 [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]);
1280 [window makeKeyAndVisible];
1281 [window addSubview:webView];
1282
1283 // Set the flag to allow focus() in code in UIWebView.
1284 EXPECT_TRUE([webView keyboardDisplayRequiresUserAction]);
1285 [webView setKeyboardDisplayRequiresUserAction:NO];
1286 EXPECT_FALSE([webView keyboardDisplayRequiresUserAction]);
1287
1288 // Set the focus on the textField.
1289 EXPECT_FALSE([keyboardListener_ isKeyboardVisible]);
1290 [webView stringByEvaluatingJavaScriptFromString:
1291 @"document.getElementById(\"textField\").focus();"];
1292 base::test::ios::WaitUntilCondition(^bool() {
1293 return [keyboardListener_ isKeyboardVisible];
1294 });
1295 EXPECT_TRUE([keyboardListener_ isKeyboardVisible]);
1296
1297 // Method to test.
1298 [webController_ dismissKeyboard];
1299
1300 base::test::ios::WaitUntilCondition(^bool() {
1301 return ![keyboardListener_ isKeyboardVisible];
1302 });
1303 EXPECT_FALSE([keyboardListener_ isKeyboardVisible]);
1304 }
1305
1306 TEST_F(CRWWKWebViewWebControllerTest, WebURLWithTrustLevel) {
1307 CR_TEST_REQUIRES_WK_WEB_VIEW();
1308
1309 [[[mockWebView_ stub] andReturn:[NSURL URLWithString:kTestURLString]] URL]; 574 [[[mockWebView_ stub] andReturn:[NSURL URLWithString:kTestURLString]] URL];
1310 [[[mockWebView_ stub] andReturnBool:NO] hasOnlySecureContent]; 575 [[[mockWebView_ stub] andReturnBool:NO] hasOnlySecureContent];
1311 576
1312 // Stub out the injection process. 577 // Stub out the injection process.
1313 [[mockWebView_ stub] evaluateJavaScript:OCMOCK_ANY 578 [[mockWebView_ stub] evaluateJavaScript:OCMOCK_ANY
1314 completionHandler:OCMOCK_ANY]; 579 completionHandler:OCMOCK_ANY];
1315 580
1316 // Simulate registering load request to avoid failing page load simulation. 581 // Simulate registering load request to avoid failing page load simulation.
1317 [webController_ simulateLoadRequestWithURL:GURL([kTestURLString UTF8String])]; 582 [webController_ simulateLoadRequestWithURL:GURL([kTestURLString UTF8String])];
1318 // Simulate a page load to trigger a URL update. 583 // Simulate a page load to trigger a URL update.
1319 [static_cast<id<WKNavigationDelegate>>(webController_.get()) 584 [static_cast<id<WKNavigationDelegate>>(webController_.get())
1320 webView:mockWebView_ 585 webView:mockWebView_
1321 didCommitNavigation:nil]; 586 didCommitNavigation:nil];
1322 587
1323 web::URLVerificationTrustLevel trust_level = web::kNone; 588 web::URLVerificationTrustLevel trust_level = web::kNone;
1324 GURL gurl = [webController_ currentURLWithTrustLevel:&trust_level]; 589 GURL gurl = [webController_ currentURLWithTrustLevel:&trust_level];
1325 590
1326 EXPECT_EQ(gurl, GURL(base::SysNSStringToUTF8(kTestURLString))); 591 EXPECT_EQ(gurl, GURL(base::SysNSStringToUTF8(kTestURLString)));
1327 EXPECT_EQ(web::kAbsolute, trust_level); 592 EXPECT_EQ(web::kAbsolute, trust_level);
1328 } 593 }
1329 594
1330 // A separate test class, as none of the |CRWUIWebViewWebControllerTest| setup 595 // A separate test class, as none of the |CRWUIWebViewWebControllerTest| setup
1331 // is needed; 596 // is needed;
1332 typedef web::WebTestWithUIWebViewWebController CRWUIWebControllerObserversTest; 597 typedef web::WebTestWithWKWebViewWebController CRWWebControllerObserversTest;
1333 typedef web::WebTestWithWKWebViewWebController CRWWKWebControllerObserversTest;
1334 598
1335 // Tests that CRWWebControllerObservers are called. 599 // Tests that CRWWebControllerObservers are called.
1336 WEB_TEST_F(CRWUIWebControllerObserversTest, 600 TEST_F(CRWWebControllerObserversTest, Observers) {
1337 CRWWKWebControllerObserversTest,
1338 Observers) {
1339 base::scoped_nsobject<CountingObserver> observer( 601 base::scoped_nsobject<CountingObserver> observer(
1340 [[CountingObserver alloc] init]); 602 [[CountingObserver alloc] init]);
1341 CRWWebController* web_controller = this->webController_; 603 CRWWebController* web_controller = webController_;
1342 EXPECT_EQ(0u, [web_controller observerCount]); 604 EXPECT_EQ(0u, [web_controller observerCount]);
1343 [web_controller addObserver:observer]; 605 [web_controller addObserver:observer];
1344 EXPECT_EQ(1u, [web_controller observerCount]); 606 EXPECT_EQ(1u, [web_controller observerCount]);
1345 607
1346 EXPECT_EQ(0, [observer pageLoadedCount]); 608 EXPECT_EQ(0, [observer pageLoadedCount]);
1347 [web_controller webStateImpl]->OnPageLoaded(GURL("http://test"), false); 609 [web_controller webStateImpl]->OnPageLoaded(GURL("http://test"), false);
1348 EXPECT_EQ(0, [observer pageLoadedCount]); 610 EXPECT_EQ(0, [observer pageLoadedCount]);
1349 [web_controller webStateImpl]->OnPageLoaded(GURL("http://test"), true); 611 [web_controller webStateImpl]->OnPageLoaded(GURL("http://test"), true);
1350 EXPECT_EQ(1, [observer pageLoadedCount]); 612 EXPECT_EQ(1, [observer pageLoadedCount]);
1351 613
1352 EXPECT_EQ(0, [observer messageCount]); 614 EXPECT_EQ(0, [observer messageCount]);
1353 // Non-matching prefix. 615 // Non-matching prefix.
1354 EXPECT_FALSE([web_controller webStateImpl]->OnScriptCommandReceived( 616 EXPECT_FALSE([web_controller webStateImpl]->OnScriptCommandReceived(
1355 "a", base::DictionaryValue(), GURL("http://test"), true)); 617 "a", base::DictionaryValue(), GURL("http://test"), true));
1356 EXPECT_EQ(0, [observer messageCount]); 618 EXPECT_EQ(0, [observer messageCount]);
1357 // Matching prefix. 619 // Matching prefix.
1358 EXPECT_TRUE([web_controller webStateImpl]->OnScriptCommandReceived( 620 EXPECT_TRUE([web_controller webStateImpl]->OnScriptCommandReceived(
1359 base::SysNSStringToUTF8([observer commandPrefix]) + ".foo", 621 base::SysNSStringToUTF8([observer commandPrefix]) + ".foo",
1360 base::DictionaryValue(), GURL("http://test"), true)); 622 base::DictionaryValue(), GURL("http://test"), true));
1361 EXPECT_EQ(1, [observer messageCount]); 623 EXPECT_EQ(1, [observer messageCount]);
1362 624
1363 [web_controller removeObserver:observer]; 625 [web_controller removeObserver:observer];
1364 EXPECT_EQ(0u, [web_controller observerCount]); 626 EXPECT_EQ(0u, [web_controller observerCount]);
1365 }; 627 };
1366 628
1367 // Test fixture for window.open tests. 629 // Test fixture for window.open tests.
1368 class CRWWKWebControllerWindowOpenTest 630 class CRWWebControllerWindowOpenTest
1369 : public web::WebTestWithWKWebViewWebController { 631 : public web::WebTestWithWKWebViewWebController {
1370 protected: 632 protected:
1371 void SetUp() override { 633 void SetUp() override {
1372 CR_TEST_REQUIRES_WK_WEB_VIEW();
1373 web::WebTestWithWKWebViewWebController::SetUp(); 634 web::WebTestWithWKWebViewWebController::SetUp();
1374 635
1375 // Configure web delegate. 636 // Configure web delegate.
1376 delegate_.reset([[MockInteractionLoader alloc] 637 delegate_.reset([[MockInteractionLoader alloc]
1377 initWithRepresentedObject: 638 initWithRepresentedObject:
1378 [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)]]); 639 [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)]]);
1379 ASSERT_TRUE([delegate_ blockPopups]); 640 ASSERT_TRUE([delegate_ blockPopups]);
1380 [webController_ setDelegate:delegate_]; 641 [webController_ setDelegate:delegate_];
1381 642
1382 // Configure child web controller. 643 // Configure child web controller.
(...skipping 28 matching lines...) Expand all
1411 WaitForBackgroundTasks(); 672 WaitForBackgroundTasks();
1412 return windowJSObject; 673 return windowJSObject;
1413 } 674 }
1414 // A CRWWebDelegate mock used for testing. 675 // A CRWWebDelegate mock used for testing.
1415 base::scoped_nsobject<id> delegate_; 676 base::scoped_nsobject<id> delegate_;
1416 // A child CRWWebController used for testing. 677 // A child CRWWebController used for testing.
1417 base::scoped_nsobject<CRWWebController> child_; 678 base::scoped_nsobject<CRWWebController> child_;
1418 }; 679 };
1419 680
1420 // Tests that absence of web delegate is handled gracefully. 681 // Tests that absence of web delegate is handled gracefully.
1421 TEST_F(CRWWKWebControllerWindowOpenTest, NoDelegate) { 682 TEST_F(CRWWebControllerWindowOpenTest, NoDelegate) {
1422 CR_TEST_REQUIRES_WK_WEB_VIEW();
1423
1424 [webController_ setDelegate:nil]; 683 [webController_ setDelegate:nil];
1425 684
1426 EXPECT_NSEQ(@"", OpenWindowByDOM()); 685 EXPECT_NSEQ(@"", OpenWindowByDOM());
1427 686
1428 EXPECT_FALSE([delegate_ blockedPopupInfo]); 687 EXPECT_FALSE([delegate_ blockedPopupInfo]);
1429 } 688 }
1430 689
1431 // Tests that window.open triggered by user gesture opens a new non-popup 690 // Tests that window.open triggered by user gesture opens a new non-popup
1432 // window. 691 // window.
1433 TEST_F(CRWWKWebControllerWindowOpenTest, OpenWithUserGesture) { 692 TEST_F(CRWWebControllerWindowOpenTest, OpenWithUserGesture) {
1434 CR_TEST_REQUIRES_WK_WEB_VIEW();
1435
1436 SEL selector = @selector(webPageOrderedOpen); 693 SEL selector = @selector(webPageOrderedOpen);
1437 [delegate_ onSelector:selector 694 [delegate_ onSelector:selector
1438 callBlockExpectation:^(){ 695 callBlockExpectation:^(){
1439 }]; 696 }];
1440 697
1441 [webController_ touched:YES]; 698 [webController_ touched:YES];
1442 EXPECT_NSEQ(@"[object Window]", OpenWindowByDOM()); 699 EXPECT_NSEQ(@"[object Window]", OpenWindowByDOM());
1443 EXPECT_FALSE([delegate_ blockedPopupInfo]); 700 EXPECT_FALSE([delegate_ blockedPopupInfo]);
1444 } 701 }
1445 702
1446 // Tests that window.open executed w/o user gesture does not open a new window. 703 // Tests that window.open executed w/o user gesture does not open a new window.
1447 // Once the blocked popup is allowed a new window is opened. 704 // Once the blocked popup is allowed a new window is opened.
1448 TEST_F(CRWWKWebControllerWindowOpenTest, AllowPopup) { 705 TEST_F(CRWWebControllerWindowOpenTest, AllowPopup) {
1449 CR_TEST_REQUIRES_WK_WEB_VIEW();
1450
1451 SEL selector = 706 SEL selector =
1452 @selector(webPageOrderedOpen:referrer:windowName:inBackground:); 707 @selector(webPageOrderedOpen:referrer:windowName:inBackground:);
1453 [delegate_ onSelector:selector 708 [delegate_ onSelector:selector
1454 callBlockExpectation:^(const GURL& new_window_url, 709 callBlockExpectation:^(const GURL& new_window_url,
1455 const web::Referrer& referrer, 710 const web::Referrer& referrer,
1456 NSString* obsoleted_window_name, 711 NSString* obsoleted_window_name,
1457 BOOL in_background) { 712 BOOL in_background) {
1458 EXPECT_EQ("javascript:void(0);", new_window_url.spec()); 713 EXPECT_EQ("javascript:void(0);", new_window_url.spec());
1459 EXPECT_EQ("", referrer.url.spec()); 714 EXPECT_EQ("", referrer.url.spec());
1460 EXPECT_FALSE(in_background); 715 EXPECT_FALSE(in_background);
1461 }]; 716 }];
1462 717
1463 ASSERT_FALSE([webController_ userIsInteracting]); 718 ASSERT_FALSE([webController_ userIsInteracting]);
1464 EXPECT_NSEQ(@"", OpenWindowByDOM()); 719 EXPECT_NSEQ(@"", OpenWindowByDOM());
1465 base::test::ios::WaitUntilCondition(^bool() { 720 base::test::ios::WaitUntilCondition(^bool() {
1466 return [delegate_ blockedPopupInfo]; 721 return [delegate_ blockedPopupInfo];
1467 }); 722 });
1468 723
1469 if ([delegate_ blockedPopupInfo]) 724 if ([delegate_ blockedPopupInfo])
1470 [delegate_ blockedPopupInfo]->ShowPopup(); 725 [delegate_ blockedPopupInfo]->ShowPopup();
1471 726
1472 EXPECT_EQ("", [delegate_ sourceURL].spec()); 727 EXPECT_EQ("", [delegate_ sourceURL].spec());
1473 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec()); 728 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec());
1474 } 729 }
1475 730
1476 // Tests that window.open executed w/o user gesture opens a new window, assuming 731 // Tests that window.open executed w/o user gesture opens a new window, assuming
1477 // that delegate allows popups. 732 // that delegate allows popups.
1478 TEST_F(CRWWKWebControllerWindowOpenTest, DontBlockPopup) { 733 TEST_F(CRWWebControllerWindowOpenTest, DontBlockPopup) {
1479 CR_TEST_REQUIRES_WK_WEB_VIEW();
1480
1481 [delegate_ setBlockPopups:NO]; 734 [delegate_ setBlockPopups:NO];
1482 SEL selector = @selector(webPageOrderedOpen); 735 SEL selector = @selector(webPageOrderedOpen);
1483 [delegate_ onSelector:selector 736 [delegate_ onSelector:selector
1484 callBlockExpectation:^(){ 737 callBlockExpectation:^(){
1485 }]; 738 }];
1486 739
1487 EXPECT_NSEQ(@"[object Window]", OpenWindowByDOM()); 740 EXPECT_NSEQ(@"[object Window]", OpenWindowByDOM());
1488 EXPECT_FALSE([delegate_ blockedPopupInfo]); 741 EXPECT_FALSE([delegate_ blockedPopupInfo]);
1489 742
1490 EXPECT_EQ("", [delegate_ sourceURL].spec()); 743 EXPECT_EQ("", [delegate_ sourceURL].spec());
1491 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec()); 744 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec());
1492 } 745 }
1493 746
1494 // Tests that window.open executed w/o user gesture does not open a new window. 747 // Tests that window.open executed w/o user gesture does not open a new window.
1495 TEST_F(CRWWKWebControllerWindowOpenTest, BlockPopup) { 748 TEST_F(CRWWebControllerWindowOpenTest, BlockPopup) {
1496 CR_TEST_REQUIRES_WK_WEB_VIEW();
1497
1498 ASSERT_FALSE([webController_ userIsInteracting]); 749 ASSERT_FALSE([webController_ userIsInteracting]);
1499 EXPECT_NSEQ(@"", OpenWindowByDOM()); 750 EXPECT_NSEQ(@"", OpenWindowByDOM());
1500 base::test::ios::WaitUntilCondition(^bool() { 751 base::test::ios::WaitUntilCondition(^bool() {
1501 return [delegate_ blockedPopupInfo]; 752 return [delegate_ blockedPopupInfo];
1502 }); 753 });
1503 754
1504 EXPECT_EQ("", [delegate_ sourceURL].spec()); 755 EXPECT_EQ("", [delegate_ sourceURL].spec());
1505 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec()); 756 EXPECT_EQ("javascript:void(0);", [delegate_ popupURL].spec());
1506 }; 757 };
1507 758
1508 // Fixture class to test WKWebView crashes. 759 // Fixture class to test WKWebView crashes.
1509 class CRWWKWebControllerWebProcessTest 760 class CRWWebControllerWebProcessTest
1510 : public web::WebTestWithWKWebViewWebController { 761 : public web::WebTestWithWKWebViewWebController {
1511 protected: 762 protected:
1512 void SetUp() override { 763 void SetUp() override {
1513 CR_TEST_REQUIRES_WK_WEB_VIEW();
1514 web::WebTestWithWKWebViewWebController::SetUp(); 764 web::WebTestWithWKWebViewWebController::SetUp();
1515 webView_.reset(web::CreateTerminatedWKWebView()); 765 webView_.reset(web::CreateTerminatedWKWebView());
1516 base::scoped_nsobject<TestWebViewContentView> webViewContentView( 766 base::scoped_nsobject<TestWebViewContentView> webViewContentView(
1517 [[TestWebViewContentView alloc] 767 [[TestWebViewContentView alloc]
1518 initWithMockWebView:webView_ 768 initWithMockWebView:webView_
1519 scrollView:[webView_ scrollView]]); 769 scrollView:[webView_ scrollView]]);
1520 [webController_ injectWebViewContentView:webViewContentView]; 770 [webController_ injectWebViewContentView:webViewContentView];
1521 } 771 }
1522 base::scoped_nsobject<WKWebView> webView_; 772 base::scoped_nsobject<WKWebView> webView_;
1523 }; 773 };
1524 774
1525 // Tests that -[CRWWebDelegate webControllerWebProcessDidCrash:] is called 775 // Tests that -[CRWWebDelegate webControllerWebProcessDidCrash:] is called
1526 // when WKWebView web process has crashed. 776 // when WKWebView web process has crashed.
1527 TEST_F(CRWWKWebControllerWebProcessTest, Crash) { 777 TEST_F(CRWWebControllerWebProcessTest, Crash) {
1528 CR_TEST_REQUIRES_WK_WEB_VIEW(); 778 id delegate = [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)];
779 [[delegate expect] webControllerWebProcessDidCrash:webController_];
1529 780
1530 id delegate = [OCMockObject niceMockForProtocol:@protocol(CRWWebDelegate)]; 781 [webController_ setDelegate:delegate];
1531 [[delegate expect] webControllerWebProcessDidCrash:this->webController_];
1532
1533 [this->webController_ setDelegate:delegate];
1534 web::SimulateWKWebViewCrash(webView_); 782 web::SimulateWKWebViewCrash(webView_);
1535 783
1536 EXPECT_OCMOCK_VERIFY(delegate); 784 EXPECT_OCMOCK_VERIFY(delegate);
1537 EXPECT_FALSE([this->webController_ isViewAlive]); 785 EXPECT_FALSE([webController_ isViewAlive]);
1538 [this->webController_ setDelegate:nil]; 786 [webController_ setDelegate:nil];
1539 };
1540
1541 // Tests that WKWebView does not crash if deallocation happens during JavaScript
stuartmorgan 2016/01/28 22:24:46 I forget, was the fix for this in iOS 9 (meaning w
Eugene But (OOO till 7-30) 2016/02/02 22:55:02 Yes, this crash was fixed in iOS9. Workaround was
1542 // evaluation.
1543 typedef web::WebTestWithWKWebViewWebController DeallocationDuringJSEvaluation;
1544 TEST_F(DeallocationDuringJSEvaluation, NoCrash) {
1545 CR_TEST_REQUIRES_WK_WEB_VIEW();
1546
1547 this->LoadHtml(@"<html><body></body></html>");
1548 [webController_ evaluateJavaScript:@"null"
1549 stringResultHandler:^(NSString* value, NSError*) {
1550 // Block can not be empty in order to reproduce the crash:
1551 // https://bugs.webkit.org/show_bug.cgi?id=140203
1552 VLOG(1) << "Script has been flushed.";
1553 }];
1554 // -evaluateJavaScript:stringResultHandler: is asynchronous so JavaScript
1555 // evaluation will not happen until TearDown, which deallocates
1556 // CRWWebController, which in its turn will deallocate WKWebView to create a
1557 // crashy condition.
1558 }; 787 };
1559 788
1560 } // namespace 789 } // namespace
OLDNEW
« no previous file with comments | « ios/web/web_state/ui/crw_web_controller_observer_unittest.mm ('k') | ios/web/web_state/ui/web_view_js_utils_unittest.mm » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698