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

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