summaryrefslogtreecommitdiffstats
path: root/chrome/browser/power/process_power_collector_unittest.cc
blob: a112410cffda8795c065985b26f9c8ddb58eb2ff (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright 2014 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.

#include "chrome/browser/power/process_power_collector.h"

#include "apps/app_window_contents.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/apps/chrome_app_delegate.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/power/origin_power_map.h"
#include "components/power/origin_power_map_factory.h"
#include "content/public/browser/site_instance.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/mock_render_process_host.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/app_window/apps_client.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "extensions/common/extension.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/power_manager/power_supply_properties.pb.h"
#endif

using power::OriginPowerMap;
using power::OriginPowerMapFactory;

class BrowserProcessPowerTest : public BrowserWithTestWindowTest {
 public:
  BrowserProcessPowerTest() {}
  virtual ~BrowserProcessPowerTest() {}

  virtual void SetUp() OVERRIDE {
    BrowserWithTestWindowTest::SetUp();
    collector.reset(new ProcessPowerCollector);

#if defined(OS_CHROMEOS)
    power_manager::PowerSupplyProperties prop;
    prop.set_external_power(power_manager::PowerSupplyProperties::AC);
    prop.set_battery_state(power_manager::PowerSupplyProperties::DISCHARGING);
    prop.set_battery_percent(20.00);
    prop.set_battery_discharge_rate(1);
    collector->PowerChanged(prop);
#endif

    profile_manager_.reset(
        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
    ASSERT_TRUE(profile_manager_->SetUp());
  }

  virtual void TearDown() OVERRIDE {
    collector.reset();
    BrowserWithTestWindowTest::TearDown();
  }

  // Mocks out CPU usage for all processes as |value| percent.
  double ReturnCpuAsConstant(double value, base::ProcessHandle handle) {
    return value;
  }

 protected:
  content::MockRenderProcessHost* GetProcess(Browser* browser) {
    return static_cast<content::MockRenderProcessHost*>(
        browser->tab_strip_model()
            ->GetActiveWebContents()
            ->GetRenderViewHost()
            ->GetProcess());
  }

  scoped_ptr<base::ProcessHandle> MakeProcessHandle(int process_id) {
    scoped_ptr<base::ProcessHandle> proc_handle(new base::ProcessHandle(
#if defined(OS_WIN)
        reinterpret_cast<HANDLE>(process_id))
#else
        process_id)
#endif
                                                );
    return proc_handle.Pass();
  }

  scoped_ptr<ProcessPowerCollector> collector;
  scoped_ptr<TestingProfileManager> profile_manager_;
};

class TestAppWindowContents : public extensions::AppWindowContents {
 public:
  explicit TestAppWindowContents(content::WebContents* web_contents)
      : web_contents_(web_contents) {}

  // apps:AppWindowContents
  virtual void Initialize(content::BrowserContext* context,
                          const GURL& url) OVERRIDE {}
  virtual void LoadContents(int32 creator_process_id) OVERRIDE {}
  virtual void NativeWindowChanged(
      extensions::NativeAppWindow* native_app_window) OVERRIDE {}
  virtual void NativeWindowClosed() OVERRIDE {}
  virtual void DispatchWindowShownForTests() const OVERRIDE {}
  virtual content::WebContents* GetWebContents() const OVERRIDE {
    return web_contents_.get();
  }

 private:
  scoped_ptr<content::WebContents> web_contents_;
};

TEST_F(BrowserProcessPowerTest, NoSite) {
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(0u, collector->metrics_map_for_testing()->size());
}

TEST_F(BrowserProcessPowerTest, OneSite) {
  GURL url("http://www.google.com");
  AddTab(browser(), url);
  collector->UpdatePowerConsumptionForTesting();
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(1u, metrics_map->size());

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());

  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(5, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(100, origin_power_map->GetPowerForOrigin(url));
}

TEST_F(BrowserProcessPowerTest, MultipleSites) {
  Browser::CreateParams native_params(profile(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  GURL url1("http://www.google.com");
  GURL url2("http://www.example.com");
  GURL url3("https://www.google.com");
  scoped_ptr<Browser> browser2(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  scoped_ptr<Browser> browser3(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  AddTab(browser(), url1);
  AddTab(browser2.get(), url2);
  AddTab(browser3.get(), url3);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(browser2.get())->SetProcessHandle(MakeProcessHandle(2).Pass());
  GetProcess(browser3.get())->SetProcessHandle(MakeProcessHandle(3).Pass());

  collector->UpdatePowerConsumptionForTesting();
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(3u, metrics_map->size());

  // Since all handlers are uninitialized, this should be 0.
  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url1));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url2));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url3));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(15, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url1));
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url2));
  EXPECT_EQ(33, origin_power_map->GetPowerForOrigin(url3));

  // Close some tabs and verify that they are removed from the metrics map.
  chrome::CloseTab(browser2.get());
  chrome::CloseTab(browser3.get());

  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(1u, metrics_map->size());
}

