QUIC - cleanup changes to sync chromium tree with internal source.
[chromium-blink-merge.git] / ios / web / public / test / js_test_util.mm
blobe0ceab549de029b15943da78f4ec85c82ca8d762
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/public/test/js_test_util.h"
7 #import <UIKit/UIKit.h>
8 #import <WebKit/WebKit.h>
10 #import "base/logging.h"
11 #import "base/mac/scoped_nsobject.h"
12 #import "base/test/ios/wait_util.h"
13 #import "base/time/time.h"
14 #import "ios/web/public/web_state/js/crw_js_injection_manager.h"
15 #import "ios/web/public/web_state/js/crw_js_injection_receiver.h"
17 using base::Time;
18 using base::TimeDelta;
20 namespace {
21 // The amount of time (in secs) |evaluate:StringResultHandler:| is given time to
22 // process until the test fails.
23 const NSTimeInterval kTimeout = 5.0;
26 namespace web {
28 NSString* EvaluateJavaScriptAsString(CRWJSInjectionManager* manager,
29                                      NSString* script) {
30   __block base::scoped_nsobject<NSString> evaluationResult;
31   [manager evaluate:script
32       stringResultHandler:^(NSString* result, NSError* error) {
33         DCHECK(result);
34         evaluationResult.reset([result copy]);
35       }];
36   // TODO(shreyasv): This is a temporary solution to have some duplicated code.
37   // The right way to implement this is to use |WaitUntilCondition|. Move to
38   // that when that function lives in ios/.
39   Time startTime = Time::Now();
40   while (!evaluationResult.get() &&
41          (Time::Now() - startTime < TimeDelta::FromSeconds(kTimeout))) {
42     NSDate* beforeDate = [NSDate dateWithTimeIntervalSinceNow:.01];
43     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
44                              beforeDate:beforeDate];
45   }
46   DCHECK(evaluationResult);
47   return [[evaluationResult retain] autorelease];
50 NSString* EvaluateJavaScriptAsString(CRWJSInjectionReceiver* receiver,
51                                      NSString* script) {
52   base::scoped_nsobject<CRWJSInjectionManager> manager(
53       [[CRWJSInjectionManager alloc] initWithReceiver:receiver]);
54   return EvaluateJavaScriptAsString(manager, script);
57 NSString* EvaluateJavaScriptAsString(UIWebView* web_view, NSString* script) {
58   return [web_view stringByEvaluatingJavaScriptFromString:script];
61 id EvaluateJavaScript(WKWebView* web_view, NSString* script) {
62   __block base::scoped_nsobject<id> result;
63   [web_view evaluateJavaScript:script
64              completionHandler:^(id evaluationResult, NSError* error) {
65                DCHECK(!error);
66                result.reset([evaluationResult copy]);
67              }];
68   base::test::ios::WaitUntilCondition(^bool() {
69     return result;
70   });
71   return [[result retain] autorelease];
74 }  // namespace web