summaryrefslogtreecommitdiffstats
path: root/ios/web/webui/crw_web_ui_manager_unittest.mm
blob: c5fac6f73bff7c276da62be79df11d725117de7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "ios/web/webui/crw_web_ui_manager.h"

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#import "base/mac/scoped_nsobject.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#import "base/strings/sys_string_conversions.h"
#include "base/values.h"
#include "ios/web/public/test/scoped_testing_web_client.h"
#include "ios/web/public/test/test_browser_state.h"
#import "ios/web/public/test/test_web_client.h"
#include "ios/web/web_state/web_state_impl.h"
#import "ios/web/webui/crw_web_ui_page_builder.h"
#include "ios/web/webui/url_fetcher_block_adapter.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gtest_mac.h"
#include "testing/platform_test.h"

namespace web {

// Path for test favicon file.
const char kFaviconPath[] = "ios/web/test/data/testfavicon.png";
// URL for mock WebUI page.
const char kTestChromeUrl[] = "chrome://test";
// URL for mock favicon.
const char kFaviconUrl[] = "chrome://favicon";
// HTML for mock WebUI page.
NSString* kHtml = @"<html>Hello World</html>";

// Mock of WebStateImpl to check that LoadHtml and ExecuteJavaScriptAsync are
// called as expected.
class MockWebStateImpl : public WebStateImpl {
 public:
  MockWebStateImpl(BrowserState* browser_state) : WebStateImpl(browser_state) {}
  MOCK_METHOD2(LoadWebUIHtml,
               void(const base::string16& html, const GURL& url));
  MOCK_METHOD1(ExecuteJavaScriptAsync, void(const base::string16& javascript));
};

// Mock of URLFetcherBlockAdapter to provide mock resources.
class MockURLFetcherBlockAdapter : public URLFetcherBlockAdapter {
 public:
  MockURLFetcherBlockAdapter(
      const GURL& url,
      net::URLRequestContextGetter* request_context,
      URLFetcherBlockAdapterCompletion completion_handler)
      : URLFetcherBlockAdapter(url, request_context, completion_handler),
        url_(url),
        completion_handler_(completion_handler) {}

  void Start() override {
    if (url_.spec() == kTestChromeUrl) {
      completion_handler_.get()([kHtml dataUsingEncoding:NSUTF8StringEncoding],
                                this);
    } else if (url_.spec() == kFaviconUrl) {
      base::FilePath favicon_path;
      ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &favicon_path));
      favicon_path = favicon_path.AppendASCII(kFaviconPath);
      completion_handler_.get()(
          [NSData dataWithContentsOfFile:base::SysUTF8ToNSString(
                                             favicon_path.value())],
          this);
    } else {
      NOTREACHED();
    }
  }

 private:
  // The URL to fetch.
  const GURL url_;
  // Callback for resource load.
  base::mac::ScopedBlock<URLFetcherBlockAdapterCompletion> completion_handler_;
};

class AppSpecificTestWebClient : public TestWebClient {
public:
  bool IsAppSpecificURL(const GURL& url) const override {
    return url.SchemeIs("chrome");
  }
};

}  // namespace web

// Subclass of CRWWebUIManager for testing.
@interface CRWTestWebUIManager : CRWWebUIManager
// Use mock URLFetcherBlockAdapter.
- (scoped_ptr<web::URLFetcherBlockAdapter>)
        fetcherForURL:(const GURL&)URL
    completionHandler:(web::URLFetcherBlockAdapterCompletion)handler;
@end

@implementation CRWTestWebUIManager
- (scoped_ptr<web::URLFetcherBlockAdapter>)
        fetcherForURL:(const GURL&)URL
    completionHandler:(web::URLFetcherBlockAdapterCompletion)handler {
  return scoped_ptr<web::URLFetcherBlockAdapter>(
      new web::MockURLFetcherBlockAdapter(URL, nil, handler));
}
@end

namespace web {

// Test fixture for testing CRWWebUIManager
class CRWWebUIManagerTest : public PlatformTest {
 public:
  CRWWebUIManagerTest()
      : web_client_(make_scoped_ptr(new web::AppSpecificTestWebClient)) {}

 protected:
  void SetUp() override {
    PlatformTest::SetUp();
    test_browser_state_.reset(new TestBrowserState());
    web_state_impl_.reset(new MockWebStateImpl(test_browser_state_.get()));
    web_ui_manager_.reset(
        [[CRWTestWebUIManager alloc] initWithWebState:web_state_impl_.get()]);
  }

  // TestBrowserState for creation of WebStateImpl.
  scoped_ptr<TestBrowserState> test_browser_state_;
  // MockWebStateImpl for detection of LoadHtml and EvaluateJavaScriptAync
  // calls.
  scoped_ptr<MockWebStateImpl> web_state_impl_;
  // WebUIManager for testing.
  base::scoped_nsobject<CRWTestWebUIManager> web_ui_manager_;
  // The WebClient used in tests.
  web::ScopedTestingWebClient web_client_;
};

// Tests that CRWWebUIManager observes provisional navigation and invokes an
// HTML load in web state.
TEST_F(CRWWebUIManagerTest, LoadWebUI) {
  base::string16 html(base::SysNSStringToUTF16(kHtml));
  GURL url(kTestChromeUrl);
  EXPECT_CALL(*web_state_impl_, LoadWebUIHtml(html, url));
  web_state_impl_->OnProvisionalNavigationStarted(url);
}

// Tests that CRWWebUIManager responds to OnScriptCommandReceieved call and runs
// JavaScript to set favicon background.
TEST_F(CRWWebUIManagerTest, HandleFaviconRequest) {
  GURL test_url(kTestChromeUrl);
  std::string favicon_url_string(kFaviconUrl);

  // Create mock JavaScript message to request favicon.
  base::ListValue* arguments(new base::ListValue());
  arguments->AppendString(favicon_url_string);
  scoped_ptr<base::DictionaryValue> message(new base::DictionaryValue());
  message->SetString("message", "webui.requestFavicon");
  message->Set("arguments", arguments);

  // Create expected JavaScript to call.
  base::FilePath favicon_path;
  ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &favicon_path));
  favicon_path = favicon_path.AppendASCII(kFaviconPath);
  NSData* expected_data = [NSData
      dataWithContentsOfFile:base::SysUTF8ToNSString(favicon_path.value())];
  base::string16 expected_javascript = base::SysNSStringToUTF16([NSString
      stringWithFormat:
          @"chrome.setFaviconBackground('%s', 'data:image/png;base64,%@');",
          favicon_url_string.c_str(),
          [expected_data base64EncodedStringWithOptions:0]]);

  EXPECT_CALL(*web_state_impl_, ExecuteJavaScriptAsync(expected_javascript));
  web_state_impl_->OnScriptCommandReceived("webui.requestFavicon", *message,
                                           test_url, false);
}
}  // namespace web