TEST_F(BrowserProcessPowerTest, IncognitoDoesntRecordPowerUsage) {
  Browser::CreateParams native_params(profile()->GetOffTheRecordProfile(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  scoped_ptr<Browser> incognito_browser(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));
  GURL url("http://www.google.com");
  AddTab(browser(), url);

  GURL hidden_url("http://foo.com");
  AddTab(incognito_browser.get(), hidden_url);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(incognito_browser.get())
      ->SetProcessHandle(MakeProcessHandle(2).Pass());

  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  ProcessPowerCollector::ProcessMetricsMap* metrics_map =
      collector->metrics_map_for_testing();
  EXPECT_EQ(1u, metrics_map->size());

  OriginPowerMap* origin_power_map =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(url));

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(5, collector->UpdatePowerConsumptionForTesting());

  // Verify that the incognito data was not stored.
  EXPECT_EQ(100, origin_power_map->GetPowerForOrigin(url));
  EXPECT_EQ(0, origin_power_map->GetPowerForOrigin(hidden_url));

  chrome::CloseTab(incognito_browser.get());
}

TEST_F(BrowserProcessPowerTest, MultipleProfilesRecordSeparately) {
  scoped_ptr<Profile> other_profile(CreateProfile());
  Browser::CreateParams native_params(other_profile.get(),
                                      chrome::HOST_DESKTOP_TYPE_NATIVE);
  scoped_ptr<Browser> other_user(
      chrome::CreateBrowserWithTestWindowForParams(&native_params));

  GURL url("http://www.google.com");
  AddTab(browser(), url);

  GURL hidden_url("http://foo.com");
  AddTab(other_user.get(), hidden_url);

  // Create fake process numbers.
  GetProcess(browser())->SetProcessHandle(MakeProcessHandle(1).Pass());
  GetProcess(other_user.get())->SetProcessHandle(MakeProcessHandle(2).Pass());

  EXPECT_DOUBLE_EQ(0, collector->UpdatePowerConsumptionForTesting());
  EXPECT_EQ(2u, collector->metrics_map_for_testing()->size());

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  EXPECT_DOUBLE_EQ(10, collector->UpdatePowerConsumptionForTesting());

  // profile() should have an entry for |url| but not |hidden_url|.
  OriginPowerMap* origin_power_map_first =
      OriginPowerMapFactory::GetForBrowserContext(profile());
  EXPECT_EQ(100, origin_power_map_first->GetPowerForOrigin(url));
  EXPECT_EQ(0, origin_power_map_first->GetPowerForOrigin(hidden_url));

  // |other_profile| should have an entry for |hidden_url| but not |url|.
  OriginPowerMap* origin_power_map_second =
      OriginPowerMapFactory::GetForBrowserContext(other_profile.get());
  EXPECT_EQ(0, origin_power_map_second->GetPowerForOrigin(url));
  EXPECT_EQ(100, origin_power_map_second->GetPowerForOrigin(hidden_url));

  // Clean up
  chrome::CloseTab(other_user.get());
}

TEST_F(BrowserProcessPowerTest, AppsRecordPowerUsage) {
// Install an app (an extension*).
#if defined(OS_WIN)
  base::FilePath extension_path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
  base::FilePath extension_path(FILE_PATH_LITERAL("/foo"));
#endif
  base::DictionaryValue manifest;
  manifest.SetString("name", "Fake Name");
  manifest.SetString("version", "1");
  std::string error;
  char kTestAppId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  scoped_refptr<extensions::Extension> extension(
      extensions::Extension::Create(extension_path,
                                    extensions::Manifest::INTERNAL,
                                    manifest,
                                    extensions::Extension::NO_FLAGS,
                                    kTestAppId,
                                    &error));
  EXPECT_TRUE(extension.get()) << error;
  // Increment the apps count to avoid a DCHECK later.
  extensions::AppsClient::Get()->IncrementKeepAliveCount();

  Profile* current_profile =
      profile_manager_->CreateTestingProfile("Test user");
  GURL url("chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  extensions::AppWindow* window = new extensions::AppWindow(
      current_profile, new ChromeAppDelegate(), extension.get());
  content::WebContents* web_contents(
      content::WebContents::Create(content::WebContents::CreateParams(
          current_profile,
          content::SiteInstance::CreateForURL(current_profile, url))));
  window->SetAppWindowContentsForTesting(
      scoped_ptr<extensions::AppWindowContents>(
          new TestAppWindowContents(web_contents)));
  extensions::AppWindowRegistry* app_registry =
      extensions::AppWindowRegistry::Get(current_profile);
  app_registry->AddAppWindow(window);

  collector->set_cpu_usage_callback_for_testing(
      base::Bind(&BrowserProcessPowerTest::ReturnCpuAsConstant,
                 base::Unretained(this),
                 5));
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(1u, collector->metrics_map_for_testing()->size());

  // Clear the AppWindowContents before trying to close.
  window->SetAppWindowContentsForTesting(
      scoped_ptr<extensions::AppWindowContents>());
  window->OnNativeClose();
  collector->UpdatePowerConsumptionForTesting();
  EXPECT_EQ(0u, collector->metrics_map_for_testing()->size());
}