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 "chrome/browser/chromeos/policy/device_status_collector.h"
10 #include "base/bind.h"
11 #include "base/environment.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/prefs/testing_pref_service.h"
17 #include "base/run_loop.h"
18 #include "base/threading/sequenced_worker_pool.h"
19 #include "chrome/browser/chromeos/login/users/mock_user_manager.h"
20 #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
21 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
22 #include "chrome/browser/chromeos/policy/device_local_account.h"
23 #include "chrome/browser/chromeos/policy/stub_enterprise_install_attributes.h"
24 #include "chrome/browser/chromeos/settings/cros_settings.h"
25 #include "chrome/browser/chromeos/settings/device_settings_service.h"
26 #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/test/base/testing_browser_process.h"
29 #include "chromeos/dbus/cros_disks_client.h"
30 #include "chromeos/dbus/dbus_thread_manager.h"
31 #include "chromeos/dbus/shill_device_client.h"
32 #include "chromeos/dbus/shill_ipconfig_client.h"
33 #include "chromeos/dbus/shill_service_client.h"
34 #include "chromeos/disks/disk_mount_manager.h"
35 #include "chromeos/disks/mock_disk_mount_manager.h"
36 #include "chromeos/network/network_handler.h"
37 #include "chromeos/network/network_state.h"
38 #include "chromeos/network/network_state_handler.h"
39 #include "chromeos/settings/cros_settings_names.h"
40 #include "chromeos/settings/cros_settings_provider.h"
41 #include "chromeos/system/fake_statistics_provider.h"
42 #include "content/public/browser/browser_thread.h"
43 #include "content/public/browser/geolocation_provider.h"
44 #include "content/public/test/test_browser_thread.h"
45 #include "content/public/test/test_utils.h"
46 #include "policy/proto/device_management_backend.pb.h"
47 #include "storage/browser/fileapi/external_mount_points.h"
48 #include "storage/browser/fileapi/mount_points.h"
49 #include "storage/common/fileapi/file_system_mount_option.h"
50 #include "storage/common/fileapi/file_system_types.h"
51 #include "testing/gmock/include/gmock/gmock.h"
52 #include "testing/gtest/include/gtest/gtest.h"
53 #include "third_party/cros_system_api/dbus/service_constants.h"
55 using ::testing::Return
;
56 using ::testing::ReturnRef
;
58 using base::TimeDelta
;
59 using chromeos::disks::DiskMountManager
;
61 namespace em
= enterprise_management
;
65 const int64 kMillisecondsPerDay
= Time::kMicrosecondsPerDay
/ 1000;
66 const char kKioskAccountId
[] = "kiosk_user@localhost";
67 const char kKioskAppId
[] = "kiosk_app_id";
68 const char kExternalMountPoint
[] = "/a/b/c";
70 scoped_ptr
<content::Geoposition
> mock_position_to_return_next
;
72 void SetMockPositionToReturnNext(const content::Geoposition
&position
) {
73 mock_position_to_return_next
.reset(new content::Geoposition(position
));
76 void MockPositionUpdateRequester(
77 const content::GeolocationProvider::LocationUpdateCallback
& callback
) {
78 if (!mock_position_to_return_next
.get())
81 // If the fix is invalid, the DeviceStatusCollector will immediately request
82 // another update when it receives the callback. This is desirable and safe in
83 // real life where geolocation updates arrive asynchronously. In this testing
84 // harness, the callback is invoked synchronously upon request, leading to a
85 // request-callback loop. The loop is broken by returning the mock position
87 scoped_ptr
<content::Geoposition
> position(
88 mock_position_to_return_next
.release());
89 callback
.Run(*position
);
92 class TestingDeviceStatusCollector
: public policy::DeviceStatusCollector
{
94 TestingDeviceStatusCollector(
95 PrefService
* local_state
,
96 chromeos::system::StatisticsProvider
* provider
,
97 const policy::DeviceStatusCollector::LocationUpdateRequester
&
98 location_update_requester
,
99 const policy::DeviceStatusCollector::VolumeInfoFetcher
&
101 const policy::DeviceStatusCollector::CPUStatisticsFetcher
& cpu_fetcher
)
102 : policy::DeviceStatusCollector(local_state
,
104 location_update_requester
,
107 // Set the baseline time to a fixed value (1 AM) to prevent test flakiness
108 // due to a single activity period spanning two days.
109 SetBaselineTime(Time::Now().LocalMidnight() + TimeDelta::FromHours(1));
112 void Simulate(ui::IdleState
* states
, int len
) {
113 for (int i
= 0; i
< len
; i
++)
114 IdleStateCallback(states
[i
]);
117 void set_max_stored_past_activity_days(unsigned int value
) {
118 max_stored_past_activity_days_
= value
;
121 void set_max_stored_future_activity_days(unsigned int value
) {
122 max_stored_future_activity_days_
= value
;
125 // Reset the baseline time.
126 void SetBaselineTime(Time time
) {
127 baseline_time_
= time
;
128 baseline_offset_periods_
= 0;
131 void set_kiosk_account(scoped_ptr
<policy::DeviceLocalAccount
> account
) {
132 kiosk_account_
= account
.Pass();
135 scoped_ptr
<policy::DeviceLocalAccount
>
136 GetAutoLaunchedKioskSessionInfo() override
{
138 return make_scoped_ptr(new policy::DeviceLocalAccount(*kiosk_account_
));
139 return scoped_ptr
<policy::DeviceLocalAccount
>();
142 std::string
GetAppVersion(const std::string
& app_id
) override
{
143 // Just return the app_id as the version - this makes it easy for tests
144 // to confirm that the correct app's version was requested.
148 void RefreshSampleResourceUsage() {
149 SampleHardwareStatus();
150 content::BrowserThread::GetBlockingPool()->FlushForTesting();
154 void CheckIdleState() override
{
155 // This should never be called in testing, as it results in a dbus call.
159 // Each time this is called, returns a time that is a fixed increment
160 // later than the previous time.
161 Time
GetCurrentTime() override
{
162 int poll_interval
= policy::DeviceStatusCollector::kIdlePollIntervalSeconds
;
163 return baseline_time_
+
164 TimeDelta::FromSeconds(poll_interval
* baseline_offset_periods_
++);
168 // Baseline time for the fake times returned from GetCurrentTime().
171 // The number of simulated periods since the baseline time.
172 int baseline_offset_periods_
;
174 scoped_ptr
<policy::DeviceLocalAccount
> kiosk_account_
;
177 // Return the total number of active milliseconds contained in a device
179 int64
GetActiveMilliseconds(em::DeviceStatusReportRequest
& status
) {
180 int64 active_milliseconds
= 0;
181 for (int i
= 0; i
< status
.active_period_size(); i
++) {
182 active_milliseconds
+= status
.active_period(i
).active_duration();
184 return active_milliseconds
;
187 // Mock CPUStatisticsFetcher used to return an empty set of statistics.
188 std::string
GetEmptyCPUStatistics() {
189 return std::string();
192 std::string
GetFakeCPUStatistics(const std::string
& fake
) {
196 // Mock VolumeInfoFetcher used to return empty VolumeInfo, to avoid warnings
197 // and test slowdowns from trying to fetch information about non-existent
199 std::vector
<em::VolumeInfo
> GetEmptyVolumeInfo(
200 const std::vector
<std::string
>& mount_points
) {
201 return std::vector
<em::VolumeInfo
>();
204 std::vector
<em::VolumeInfo
> GetFakeVolumeInfo(
205 const std::vector
<em::VolumeInfo
>& volume_info
,
206 const std::vector
<std::string
>& mount_points
) {
207 EXPECT_EQ(volume_info
.size(), mount_points
.size());
208 // Make sure there's a matching mount point for every volume info.
209 for (const em::VolumeInfo
& info
: volume_info
) {
211 for (const std::string
& mount_point
: mount_points
) {
212 if (info
.volume_id() == mount_point
) {
217 EXPECT_TRUE(found
) << "Could not find matching mount point for "
227 // Though it is a unit test, this test is linked with browser_tests so that it
228 // runs in a separate process. The intention is to avoid overriding the timezone
229 // environment variable for other tests.
230 class DeviceStatusCollectorTest
: public testing::Test
{
232 DeviceStatusCollectorTest()
233 : ui_thread_(content::BrowserThread::UI
, &message_loop_
),
234 file_thread_(content::BrowserThread::FILE, &message_loop_
),
235 io_thread_(content::BrowserThread::IO
, &message_loop_
),
236 install_attributes_("managed.com",
239 DEVICE_MODE_ENTERPRISE
),
240 user_manager_(new chromeos::MockUserManager()),
241 user_manager_enabler_(user_manager_
),
242 fake_device_local_account_(
243 policy::DeviceLocalAccount::TYPE_KIOSK_APP
,
246 std::string() /* kiosk_app_update_url */) {
247 // Run this test with a well-known timezone so that Time::LocalMidnight()
248 // returns the same values on all machines.
249 scoped_ptr
<base::Environment
> env(base::Environment::Create());
250 env
->SetVar("TZ", "UTC");
252 // Initialize our mock mounted disk volumes.
253 scoped_ptr
<chromeos::disks::MockDiskMountManager
> mock_disk_mount_manager
=
254 make_scoped_ptr(new chromeos::disks::MockDiskMountManager());
255 AddMountPoint("/mount/volume1");
256 AddMountPoint("/mount/volume2");
257 EXPECT_CALL(*mock_disk_mount_manager
, mount_points())
258 .WillRepeatedly(ReturnRef(mount_point_map_
));
260 // Setup a fake file system that should show up in mount points.
261 storage::ExternalMountPoints::GetSystemInstance()->RevokeAllFileSystems();
262 storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
263 "c", storage::kFileSystemTypeNativeLocal
,
264 storage::FileSystemMountOption(),
265 base::FilePath(FILE_PATH_LITERAL(kExternalMountPoint
)));
267 // Just verify that we are properly setting the mount points.
268 std::vector
<storage::MountPoints::MountPointInfo
> external_mount_points
;
269 storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo(
270 &external_mount_points
);
271 EXPECT_FALSE(external_mount_points
.empty());
273 // DiskMountManager takes ownership of the MockDiskMountManager.
274 DiskMountManager::InitializeForTesting(mock_disk_mount_manager
.release());
275 TestingDeviceStatusCollector::RegisterPrefs(prefs_
.registry());
277 // Remove the real DeviceSettingsProvider and replace it with a stub.
278 cros_settings_
= chromeos::CrosSettings::Get();
279 device_settings_provider_
=
280 cros_settings_
->GetProvider(chromeos::kReportDeviceVersionInfo
);
281 EXPECT_TRUE(device_settings_provider_
!= NULL
);
283 cros_settings_
->RemoveSettingsProvider(device_settings_provider_
));
284 cros_settings_
->AddSettingsProvider(&stub_settings_provider_
);
286 RestartStatusCollector(base::Bind(&GetEmptyVolumeInfo
),
287 base::Bind(&GetEmptyCPUStatistics
));
290 void AddMountPoint(const std::string
& mount_point
) {
291 mount_point_map_
.insert(DiskMountManager::MountPointMap::value_type(
293 DiskMountManager::MountPointInfo(
294 mount_point
, mount_point
, chromeos::MOUNT_TYPE_DEVICE
,
295 chromeos::disks::MOUNT_CONDITION_NONE
)));
298 ~DeviceStatusCollectorTest() override
{
299 // Finish pending tasks.
300 content::BrowserThread::GetBlockingPool()->FlushForTesting();
301 message_loop_
.RunUntilIdle();
302 storage::ExternalMountPoints::GetSystemInstance()->RevokeAllFileSystems();
303 DiskMountManager::Shutdown();
305 // Restore the real DeviceSettingsProvider.
307 cros_settings_
->RemoveSettingsProvider(&stub_settings_provider_
));
308 cros_settings_
->AddSettingsProvider(device_settings_provider_
);
311 void SetUp() override
{
312 // Disable network interface reporting since it requires additional setup.
313 cros_settings_
->SetBoolean(chromeos::kReportDeviceNetworkInterfaces
, false);
316 void RestartStatusCollector(
317 const policy::DeviceStatusCollector::VolumeInfoFetcher
& volume_info
,
318 const policy::DeviceStatusCollector::CPUStatisticsFetcher
& cpu_stats
) {
319 policy::DeviceStatusCollector::LocationUpdateRequester callback
=
320 base::Bind(&MockPositionUpdateRequester
);
321 std::vector
<em::VolumeInfo
> expected_volume_info
;
322 status_collector_
.reset(new TestingDeviceStatusCollector(
323 &prefs_
, &fake_statistics_provider_
, callback
, volume_info
, cpu_stats
));
328 status_collector_
->GetDeviceStatus(&status_
);
331 void CheckThatNoLocationIsReported() {
333 EXPECT_FALSE(status_
.has_device_location());
336 void CheckThatAValidLocationIsReported() {
337 // Checks that a location is being reported which matches the valid fix
338 // set using SetMockPositionToReturnNext().
340 EXPECT_TRUE(status_
.has_device_location());
341 em::DeviceLocation location
= status_
.device_location();
342 if (location
.has_error_code())
343 EXPECT_EQ(em::DeviceLocation::ERROR_CODE_NONE
, location
.error_code());
344 EXPECT_TRUE(location
.has_latitude());
345 EXPECT_TRUE(location
.has_longitude());
346 EXPECT_TRUE(location
.has_accuracy());
347 EXPECT_TRUE(location
.has_timestamp());
348 EXPECT_FALSE(location
.has_altitude());
349 EXPECT_FALSE(location
.has_altitude_accuracy());
350 EXPECT_FALSE(location
.has_heading());
351 EXPECT_FALSE(location
.has_speed());
352 EXPECT_FALSE(location
.has_error_message());
353 EXPECT_DOUBLE_EQ(4.3, location
.latitude());
354 EXPECT_DOUBLE_EQ(-7.8, location
.longitude());
355 EXPECT_DOUBLE_EQ(3., location
.accuracy());
356 // Check that the timestamp is not older than ten minutes.
357 EXPECT_TRUE(Time::Now() - Time::FromDoubleT(location
.timestamp() / 1000.) <
358 TimeDelta::FromMinutes(10));
361 void CheckThatALocationErrorIsReported() {
363 EXPECT_TRUE(status_
.has_device_location());
364 em::DeviceLocation location
= status_
.device_location();
365 EXPECT_TRUE(location
.has_error_code());
366 EXPECT_EQ(em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE
,
367 location
.error_code());
370 void MockRunningKioskApp(const DeviceLocalAccount
& account
) {
371 std::vector
<DeviceLocalAccount
> accounts
;
372 accounts
.push_back(account
);
373 SetDeviceLocalAccounts(cros_settings_
, accounts
);
374 user_manager_
->CreateKioskAppUser(account
.user_id
);
375 EXPECT_CALL(*user_manager_
, IsLoggedInAsKioskApp()).WillRepeatedly(
380 // Convenience method.
381 int64
ActivePeriodMilliseconds() {
382 return policy::DeviceStatusCollector::kIdlePollIntervalSeconds
* 1000;
385 // Since this is a unit test running in browser_tests we must do additional
386 // unit test setup and make a TestingBrowserProcess. Must be first member.
387 TestingBrowserProcessInitializer initializer_
;
388 base::MessageLoopForUI message_loop_
;
389 content::TestBrowserThread ui_thread_
;
390 content::TestBrowserThread file_thread_
;
391 content::TestBrowserThread io_thread_
;
393 ScopedStubEnterpriseInstallAttributes install_attributes_
;
394 TestingPrefServiceSimple prefs_
;
395 chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_
;
396 DiskMountManager::MountPointMap mount_point_map_
;
397 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_
;
398 chromeos::ScopedTestCrosSettings test_cros_settings_
;
399 chromeos::CrosSettings
* cros_settings_
;
400 chromeos::CrosSettingsProvider
* device_settings_provider_
;
401 chromeos::StubCrosSettingsProvider stub_settings_provider_
;
402 chromeos::MockUserManager
* user_manager_
;
403 chromeos::ScopedUserManagerEnabler user_manager_enabler_
;
404 em::DeviceStatusReportRequest status_
;
405 scoped_ptr
<TestingDeviceStatusCollector
> status_collector_
;
406 const policy::DeviceLocalAccount fake_device_local_account_
;
409 TEST_F(DeviceStatusCollectorTest
, AllIdle
) {
410 ui::IdleState test_states
[] = {
415 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
417 // Test reporting with no data.
419 EXPECT_EQ(0, status_
.active_period_size());
420 EXPECT_EQ(0, GetActiveMilliseconds(status_
));
422 // Test reporting with a single idle sample.
423 status_collector_
->Simulate(test_states
, 1);
425 EXPECT_EQ(0, status_
.active_period_size());
426 EXPECT_EQ(0, GetActiveMilliseconds(status_
));
428 // Test reporting with multiple consecutive idle samples.
429 status_collector_
->Simulate(test_states
,
430 sizeof(test_states
) / sizeof(ui::IdleState
));
432 EXPECT_EQ(0, status_
.active_period_size());
433 EXPECT_EQ(0, GetActiveMilliseconds(status_
));
436 TEST_F(DeviceStatusCollectorTest
, AllActive
) {
437 ui::IdleState test_states
[] = {
438 ui::IDLE_STATE_ACTIVE
,
439 ui::IDLE_STATE_ACTIVE
,
440 ui::IDLE_STATE_ACTIVE
442 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
444 // Test a single active sample.
445 status_collector_
->Simulate(test_states
, 1);
447 EXPECT_EQ(1, status_
.active_period_size());
448 EXPECT_EQ(1 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
449 status_
.clear_active_period(); // Clear the result protobuf.
451 // Test multiple consecutive active samples.
452 status_collector_
->Simulate(test_states
,
453 sizeof(test_states
) / sizeof(ui::IdleState
));
455 EXPECT_EQ(1, status_
.active_period_size());
456 EXPECT_EQ(4 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
459 TEST_F(DeviceStatusCollectorTest
, MixedStates
) {
460 ui::IdleState test_states
[] = {
461 ui::IDLE_STATE_ACTIVE
,
463 ui::IDLE_STATE_ACTIVE
,
464 ui::IDLE_STATE_ACTIVE
,
467 ui::IDLE_STATE_ACTIVE
469 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
470 status_collector_
->Simulate(test_states
,
471 sizeof(test_states
) / sizeof(ui::IdleState
));
473 EXPECT_EQ(4 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
476 TEST_F(DeviceStatusCollectorTest
, StateKeptInPref
) {
477 ui::IdleState test_states
[] = {
478 ui::IDLE_STATE_ACTIVE
,
480 ui::IDLE_STATE_ACTIVE
,
481 ui::IDLE_STATE_ACTIVE
,
485 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
486 status_collector_
->Simulate(test_states
,
487 sizeof(test_states
) / sizeof(ui::IdleState
));
489 // Process the list a second time after restarting the collector. It should be
490 // able to count the active periods found by the original collector, because
491 // the results are stored in a pref.
492 RestartStatusCollector(base::Bind(&GetEmptyVolumeInfo
),
493 base::Bind(&GetEmptyCPUStatistics
));
494 status_collector_
->Simulate(test_states
,
495 sizeof(test_states
) / sizeof(ui::IdleState
));
498 EXPECT_EQ(6 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
501 TEST_F(DeviceStatusCollectorTest
, Times
) {
502 ui::IdleState test_states
[] = {
503 ui::IDLE_STATE_ACTIVE
,
505 ui::IDLE_STATE_ACTIVE
,
506 ui::IDLE_STATE_ACTIVE
,
510 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
511 status_collector_
->Simulate(test_states
,
512 sizeof(test_states
) / sizeof(ui::IdleState
));
514 EXPECT_EQ(3 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
517 TEST_F(DeviceStatusCollectorTest
, MaxStoredPeriods
) {
518 ui::IdleState test_states
[] = {
519 ui::IDLE_STATE_ACTIVE
,
522 const int kMaxDays
= 10;
524 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
525 status_collector_
->set_max_stored_past_activity_days(kMaxDays
- 1);
526 status_collector_
->set_max_stored_future_activity_days(1);
527 Time baseline
= Time::Now().LocalMidnight();
529 // Simulate 12 active periods.
530 for (int i
= 0; i
< kMaxDays
+ 2; i
++) {
531 status_collector_
->Simulate(test_states
,
532 sizeof(test_states
) / sizeof(ui::IdleState
));
533 // Advance the simulated clock by a day.
534 baseline
+= TimeDelta::FromDays(1);
535 status_collector_
->SetBaselineTime(baseline
);
538 // Check that we don't exceed the max number of periods.
540 EXPECT_EQ(kMaxDays
- 1, status_
.active_period_size());
542 // Simulate some future times.
543 for (int i
= 0; i
< kMaxDays
+ 2; i
++) {
544 status_collector_
->Simulate(test_states
,
545 sizeof(test_states
) / sizeof(ui::IdleState
));
546 // Advance the simulated clock by a day.
547 baseline
+= TimeDelta::FromDays(1);
548 status_collector_
->SetBaselineTime(baseline
);
550 // Set the clock back so the previous simulated times are in the future.
551 baseline
-= TimeDelta::FromDays(20);
552 status_collector_
->SetBaselineTime(baseline
);
554 // Collect one more data point to trigger pruning.
555 status_collector_
->Simulate(test_states
, 1);
557 // Check that we don't exceed the max number of periods.
558 status_
.clear_active_period();
560 EXPECT_LT(status_
.active_period_size(), kMaxDays
);
563 TEST_F(DeviceStatusCollectorTest
, ActivityTimesEnabledByDefault
) {
564 // Device activity times should be reported by default.
565 ui::IdleState test_states
[] = {
566 ui::IDLE_STATE_ACTIVE
,
567 ui::IDLE_STATE_ACTIVE
,
568 ui::IDLE_STATE_ACTIVE
570 status_collector_
->Simulate(test_states
,
571 sizeof(test_states
) / sizeof(ui::IdleState
));
573 EXPECT_EQ(1, status_
.active_period_size());
574 EXPECT_EQ(3 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
577 TEST_F(DeviceStatusCollectorTest
, ActivityTimesOff
) {
578 // Device activity times should not be reported if explicitly disabled.
579 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, false);
581 ui::IdleState test_states
[] = {
582 ui::IDLE_STATE_ACTIVE
,
583 ui::IDLE_STATE_ACTIVE
,
584 ui::IDLE_STATE_ACTIVE
586 status_collector_
->Simulate(test_states
,
587 sizeof(test_states
) / sizeof(ui::IdleState
));
589 EXPECT_EQ(0, status_
.active_period_size());
590 EXPECT_EQ(0, GetActiveMilliseconds(status_
));
593 TEST_F(DeviceStatusCollectorTest
, ActivityCrossingMidnight
) {
594 ui::IdleState test_states
[] = {
595 ui::IDLE_STATE_ACTIVE
597 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
599 // Set the baseline time to 10 seconds after midnight.
600 status_collector_
->SetBaselineTime(
601 Time::Now().LocalMidnight() + TimeDelta::FromSeconds(10));
603 status_collector_
->Simulate(test_states
, 1);
605 ASSERT_EQ(2, status_
.active_period_size());
607 em::ActiveTimePeriod period0
= status_
.active_period(0);
608 em::ActiveTimePeriod period1
= status_
.active_period(1);
609 EXPECT_EQ(ActivePeriodMilliseconds() - 10000, period0
.active_duration());
610 EXPECT_EQ(10000, period1
.active_duration());
612 em::TimePeriod time_period0
= period0
.time_period();
613 em::TimePeriod time_period1
= period1
.time_period();
615 EXPECT_EQ(time_period0
.end_timestamp(), time_period1
.start_timestamp());
617 // Ensure that the start and end times for the period are a day apart.
618 EXPECT_EQ(time_period0
.end_timestamp() - time_period0
.start_timestamp(),
619 kMillisecondsPerDay
);
620 EXPECT_EQ(time_period1
.end_timestamp() - time_period1
.start_timestamp(),
621 kMillisecondsPerDay
);
624 TEST_F(DeviceStatusCollectorTest
, ActivityTimesKeptUntilSubmittedSuccessfully
) {
625 ui::IdleState test_states
[] = {
626 ui::IDLE_STATE_ACTIVE
,
627 ui::IDLE_STATE_ACTIVE
,
629 cros_settings_
->SetBoolean(chromeos::kReportDeviceActivityTimes
, true);
631 status_collector_
->Simulate(test_states
, 2);
633 EXPECT_EQ(2 * ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
634 em::DeviceStatusReportRequest
first_status(status_
);
636 // The collector returns the same status again.
638 EXPECT_EQ(first_status
.SerializeAsString(), status_
.SerializeAsString());
640 // After indicating a successful submit, the submitted status gets cleared,
641 // but what got collected meanwhile sticks around.
642 status_collector_
->Simulate(test_states
, 1);
643 status_collector_
->OnSubmittedSuccessfully();
645 EXPECT_EQ(ActivePeriodMilliseconds(), GetActiveMilliseconds(status_
));
648 TEST_F(DeviceStatusCollectorTest
, DevSwitchBootMode
) {
649 // Test that boot mode data is reported by default.
650 fake_statistics_provider_
.SetMachineStatistic(
651 chromeos::system::kDevSwitchBootKey
,
652 chromeos::system::kDevSwitchBootValueVerified
);
654 EXPECT_EQ("Verified", status_
.boot_mode());
656 // Test that boot mode data is not reported if the pref turned off.
657 cros_settings_
->SetBoolean(chromeos::kReportDeviceBootMode
, false);
660 EXPECT_FALSE(status_
.has_boot_mode());
662 // Turn the pref on, and check that the status is reported iff the
663 // statistics provider returns valid data.
664 cros_settings_
->SetBoolean(chromeos::kReportDeviceBootMode
, true);
666 fake_statistics_provider_
.SetMachineStatistic(
667 chromeos::system::kDevSwitchBootKey
, "(error)");
669 EXPECT_FALSE(status_
.has_boot_mode());
671 fake_statistics_provider_
.SetMachineStatistic(
672 chromeos::system::kDevSwitchBootKey
, " ");
674 EXPECT_FALSE(status_
.has_boot_mode());
676 fake_statistics_provider_
.SetMachineStatistic(
677 chromeos::system::kDevSwitchBootKey
,
678 chromeos::system::kDevSwitchBootValueVerified
);
680 EXPECT_EQ("Verified", status_
.boot_mode());
682 fake_statistics_provider_
.SetMachineStatistic(
683 chromeos::system::kDevSwitchBootKey
,
684 chromeos::system::kDevSwitchBootValueDev
);
686 EXPECT_EQ("Dev", status_
.boot_mode());
689 TEST_F(DeviceStatusCollectorTest
, VersionInfo
) {
690 // Expect the version info to be reported by default.
692 EXPECT_TRUE(status_
.has_browser_version());
693 EXPECT_TRUE(status_
.has_os_version());
694 EXPECT_TRUE(status_
.has_firmware_version());
696 // When the pref to collect this data is not enabled, expect that none of
697 // the fields are present in the protobuf.
698 cros_settings_
->SetBoolean(chromeos::kReportDeviceVersionInfo
, false);
700 EXPECT_FALSE(status_
.has_browser_version());
701 EXPECT_FALSE(status_
.has_os_version());
702 EXPECT_FALSE(status_
.has_firmware_version());
704 cros_settings_
->SetBoolean(chromeos::kReportDeviceVersionInfo
, true);
706 EXPECT_TRUE(status_
.has_browser_version());
707 EXPECT_TRUE(status_
.has_os_version());
708 EXPECT_TRUE(status_
.has_firmware_version());
710 // Check that the browser version is not empty. OS version & firmware
711 // don't have any reasonable values inside the unit test, so those
713 EXPECT_NE("", status_
.browser_version());
716 TEST_F(DeviceStatusCollectorTest
, Location
) {
717 content::Geoposition valid_fix
;
718 valid_fix
.latitude
= 4.3;
719 valid_fix
.longitude
= -7.8;
720 valid_fix
.accuracy
= 3.;
721 valid_fix
.timestamp
= Time::Now();
723 content::Geoposition invalid_fix
;
724 invalid_fix
.error_code
=
725 content::Geoposition::ERROR_CODE_POSITION_UNAVAILABLE
;
726 invalid_fix
.timestamp
= Time::Now();
728 // Check that when device location reporting is disabled, no location is
730 SetMockPositionToReturnNext(valid_fix
);
731 CheckThatNoLocationIsReported();
733 // Check that when device location reporting is enabled and a valid fix is
734 // available, the location is reported and is stored in local state.
735 SetMockPositionToReturnNext(valid_fix
);
736 cros_settings_
->SetBoolean(chromeos::kReportDeviceLocation
, true);
737 EXPECT_FALSE(prefs_
.GetDictionary(prefs::kDeviceLocation
)->empty());
738 CheckThatAValidLocationIsReported();
740 // Restart the status collector. Check that the last known location has been
741 // retrieved from local state without requesting a geolocation update.
742 SetMockPositionToReturnNext(valid_fix
);
743 RestartStatusCollector(base::Bind(&GetEmptyVolumeInfo
),
744 base::Bind(&GetEmptyCPUStatistics
));
745 CheckThatAValidLocationIsReported();
746 EXPECT_TRUE(mock_position_to_return_next
.get());
748 // Check that after disabling location reporting again, the last known
749 // location has been cleared from local state and is no longer reported.
750 SetMockPositionToReturnNext(valid_fix
);
751 cros_settings_
->SetBoolean(chromeos::kReportDeviceLocation
, false);
752 // Allow the new pref to propagate to the status collector.
753 message_loop_
.RunUntilIdle();
754 EXPECT_TRUE(prefs_
.GetDictionary(prefs::kDeviceLocation
)->empty());
755 CheckThatNoLocationIsReported();
757 // Check that after enabling location reporting again, an error is reported
758 // if no valid fix is available.
759 SetMockPositionToReturnNext(invalid_fix
);
760 cros_settings_
->SetBoolean(chromeos::kReportDeviceLocation
, true);
761 // Allow the new pref to propagate to the status collector.
762 message_loop_
.RunUntilIdle();
763 CheckThatALocationErrorIsReported();
766 TEST_F(DeviceStatusCollectorTest
, ReportUsers
) {
767 user_manager_
->CreatePublicAccountUser("public@localhost");
768 user_manager_
->AddUser("user0@managed.com");
769 user_manager_
->AddUser("user1@managed.com");
770 user_manager_
->AddUser("user2@managed.com");
771 user_manager_
->AddUser("user3@unmanaged.com");
772 user_manager_
->AddUser("user4@managed.com");
773 user_manager_
->AddUser("user5@managed.com");
775 // Verify that users are reported by default.
777 EXPECT_EQ(6, status_
.user_size());
779 // Verify that users are reported after enabling the setting.
780 cros_settings_
->SetBoolean(chromeos::kReportDeviceUsers
, true);
782 EXPECT_EQ(6, status_
.user_size());
783 EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED
, status_
.user(0).type());
784 EXPECT_EQ("user0@managed.com", status_
.user(0).email());
785 EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED
, status_
.user(1).type());
786 EXPECT_EQ("user1@managed.com", status_
.user(1).email());
787 EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED
, status_
.user(2).type());
788 EXPECT_EQ("user2@managed.com", status_
.user(2).email());
789 EXPECT_EQ(em::DeviceUser::USER_TYPE_UNMANAGED
, status_
.user(3).type());
790 EXPECT_FALSE(status_
.user(3).has_email());
791 EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED
, status_
.user(4).type());
792 EXPECT_EQ("user4@managed.com", status_
.user(4).email());
793 EXPECT_EQ(em::DeviceUser::USER_TYPE_MANAGED
, status_
.user(5).type());
794 EXPECT_EQ("user5@managed.com", status_
.user(5).email());
796 // Verify that users are no longer reported if setting is disabled.
797 cros_settings_
->SetBoolean(chromeos::kReportDeviceUsers
, false);
799 EXPECT_EQ(0, status_
.user_size());
802 TEST_F(DeviceStatusCollectorTest
, TestVolumeInfo
) {
803 std::vector
<std::string
> expected_mount_points
;
804 std::vector
<em::VolumeInfo
> expected_volume_info
;
806 for (const auto& mount_info
:
807 DiskMountManager::GetInstance()->mount_points()) {
808 expected_mount_points
.push_back(mount_info
.first
);
810 expected_mount_points
.push_back(kExternalMountPoint
);
812 for (const std::string
& mount_point
: expected_mount_points
) {
814 info
.set_volume_id(mount_point
);
815 // Just put unique numbers in for storage_total/free.
816 info
.set_storage_total(size
++);
817 info
.set_storage_free(size
++);
818 expected_volume_info
.push_back(info
);
820 EXPECT_FALSE(expected_volume_info
.empty());
822 RestartStatusCollector(base::Bind(&GetFakeVolumeInfo
, expected_volume_info
),
823 base::Bind(&GetEmptyCPUStatistics
));
824 message_loop_
.RunUntilIdle();
827 EXPECT_EQ(expected_mount_points
.size(),
828 static_cast<size_t>(status_
.volume_info_size()));
830 // Walk the returned VolumeInfo to make sure it matches.
831 for (const em::VolumeInfo
& expected_info
: expected_volume_info
) {
833 for (const em::VolumeInfo
& info
: status_
.volume_info()) {
834 if (info
.volume_id() == expected_info
.volume_id()) {
835 EXPECT_EQ(expected_info
.storage_total(), info
.storage_total());
836 EXPECT_EQ(expected_info
.storage_free(), info
.storage_free());
841 EXPECT_TRUE(found
) << "No matching VolumeInfo for "
842 << expected_info
.volume_id();
845 // Now turn off hardware status reporting - should have no data.
846 cros_settings_
->SetBoolean(chromeos::kReportDeviceHardwareStatus
, false);
848 EXPECT_EQ(0, status_
.volume_info_size());
851 TEST_F(DeviceStatusCollectorTest
, TestAvailableMemory
) {
852 // Refresh our samples. Sample more than kMaxHardwareSamples times to
853 // make sure that the code correctly caps the number of cached samples.
854 for (int i
= 0; i
< static_cast<int>(
855 DeviceStatusCollector::kMaxResourceUsageSamples
+ 1);
857 status_collector_
->RefreshSampleResourceUsage();
858 message_loop_
.RunUntilIdle();
861 EXPECT_EQ(static_cast<int>(DeviceStatusCollector::kMaxResourceUsageSamples
),
862 status_
.system_ram_free().size());
863 EXPECT_TRUE(status_
.has_system_ram_total());
864 // No good way to inject specific test values for available system RAM, so
865 // just make sure it's > 0.
866 EXPECT_GT(status_
.system_ram_total(), 0);
869 TEST_F(DeviceStatusCollectorTest
, TestCPUSamples
) {
870 // Mock 100% CPU usage.
871 std::string
full_cpu_usage("cpu 500 0 500 0 0 0 0");
872 RestartStatusCollector(base::Bind(&GetEmptyVolumeInfo
),
873 base::Bind(&GetFakeCPUStatistics
, full_cpu_usage
));
874 message_loop_
.RunUntilIdle();
876 ASSERT_EQ(1, status_
.cpu_utilization_pct().size());
877 EXPECT_EQ(100, status_
.cpu_utilization_pct(0));
879 // Now sample CPU usage again (active usage counters will not increase
880 // so should show 0% cpu usage).
881 status_collector_
->RefreshSampleResourceUsage();
882 message_loop_
.RunUntilIdle();
884 ASSERT_EQ(2, status_
.cpu_utilization_pct().size());
885 EXPECT_EQ(0, status_
.cpu_utilization_pct(1));
887 // Now store a bunch of 0% cpu usage and make sure we cap the max number of
890 i
< static_cast<int>(DeviceStatusCollector::kMaxResourceUsageSamples
);
892 status_collector_
->RefreshSampleResourceUsage();
893 message_loop_
.RunUntilIdle();
897 // Should not be more than kMaxResourceUsageSamples, and they should all show
899 EXPECT_EQ(static_cast<int>(DeviceStatusCollector::kMaxResourceUsageSamples
),
900 status_
.cpu_utilization_pct().size());
901 for (const auto utilization
: status_
.cpu_utilization_pct())
902 EXPECT_EQ(0, utilization
);
904 // Turning off hardware reporting should not report CPU utilization.
905 cros_settings_
->SetBoolean(chromeos::kReportDeviceHardwareStatus
, false);
907 EXPECT_EQ(0, status_
.cpu_utilization_pct().size());
910 TEST_F(DeviceStatusCollectorTest
, NoSessionStatusIfNotKioskMode
) {
911 // Should not report session status if we don't have an active kiosk app.
912 cros_settings_
->SetBoolean(chromeos::kReportDeviceSessionStatus
, true);
913 em::SessionStatusReportRequest session_status
;
914 EXPECT_FALSE(status_collector_
->GetDeviceSessionStatus(&session_status
));
917 TEST_F(DeviceStatusCollectorTest
, NoSessionStatusIfSessionReportingDisabled
) {
918 // Should not report session status if session status reporting is disabled.
919 cros_settings_
->SetBoolean(chromeos::kReportDeviceSessionStatus
, false);
920 status_collector_
->set_kiosk_account(make_scoped_ptr(
921 new policy::DeviceLocalAccount(fake_device_local_account_
)).Pass());
922 // Set up a device-local account for single-app kiosk mode.
923 MockRunningKioskApp(fake_device_local_account_
);
925 em::SessionStatusReportRequest session_status
;
926 EXPECT_FALSE(status_collector_
->GetDeviceSessionStatus(&session_status
));
929 TEST_F(DeviceStatusCollectorTest
, ReportSessionStatus
) {
930 cros_settings_
->SetBoolean(chromeos::kReportDeviceSessionStatus
, true);
931 status_collector_
->set_kiosk_account(make_scoped_ptr(
932 new policy::DeviceLocalAccount(fake_device_local_account_
)).Pass());
934 // Set up a device-local account for single-app kiosk mode.
935 MockRunningKioskApp(fake_device_local_account_
);
937 em::SessionStatusReportRequest session_status
;
938 EXPECT_TRUE(status_collector_
->GetDeviceSessionStatus(&session_status
));
939 ASSERT_EQ(1, session_status
.installed_apps_size());
940 EXPECT_EQ(kKioskAccountId
, session_status
.device_local_account_id());
941 const em::AppStatus app
= session_status
.installed_apps(0);
942 EXPECT_EQ(kKioskAppId
, app
.app_id());
943 // Test code just sets the version to the app ID.
944 EXPECT_EQ(kKioskAppId
, app
.extension_version());
945 EXPECT_FALSE(app
.has_status());
946 EXPECT_FALSE(app
.has_error());
949 // Fake device state.
950 struct FakeDeviceData
{
951 const char* device_path
;
953 const char* object_path
;
954 const char* mac_address
;
957 int expected_type
; // proto enum type value, -1 for not present.
960 static const FakeDeviceData kFakeDevices
[] = {
961 { "/device/ethernet", shill::kTypeEthernet
, "ethernet",
962 "112233445566", "", "",
963 em::NetworkInterface::TYPE_ETHERNET
},
964 { "/device/cellular1", shill::kTypeCellular
, "cellular1",
965 "abcdefabcdef", "A10000009296F2", "",
966 em::NetworkInterface::TYPE_CELLULAR
},
967 { "/device/cellular2", shill::kTypeCellular
, "cellular2",
968 "abcdefabcdef", "", "352099001761481",
969 em::NetworkInterface::TYPE_CELLULAR
},
970 { "/device/wifi", shill::kTypeWifi
, "wifi",
971 "aabbccddeeff", "", "",
972 em::NetworkInterface::TYPE_WIFI
},
973 { "/device/bluetooth", shill::kTypeBluetooth
, "bluetooth",
975 em::NetworkInterface::TYPE_BLUETOOTH
},
976 { "/device/vpn", shill::kTypeVPN
, "vpn",
981 // Fake network state.
982 struct FakeNetworkState
{
984 const char* device_path
;
987 const char* connection_status
;
993 // List of fake networks - primarily used to make sure that signal strength
994 // and connection state are properly populated in status reports. Note that
995 // by convention shill will not report a signal strength of 0 for a visible
996 // network, so we use 1 below.
997 static const FakeNetworkState kFakeNetworks
[] = {
998 { "offline", "/device/wifi", shill::kTypeWifi
, 35,
999 shill::kStateOffline
, em::NetworkState::OFFLINE
, "", "" },
1000 { "ethernet", "/device/ethernet", shill::kTypeEthernet
, 0,
1001 shill::kStateOnline
, em::NetworkState::ONLINE
,
1002 "192.168.0.1", "8.8.8.8" },
1003 { "wifi", "/device/wifi", shill::kTypeWifi
, 23, shill::kStatePortal
,
1004 em::NetworkState::PORTAL
, "", "" },
1005 { "idle", "/device/cellular1", shill::kTypeCellular
, 0, shill::kStateIdle
,
1006 em::NetworkState::IDLE
, "", "" },
1007 { "carrier", "/device/cellular1", shill::kTypeCellular
, 0,
1008 shill::kStateCarrier
, em::NetworkState::CARRIER
, "", "" },
1009 { "association", "/device/cellular1", shill::kTypeCellular
, 0,
1010 shill::kStateAssociation
, em::NetworkState::ASSOCIATION
, "", "" },
1011 { "config", "/device/cellular1", shill::kTypeCellular
, 0,
1012 shill::kStateConfiguration
, em::NetworkState::CONFIGURATION
, "", "" },
1013 { "ready", "/device/cellular1", shill::kTypeCellular
, 0, shill::kStateReady
,
1014 em::NetworkState::READY
, "", "" },
1015 { "disconnect", "/device/wifi", shill::kTypeWifi
, 1,
1016 shill::kStateDisconnect
, em::NetworkState::DISCONNECT
, "", "" },
1017 { "failure", "/device/wifi", shill::kTypeWifi
, 1, shill::kStateFailure
,
1018 em::NetworkState::FAILURE
, "", "" },
1019 { "activation-failure", "/device/cellular1", shill::kTypeCellular
, 0,
1020 shill::kStateActivationFailure
, em::NetworkState::ACTIVATION_FAILURE
,
1022 { "unknown", "", shill::kTypeWifi
, 1, "unknown", em::NetworkState::UNKNOWN
,
1026 static const FakeNetworkState kUnconfiguredNetwork
= {
1027 "unconfigured", "/device/unconfigured", shill::kTypeWifi
, 35,
1028 shill::kStateOffline
, em::NetworkState::OFFLINE
, "", ""
1031 class DeviceStatusCollectorNetworkInterfacesTest
1032 : public DeviceStatusCollectorTest
{
1034 void SetUp() override
{
1035 chromeos::DBusThreadManager::Initialize();
1036 chromeos::NetworkHandler::Initialize();
1037 chromeos::ShillDeviceClient::TestInterface
* test_device_client
=
1038 chromeos::DBusThreadManager::Get()->GetShillDeviceClient()->
1040 test_device_client
->ClearDevices();
1041 for (size_t i
= 0; i
< arraysize(kFakeDevices
); ++i
) {
1042 const FakeDeviceData
& dev
= kFakeDevices
[i
];
1043 test_device_client
->AddDevice(dev
.device_path
, dev
.type
,
1045 if (*dev
.mac_address
) {
1046 test_device_client
->SetDeviceProperty(
1047 dev
.device_path
, shill::kAddressProperty
,
1048 base::StringValue(dev
.mac_address
));
1051 test_device_client
->SetDeviceProperty(
1052 dev
.device_path
, shill::kMeidProperty
,
1053 base::StringValue(dev
.meid
));
1056 test_device_client
->SetDeviceProperty(
1057 dev
.device_path
, shill::kImeiProperty
,
1058 base::StringValue(dev
.imei
));
1062 chromeos::ShillServiceClient::TestInterface
* service_client
=
1063 chromeos::DBusThreadManager::Get()->GetShillServiceClient()->
1065 service_client
->ClearServices();
1067 // Now add services for every fake network.
1068 for (const FakeNetworkState
& fake_network
: kFakeNetworks
) {
1069 // Shill forces non-visible networks to report a disconnected state.
1071 fake_network
.connection_status
!= shill::kStateDisconnect
;
1072 service_client
->AddService(
1073 fake_network
.name
, /* service_path */
1074 fake_network
.name
/* guid */,
1075 fake_network
.name
/* name */,
1076 fake_network
.type
/* type */,
1077 fake_network
.connection_status
,
1079 service_client
->SetServiceProperty(
1080 fake_network
.name
, shill::kSignalStrengthProperty
,
1081 base::FundamentalValue(fake_network
.signal_strength
));
1082 service_client
->SetServiceProperty(
1083 fake_network
.name
, shill::kDeviceProperty
,
1084 base::StringValue(fake_network
.device_path
));
1085 // Set the profile so this shows up as a configured network.
1086 service_client
->SetServiceProperty(
1087 fake_network
.name
, shill::kProfileProperty
,
1088 base::StringValue(fake_network
.name
));
1089 if (strlen(fake_network
.address
) > 0) {
1090 // Set the IP config.
1091 base::DictionaryValue ip_config_properties
;
1092 ip_config_properties
.SetStringWithoutPathExpansion(
1093 shill::kAddressProperty
, fake_network
.address
);
1094 ip_config_properties
.SetStringWithoutPathExpansion(
1095 shill::kGatewayProperty
, fake_network
.gateway
);
1096 chromeos::ShillIPConfigClient::TestInterface
* ip_config_test
=
1097 chromeos::DBusThreadManager::Get()->GetShillIPConfigClient()->
1099 const std::string kIPConfigPath
= "test_ip_config";
1100 ip_config_test
->AddIPConfig(kIPConfigPath
, ip_config_properties
);
1101 service_client
->SetServiceProperty(
1102 fake_network
.name
, shill::kIPConfigProperty
,
1103 base::StringValue(kIPConfigPath
));
1107 // Now add an unconfigured network - it should not show up in the
1108 // reported list of networks because it doesn't have a profile specified.
1109 service_client
->AddService(
1110 kUnconfiguredNetwork
.name
, /* service_path */
1111 kUnconfiguredNetwork
.name
/* guid */,
1112 kUnconfiguredNetwork
.name
/* name */,
1113 kUnconfiguredNetwork
.type
/* type */,
1114 kUnconfiguredNetwork
.connection_status
,
1115 true /* visible */);
1116 service_client
->SetServiceProperty(
1117 kUnconfiguredNetwork
.name
, shill::kSignalStrengthProperty
,
1118 base::FundamentalValue(kUnconfiguredNetwork
.signal_strength
));
1119 service_client
->SetServiceProperty(
1120 kUnconfiguredNetwork
.name
, shill::kDeviceProperty
,
1121 base::StringValue(kUnconfiguredNetwork
.device_path
));
1123 // Flush out pending state updates.
1124 base::RunLoop().RunUntilIdle();
1126 chromeos::NetworkStateHandler::NetworkStateList state_list
;
1127 chromeos::NetworkStateHandler
* network_state_handler
=
1128 chromeos::NetworkHandler::Get()->network_state_handler();
1129 network_state_handler
->GetNetworkListByType(
1130 chromeos::NetworkTypePattern::Default(),
1131 true, // configured_only
1132 false, // visible_only,
1133 0, // no limit to number of results
1135 ASSERT_EQ(arraysize(kFakeNetworks
), state_list
.size());
1138 void TearDown() override
{
1139 chromeos::NetworkHandler::Shutdown();
1140 chromeos::DBusThreadManager::Shutdown();
1144 TEST_F(DeviceStatusCollectorNetworkInterfacesTest
, NoNetworkStateIfNotKiosk
) {
1145 // If not in an active kiosk session, there should be network interfaces
1146 // reported, but no network state.
1148 EXPECT_LT(0, status_
.network_interface_size());
1149 EXPECT_EQ(0, status_
.network_state_size());
1152 TEST_F(DeviceStatusCollectorNetworkInterfacesTest
, NetworkInterfaces
) {
1153 // Mock that we are in kiosk mode so we report network state.
1154 status_collector_
->set_kiosk_account(make_scoped_ptr(
1155 new policy::DeviceLocalAccount(fake_device_local_account_
)).Pass());
1157 // Interfaces should be reported by default.
1159 EXPECT_LT(0, status_
.network_interface_size());
1160 EXPECT_LT(0, status_
.network_state_size());
1162 // No interfaces should be reported if the policy is off.
1163 cros_settings_
->SetBoolean(chromeos::kReportDeviceNetworkInterfaces
, false);
1165 EXPECT_EQ(0, status_
.network_interface_size());
1166 EXPECT_EQ(0, status_
.network_state_size());
1168 // Switch the policy on and verify the interface list is present.
1169 cros_settings_
->SetBoolean(chromeos::kReportDeviceNetworkInterfaces
, true);
1173 for (size_t i
= 0; i
< arraysize(kFakeDevices
); ++i
) {
1174 const FakeDeviceData
& dev
= kFakeDevices
[i
];
1175 if (dev
.expected_type
== -1)
1178 // Find the corresponding entry in reporting data.
1179 bool found_match
= false;
1180 google::protobuf::RepeatedPtrField
<em::NetworkInterface
>::const_iterator
1182 for (iface
= status_
.network_interface().begin();
1183 iface
!= status_
.network_interface().end();
1185 // Check whether type, field presence and field values match.
1186 if (dev
.expected_type
== iface
->type() &&
1187 iface
->has_mac_address() == !!*dev
.mac_address
&&
1188 iface
->has_meid() == !!*dev
.meid
&&
1189 iface
->has_imei() == !!*dev
.imei
&&
1190 iface
->mac_address() == dev
.mac_address
&&
1191 iface
->meid() == dev
.meid
&&
1192 iface
->imei() == dev
.imei
&&
1193 iface
->device_path() == dev
.device_path
) {
1199 EXPECT_TRUE(found_match
) << "No matching interface for fake device " << i
;
1203 EXPECT_EQ(count
, status_
.network_interface_size());
1205 // Now make sure network state list is correct.
1206 EXPECT_EQ(arraysize(kFakeNetworks
),
1207 static_cast<size_t>(status_
.network_state_size()));
1208 for (const FakeNetworkState
& state
: kFakeNetworks
) {
1209 bool found_match
= false;
1210 for (const em::NetworkState
& proto_state
: status_
.network_state()) {
1211 // Make sure every item has a matching entry in the proto.
1212 if (proto_state
.has_device_path() == (strlen(state
.device_path
) > 0) &&
1213 proto_state
.signal_strength() == state
.signal_strength
&&
1214 proto_state
.connection_state() == state
.expected_state
) {
1215 if (proto_state
.has_ip_address())
1216 EXPECT_EQ(proto_state
.ip_address(), state
.address
);
1218 EXPECT_EQ(0U, strlen(state
.address
));
1219 if (proto_state
.has_gateway())
1220 EXPECT_EQ(proto_state
.gateway(), state
.gateway
);
1222 EXPECT_EQ(0U, strlen(state
.gateway
));
1227 EXPECT_TRUE(found_match
) << "No matching state for fake network "
1228 << " (" << state
.name
<< ")";
1232 } // namespace policy