Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ios / web / test / wk_web_view_crash_utils.mm
blob936dc3064c23d1fe747ef3e2e8ded6048dfe9779
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/test/wk_web_view_crash_utils.h"
7 #import <Foundation/Foundation.h>
8 #import <WebKit/WebKit.h>
10 #include "base/ios/ios_util.h"
11 #include "base/logging.h"
12 #import "base/mac/scoped_nsobject.h"
13 #include "ios/web/public/test/test_browser_state.h"
14 #import "ios/web/public/web_view_creation_util.h"
15 #import "third_party/ocmock/OCMock/NSInvocation+OCMAdditions.h"
16 #import "third_party/ocmock/OCMock/OCMock.h"
18 namespace {
20 // Returns an OCMocked WKWebView whose |evaluateJavaScript:stringResultHandler:|
21 // method has been mocked to execute |block| instead. |block| cannot be nil.
22 WKWebView* CreateMockWKWebViewWithStubbedJSEvalFunction(
23     void (^block)(NSInvocation*)) {
24   DCHECK(block);
25   web::TestBrowserState browser_state;
26   base::scoped_nsobject<WKWebView> webView(
27       web::CreateWKWebView(CGRectZero, &browser_state));
28   id mockWebView = [OCMockObject partialMockForObject:webView];
29   [[[mockWebView stub] andDo:^void(NSInvocation* invocation) {
30       block(invocation);
31   }] evaluateJavaScript:OCMOCK_ANY completionHandler:OCMOCK_ANY];
32   return [mockWebView retain];
35 }  // namespace
37 namespace web {
39 void SimulateWKWebViewCrash(WKWebView* webView) {
40   if (base::ios::IsRunningOnIOS9OrLater()) {
41     SEL selector = @selector(webViewWebContentProcessDidTerminate:);
42     if ([webView.navigationDelegate respondsToSelector:selector]) {
43       [webView.navigationDelegate performSelector:selector withObject:webView];
44     }
45   }
46   [webView performSelector:@selector(_processDidExit)];
49 WKWebView* CreateTerminatedWKWebView() {
50   id fail = ^void(NSInvocation* invocation) {
51       // Always fails with WKErrorWebContentProcessTerminated error.
52       NSError* error =
53           [NSError errorWithDomain:WKErrorDomain
54                               code:WKErrorWebContentProcessTerminated
55                           userInfo:nil];
57       void (^completionHandler)(id, NSError*) =
58           [invocation getArgumentAtIndexAsObject:3];
59       completionHandler(nil, error);
60   };
61   return CreateMockWKWebViewWithStubbedJSEvalFunction(fail);
64 WKWebView* CreateHealthyWKWebView() {
65   id succeed = ^void(NSInvocation* invocation) {
66       void (^completionHandler)(id, NSError*) =
67           [invocation getArgumentAtIndexAsObject:3];
68       // Always succceeds with nil result.
69       completionHandler(nil, nil);
70   };
71   return CreateMockWKWebViewWithStubbedJSEvalFunction(succeed);
74 }  // namespace web