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.
4
5#include <string>
6
7#include "base/strings/string16.h"
8#include "base/strings/stringprintf.h"
9#include "base/strings/utf_string_conversions.h"
10#include "chrome/browser/extensions/api/push_messaging/sync_setup_helper.h"
11#include "chrome/browser/extensions/extension_apitest.h"
12#include "chrome/browser/extensions/extension_service.h"
13#include "chrome/browser/ui/browser.h"
14#include "chrome/browser/ui/tabs/tab_strip_model.h"
15#include "chrome/common/chrome_switches.h"
16#include "chrome/test/base/ui_test_utils.h"
17#include "content/public/browser/render_frame_host.h"
18#include "extensions/common/extension_set.h"
19#include "extensions/test/result_catcher.h"
20#include "net/dns/mock_host_resolver.h"
21
22namespace {
23const char kTestExtensionId[] = "mfaehphpebmlbfdiegjnpidmibldjbjk";
24const char kPasswordFileForTest[] = "password-file-for-test";
25const char kOverrideUserDataDir[] = "override-user-data-dir";
26}  // namespace
27
28namespace extensions {
29
30// This class provides tests specific to the push messaging
31// canary test server.  These tests require network access,
32// and should not be run by normal buildbots as part of the normal
33// checkin process.
34class PushMessagingCanaryTest : public ExtensionApiTest {
35 public:
36  PushMessagingCanaryTest() {
37    sync_setup_helper_.reset(new SyncSetupHelper());
38  }
39
40  virtual ~PushMessagingCanaryTest() {
41  }
42
43  virtual void SetUp() OVERRIDE {
44    CommandLine* command_line = CommandLine::ForCurrentProcess();
45
46    ASSERT_TRUE(command_line->HasSwitch(kPasswordFileForTest));
47    base::FilePath password_file =
48        command_line->GetSwitchValuePath(kPasswordFileForTest);
49    ASSERT_TRUE(sync_setup_helper_->ReadPasswordFile(password_file));
50
51    // The test framework overrides any command line user-data-dir
52    // argument with a /tmp/.org.chromium.Chromium.XXXXXX directory.
53    // That happens in the ChromeTestLauncherDelegate, and affects
54    // all unit tests (no opt out available).  It intentionally erases
55    // any --user-data-dir switch if present and appends a new one.
56    // Re-override the default data dir for our test so we can persist
57    // the profile for this particular test so we can persist the max
58    // invalidation version between runs.
59    const base::FilePath& override_user_data_dir =
60        command_line->GetSwitchValuePath(kOverrideUserDataDir);
61    ASSERT_TRUE(!override_user_data_dir.empty());
62    command_line->AppendSwitchPath(switches::kUserDataDir,
63                                   base::FilePath(override_user_data_dir));
64    LOG(INFO) << "command line file override switch is "
65              << override_user_data_dir.value();
66
67    ExtensionApiTest::SetUp();
68  }
69
70  void InitializeSync() {
71    ASSERT_TRUE(sync_setup_helper_->InitializeSync(profile()));
72  }
73
74  // InProcessBrowserTest override. Destroys the sync client and sync
75  // profile created by the test.  We must clean up ProfileSyncServiceHarness
76  // now before the profile is cleaned up.
77  virtual void TearDownOnMainThread() OVERRIDE {
78    sync_setup_helper_.reset();
79  }
80
81  const SyncSetupHelper* sync_setup_helper() const {
82    return sync_setup_helper_.get();
83  }
84
85 protected:
86  // Override InProcessBrowserTest. Change behavior of the default host
87  // resolver to avoid DNS lookup errors, so we can make network calls.
88  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
89    // The resolver object lifetime is managed by sync_test_setup, not here.
90    EnableDNSLookupForThisTest(
91        new net::RuleBasedHostResolverProc(host_resolver()));
92  }
93
94  virtual void TearDownInProcessBrowserTestFixture() OVERRIDE {
95    DisableDNSLookupForThisTest();
96  }
97
98
99  // Change behavior of the default host resolver to allow DNS lookup
100  // to proceed instead of being blocked by the test infrastructure.
101  void EnableDNSLookupForThisTest(
102      net::RuleBasedHostResolverProc* host_resolver) {
103    // mock_host_resolver_override_ takes ownership of the resolver.
104    scoped_refptr<net::RuleBasedHostResolverProc> resolver =
105        new net::RuleBasedHostResolverProc(host_resolver);
106    resolver->AllowDirectLookup("*.google.com");
107    // On Linux, we use Chromium's NSS implementation which uses the following
108    // hosts for certificate verification. Without these overrides, running the
109    // integration tests on Linux causes error as we make external DNS lookups.
110    resolver->AllowDirectLookup("*.thawte.com");
111    resolver->AllowDirectLookup("*.geotrust.com");
112    resolver->AllowDirectLookup("*.gstatic.com");
113    resolver->AllowDirectLookup("*.googleapis.com");
114    mock_host_resolver_override_.reset(
115        new net::ScopedDefaultHostResolverProc(resolver.get()));
116  }
117
118  // We need to reset the DNS lookup when we finish, or the test will fail.
119  void DisableDNSLookupForThisTest() {
120    mock_host_resolver_override_.reset();
121  }
122
123 private:
124  scoped_ptr<SyncSetupHelper> sync_setup_helper_;
125
126  // This test needs to make live DNS requests for access to
127  // GAIA and sync server URLs under google.com. We use a scoped version
128  // to override the default resolver while the test is active.
129  scoped_ptr<net::ScopedDefaultHostResolverProc> mock_host_resolver_override_;
130};
131
132// Test that a push can make a round trip through the servers.
133// This test is disabled to keep it from running on trybots since
134// it requires network access, and it is not a good idea to run
135// this test as part of a checkin or nightly test.
136IN_PROC_BROWSER_TEST_F(PushMessagingCanaryTest, MANUAL_ReceivesPush) {
137  InitializeSync();
138
139  const ExtensionSet* installed_extensions = extension_service()->extensions();
140  if (!installed_extensions->Contains(kTestExtensionId)) {
141    const Extension* extension =
142        LoadExtension(test_data_dir_.AppendASCII("push_messaging_canary"));
143    ASSERT_TRUE(extension);
144  }
145  ASSERT_TRUE(installed_extensions->Contains(kTestExtensionId));
146
147  ResultCatcher catcher;
148  catcher.RestrictToBrowserContext(profile());
149
150  const Extension* extension =
151      extension_service()->extensions()->GetByID(kTestExtensionId);
152  ASSERT_TRUE(extension);
153  ui_test_utils::NavigateToURL(
154      browser(), extension->GetResourceURL("push_messaging_canary.html"));
155
156  const std::string& client_id = sync_setup_helper()->client_id();
157  const std::string& client_secret = sync_setup_helper()->client_secret();
158  const std::string& refresh_token = sync_setup_helper()->refresh_token();
159
160  const base::string16& script_string = base::UTF8ToUTF16(base::StringPrintf(
161      "startTestWithCredentials('%s', '%s', '%s');",
162      client_id.c_str(), client_secret.c_str(), refresh_token.c_str()));
163
164  browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
165      ExecuteJavaScript(script_string);
166
167  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
168}
169
170}  // namespace extensions
171