1 // Copyright (c) 2012 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 #include "base/file_util.h"
6 #include "base/json/json_file_value_serializer.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/threading/thread.h"
9 #include "chrome/browser/chrome_notification_types.h"
10 #include "chrome/browser/extensions/extension_service_unittest.h"
11 #include "chrome/browser/extensions/unpacked_installer.h"
12 #include "chrome/browser/extensions/user_script_listener.h"
13 #include "chrome/common/chrome_paths.h"
14 #include "chrome/common/extensions/extension_file_util.h"
15 #include "chrome/test/base/testing_profile.h"
16 #include "content/public/browser/notification_service.h"
17 #include "content/public/browser/resource_controller.h"
18 #include "content/public/browser/resource_throttle.h"
19 #include "net/base/request_priority.h"
20 #include "net/url_request/url_request.h"
21 #include "net/url_request/url_request_filter.h"
22 #include "net/url_request/url_request_test_job.h"
23 #include "net/url_request/url_request_test_util.h"
24 #include "testing/gtest/include/gtest/gtest.h"
26 using content::ResourceController;
27 using content::ResourceThrottle;
29 namespace extensions {
33 const char kMatchingUrl[] = "http://google.com/";
34 const char kNotMatchingUrl[] = "http://example.com/";
35 const char kTestData[] = "Hello, World!";
37 class ThrottleController : public base::SupportsUserData::Data,
38 public ResourceController {
40 ThrottleController(net::URLRequest* request, ResourceThrottle* throttle)
43 throttle_->set_controller_for_testing(this);
46 // ResourceController implementation:
47 virtual void Resume() OVERRIDE {
50 virtual void Cancel() OVERRIDE {
53 virtual void CancelAndIgnore() OVERRIDE {
56 virtual void CancelWithError(int error_code) OVERRIDE {
61 net::URLRequest* request_;
62 scoped_ptr<ResourceThrottle> throttle_;
65 // A simple test net::URLRequestJob. We don't care what it does, only that
66 // whether it starts and finishes.
67 class SimpleTestJob : public net::URLRequestTestJob {
69 SimpleTestJob(net::URLRequest* request,
70 net::NetworkDelegate* network_delegate)
71 : net::URLRequestTestJob(request,
77 virtual ~SimpleTestJob() {}
80 // Yoinked from extension_manifest_unittest.cc.
81 DictionaryValue* LoadManifestFile(const base::FilePath path,
83 EXPECT_TRUE(base::PathExists(path));
84 JSONFileValueSerializer serializer(path);
85 return static_cast<DictionaryValue*>(serializer.Deserialize(NULL, error));
88 scoped_refptr<Extension> LoadExtension(const std::string& filename,
91 PathService::Get(chrome::DIR_TEST_DATA, &path);
93 AppendASCII("extensions").
94 AppendASCII("manifest_tests").
95 AppendASCII(filename.c_str());
96 scoped_ptr<DictionaryValue> value(LoadManifestFile(path, error));
99 return Extension::Create(path.DirName(), Manifest::UNPACKED, *value,
100 Extension::NO_FLAGS, error);
103 class SimpleTestJobProtocolHandler
104 : public net::URLRequestJobFactory::ProtocolHandler {
106 SimpleTestJobProtocolHandler() {}
107 virtual ~SimpleTestJobProtocolHandler() {}
109 // net::URLRequestJobFactory::ProtocolHandler
110 virtual net::URLRequestJob* MaybeCreateJob(
111 net::URLRequest* request,
112 net::NetworkDelegate* network_delegate) const OVERRIDE {
113 return new SimpleTestJob(request, network_delegate);
117 DISALLOW_COPY_AND_ASSIGN(SimpleTestJobProtocolHandler);
122 class UserScriptListenerTest : public ExtensionServiceTestBase {
124 UserScriptListenerTest() {
125 net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler(
126 "http", "google.com",
127 scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
128 new SimpleTestJobProtocolHandler()));
129 net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler(
130 "http", "example.com",
131 scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(
132 new SimpleTestJobProtocolHandler()));
135 virtual ~UserScriptListenerTest() {
136 net::URLRequestFilter::GetInstance()->RemoveHostnameHandler("http",
138 net::URLRequestFilter::GetInstance()->RemoveHostnameHandler("http",
142 virtual void SetUp() OVERRIDE {
143 ExtensionServiceTestBase::SetUp();
145 InitializeEmptyExtensionService();
147 base::MessageLoop::current()->RunUntilIdle();
149 listener_ = new UserScriptListener();
152 virtual void TearDown() OVERRIDE {
154 base::MessageLoop::current()->RunUntilIdle();
155 ExtensionServiceTestBase::TearDown();
159 net::TestURLRequest* StartTestRequest(net::URLRequest::Delegate* delegate,
160 const std::string& url_string,
161 net::TestURLRequestContext* context) {
162 GURL url(url_string);
163 net::TestURLRequest* request =
164 new net::TestURLRequest(url, net::DEFAULT_PRIORITY, delegate, context);
166 ResourceThrottle* throttle =
167 listener_->CreateResourceThrottle(url, ResourceType::MAIN_FRAME);
171 request->SetUserData(NULL, new ThrottleController(request, throttle));
173 throttle->WillStartRequest(&defer);
182 void LoadTestExtension() {
183 base::FilePath test_dir;
184 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
185 base::FilePath extension_path = test_dir
186 .AppendASCII("extensions")
188 .AppendASCII("Extensions")
189 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
190 .AppendASCII("1.0.0.0");
191 UnpackedInstaller::Create(service_)->Load(extension_path);
194 void UnloadTestExtension() {
195 ASSERT_FALSE(service_->extensions()->is_empty());
196 service_->UnloadExtension((*service_->extensions()->begin())->id(),
197 UnloadedExtensionInfo::REASON_DISABLE);
200 scoped_refptr<UserScriptListener> listener_;
205 TEST_F(UserScriptListenerTest, DelayAndUpdate) {
207 base::MessageLoop::current()->RunUntilIdle();
209 net::TestDelegate delegate;
210 net::TestURLRequestContext context;
211 scoped_ptr<net::TestURLRequest> request(
212 StartTestRequest(&delegate, kMatchingUrl, &context));
213 ASSERT_FALSE(request->is_pending());
215 content::NotificationService::current()->Notify(
216 chrome::NOTIFICATION_USER_SCRIPTS_UPDATED,
217 content::Source<Profile>(profile_.get()),
218 content::NotificationService::NoDetails());
219 base::MessageLoop::current()->RunUntilIdle();
220 EXPECT_EQ(kTestData, delegate.data_received());
223 TEST_F(UserScriptListenerTest, DelayAndUnload) {
225 base::MessageLoop::current()->RunUntilIdle();
227 net::TestDelegate delegate;
228 net::TestURLRequestContext context;
229 scoped_ptr<net::TestURLRequest> request(
230 StartTestRequest(&delegate, kMatchingUrl, &context));
231 ASSERT_FALSE(request->is_pending());
233 UnloadTestExtension();
234 base::MessageLoop::current()->RunUntilIdle();
236 // This is still not enough to start delayed requests. We have to notify the
237 // listener that the user scripts have been updated.
238 ASSERT_FALSE(request->is_pending());
240 content::NotificationService::current()->Notify(
241 chrome::NOTIFICATION_USER_SCRIPTS_UPDATED,
242 content::Source<Profile>(profile_.get()),
243 content::NotificationService::NoDetails());
244 base::MessageLoop::current()->RunUntilIdle();
245 EXPECT_EQ(kTestData, delegate.data_received());
248 TEST_F(UserScriptListenerTest, NoDelayNoExtension) {
249 net::TestDelegate delegate;
250 net::TestURLRequestContext context;
251 scoped_ptr<net::TestURLRequest> request(
252 StartTestRequest(&delegate, kMatchingUrl, &context));
254 // The request should be started immediately.
255 ASSERT_TRUE(request->is_pending());
257 base::MessageLoop::current()->RunUntilIdle();
258 EXPECT_EQ(kTestData, delegate.data_received());
261 TEST_F(UserScriptListenerTest, NoDelayNotMatching) {
263 base::MessageLoop::current()->RunUntilIdle();
265 net::TestDelegate delegate;
266 net::TestURLRequestContext context;
267 scoped_ptr<net::TestURLRequest> request(StartTestRequest(&delegate,
271 // The request should be started immediately.
272 ASSERT_TRUE(request->is_pending());
274 base::MessageLoop::current()->RunUntilIdle();
275 EXPECT_EQ(kTestData, delegate.data_received());
278 TEST_F(UserScriptListenerTest, MultiProfile) {
280 base::MessageLoop::current()->RunUntilIdle();
282 // Fire up a second profile and have it load and extension with a content
284 TestingProfile profile2;
286 scoped_refptr<Extension> extension = LoadExtension(
287 "content_script_yahoo.json", &error);
288 ASSERT_TRUE(extension.get());
290 content::NotificationService::current()->Notify(
291 chrome::NOTIFICATION_EXTENSION_LOADED,
292 content::Source<Profile>(&profile2),
293 content::Details<Extension>(extension.get()));
295 net::TestDelegate delegate;
296 net::TestURLRequestContext context;
297 scoped_ptr<net::TestURLRequest> request(
298 StartTestRequest(&delegate, kMatchingUrl, &context));
299 ASSERT_FALSE(request->is_pending());
301 // When the first profile's user scripts are ready, the request should still
302 // be blocked waiting for profile2.
303 content::NotificationService::current()->Notify(
304 chrome::NOTIFICATION_USER_SCRIPTS_UPDATED,
305 content::Source<Profile>(profile_.get()),
306 content::NotificationService::NoDetails());
307 base::MessageLoop::current()->RunUntilIdle();
308 ASSERT_FALSE(request->is_pending());
309 EXPECT_TRUE(delegate.data_received().empty());
311 // After profile2 is ready, the request should proceed.
312 content::NotificationService::current()->Notify(
313 chrome::NOTIFICATION_USER_SCRIPTS_UPDATED,
314 content::Source<Profile>(&profile2),
315 content::NotificationService::NoDetails());
316 base::MessageLoop::current()->RunUntilIdle();
317 EXPECT_EQ(kTestData, delegate.data_received());
320 // Test when the script updated notification occurs before the throttle's
321 // WillStartRequest function is called. This can occur when there are multiple
323 TEST_F(UserScriptListenerTest, ResumeBeforeStart) {
325 base::MessageLoop::current()->RunUntilIdle();
326 net::TestDelegate delegate;
327 net::TestURLRequestContext context;
328 GURL url(kMatchingUrl);
329 scoped_ptr<net::TestURLRequest> request(
330 new net::TestURLRequest(url, net::DEFAULT_PRIORITY, &delegate, &context));
332 ResourceThrottle* throttle =
333 listener_->CreateResourceThrottle(url, ResourceType::MAIN_FRAME);
334 ASSERT_TRUE(throttle);
335 request->SetUserData(NULL, new ThrottleController(request.get(), throttle));
337 ASSERT_FALSE(request->is_pending());
339 content::NotificationService::current()->Notify(
340 chrome::NOTIFICATION_USER_SCRIPTS_UPDATED,
341 content::Source<Profile>(profile_.get()),
342 content::NotificationService::NoDetails());
343 base::MessageLoop::current()->RunUntilIdle();
346 throttle->WillStartRequest(&defer);
352 } // namespace extensions