1//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//      http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
16
17#include "shill/manager.h"
18
19#include <map>
20#include <memory>
21#include <set>
22
23#include <base/files/file_util.h>
24#include <base/files/scoped_temp_dir.h>
25#include <base/stl_util.h>
26#include <base/strings/stringprintf.h>
27#if defined(__ANDROID__)
28#include <dbus/service_constants.h>
29#else
30#include <chromeos/dbus/service_constants.h>
31#endif  // __ANDROID__
32#include <gmock/gmock.h>
33#include <gtest/gtest.h>
34
35#include "shill/adaptor_interfaces.h"
36#include "shill/ephemeral_profile.h"
37#include "shill/error.h"
38#include "shill/fake_store.h"
39#include "shill/geolocation_info.h"
40#include "shill/key_value_store.h"
41#include "shill/link_monitor.h"
42#include "shill/logging.h"
43#include "shill/mock_adaptors.h"
44#include "shill/mock_connection.h"
45#include "shill/mock_control.h"
46#include "shill/mock_crypto_util_proxy.h"
47#include "shill/mock_device.h"
48#include "shill/mock_device_claimer.h"
49#include "shill/mock_device_info.h"
50#include "shill/mock_log.h"
51#include "shill/mock_metrics.h"
52#include "shill/mock_power_manager.h"
53#include "shill/mock_profile.h"
54#include "shill/mock_resolver.h"
55#include "shill/mock_service.h"
56#include "shill/mock_store.h"
57#include "shill/portal_detector.h"
58#include "shill/property_store_unittest.h"
59#include "shill/resolver.h"
60#include "shill/service_under_test.h"
61#include "shill/store_factory.h"
62#include "shill/testing.h"
63#include "shill/upstart/mock_upstart.h"
64#include "shill/wimax/wimax_service.h"
65
66#if !defined(DISABLE_WIFI)
67#include "shill/wifi/mock_wifi_provider.h"
68#include "shill/wifi/mock_wifi_service.h"
69#include "shill/wifi/wifi_service.h"
70#if defined(__BRILLO__)
71#include "shill/wifi/mock_wifi_driver_hal.h"
72#endif  // __BRILLO__
73#endif  // DISABLE_WIFI
74
75#if !defined(DISABLE_WIRED_8021X)
76#include "shill/ethernet/mock_ethernet_eap_provider.h"
77#endif  // DISABLE_WIRED_8021X
78
79using base::Bind;
80using base::FilePath;
81using base::ScopedTempDir;
82using base::Unretained;
83using std::map;
84using std::set;
85using std::string;
86using std::vector;
87
88namespace shill {
89using ::testing::_;
90using ::testing::AnyNumber;
91using ::testing::AtLeast;
92using ::testing::ContainerEq;
93using ::testing::DoAll;
94using ::testing::ElementsAre;
95using ::testing::HasSubstr;
96using ::testing::InSequence;
97using ::testing::Invoke;
98using ::testing::Mock;
99using ::testing::Ne;
100using ::testing::NiceMock;
101using ::testing::Ref;
102using ::testing::Return;
103using ::testing::ReturnNull;
104using ::testing::ReturnRef;
105using ::testing::SaveArg;
106using ::testing::SetArgumentPointee;
107using ::testing::StrEq;
108using ::testing::StrictMock;
109using ::testing::Test;
110using ::testing::WithArg;
111
112class ManagerTest : public PropertyStoreTest {
113 public:
114  ManagerTest()
115      : power_manager_(new MockPowerManager(nullptr, control_interface())),
116        device_info_(new NiceMock<MockDeviceInfo>(control_interface(),
117                                                  nullptr,
118                                                  nullptr,
119                                                  nullptr)),
120        manager_adaptor_(new NiceMock<ManagerMockAdaptor>()),
121#if !defined(DISABLE_WIRED_8021X)
122        ethernet_eap_provider_(new NiceMock<MockEthernetEapProvider>()),
123#endif  // DISABLE_WIRED_8021X
124#if !defined(DISABLE_WIFI)
125        wifi_provider_(new NiceMock<MockWiFiProvider>()),
126#endif  // DISABLE_WIFI
127        crypto_util_proxy_(
128            new NiceMock<MockCryptoUtilProxy>(dispatcher())),
129        upstart_(new NiceMock<MockUpstart>(control_interface())) {
130    ON_CALL(*control_interface(), CreatePowerManagerProxy(_, _, _))
131        .WillByDefault(ReturnNull());
132
133    mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
134                                                     dispatcher(),
135                                                     metrics(),
136                                                     manager(),
137                                                     "null0",
138                                                     "addr0",
139                                                     0));
140    mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
141                                                     dispatcher(),
142                                                     metrics(),
143                                                     manager(),
144                                                     "null1",
145                                                     "addr1",
146                                                     1));
147    mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
148                                                     dispatcher(),
149                                                     metrics(),
150                                                     manager(),
151                                                     "null2",
152                                                     "addr2",
153                                                     2));
154    mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
155                                                     dispatcher(),
156                                                     metrics(),
157                                                     manager(),
158                                                     "null3",
159                                                     "addr3",
160                                                     3));
161    manager()->connect_profiles_to_rpc_ = false;
162    SetRunning(true);
163
164    // Replace the manager's adaptor with a quieter one, and one
165    // we can do EXPECT*() against.  Passes ownership.
166    manager()->adaptor_.reset(manager_adaptor_);
167
168#if !defined(DISABLE_WIRED_8021X)
169    // Replace the manager's Ethernet EAP provider with our mock.
170    // Passes ownership.
171    manager()->ethernet_eap_provider_.reset(ethernet_eap_provider_);
172#endif  // DISABLE_WIRED_8021X
173
174#if !defined(DISABLE_WIFI)
175    // Replace the manager's WiFi provider with our mock.  Passes
176    // ownership.
177    manager()->wifi_provider_.reset(wifi_provider_);
178#if defined(__BRILLO__)
179    manager()->wifi_driver_hal_ = &wifi_driver_hal_;
180#endif  // __BRILLO__
181#endif  // DISABLE_WIFI
182
183    // Update the manager's map from technology to provider.
184    manager()->UpdateProviderMapping();
185
186    // Replace the manager's crypto util proxy with our mock.  Passes
187    // ownership.
188    manager()->crypto_util_proxy_.reset(crypto_util_proxy_);
189
190    // Replace the manager's upstart instance with our mock.  Passes
191    // ownership.
192    manager()->upstart_.reset(upstart_);
193  }
194  virtual ~ManagerTest() {}
195
196  void SetMetrics(Metrics* metrics) {
197    manager()->set_metrics(metrics);
198  }
199
200  bool IsDeviceRegistered(const DeviceRefPtr& device,
201                          Technology::Identifier tech) {
202    auto devices = manager()->FilterByTechnology(tech);
203    return (devices.size() == 1 && devices[0].get() == device.get());
204  }
205  bool ServiceOrderIs(ServiceRefPtr svc1, ServiceRefPtr svc2);
206
207  void AdoptProfile(Manager* manager, ProfileRefPtr profile) {
208    manager->profiles_.push_back(profile);
209  }
210
211  void SetRunning(bool running) {
212    manager()->running_ = running;
213  }
214
215  ProfileRefPtr GetEphemeralProfile(Manager* manager) {
216    return manager->ephemeral_profile_;
217  }
218
219  vector<ProfileRefPtr>& GetProfiles(Manager* manager) {
220    return manager->profiles_;
221  }
222
223  Profile* CreateProfileForManager(Manager* manager) {
224    Profile::Identifier id("rather", "irrelevant");
225    std::unique_ptr<FakeStore> storage(new FakeStore());
226    if (!storage->Open())
227      return nullptr;
228    Profile* profile(new Profile(
229        control_interface(), metrics(), manager, id, FilePath(), false));
230    profile->set_storage(storage.release());  // Passes ownership of "storage".
231    return profile;  // Passes ownership of "profile".
232  }
233
234  bool CreateBackingStoreForService(ScopedTempDir* temp_dir,
235                                    const string& user_identifier,
236                                    const string& profile_identifier,
237                                    const string& service_name) {
238    std::unique_ptr<StoreInterface> store(
239        StoreFactory::GetInstance()->CreateStore(
240            Profile::GetFinalStoragePath(
241                temp_dir->path(),
242                Profile::Identifier(user_identifier,
243                                    profile_identifier))));
244    return store->Open() &&
245        store->SetString(service_name, "rather", "irrelevant") &&
246        store->Close();
247  }
248
249  Error::Type TestCreateProfile(Manager* manager, const string& name) {
250    Error error;
251    string path;
252    manager->CreateProfile(name, &path, &error);
253    return error.type();
254  }
255
256  Error::Type TestPopAnyProfile(Manager* manager) {
257    Error error;
258    manager->PopAnyProfile(&error);
259    return error.type();
260  }
261
262  Error::Type TestPopAllUserProfiles(Manager* manager) {
263    Error error;
264    manager->PopAllUserProfiles(&error);
265    return error.type();
266  }
267
268  Error::Type TestPopProfile(Manager* manager, const string& name) {
269    Error error;
270    manager->PopProfile(name, &error);
271    return error.type();
272  }
273
274  Error::Type TestPushProfile(Manager* manager, const string& name) {
275    Error error;
276    string path;
277    manager->PushProfile(name, &path, &error);
278    return error.type();
279  }
280
281  Error::Type TestInsertUserProfile(Manager* manager,
282                                    const string& name,
283                                    const string& user_hash) {
284    Error error;
285    string path;
286    manager->InsertUserProfile(name, user_hash, &path, &error);
287    return error.type();
288  }
289
290  scoped_refptr<MockProfile> AddNamedMockProfileToManager(
291      Manager* manager, const string& name) {
292    scoped_refptr<MockProfile> profile(
293        new MockProfile(control_interface(), metrics(), manager, ""));
294    EXPECT_CALL(*profile, GetRpcIdentifier()).WillRepeatedly(Return(name));
295    EXPECT_CALL(*profile, UpdateDevice(_)).WillRepeatedly(Return(false));
296    AdoptProfile(manager, profile);
297    return profile;
298  }
299
300  void AddMockProfileToManager(Manager* manager) {
301    AddNamedMockProfileToManager(manager, "/");
302  }
303
304  void CompleteServiceSort() {
305    EXPECT_TRUE(IsSortServicesTaskPending());
306    dispatcher()->DispatchPendingEvents();
307    EXPECT_FALSE(IsSortServicesTaskPending());
308  }
309
310  bool IsSortServicesTaskPending() {
311    return !manager()->sort_services_task_.IsCancelled();
312  }
313
314  void RefreshConnectionState() {
315    manager()->RefreshConnectionState();
316  }
317
318  RpcIdentifier GetDefaultServiceRpcIdentifier() {
319    return manager()->GetDefaultServiceRpcIdentifier(nullptr);
320  }
321
322  void SetResolver(Resolver* resolver) {
323    manager()->resolver_ = resolver;
324  }
325
326  bool SetIgnoredDNSSearchPaths(const string& search_paths, Error* error) {
327    return manager()->SetIgnoredDNSSearchPaths(search_paths, error);
328  }
329
330  bool SetCheckPortalList(const string& check_portal_list, Error* error) {
331    return manager()->SetCheckPortalList(check_portal_list, error);
332  }
333
334  const string& GetIgnoredDNSSearchPaths() {
335    return manager()->props_.ignored_dns_search_paths;
336  }
337
338#if !defined(DISABLE_WIFI)
339  WiFiServiceRefPtr ReleaseTempMockService() {
340    // Take a reference to hold during this function.
341    WiFiServiceRefPtr temp_service = temp_mock_service_;
342    temp_mock_service_ = nullptr;
343    return temp_service;
344  }
345#endif  // DISABLE_WIFI
346
347  void SetDeviceClaimer(DeviceClaimer* device_claimer) {
348    manager()->device_claimer_.reset(device_claimer);
349  }
350
351  void VerifyPassiveMode() {
352    EXPECT_NE(nullptr, manager()->device_claimer_.get());
353    EXPECT_TRUE(manager()->device_claimer_->default_claimer());
354  }
355
356 protected:
357  typedef scoped_refptr<MockService> MockServiceRefPtr;
358
359  class ServiceWatcher : public base::SupportsWeakPtr<ServiceWatcher> {
360   public:
361    ServiceWatcher() {}
362    virtual ~ServiceWatcher() {}
363
364    MOCK_METHOD1(OnDefaultServiceChanged, void(const ServiceRefPtr& service));
365
366   private:
367    DISALLOW_COPY_AND_ASSIGN(ServiceWatcher);
368  };
369
370  class TerminationActionTest :
371      public base::SupportsWeakPtr<TerminationActionTest> {
372   public:
373    static const char kActionName[];
374
375    TerminationActionTest() : manager_(nullptr) {}
376    virtual ~TerminationActionTest() {}
377
378    MOCK_METHOD1(Done, void(const Error& error));
379
380    void Action() {
381      manager_->TerminationActionComplete("action");
382    }
383
384    void set_manager(Manager* manager) { manager_ = manager; }
385
386   private:
387    Manager* manager_;
388    DISALLOW_COPY_AND_ASSIGN(TerminationActionTest);
389  };
390
391  class DestinationVerificationTest :
392      public base::SupportsWeakPtr<DestinationVerificationTest> {
393   public:
394    DestinationVerificationTest() {}
395    virtual ~DestinationVerificationTest() {}
396
397    MOCK_METHOD2(ResultBoolCallbackStub, void(const Error& result, bool flag));
398    MOCK_METHOD2(ResultStringCallbackStub, void(const Error& result,
399                                                const string& value));
400   private:
401    DISALLOW_COPY_AND_ASSIGN(DestinationVerificationTest);
402  };
403
404  class DisableTechnologyReplyHandler :
405      public base::SupportsWeakPtr<DisableTechnologyReplyHandler> {
406   public:
407    DisableTechnologyReplyHandler() {}
408    virtual ~DisableTechnologyReplyHandler() {}
409
410    MOCK_METHOD1(ReportResult, void(const Error&));
411
412   private:
413    DISALLOW_COPY_AND_ASSIGN(DisableTechnologyReplyHandler);
414  };
415
416  class ResultCallbackObserver {
417   public:
418    ResultCallbackObserver()
419        : result_callback_(
420              Bind(&ResultCallbackObserver::OnResultCallback,
421                   Unretained(this))) {}
422    virtual ~ResultCallbackObserver() {}
423
424    MOCK_METHOD1(OnResultCallback, void(const Error& error));
425
426    const ResultCallback& result_callback() const {
427      return result_callback_;
428    }
429
430   private:
431    ResultCallback result_callback_;
432
433    DISALLOW_COPY_AND_ASSIGN(ResultCallbackObserver);
434  };
435
436  void SetSuspending(bool suspending) {
437    power_manager_->suspending_ = suspending;
438  }
439
440  void SetPowerManager() {
441    manager()->set_power_manager(power_manager_.release());
442  }
443
444  HookTable* GetTerminationActions() {
445    return &manager()->termination_actions_;
446  }
447
448  void OnSuspendImminent() {
449    manager()->OnSuspendImminent();
450  }
451
452  void OnDarkSuspendImminent() {
453    manager()->OnDarkSuspendImminent();
454  }
455
456  void OnSuspendDone() {
457    manager()->OnSuspendDone();
458  }
459
460  void OnSuspendActionsComplete(const Error& error) {
461    manager()->OnSuspendActionsComplete(error);
462  }
463
464  vector<string> EnumerateAvailableServices() {
465    return manager()->EnumerateAvailableServices(nullptr);
466  }
467
468  vector<string> EnumerateWatchedServices() {
469    return manager()->EnumerateWatchedServices(nullptr);
470  }
471
472  MockServiceRefPtr MakeAutoConnectableService() {
473    MockServiceRefPtr service = new NiceMock<MockService>(control_interface(),
474                                                          dispatcher(),
475                                                          metrics(),
476                                                          manager());
477    service->SetAutoConnect(true);
478    service->SetConnectable(true);
479    return service;
480  }
481
482#if !defined(DISABLE_WIRED_8021X)
483  void SetEapProviderService(const ServiceRefPtr& service) {
484    ethernet_eap_provider_->set_service(service);
485  }
486#endif  // DISABLE_WIRED_8021X
487
488  const std::vector<Technology::Identifier>& GetTechnologyOrder() {
489    return manager()->technology_order_;
490  }
491
492  std::unique_ptr<MockPowerManager> power_manager_;
493  vector<scoped_refptr<MockDevice>> mock_devices_;
494  std::unique_ptr<MockDeviceInfo> device_info_;
495
496#if !defined(DISABLE_WIFI)
497  // This service is held for the manager, and given ownership in a mock
498  // function.  This ensures that when the Manager takes ownership, there
499  // is only one reference left.
500  scoped_refptr<MockWiFiService> temp_mock_service_;
501#endif  // DISABLE_WIFI
502
503  // These pointers are owned by the manager, and only tracked here for
504  // EXPECT*()
505  ManagerMockAdaptor* manager_adaptor_;
506#if !defined(DISABLE_WIRED_8021X)
507  MockEthernetEapProvider* ethernet_eap_provider_;
508#endif  // DISABLE_WIRED_8021X
509#if !defined(DISABLE_WIFI)
510  MockWiFiProvider* wifi_provider_;
511#if defined(__BRILLO__)
512  MockWiFiDriverHal wifi_driver_hal_;
513#endif  // __BRILLO__
514#endif  // DISABLE_WIFI
515  MockCryptoUtilProxy* crypto_util_proxy_;
516  MockUpstart* upstart_;
517};
518
519const char ManagerTest::TerminationActionTest::kActionName[] = "action";
520
521bool ManagerTest::ServiceOrderIs(ServiceRefPtr svc0, ServiceRefPtr svc1) {
522  if (!manager()->sort_services_task_.IsCancelled()) {
523    manager()->SortServicesTask();
524  }
525  return (svc0.get() == manager()->services_[0].get() &&
526          svc1.get() == manager()->services_[1].get());
527}
528
529void SetErrorPermissionDenied(Error* error) {
530  error->Populate(Error::kPermissionDenied);
531}
532
533void SetErrorSuccess(Error* error) {
534  error->Reset();
535}
536
537MATCHER_P(IsError, error, "") {
538  return arg.type() == error->type() &&
539         arg.message() == error->message();
540}
541
542TEST_F(ManagerTest, Contains) {
543  EXPECT_TRUE(manager()->store().Contains(kStateProperty));
544  EXPECT_FALSE(manager()->store().Contains(""));
545}
546
547TEST_F(ManagerTest, PassiveModeDeviceRegistration) {
548  manager()->SetPassiveMode();
549  VerifyPassiveMode();
550
551  // Setup mock device claimer.
552  MockDeviceClaimer* device_claimer = new MockDeviceClaimer("");
553  SetDeviceClaimer(device_claimer);
554  EXPECT_CALL(*device_claimer, default_claimer()).WillRepeatedly(Return(true));
555
556  ON_CALL(*mock_devices_[0].get(), technology())
557      .WillByDefault(Return(Technology::kEthernet));
558  ON_CALL(*mock_devices_[1].get(), technology())
559      .WillByDefault(Return(Technology::kWifi));
560
561  // Device not released, should not be registered.
562  EXPECT_CALL(*device_claimer, IsDeviceReleased(mock_devices_[0]->link_name()))
563      .WillOnce(Return(false));
564  EXPECT_CALL(*device_claimer, Claim(mock_devices_[0]->link_name(), _))
565      .Times(1);
566  manager()->RegisterDevice(mock_devices_[0]);
567  EXPECT_FALSE(IsDeviceRegistered(mock_devices_[0], Technology::kEthernet));
568
569  // Device is released, should be registered.
570  EXPECT_CALL(*device_claimer, IsDeviceReleased(mock_devices_[1]->link_name()))
571      .WillOnce(Return(true));
572  EXPECT_CALL(*device_claimer, Claim(mock_devices_[1]->link_name(), _))
573      .Times(0);
574  manager()->RegisterDevice(mock_devices_[1]);
575  EXPECT_TRUE(IsDeviceRegistered(mock_devices_[1], Technology::kWifi));
576}
577
578TEST_F(ManagerTest, DeviceRegistration) {
579  ON_CALL(*mock_devices_[0].get(), technology())
580      .WillByDefault(Return(Technology::kEthernet));
581  ON_CALL(*mock_devices_[1].get(), technology())
582      .WillByDefault(Return(Technology::kWifi));
583  ON_CALL(*mock_devices_[2].get(), technology())
584      .WillByDefault(Return(Technology::kCellular));
585
586  manager()->RegisterDevice(mock_devices_[0]);
587  manager()->RegisterDevice(mock_devices_[1]);
588  manager()->RegisterDevice(mock_devices_[2]);
589
590  EXPECT_TRUE(IsDeviceRegistered(mock_devices_[0], Technology::kEthernet));
591  EXPECT_TRUE(IsDeviceRegistered(mock_devices_[1], Technology::kWifi));
592  EXPECT_TRUE(IsDeviceRegistered(mock_devices_[2], Technology::kCellular));
593}
594
595TEST_F(ManagerTest, DeviceRegistrationAndStart) {
596  manager()->running_ = true;
597  mock_devices_[0]->enabled_persistent_ = true;
598  mock_devices_[1]->enabled_persistent_ = false;
599  EXPECT_CALL(*mock_devices_[0].get(), SetEnabled(true))
600      .Times(1);
601  EXPECT_CALL(*mock_devices_[1].get(), SetEnabled(_))
602      .Times(0);
603  manager()->RegisterDevice(mock_devices_[0]);
604  manager()->RegisterDevice(mock_devices_[1]);
605}
606
607TEST_F(ManagerTest, DeviceRegistrationWithProfile) {
608  MockProfile* profile =
609      new MockProfile(control_interface(), metrics(), manager(), "");
610  DeviceRefPtr device_ref(mock_devices_[0].get());
611  AdoptProfile(manager(), profile);  // Passes ownership.
612  EXPECT_CALL(*profile, ConfigureDevice(device_ref));
613  EXPECT_CALL(*profile, UpdateDevice(device_ref));
614  manager()->RegisterDevice(mock_devices_[0]);
615}
616
617TEST_F(ManagerTest, DeviceDeregistration) {
618  ON_CALL(*mock_devices_[0].get(), technology())
619      .WillByDefault(Return(Technology::kEthernet));
620  ON_CALL(*mock_devices_[1].get(), technology())
621      .WillByDefault(Return(Technology::kWifi));
622
623  manager()->RegisterDevice(mock_devices_[0]);
624  manager()->RegisterDevice(mock_devices_[1]);
625
626  ASSERT_TRUE(IsDeviceRegistered(mock_devices_[0], Technology::kEthernet));
627  ASSERT_TRUE(IsDeviceRegistered(mock_devices_[1], Technology::kWifi));
628
629  MockProfile* profile =
630      new MockProfile(control_interface(), metrics(), manager(), "");
631  AdoptProfile(manager(), profile);  // Passes ownership.
632
633  EXPECT_CALL(*mock_devices_[0].get(), SetEnabled(false));
634  EXPECT_CALL(*profile, UpdateDevice(DeviceRefPtr(mock_devices_[0])));
635  manager()->DeregisterDevice(mock_devices_[0]);
636  EXPECT_FALSE(IsDeviceRegistered(mock_devices_[0], Technology::kEthernet));
637
638  EXPECT_CALL(*mock_devices_[1].get(), SetEnabled(false));
639  EXPECT_CALL(*profile, UpdateDevice(DeviceRefPtr(mock_devices_[1])));
640  manager()->DeregisterDevice(mock_devices_[1]);
641  EXPECT_FALSE(IsDeviceRegistered(mock_devices_[1], Technology::kWifi));
642}
643
644TEST_F(ManagerTest, ServiceRegistration) {
645  Manager manager(control_interface(),
646                  dispatcher(),
647                  metrics(),
648                  run_path(),
649                  storage_path(),
650                  string());
651  ProfileRefPtr profile(CreateProfileForManager(&manager));
652  ASSERT_TRUE(profile.get());
653  AdoptProfile(&manager, profile);
654
655  scoped_refptr<MockService> mock_service(
656      new NiceMock<MockService>(control_interface(),
657                                dispatcher(),
658                                metrics(),
659                                &manager));
660  scoped_refptr<MockService> mock_service2(
661      new NiceMock<MockService>(control_interface(),
662                                dispatcher(),
663                                metrics(),
664                                &manager));
665
666  string service1_name(mock_service->unique_name());
667  string service2_name(mock_service2->unique_name());
668
669  EXPECT_CALL(*mock_service.get(), GetRpcIdentifier())
670      .WillRepeatedly(Return(service1_name));
671  EXPECT_CALL(*mock_service2.get(), GetRpcIdentifier())
672      .WillRepeatedly(Return(service2_name));
673  // TODO(quiche): make this EXPECT_CALL work (crbug.com/203247)
674  // EXPECT_CALL(*static_cast<ManagerMockAdaptor*>(manager.adaptor_.get()),
675  //             EmitRpcIdentifierArrayChanged(kServicesProperty, _));
676
677  manager.RegisterService(mock_service);
678  manager.RegisterService(mock_service2);
679
680  Error error;
681  vector<string> rpc_ids = manager.EnumerateAvailableServices(&error);
682  set<string> ids(rpc_ids.begin(), rpc_ids.end());
683  EXPECT_EQ(2, ids.size());
684  EXPECT_TRUE(ContainsKey(ids, mock_service->GetRpcIdentifier()));
685  EXPECT_TRUE(ContainsKey(ids, mock_service2->GetRpcIdentifier()));
686
687  EXPECT_NE(nullptr, manager.FindService(service1_name).get());
688  EXPECT_NE(nullptr, manager.FindService(service2_name).get());
689
690  manager.set_power_manager(power_manager_.release());
691  manager.Stop();
692}
693
694TEST_F(ManagerTest, RegisterKnownService) {
695  Manager manager(control_interface(),
696                  dispatcher(),
697                  metrics(),
698                  run_path(),
699                  storage_path(),
700                  string());
701  ProfileRefPtr profile(CreateProfileForManager(&manager));
702  ASSERT_TRUE(profile.get());
703  AdoptProfile(&manager, profile);
704  {
705    ServiceRefPtr service1(new ServiceUnderTest(control_interface(),
706                                                dispatcher(),
707                                                metrics(),
708                                                &manager));
709    ASSERT_TRUE(profile->AdoptService(service1));
710    ASSERT_TRUE(profile->ContainsService(service1));
711  }  // Force destruction of service1.
712
713  ServiceRefPtr service2(new ServiceUnderTest(control_interface(),
714                                              dispatcher(),
715                                              metrics(),
716                                              &manager));
717  manager.RegisterService(service2);
718  EXPECT_EQ(service2->profile().get(), profile.get());
719
720  manager.set_power_manager(power_manager_.release());
721  manager.Stop();
722}
723
724TEST_F(ManagerTest, RegisterUnknownService) {
725  Manager manager(control_interface(),
726                  dispatcher(),
727                  metrics(),
728                  run_path(),
729                  storage_path(),
730                  string());
731  ProfileRefPtr profile(CreateProfileForManager(&manager));
732  ASSERT_TRUE(profile.get());
733  AdoptProfile(&manager, profile);
734  {
735    ServiceRefPtr service1(new ServiceUnderTest(control_interface(),
736                                                dispatcher(),
737                                                metrics(),
738                                                &manager));
739    ASSERT_TRUE(profile->AdoptService(service1));
740    ASSERT_TRUE(profile->ContainsService(service1));
741  }  // Force destruction of service1.
742  scoped_refptr<MockService> mock_service2(
743      new NiceMock<MockService>(control_interface(),
744                                dispatcher(),
745                                metrics(),
746                                &manager));
747  EXPECT_CALL(*mock_service2.get(), GetStorageIdentifier())
748      .WillRepeatedly(Return(mock_service2->unique_name()));
749  manager.RegisterService(mock_service2);
750  EXPECT_NE(mock_service2->profile().get(), profile.get());
751
752  manager.set_power_manager(power_manager_.release());
753  manager.Stop();
754}
755
756TEST_F(ManagerTest, DeregisterUnregisteredService) {
757  // WiFi assumes that it can deregister a service that is not
758  // registered.  (E.g. a hidden service can be deregistered when it
759  // loses its last endpoint, and again when WiFi is Stop()-ed.)
760  //
761  // So test that doing so doesn't cause a crash.
762  MockServiceRefPtr service = new NiceMock<MockService>(control_interface(),
763                                                        dispatcher(),
764                                                        metrics(),
765                                                        manager());
766  manager()->DeregisterService(service);
767}
768
769TEST_F(ManagerTest, GetProperties) {
770  AddMockProfileToManager(manager());
771  {
772    brillo::VariantDictionary props;
773    Error error;
774    string expected("portal_list");
775    manager()->mutable_store()->SetStringProperty(
776        kCheckPortalListProperty,
777        expected,
778        &error);
779    manager()->store().GetProperties(&props, &error);
780    ASSERT_FALSE(props.find(kCheckPortalListProperty) == props.end());
781    EXPECT_TRUE(props[kCheckPortalListProperty].IsTypeCompatible<string>());
782    EXPECT_EQ(props[kCheckPortalListProperty].Get<string>(), expected);
783  }
784  {
785    brillo::VariantDictionary props;
786    Error error;
787    bool expected = true;
788    manager()->mutable_store()->SetBoolProperty(kOfflineModeProperty,
789                                                expected,
790                                                &error);
791    manager()->store().GetProperties(&props, &error);
792    ASSERT_FALSE(props.find(kOfflineModeProperty) == props.end());
793    EXPECT_TRUE(props[kOfflineModeProperty].IsTypeCompatible<bool>());
794    EXPECT_EQ(props[kOfflineModeProperty].Get<bool>(), expected);
795  }
796}
797
798TEST_F(ManagerTest, GetDevicesProperty) {
799  AddMockProfileToManager(manager());
800  manager()->RegisterDevice(mock_devices_[0]);
801  manager()->RegisterDevice(mock_devices_[1]);
802  {
803    brillo::VariantDictionary props;
804    Error error;
805    manager()->store().GetProperties(&props, &error);
806    ASSERT_FALSE(props.find(kDevicesProperty) == props.end());
807    EXPECT_TRUE(
808        props[kDevicesProperty].IsTypeCompatible<vector<dbus::ObjectPath>>());
809    vector <dbus::ObjectPath> devices =
810        props[kDevicesProperty].Get<vector<dbus::ObjectPath>>();
811    EXPECT_EQ(2, devices.size());
812  }
813}
814
815TEST_F(ManagerTest, GetServicesProperty) {
816  AddMockProfileToManager(manager());
817  brillo::VariantDictionary props;
818  Error error;
819  manager()->store().GetProperties(&props, &error);
820  ASSERT_FALSE(props.find(kServicesProperty) == props.end());
821  EXPECT_TRUE(
822      props[kServicesProperty].IsTypeCompatible<vector<dbus::ObjectPath>>());
823}
824
825TEST_F(ManagerTest, MoveService) {
826  Manager manager(control_interface(),
827                  dispatcher(),
828                  metrics(),
829                  run_path(),
830                  storage_path(),
831                  string());
832  scoped_refptr<MockService> s2(new MockService(control_interface(),
833                                                dispatcher(),
834                                                metrics(),
835                                                &manager));
836  // Inject an actual profile, backed by a fake StoreInterface
837  {
838    Profile::Identifier id("irrelevant");
839    ProfileRefPtr profile(new Profile(
840        control_interface(), metrics(), &manager, id, FilePath(), false));
841    MockStore* storage = new MockStore;
842    EXPECT_CALL(*storage, ContainsGroup(s2->GetStorageIdentifier()))
843        .WillRepeatedly(Return(true));
844    EXPECT_CALL(*storage, Flush())
845        .Times(AnyNumber())
846        .WillRepeatedly(Return(true));
847    profile->set_storage(storage);
848    AdoptProfile(&manager, profile);
849  }
850  // Create a profile that already has |s2| in it.
851  ProfileRefPtr profile(
852      new EphemeralProfile(control_interface(), metrics(), &manager));
853  EXPECT_TRUE(profile->AdoptService(s2));
854
855  // Now, move the Service |s2| to another profile.
856  EXPECT_CALL(*s2.get(), Save(_)).WillOnce(Return(true));
857  ASSERT_TRUE(manager.MoveServiceToProfile(s2, manager.ActiveProfile()));
858
859  // Force destruction of the original Profile, to ensure that the Service
860  // is kept alive and populated with data.
861  profile = nullptr;
862  ASSERT_TRUE(manager.ActiveProfile()->ContainsService(s2));
863  manager.set_power_manager(power_manager_.release());
864  manager.Stop();
865}
866
867TEST_F(ManagerTest, LookupProfileByRpcIdentifier) {
868  scoped_refptr<MockProfile> mock_profile(
869      new MockProfile(control_interface(), metrics(), manager(), ""));
870  const string kProfileName("profile0");
871  EXPECT_CALL(*mock_profile, GetRpcIdentifier())
872      .WillRepeatedly(Return(kProfileName));
873  AdoptProfile(manager(), mock_profile);
874
875  EXPECT_FALSE(manager()->LookupProfileByRpcIdentifier("foo"));
876  ProfileRefPtr profile = manager()->LookupProfileByRpcIdentifier(kProfileName);
877  EXPECT_EQ(mock_profile.get(), profile.get());
878}
879
880TEST_F(ManagerTest, SetProfileForService) {
881  scoped_refptr<MockProfile> profile0(
882      new MockProfile(control_interface(), metrics(), manager(), ""));
883  string profile_name0("profile0");
884  EXPECT_CALL(*profile0, GetRpcIdentifier())
885      .WillRepeatedly(Return(profile_name0));
886  AdoptProfile(manager(), profile0);
887  scoped_refptr<MockService> service(new MockService(control_interface(),
888                                                     dispatcher(),
889                                                     metrics(),
890                                                     manager()));
891  EXPECT_FALSE(manager()->HasService(service));
892  {
893    Error error;
894    EXPECT_CALL(*profile0, AdoptService(_))
895        .WillOnce(Return(true));
896    // Expect that setting the profile of a service that does not already
897    // have one assigned does not cause a crash.
898    manager()->SetProfileForService(service, "profile0", &error);
899    EXPECT_TRUE(error.IsSuccess());
900  }
901
902  // The service should be registered as a side-effect of the profile being
903  // set for this service.
904  EXPECT_TRUE(manager()->HasService(service));
905
906  // Since we have mocked Profile::AdoptServie() above, the service's
907  // profile was not actually changed.  Do so explicitly now.
908  service->set_profile(profile0);
909
910  {
911    Error error;
912    manager()->SetProfileForService(service, "foo", &error);
913    EXPECT_EQ(Error::kInvalidArguments, error.type());
914    EXPECT_EQ("Unknown Profile foo requested for Service", error.message());
915  }
916
917  {
918    Error error;
919    manager()->SetProfileForService(service, profile_name0, &error);
920    EXPECT_EQ(Error::kInvalidArguments, error.type());
921    EXPECT_EQ("Service is already connected to this profile", error.message());
922  }
923
924  scoped_refptr<MockProfile> profile1(
925      new MockProfile(control_interface(), metrics(), manager(), ""));
926  string profile_name1("profile1");
927  EXPECT_CALL(*profile1, GetRpcIdentifier())
928      .WillRepeatedly(Return(profile_name1));
929  AdoptProfile(manager(), profile1);
930
931  {
932    Error error;
933    EXPECT_CALL(*profile1, AdoptService(_))
934        .WillOnce(Return(true));
935    EXPECT_CALL(*profile0, AbandonService(_))
936        .WillOnce(Return(true));
937    manager()->SetProfileForService(service, profile_name1, &error);
938    EXPECT_TRUE(error.IsSuccess());
939  }
940}
941
942TEST_F(ManagerTest, CreateProfile) {
943  ScopedTempDir temp_dir;
944  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
945
946  Manager manager(control_interface(),
947                  dispatcher(),
948                  metrics(),
949                  run_path(),
950                  storage_path(),
951                  temp_dir.path().value());
952
953  // Invalid name should be rejected.
954  EXPECT_EQ(Error::kInvalidArguments, TestCreateProfile(&manager, ""));
955
956  // A profile with invalid characters in it should similarly be rejected.
957  EXPECT_EQ(Error::kInvalidArguments,
958            TestCreateProfile(&manager, "valid_profile"));
959
960  // We should be able to create a machine profile.
961  EXPECT_EQ(Error::kSuccess, TestCreateProfile(&manager, "valid"));
962
963  // We should succeed in creating a valid user profile.  Verify the returned
964  // path.
965  const char kProfile[] = "~user/profile";
966  {
967    Error error;
968    string path;
969    ASSERT_TRUE(base::CreateDirectory(temp_dir.path().Append("user")));
970    manager.CreateProfile(kProfile, &path, &error);
971    EXPECT_EQ(Error::kSuccess, error.type());
972    EXPECT_EQ("/profile_rpc", path);
973  }
974
975  // We should fail in creating it a second time (already exists).
976  EXPECT_EQ(Error::kAlreadyExists, TestCreateProfile(&manager, kProfile));
977}
978
979TEST_F(ManagerTest, PushPopProfile) {
980  ScopedTempDir temp_dir;
981  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
982  Manager manager(control_interface(),
983                  dispatcher(),
984                  metrics(),
985                  run_path(),
986                  storage_path(),
987                  temp_dir.path().value());
988  vector<ProfileRefPtr>& profiles = GetProfiles(&manager);
989
990  // Pushing an invalid profile should fail.
991  EXPECT_EQ(Error::kInvalidArguments, TestPushProfile(&manager, ""));
992
993  // Create and push a default profile. Should succeed.
994  const char kDefaultProfile0[] = "default";
995  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kDefaultProfile0));
996  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kDefaultProfile0));
997  EXPECT_EQ(Error::kSuccess, TestPopProfile(&manager, kDefaultProfile0));
998
999  // Pushing a default profile that does not exist on disk will _not_
1000  // fail, because we'll use temporary storage for it.
1001  const char kMissingDefaultProfile[] = "missingdefault";
1002  EXPECT_EQ(Error::kSuccess,
1003            TestPushProfile(&manager, kMissingDefaultProfile));
1004  EXPECT_EQ(1, profiles.size());
1005  EXPECT_EQ(Error::kSuccess,
1006            TestPopProfile(&manager, kMissingDefaultProfile));
1007  EXPECT_EQ(0, profiles.size());
1008
1009  const char kProfile0[] = "~user/profile0";
1010  const char kProfile1[] = "~user/profile1";
1011  ASSERT_TRUE(base::CreateDirectory(temp_dir.path().Append("user")));
1012
1013  // Create a couple of profiles.
1014  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kProfile0));
1015  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kProfile1));
1016
1017  // Push these profiles on the stack.
1018  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile0));
1019  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile1));
1020
1021  // Pushing a profile a second time should fail.
1022  EXPECT_EQ(Error::kAlreadyExists, TestPushProfile(&manager, kProfile0));
1023  EXPECT_EQ(Error::kAlreadyExists, TestPushProfile(&manager, kProfile1));
1024
1025  Error error;
1026  // Active profile should be the last one we pushed.
1027  EXPECT_EQ(kProfile1, "~" + manager.ActiveProfile()->GetFriendlyName());
1028
1029  // Make sure a profile name that doesn't exist fails.
1030  const char kProfile2Id[] = "profile2";
1031  const string kProfile2 = base::StringPrintf("~user/%s", kProfile2Id);
1032  EXPECT_EQ(Error::kNotFound, TestPushProfile(&manager, kProfile2));
1033
1034  // Create a new service, with a specific storage name.
1035  scoped_refptr<MockService> service(
1036      new NiceMock<MockService>(control_interface(),
1037                                dispatcher(),
1038                                metrics(),
1039                                &manager));
1040  const char kServiceName[] = "service_storage_name";
1041  EXPECT_CALL(*service.get(), GetStorageIdentifier())
1042      .WillRepeatedly(Return(kServiceName));
1043  EXPECT_CALL(*service.get(), Load(_))
1044      .WillRepeatedly(Return(true));
1045
1046  // Add this service to the manager -- it should end up in the ephemeral
1047  // profile.
1048  manager.RegisterService(service);
1049  ASSERT_EQ(GetEphemeralProfile(&manager), service->profile());
1050
1051  // Create storage for a profile that contains the service storage name.
1052  ASSERT_TRUE(CreateBackingStoreForService(&temp_dir, "user", kProfile2Id,
1053                                           kServiceName));
1054
1055  // When we push the profile, the service should move away from the
1056  // ephemeral profile to this new profile since it has an entry for
1057  // this service.
1058  EXPECT_CALL(*service, ClearExplicitlyDisconnected());
1059  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile2));
1060  EXPECT_NE(GetEphemeralProfile(&manager), service->profile());
1061  EXPECT_EQ(kProfile2, "~" + service->profile()->GetFriendlyName());
1062
1063  // Insert another profile that should supersede ownership of the service.
1064  const char kProfile3Id[] = "profile3";
1065  const string kProfile3 = base::StringPrintf("~user/%s", kProfile3Id);
1066  ASSERT_TRUE(CreateBackingStoreForService(&temp_dir, "user", kProfile3Id,
1067                                           kServiceName));
1068  // We don't verify this expectation inline, since this would clear other
1069  // recurring expectations on the service.
1070  EXPECT_CALL(*service, ClearExplicitlyDisconnected());
1071  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile3));
1072  EXPECT_EQ(kProfile3, "~" + service->profile()->GetFriendlyName());
1073
1074  // Popping an invalid profile name should fail.
1075  EXPECT_EQ(Error::kInvalidArguments, TestPopProfile(&manager, "~"));
1076
1077  // Popping an profile that is not at the top of the stack should fail.
1078  EXPECT_EQ(Error::kNotSupported, TestPopProfile(&manager, kProfile0));
1079
1080  // Popping the top profile should succeed.
1081  EXPECT_CALL(*service, ClearExplicitlyDisconnected());
1082  EXPECT_EQ(Error::kSuccess, TestPopProfile(&manager, kProfile3));
1083
1084  // Moreover the service should have switched profiles to profile 2.
1085  EXPECT_EQ(kProfile2, "~" + service->profile()->GetFriendlyName());
1086
1087  // Popping the top profile should succeed.
1088  EXPECT_CALL(*service, ClearExplicitlyDisconnected());
1089  EXPECT_EQ(Error::kSuccess, TestPopAnyProfile(&manager));
1090
1091  // The service should now revert to the ephemeral profile.
1092  EXPECT_EQ(GetEphemeralProfile(&manager), service->profile());
1093
1094  // Pop the remaining two profiles off the stack.
1095  EXPECT_CALL(*service, ClearExplicitlyDisconnected()).Times(2);
1096  EXPECT_EQ(Error::kSuccess, TestPopAnyProfile(&manager));
1097  EXPECT_EQ(Error::kSuccess, TestPopAnyProfile(&manager));
1098  Mock::VerifyAndClearExpectations(service.get());
1099
1100  // Next pop should fail with "stack is empty".
1101  EXPECT_EQ(Error::kNotFound, TestPopAnyProfile(&manager));
1102
1103  const char kMachineProfile0[] = "machineprofile0";
1104  const char kMachineProfile1[] = "machineprofile1";
1105  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kMachineProfile0));
1106  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kMachineProfile1));
1107
1108  // Should be able to push a machine profile.
1109  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kMachineProfile0));
1110
1111  // Should be able to push a user profile atop a machine profile.
1112  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile0));
1113
1114  // Pushing a system-wide profile on top of a user profile should fail.
1115  EXPECT_EQ(Error::kInvalidArguments,
1116            TestPushProfile(&manager, kMachineProfile1));
1117
1118  // However if we pop the user profile, we should be able stack another
1119  // machine profile on.
1120  EXPECT_EQ(Error::kSuccess, TestPopAnyProfile(&manager));
1121  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kMachineProfile1));
1122
1123  // Add two user profiles to the top of the stack.
1124  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile0));
1125  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile1));
1126  EXPECT_EQ(4, profiles.size());
1127
1128  // PopAllUserProfiles should remove both user profiles, leaving the two
1129  // machine profiles.
1130  EXPECT_EQ(Error::kSuccess, TestPopAllUserProfiles(&manager));
1131  EXPECT_EQ(2, profiles.size());
1132  EXPECT_TRUE(profiles[0]->GetUser().empty());
1133  EXPECT_TRUE(profiles[1]->GetUser().empty());
1134
1135  // Use InsertUserProfile() instead.  Although a machine profile is valid
1136  // in this state, it cannot be added via InsertUserProfile.
1137  EXPECT_EQ(Error::kSuccess, TestPopProfile(&manager, kMachineProfile1));
1138  EXPECT_EQ(Error::kInvalidArguments,
1139            TestInsertUserProfile(&manager, kMachineProfile1, "machinehash1"));
1140  const char kUserHash0[] = "userhash0";
1141  const char kUserHash1[] = "userhash1";
1142  EXPECT_EQ(Error::kSuccess,
1143            TestInsertUserProfile(&manager, kProfile0, kUserHash0));
1144  EXPECT_EQ(Error::kSuccess,
1145            TestInsertUserProfile(&manager, kProfile1, kUserHash1));
1146  EXPECT_EQ(3, profiles.size());
1147  EXPECT_EQ(kUserHash0, profiles[1]->GetUserHash());
1148  EXPECT_EQ(kUserHash1, profiles[2]->GetUserHash());
1149}
1150
1151TEST_F(ManagerTest, RemoveProfile) {
1152  ScopedTempDir temp_dir;
1153  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1154  Manager manager(control_interface(),
1155                  dispatcher(),
1156                  metrics(),
1157                  run_path(),
1158                  storage_path(),
1159                  temp_dir.path().value());
1160
1161  const char kProfile0[] = "profile0";
1162  FilePath profile_path(
1163      Profile::GetFinalStoragePath(
1164          FilePath(storage_path()), Profile::Identifier(kProfile0)));
1165
1166  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kProfile0));
1167  ASSERT_TRUE(base::PathExists(profile_path));
1168
1169  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile0));
1170
1171  // Remove should fail since the profile is still on the stack.
1172  {
1173    Error error;
1174    manager.RemoveProfile(kProfile0, &error);
1175    EXPECT_EQ(Error::kInvalidArguments, error.type());
1176  }
1177
1178  // Profile path should still exist.
1179  EXPECT_TRUE(base::PathExists(profile_path));
1180
1181  EXPECT_EQ(Error::kSuccess, TestPopAnyProfile(&manager));
1182
1183  // This should succeed now that the profile is off the stack.
1184  {
1185    Error error;
1186    manager.RemoveProfile(kProfile0, &error);
1187    EXPECT_EQ(Error::kSuccess, error.type());
1188  }
1189
1190  // Profile path should no longer exist.
1191  EXPECT_FALSE(base::PathExists(profile_path));
1192
1193  // Another remove succeeds, due to a foible in base::DeleteFile --
1194  // it is not an error to delete a file that does not exist.
1195  {
1196    Error error;
1197    manager.RemoveProfile(kProfile0, &error);
1198    EXPECT_EQ(Error::kSuccess, error.type());
1199  }
1200
1201  // Let's create an error case that will "work".  Create a non-empty
1202  // directory in the place of the profile pathname.
1203  ASSERT_TRUE(base::CreateDirectory(profile_path.Append("foo")));
1204  {
1205    Error error;
1206    manager.RemoveProfile(kProfile0, &error);
1207    EXPECT_EQ(Error::kOperationFailed, error.type());
1208  }
1209}
1210
1211TEST_F(ManagerTest, RemoveService) {
1212  MockServiceRefPtr mock_service(
1213      new NiceMock<MockService>(control_interface(),
1214                                dispatcher(),
1215                                metrics(),
1216                                manager()));
1217
1218  // Used in expectations which cannot accept a mock refptr.
1219  const ServiceRefPtr& service = mock_service;
1220
1221  manager()->RegisterService(service);
1222  EXPECT_EQ(GetEphemeralProfile(manager()), service->profile().get());
1223
1224  scoped_refptr<MockProfile> profile(
1225      new StrictMock<MockProfile>(
1226          control_interface(), metrics(), manager(), ""));
1227  AdoptProfile(manager(), profile);
1228
1229  // If service is ephemeral, it should be unloaded and left ephemeral.
1230  EXPECT_CALL(*profile, AbandonService(service)).Times(0);
1231  EXPECT_CALL(*profile, ConfigureService(service)).Times(0);
1232  EXPECT_CALL(*mock_service, Unload()).WillOnce(Return(false));
1233  manager()->RemoveService(service);
1234  Mock::VerifyAndClearExpectations(mock_service.get());
1235  Mock::VerifyAndClearExpectations(profile.get());
1236  EXPECT_EQ(GetEphemeralProfile(manager()), service->profile().get());
1237  EXPECT_TRUE(manager()->HasService(service));  // Since Unload() was false.
1238
1239  // If service is not ephemeral and the Manager finds a profile to assign
1240  // the service to, the service should be re-parented.  Note that since we
1241  // are using a MockProfile, ConfigureService() never actually changes the
1242  // Service's profile.
1243  service->set_profile(profile);
1244  EXPECT_CALL(*profile, AbandonService(service));
1245  EXPECT_CALL(*profile, ConfigureService(service)).WillOnce(Return(true));
1246  EXPECT_CALL(*mock_service, Unload()).Times(0);
1247  manager()->RemoveService(service);
1248  Mock::VerifyAndClearExpectations(mock_service.get());
1249  Mock::VerifyAndClearExpectations(profile.get());
1250  EXPECT_TRUE(manager()->HasService(service));
1251  EXPECT_EQ(profile.get(), service->profile().get());
1252
1253  // If service becomes ephemeral since there is no profile to support it,
1254  // it should be unloaded.
1255  EXPECT_CALL(*profile, AbandonService(service));
1256  EXPECT_CALL(*profile, ConfigureService(service)).WillOnce(Return(false));
1257  EXPECT_CALL(*mock_service, Unload()).WillOnce(Return(true));
1258  manager()->RemoveService(service);
1259  EXPECT_FALSE(manager()->HasService(service));
1260}
1261
1262TEST_F(ManagerTest, CreateDuplicateProfileWithMissingKeyfile) {
1263  ScopedTempDir temp_dir;
1264  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1265  Manager manager(control_interface(),
1266                  dispatcher(),
1267                  metrics(),
1268                  run_path(),
1269                  storage_path(),
1270                  temp_dir.path().value());
1271
1272  const char kProfile0[] = "profile0";
1273  FilePath profile_path(
1274      Profile::GetFinalStoragePath(
1275          FilePath(storage_path()), Profile::Identifier(kProfile0)));
1276  ASSERT_EQ(Error::kSuccess, TestCreateProfile(&manager, kProfile0));
1277  ASSERT_TRUE(base::PathExists(profile_path));
1278  EXPECT_EQ(Error::kSuccess, TestPushProfile(&manager, kProfile0));
1279
1280  // Ensure that even if the backing filestore is removed, we still can't
1281  // create a profile twice.
1282  ASSERT_TRUE(base::DeleteFile(profile_path, false));
1283  EXPECT_EQ(Error::kAlreadyExists, TestCreateProfile(&manager, kProfile0));
1284}
1285
1286TEST_F(ManagerTest, HandleProfileEntryDeletion) {
1287  MockServiceRefPtr s_not_in_profile(
1288      new NiceMock<MockService>(control_interface(),
1289                                dispatcher(),
1290                                metrics(),
1291                                manager()));
1292  MockServiceRefPtr s_not_in_group(
1293      new NiceMock<MockService>(control_interface(),
1294                                dispatcher(),
1295                                metrics(),
1296                                manager()));
1297  MockServiceRefPtr s_configure_fail(
1298      new NiceMock<MockService>(control_interface(),
1299                                dispatcher(),
1300                                metrics(),
1301                                manager()));
1302  MockServiceRefPtr s_configure_succeed(
1303      new NiceMock<MockService>(control_interface(),
1304                                dispatcher(),
1305                                metrics(),
1306                                manager()));
1307
1308  string entry_name("entry_name");
1309  EXPECT_CALL(*s_not_in_profile.get(), GetStorageIdentifier()).Times(0);
1310  EXPECT_CALL(*s_not_in_group.get(), GetStorageIdentifier())
1311      .WillRepeatedly(Return("not_entry_name"));
1312  EXPECT_CALL(*s_configure_fail.get(), GetStorageIdentifier())
1313      .WillRepeatedly(Return(entry_name));
1314  EXPECT_CALL(*s_configure_succeed.get(), GetStorageIdentifier())
1315      .WillRepeatedly(Return(entry_name));
1316
1317  manager()->RegisterService(s_not_in_profile);
1318  manager()->RegisterService(s_not_in_group);
1319  manager()->RegisterService(s_configure_fail);
1320  manager()->RegisterService(s_configure_succeed);
1321
1322  scoped_refptr<MockProfile> profile0(
1323      new StrictMock<MockProfile>(
1324          control_interface(), metrics(), manager(), ""));
1325  scoped_refptr<MockProfile> profile1(
1326      new StrictMock<MockProfile>(
1327          control_interface(), metrics(), manager(), ""));
1328
1329  s_not_in_group->set_profile(profile1);
1330  s_configure_fail->set_profile(profile1);
1331  s_configure_succeed->set_profile(profile1);
1332
1333  AdoptProfile(manager(), profile0);
1334  AdoptProfile(manager(), profile1);
1335
1336  CompleteServiceSort();
1337
1338  // No services are a member of this profile.
1339  EXPECT_FALSE(manager()->HandleProfileEntryDeletion(profile0, entry_name));
1340  EXPECT_FALSE(IsSortServicesTaskPending());
1341
1342  // No services that are members of this profile have this entry name.
1343  EXPECT_FALSE(manager()->HandleProfileEntryDeletion(profile1, ""));
1344  EXPECT_FALSE(IsSortServicesTaskPending());
1345
1346  // Only services that are members of the profile and group will be abandoned.
1347  EXPECT_CALL(*profile1.get(),
1348              AbandonService(IsRefPtrTo(s_not_in_profile.get()))).Times(0);
1349  EXPECT_CALL(*profile1.get(),
1350              AbandonService(IsRefPtrTo(s_not_in_group.get()))).Times(0);
1351  EXPECT_CALL(*profile1.get(),
1352              AbandonService(IsRefPtrTo(s_configure_fail.get())))
1353      .WillOnce(Return(true));
1354  EXPECT_CALL(*profile1.get(),
1355              AbandonService(IsRefPtrTo(s_configure_succeed.get())))
1356      .WillOnce(Return(true));
1357
1358  // Never allow services to re-join profile1.
1359  EXPECT_CALL(*profile1.get(), ConfigureService(_))
1360      .WillRepeatedly(Return(false));
1361
1362  // Only allow one of the members of the profile and group to successfully
1363  // join profile0.
1364  EXPECT_CALL(*profile0.get(),
1365              ConfigureService(IsRefPtrTo(s_not_in_profile.get()))).Times(0);
1366  EXPECT_CALL(*profile0.get(),
1367              ConfigureService(IsRefPtrTo(s_not_in_group.get()))).Times(0);
1368  EXPECT_CALL(*profile0.get(),
1369              ConfigureService(IsRefPtrTo(s_configure_fail.get())))
1370      .WillOnce(Return(false));
1371  EXPECT_CALL(*profile0.get(),
1372              ConfigureService(IsRefPtrTo(s_configure_succeed.get())))
1373      .WillOnce(Return(true));
1374
1375  // Expect the failed-to-configure service to have Unload() called on it.
1376  EXPECT_CALL(*s_not_in_profile.get(), Unload()).Times(0);
1377  EXPECT_CALL(*s_not_in_group.get(), Unload()).Times(0);
1378  EXPECT_CALL(*s_configure_fail.get(), Unload()).Times(1);
1379  EXPECT_CALL(*s_configure_succeed.get(), Unload()).Times(0);
1380
1381  EXPECT_TRUE(manager()->HandleProfileEntryDeletion(profile1, entry_name));
1382  EXPECT_TRUE(IsSortServicesTaskPending());
1383
1384  EXPECT_EQ(GetEphemeralProfile(manager()), s_not_in_profile->profile().get());
1385  EXPECT_EQ(profile1, s_not_in_group->profile());
1386  EXPECT_EQ(GetEphemeralProfile(manager()), s_configure_fail->profile());
1387
1388  // Since we are using a MockProfile, the profile does not actually change,
1389  // since ConfigureService was not actually called on the service.
1390  EXPECT_EQ(profile1, s_configure_succeed->profile());
1391}
1392
1393TEST_F(ManagerTest, HandleProfileEntryDeletionWithUnload) {
1394  MockServiceRefPtr s_will_remove0(
1395      new NiceMock<MockService>(control_interface(),
1396                                dispatcher(),
1397                                metrics(),
1398                                manager()));
1399  MockServiceRefPtr s_will_remove1(
1400      new NiceMock<MockService>(control_interface(),
1401                                dispatcher(),
1402                                metrics(),
1403                                manager()));
1404  MockServiceRefPtr s_will_not_remove0(
1405      new NiceMock<MockService>(control_interface(),
1406                                dispatcher(),
1407                                metrics(),
1408                                manager()));
1409  MockServiceRefPtr s_will_not_remove1(
1410      new NiceMock<MockService>(control_interface(),
1411                                dispatcher(),
1412                                metrics(),
1413                                manager()));
1414
1415  EXPECT_CALL(*metrics(), NotifyDefaultServiceChanged(nullptr))
1416      .Times(4);  // Once for each registration.
1417
1418  string entry_name("entry_name");
1419  EXPECT_CALL(*s_will_remove0.get(), GetStorageIdentifier())
1420      .WillRepeatedly(Return(entry_name));
1421  EXPECT_CALL(*s_will_remove1.get(), GetStorageIdentifier())
1422      .WillRepeatedly(Return(entry_name));
1423  EXPECT_CALL(*s_will_not_remove0.get(), GetStorageIdentifier())
1424      .WillRepeatedly(Return(entry_name));
1425  EXPECT_CALL(*s_will_not_remove1.get(), GetStorageIdentifier())
1426      .WillRepeatedly(Return(entry_name));
1427
1428  manager()->RegisterService(s_will_remove0);
1429  CompleteServiceSort();
1430  manager()->RegisterService(s_will_not_remove0);
1431  CompleteServiceSort();
1432  manager()->RegisterService(s_will_remove1);
1433  CompleteServiceSort();
1434  manager()->RegisterService(s_will_not_remove1);
1435  CompleteServiceSort();
1436
1437  // One for each service added above.
1438  ASSERT_EQ(4, manager()->services_.size());
1439
1440  scoped_refptr<MockProfile> profile(
1441      new StrictMock<MockProfile>(
1442          control_interface(), metrics(), manager(), ""));
1443
1444  s_will_remove0->set_profile(profile);
1445  s_will_remove1->set_profile(profile);
1446  s_will_not_remove0->set_profile(profile);
1447  s_will_not_remove1->set_profile(profile);
1448
1449  AdoptProfile(manager(), profile);
1450
1451  // Deny any of the services re-entry to the profile.
1452  EXPECT_CALL(*profile, ConfigureService(_))
1453      .WillRepeatedly(Return(false));
1454
1455  EXPECT_CALL(*profile, AbandonService(ServiceRefPtr(s_will_remove0)))
1456      .WillOnce(Return(true));
1457  EXPECT_CALL(*profile, AbandonService(ServiceRefPtr(s_will_remove1)))
1458      .WillOnce(Return(true));
1459  EXPECT_CALL(*profile, AbandonService(ServiceRefPtr(s_will_not_remove0)))
1460      .WillOnce(Return(true));
1461  EXPECT_CALL(*profile, AbandonService(ServiceRefPtr(s_will_not_remove1)))
1462      .WillOnce(Return(true));
1463
1464  EXPECT_CALL(*s_will_remove0, Unload())
1465      .WillOnce(Return(true));
1466  EXPECT_CALL(*s_will_remove1, Unload())
1467      .WillOnce(Return(true));
1468  EXPECT_CALL(*s_will_not_remove0, Unload())
1469      .WillOnce(Return(false));
1470  EXPECT_CALL(*s_will_not_remove1, Unload())
1471      .WillOnce(Return(false));
1472
1473
1474  // This will cause all the profiles to be unloaded.
1475  EXPECT_FALSE(IsSortServicesTaskPending());
1476  EXPECT_TRUE(manager()->HandleProfileEntryDeletion(profile, entry_name));
1477  EXPECT_TRUE(IsSortServicesTaskPending());
1478
1479  // 2 of the 4 services added above should have been unregistered and
1480  // removed, leaving 2.
1481  EXPECT_EQ(2, manager()->services_.size());
1482  EXPECT_EQ(s_will_not_remove0.get(), manager()->services_[0].get());
1483  EXPECT_EQ(s_will_not_remove1.get(), manager()->services_[1].get());
1484}
1485
1486TEST_F(ManagerTest, PopProfileWithUnload) {
1487  MockServiceRefPtr s_will_remove0(
1488      new NiceMock<MockService>(control_interface(),
1489                                dispatcher(),
1490                                metrics(),
1491                                manager()));
1492  MockServiceRefPtr s_will_remove1(
1493      new NiceMock<MockService>(control_interface(),
1494                                dispatcher(),
1495                                metrics(),
1496                                manager()));
1497  MockServiceRefPtr s_will_not_remove0(
1498      new NiceMock<MockService>(control_interface(),
1499                                dispatcher(),
1500                                metrics(),
1501                                manager()));
1502  MockServiceRefPtr s_will_not_remove1(
1503      new NiceMock<MockService>(control_interface(),
1504                                dispatcher(),
1505                                metrics(),
1506                                manager()));
1507
1508  EXPECT_CALL(*metrics(), NotifyDefaultServiceChanged(nullptr))
1509      .Times(5);  // Once for each registration, and one after profile pop.
1510
1511  manager()->RegisterService(s_will_remove0);
1512  CompleteServiceSort();
1513  manager()->RegisterService(s_will_not_remove0);
1514  CompleteServiceSort();
1515  manager()->RegisterService(s_will_remove1);
1516  CompleteServiceSort();
1517  manager()->RegisterService(s_will_not_remove1);
1518  CompleteServiceSort();
1519
1520  // One for each service added above.
1521  ASSERT_EQ(4, manager()->services_.size());
1522
1523  scoped_refptr<MockProfile> profile0(
1524      new StrictMock<MockProfile>(
1525          control_interface(), metrics(), manager(), ""));
1526  scoped_refptr<MockProfile> profile1(
1527      new StrictMock<MockProfile>(
1528          control_interface(), metrics(), manager(), ""));
1529
1530  s_will_remove0->set_profile(profile1);
1531  s_will_remove1->set_profile(profile1);
1532  s_will_not_remove0->set_profile(profile1);
1533  s_will_not_remove1->set_profile(profile1);
1534
1535  AdoptProfile(manager(), profile0);
1536  AdoptProfile(manager(), profile1);
1537
1538  // Deny any of the services entry to profile0, so they will all be unloaded.
1539  EXPECT_CALL(*profile0, ConfigureService(_))
1540      .WillRepeatedly(Return(false));
1541
1542  EXPECT_CALL(*s_will_remove0, Unload())
1543      .WillOnce(Return(true));
1544  EXPECT_CALL(*s_will_remove1, Unload())
1545      .WillOnce(Return(true));
1546  EXPECT_CALL(*s_will_not_remove0, Unload())
1547      .WillRepeatedly(Return(false));
1548  EXPECT_CALL(*s_will_not_remove1, Unload())
1549      .WillOnce(Return(false));
1550
1551  // Ignore calls to Profile::GetRpcIdentifier because of emitted changes of the
1552  // profile list.
1553  EXPECT_CALL(*profile0, GetRpcIdentifier()).Times(AnyNumber());
1554  EXPECT_CALL(*profile1, GetRpcIdentifier()).Times(AnyNumber());
1555
1556  // This will pop profile1, which should cause all our profiles to unload.
1557  manager()->PopProfileInternal();
1558  CompleteServiceSort();
1559
1560  // 2 of the 4 services added above should have been unregistered and
1561  // removed, leaving 2.
1562  EXPECT_EQ(2, manager()->services_.size());
1563  EXPECT_EQ(s_will_not_remove0.get(), manager()->services_[0].get());
1564  EXPECT_EQ(s_will_not_remove1.get(), manager()->services_[1].get());
1565
1566  // Expect the unloaded services to lose their profile reference.
1567  EXPECT_FALSE(s_will_remove0->profile());
1568  EXPECT_FALSE(s_will_remove1->profile());
1569
1570  // If we explicitly deregister a service, the effect should be the same
1571  // with respect to the profile reference.
1572  ASSERT_TRUE(s_will_not_remove0->profile());
1573  manager()->DeregisterService(s_will_not_remove0);
1574  EXPECT_FALSE(s_will_not_remove0->profile());
1575}
1576
1577TEST_F(ManagerTest, SetProperty) {
1578  {
1579    Error error;
1580    const bool offline_mode = true;
1581    EXPECT_TRUE(manager()->mutable_store()->SetAnyProperty(
1582        kOfflineModeProperty, brillo::Any(offline_mode), &error));
1583  }
1584  {
1585    Error error;
1586    const string country("a_country");
1587    EXPECT_TRUE(manager()->mutable_store()->SetAnyProperty(
1588        kCountryProperty, brillo::Any(country), &error));
1589  }
1590  // Attempt to write with value of wrong type should return InvalidArgs.
1591  {
1592    Error error;
1593    EXPECT_FALSE(manager()->mutable_store()->SetAnyProperty(
1594        kCountryProperty, PropertyStoreTest::kBoolV, &error));
1595    EXPECT_EQ(Error::kInvalidArguments, error.type());
1596  }
1597  {
1598    Error error;
1599    EXPECT_FALSE(manager()->mutable_store()->SetAnyProperty(
1600        kOfflineModeProperty, PropertyStoreTest::kStringV, &error));
1601    EXPECT_EQ(Error::kInvalidArguments, error.type());
1602  }
1603  // Attempt to write R/O property should return InvalidArgs.
1604  {
1605    Error error;
1606    EXPECT_FALSE(manager()->mutable_store()->SetAnyProperty(
1607        kEnabledTechnologiesProperty, PropertyStoreTest::kStringsV, &error));
1608    EXPECT_EQ(Error::kInvalidArguments, error.type());
1609  }
1610}
1611
1612TEST_F(ManagerTest, RequestScan) {
1613  {
1614    Error error;
1615    manager()->RegisterDevice(mock_devices_[0].get());
1616    manager()->RegisterDevice(mock_devices_[1].get());
1617    EXPECT_CALL(*mock_devices_[0], technology())
1618        .WillRepeatedly(Return(Technology::kWifi));
1619    EXPECT_CALL(*mock_devices_[0], Scan(Device::kFullScan, _, _));
1620    EXPECT_CALL(*mock_devices_[1], technology())
1621        .WillRepeatedly(Return(Technology::kUnknown));
1622    EXPECT_CALL(*mock_devices_[1], Scan(_, _, _)).Times(0);
1623    EXPECT_CALL(*metrics(), NotifyUserInitiatedEvent(
1624        Metrics::kUserInitiatedEventWifiScan)).Times(1);
1625    manager()->RequestScan(Device::kFullScan, kTypeWifi, &error);
1626    manager()->DeregisterDevice(mock_devices_[0].get());
1627    manager()->DeregisterDevice(mock_devices_[1].get());
1628    Mock::VerifyAndClearExpectations(mock_devices_[0].get());
1629    Mock::VerifyAndClearExpectations(mock_devices_[1].get());
1630
1631    manager()->RegisterDevice(mock_devices_[0].get());
1632    EXPECT_CALL(*mock_devices_[0], technology())
1633        .WillRepeatedly(Return(Technology::kWifi));
1634    EXPECT_CALL(*metrics(), NotifyUserInitiatedEvent(
1635        Metrics::kUserInitiatedEventWifiScan)).Times(1);
1636    EXPECT_CALL(*mock_devices_[0], Scan(Device::kFullScan, _, _));
1637    manager()->RequestScan(Device::kFullScan, kTypeWifi, &error);
1638    manager()->DeregisterDevice(mock_devices_[0].get());
1639    Mock::VerifyAndClearExpectations(mock_devices_[0].get());
1640
1641    manager()->RegisterDevice(mock_devices_[0].get());
1642    EXPECT_CALL(*mock_devices_[0], technology())
1643        .WillRepeatedly(Return(Technology::kUnknown));
1644    EXPECT_CALL(*metrics(), NotifyUserInitiatedEvent(
1645        Metrics::kUserInitiatedEventWifiScan)).Times(0);
1646    EXPECT_CALL(*mock_devices_[0], Scan(_, _, _)).Times(0);
1647    manager()->RequestScan(Device::kFullScan, kTypeWifi, &error);
1648    manager()->DeregisterDevice(mock_devices_[0].get());
1649    Mock::VerifyAndClearExpectations(mock_devices_[0].get());
1650  }
1651
1652  {
1653    Error error;
1654    manager()->RequestScan(Device::kFullScan, "bogus_device_type", &error);
1655    EXPECT_EQ(Error::kInvalidArguments, error.type());
1656  }
1657}
1658
1659TEST_F(ManagerTest, GetServiceNoType) {
1660  KeyValueStore args;
1661  Error e;
1662  manager()->GetService(args, &e);
1663  EXPECT_EQ(Error::kInvalidArguments, e.type());
1664  EXPECT_EQ("must specify service type", e.message());
1665}
1666
1667TEST_F(ManagerTest, GetServiceUnknownType) {
1668  KeyValueStore args;
1669  Error e;
1670  args.SetString(kTypeProperty, kTypeEthernet);
1671  manager()->GetService(args, &e);
1672  EXPECT_EQ(Error::kNotSupported, e.type());
1673  EXPECT_EQ("service type is unsupported", e.message());
1674}
1675
1676#if !defined(DISABLE_WIRED_8021X)
1677TEST_F(ManagerTest, GetServiceEthernetEap) {
1678  KeyValueStore args;
1679  Error e;
1680  ServiceRefPtr service = new NiceMock<MockService>(control_interface(),
1681                                                    dispatcher(),
1682                                                    metrics(),
1683                                                    manager());
1684  args.SetString(kTypeProperty, kTypeEthernetEap);
1685  SetEapProviderService(service);
1686  EXPECT_EQ(service, manager()->GetService(args, &e));
1687  EXPECT_TRUE(e.IsSuccess());
1688}
1689#endif  // DISABLE_WIRED_8021X
1690
1691#if !defined(DISABLE_WIFI)
1692TEST_F(ManagerTest, GetServiceWifi) {
1693  KeyValueStore args;
1694  Error e;
1695  WiFiServiceRefPtr wifi_service;
1696  args.SetString(kTypeProperty, kTypeWifi);
1697  EXPECT_CALL(*wifi_provider_, GetService(_, _))
1698      .WillRepeatedly(Return(wifi_service));
1699  manager()->GetService(args, &e);
1700  EXPECT_TRUE(e.IsSuccess());
1701}
1702#endif  // DISABLE_WIFI
1703
1704TEST_F(ManagerTest, GetServiceVPNUnknownType) {
1705  KeyValueStore args;
1706  Error e;
1707  args.SetString(kTypeProperty, kTypeVPN);
1708  scoped_refptr<MockProfile> profile(
1709      new StrictMock<MockProfile>(
1710          control_interface(), metrics(), manager(), ""));
1711  AdoptProfile(manager(), profile);
1712  ServiceRefPtr service = manager()->GetService(args, &e);
1713  EXPECT_EQ(Error::kNotSupported, e.type());
1714  EXPECT_FALSE(service);
1715}
1716
1717TEST_F(ManagerTest, GetServiceVPN) {
1718  KeyValueStore args;
1719  Error e;
1720  args.SetString(kTypeProperty, kTypeVPN);
1721  args.SetString(kProviderTypeProperty, kProviderOpenVpn);
1722  args.SetString(kProviderHostProperty, "10.8.0.1");
1723  args.SetString(kNameProperty, "vpn-name");
1724  scoped_refptr<MockProfile> profile(
1725      new StrictMock<MockProfile>(
1726          control_interface(), metrics(), manager(), ""));
1727  AdoptProfile(manager(), profile);
1728
1729#if defined(DISABLE_VPN)
1730
1731  ServiceRefPtr service = manager()->GetService(args, &e);
1732  EXPECT_EQ(Error::kNotSupported, e.type());
1733  EXPECT_FALSE(service);
1734
1735#else
1736
1737  ServiceRefPtr updated_service;
1738  EXPECT_CALL(*profile, UpdateService(_))
1739      .WillOnce(DoAll(SaveArg<0>(&updated_service), Return(true)));
1740  ServiceRefPtr configured_service;
1741  EXPECT_CALL(*profile, LoadService(_))
1742      .WillOnce(Return(false));
1743  EXPECT_CALL(*profile, ConfigureService(_))
1744      .WillOnce(DoAll(SaveArg<0>(&configured_service), Return(true)));
1745  ServiceRefPtr service = manager()->GetService(args, &e);
1746  EXPECT_TRUE(e.IsSuccess());
1747  EXPECT_TRUE(service);
1748  EXPECT_EQ(service, updated_service);
1749  EXPECT_EQ(service, configured_service);
1750
1751#endif  // DISABLE_VPN
1752}
1753
1754#if !defined(DISABLE_WIMAX)
1755
1756TEST_F(ManagerTest, GetServiceWiMaxNoNetworkId) {
1757  KeyValueStore args;
1758  Error e;
1759  args.SetString(kTypeProperty, kTypeWimax);
1760  ServiceRefPtr service = manager()->GetService(args, &e);
1761  EXPECT_EQ(Error::kInvalidArguments, e.type());
1762  EXPECT_EQ("Missing WiMAX network id.", e.message());
1763  EXPECT_FALSE(service);
1764}
1765
1766TEST_F(ManagerTest, GetServiceWiMax) {
1767  KeyValueStore args;
1768  Error e;
1769  args.SetString(kTypeProperty, kTypeWimax);
1770  args.SetString(WiMaxService::kNetworkIdProperty, "01234567");
1771  args.SetString(kNameProperty, "WiMAX Network");
1772  ServiceRefPtr service = manager()->GetService(args, &e);
1773  EXPECT_TRUE(e.IsSuccess());
1774  EXPECT_TRUE(service);
1775}
1776
1777#endif  // DISABLE_WIMAX
1778
1779TEST_F(ManagerTest, ConfigureServiceWithInvalidProfile) {
1780  // Manager calls ActiveProfile() so we need at least one profile installed.
1781  scoped_refptr<MockProfile> profile(
1782      new NiceMock<MockProfile>(
1783          control_interface(), metrics(), manager(), ""));
1784  AdoptProfile(manager(), profile);
1785
1786  KeyValueStore args;
1787  args.SetString(kProfileProperty, "xxx");
1788  Error error;
1789  manager()->ConfigureService(args, &error);
1790  EXPECT_EQ(Error::kInvalidArguments, error.type());
1791  EXPECT_EQ("Invalid profile name xxx", error.message());
1792}
1793
1794TEST_F(ManagerTest, ConfigureServiceWithGetServiceFailure) {
1795  // Manager calls ActiveProfile() so we need at least one profile installed.
1796  scoped_refptr<MockProfile> profile(
1797      new NiceMock<MockProfile>(
1798          control_interface(), metrics(), manager(), ""));
1799  AdoptProfile(manager(), profile);
1800
1801  KeyValueStore args;
1802  Error error;
1803  manager()->ConfigureService(args, &error);
1804  EXPECT_EQ(Error::kInvalidArguments, error.type());
1805  EXPECT_EQ("must specify service type", error.message());
1806}
1807
1808#if !defined(DISABLE_WIFI)
1809// TODO(zqiu): Consider creating a TestProvider to provide generic services,
1810// (MockService) instead of using technology specific (wifi) services. This
1811// will remove the dependency for wifi from ConfigureXXX tests.
1812//
1813// A registered service in the ephemeral profile should be moved to the
1814// active profile as a part of configuration if no profile was explicitly
1815// specified.
1816TEST_F(ManagerTest, ConfigureRegisteredServiceWithoutProfile) {
1817  scoped_refptr<MockProfile> profile(
1818      new NiceMock<MockProfile>(
1819          control_interface(), metrics(), manager(), ""));
1820
1821  AdoptProfile(manager(), profile);  // This is now the active profile.
1822
1823  const vector<uint8_t> ssid;
1824  scoped_refptr<MockWiFiService> service(
1825      new NiceMock<MockWiFiService>(control_interface(),
1826                                    dispatcher(),
1827                                    metrics(),
1828                                    manager(),
1829                                    wifi_provider_,
1830                                    ssid,
1831                                    "",
1832                                    "",
1833                                    false));
1834
1835  manager()->RegisterService(service);
1836  service->set_profile(GetEphemeralProfile(manager()));
1837
1838  EXPECT_CALL(*wifi_provider_, GetService(_, _))
1839      .WillOnce(Return(service));
1840  EXPECT_CALL(*profile, UpdateService(ServiceRefPtr(service.get())))
1841      .WillOnce(Return(true));
1842  EXPECT_CALL(*profile, AdoptService(ServiceRefPtr(service.get())))
1843      .WillOnce(Return(true));
1844
1845  KeyValueStore args;
1846  args.SetString(kTypeProperty, kTypeWifi);
1847  Error error;
1848  manager()->ConfigureService(args, &error);
1849  EXPECT_TRUE(error.IsSuccess());
1850}
1851
1852// If we configure a service that was already registered and explicitly
1853// specify a profile, it should be moved from the profile it was previously
1854// in to the specified profile if one was requested.
1855TEST_F(ManagerTest, ConfigureRegisteredServiceWithProfile) {
1856  scoped_refptr<MockProfile> profile0(
1857      new NiceMock<MockProfile>(
1858          control_interface(), metrics(), manager(), ""));
1859  scoped_refptr<MockProfile> profile1(
1860      new NiceMock<MockProfile>(
1861          control_interface(), metrics(), manager(), ""));
1862
1863  const string kProfileName0 = "profile0";
1864  const string kProfileName1 = "profile1";
1865
1866  EXPECT_CALL(*profile0, GetRpcIdentifier())
1867      .WillRepeatedly(Return(kProfileName0));
1868  EXPECT_CALL(*profile1, GetRpcIdentifier())
1869      .WillRepeatedly(Return(kProfileName1));
1870
1871  AdoptProfile(manager(), profile0);
1872  AdoptProfile(manager(), profile1);  // profile1 is now the ActiveProfile.
1873
1874  const vector<uint8_t> ssid;
1875  scoped_refptr<MockWiFiService> service(
1876      new NiceMock<MockWiFiService>(control_interface(),
1877                                    dispatcher(),
1878                                    metrics(),
1879                                    manager(),
1880                                    wifi_provider_,
1881                                    ssid,
1882                                    "",
1883                                    "",
1884                                    false));
1885
1886  manager()->RegisterService(service);
1887  service->set_profile(profile1);
1888
1889  EXPECT_CALL(*wifi_provider_, GetService(_, _))
1890      .WillOnce(Return(service));
1891  EXPECT_CALL(*profile0, LoadService(ServiceRefPtr(service.get())))
1892      .WillOnce(Return(true));
1893  EXPECT_CALL(*profile0, UpdateService(ServiceRefPtr(service.get())))
1894      .WillOnce(Return(true));
1895  EXPECT_CALL(*profile0, AdoptService(ServiceRefPtr(service.get())))
1896      .WillOnce(Return(true));
1897  EXPECT_CALL(*profile1, AbandonService(ServiceRefPtr(service.get())))
1898      .WillOnce(Return(true));
1899
1900  KeyValueStore args;
1901  args.SetString(kTypeProperty, kTypeWifi);
1902  args.SetString(kProfileProperty, kProfileName0);
1903  Error error;
1904  manager()->ConfigureService(args, &error);
1905  EXPECT_TRUE(error.IsSuccess());
1906  service->set_profile(nullptr);  // Breaks refcounting loop.
1907}
1908
1909// If we configure a service that is already a member of the specified
1910// profile, the Manager should not call LoadService or AdoptService again
1911// on this service.
1912TEST_F(ManagerTest, ConfigureRegisteredServiceWithSameProfile) {
1913  scoped_refptr<MockProfile> profile0(
1914      new NiceMock<MockProfile>(
1915          control_interface(), metrics(), manager(), ""));
1916
1917  const string kProfileName0 = "profile0";
1918
1919  EXPECT_CALL(*profile0, GetRpcIdentifier())
1920      .WillRepeatedly(Return(kProfileName0));
1921
1922  AdoptProfile(manager(), profile0);  // profile0 is now the ActiveProfile.
1923
1924  const vector<uint8_t> ssid;
1925  scoped_refptr<MockWiFiService> service(
1926      new NiceMock<MockWiFiService>(control_interface(),
1927                                    dispatcher(),
1928                                    metrics(),
1929                                    manager(),
1930                                    wifi_provider_,
1931                                    ssid,
1932                                    "",
1933                                    "",
1934                                    false));
1935
1936  manager()->RegisterService(service);
1937  service->set_profile(profile0);
1938
1939  EXPECT_CALL(*wifi_provider_, GetService(_, _))
1940      .WillOnce(Return(service));
1941  EXPECT_CALL(*profile0, LoadService(ServiceRefPtr(service.get())))
1942      .Times(0);
1943  EXPECT_CALL(*profile0, UpdateService(ServiceRefPtr(service.get())))
1944      .WillOnce(Return(true));
1945  EXPECT_CALL(*profile0, AdoptService(ServiceRefPtr(service.get())))
1946      .Times(0);
1947
1948  KeyValueStore args;
1949  args.SetString(kTypeProperty, kTypeWifi);
1950  args.SetString(kProfileProperty, kProfileName0);
1951  Error error;
1952  manager()->ConfigureService(args, &error);
1953  EXPECT_TRUE(error.IsSuccess());
1954  service->set_profile(nullptr);  // Breaks refcounting loop.
1955}
1956
1957// An unregistered service should remain unregistered, but its contents should
1958// be saved to the specified profile nonetheless.
1959TEST_F(ManagerTest, ConfigureUnregisteredServiceWithProfile) {
1960  scoped_refptr<MockProfile> profile0(
1961      new NiceMock<MockProfile>(
1962          control_interface(), metrics(), manager(), ""));
1963  scoped_refptr<MockProfile> profile1(
1964      new NiceMock<MockProfile>(
1965          control_interface(), metrics(), manager(), ""));
1966
1967  const string kProfileName0 = "profile0";
1968  const string kProfileName1 = "profile1";
1969
1970  EXPECT_CALL(*profile0, GetRpcIdentifier())
1971      .WillRepeatedly(Return(kProfileName0));
1972  EXPECT_CALL(*profile1, GetRpcIdentifier())
1973      .WillRepeatedly(Return(kProfileName1));
1974
1975  AdoptProfile(manager(), profile0);
1976  AdoptProfile(manager(), profile1);  // profile1 is now the ActiveProfile.
1977
1978  const vector<uint8_t> ssid;
1979  scoped_refptr<MockWiFiService> service(
1980      new NiceMock<MockWiFiService>(control_interface(),
1981                                    dispatcher(),
1982                                    metrics(),
1983                                    manager(),
1984                                    wifi_provider_,
1985                                    ssid,
1986                                    "",
1987                                    "",
1988                                    false));
1989
1990  service->set_profile(profile1);
1991
1992  EXPECT_CALL(*wifi_provider_, GetService(_, _))
1993      .WillOnce(Return(service));
1994  EXPECT_CALL(*profile0, UpdateService(ServiceRefPtr(service.get())))
1995      .WillOnce(Return(true));
1996  EXPECT_CALL(*profile0, AdoptService(_))
1997      .Times(0);
1998  EXPECT_CALL(*profile1, AdoptService(_))
1999      .Times(0);
2000
2001  KeyValueStore args;
2002  args.SetString(kTypeProperty, kTypeWifi);
2003  args.SetString(kProfileProperty, kProfileName0);
2004  Error error;
2005  manager()->ConfigureService(args, &error);
2006  EXPECT_TRUE(error.IsSuccess());
2007}
2008
2009TEST_F(ManagerTest, ConfigureServiceForProfileWithNoType) {
2010  KeyValueStore args;
2011  Error error;
2012  ServiceRefPtr service =
2013      manager()->ConfigureServiceForProfile("", args, &error);
2014  EXPECT_EQ(Error::kInvalidArguments, error.type());
2015  EXPECT_EQ("must specify service type", error.message());
2016  EXPECT_EQ(nullptr, service.get());
2017}
2018
2019TEST_F(ManagerTest, ConfigureServiceForProfileWithWrongType) {
2020  KeyValueStore args;
2021  args.SetString(kTypeProperty, kTypeCellular);
2022  Error error;
2023  ServiceRefPtr service =
2024      manager()->ConfigureServiceForProfile("", args, &error);
2025  EXPECT_EQ(Error::kNotSupported, error.type());
2026  EXPECT_EQ("service type is unsupported", error.message());
2027  EXPECT_EQ(nullptr, service.get());
2028}
2029
2030TEST_F(ManagerTest, ConfigureServiceForProfileWithMissingProfile) {
2031  KeyValueStore args;
2032  args.SetString(kTypeProperty, kTypeWifi);
2033  Error error;
2034  ServiceRefPtr service =
2035      manager()->ConfigureServiceForProfile("/profile/foo", args, &error);
2036  EXPECT_EQ(Error::kNotFound, error.type());
2037  EXPECT_EQ("Profile specified was not found", error.message());
2038  EXPECT_EQ(nullptr, service.get());
2039}
2040
2041TEST_F(ManagerTest, ConfigureServiceForProfileWithProfileMismatch) {
2042  const string kProfileName0 = "profile0";
2043  const string kProfileName1 = "profile1";
2044  scoped_refptr<MockProfile> profile0(
2045      AddNamedMockProfileToManager(manager(), kProfileName0));
2046
2047  KeyValueStore args;
2048  args.SetString(kTypeProperty, kTypeWifi);
2049  args.SetString(kProfileProperty, kProfileName1);
2050  Error error;
2051  ServiceRefPtr service =
2052      manager()->ConfigureServiceForProfile(kProfileName0, args, &error);
2053  EXPECT_EQ(Error::kInvalidArguments, error.type());
2054  EXPECT_EQ("Profile argument does not match that in "
2055            "the configuration arguments", error.message());
2056  EXPECT_EQ(nullptr, service.get());
2057}
2058
2059TEST_F(ManagerTest,
2060       ConfigureServiceForProfileWithNoMatchingServiceFailGetService) {
2061  const string kProfileName0 = "profile0";
2062  scoped_refptr<MockProfile> profile0(
2063      AddNamedMockProfileToManager(manager(), kProfileName0));
2064  KeyValueStore args;
2065  args.SetString(kTypeProperty, kTypeWifi);
2066  args.SetString(kProfileProperty, kProfileName0);
2067
2068  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2069      .WillOnce(Return(WiFiServiceRefPtr()));
2070  EXPECT_CALL(*wifi_provider_, GetService(_, _))
2071      .WillOnce(Return(WiFiServiceRefPtr()));
2072  Error error;
2073  ServiceRefPtr service =
2074      manager()->ConfigureServiceForProfile(kProfileName0, args, &error);
2075  // Since we didn't set the error in the GetService expectation above...
2076  EXPECT_TRUE(error.IsSuccess());
2077  EXPECT_EQ(nullptr, service.get());
2078}
2079
2080TEST_F(ManagerTest, ConfigureServiceForProfileCreateNewService) {
2081  const string kProfileName0 = "profile0";
2082  scoped_refptr<MockProfile> profile0(
2083      AddNamedMockProfileToManager(manager(), kProfileName0));
2084
2085  KeyValueStore args;
2086  args.SetString(kTypeProperty, kTypeWifi);
2087
2088  scoped_refptr<MockWiFiService> mock_service(
2089      new NiceMock<MockWiFiService>(control_interface(),
2090                                    dispatcher(),
2091                                    metrics(),
2092                                    manager(),
2093                                    wifi_provider_,
2094                                    vector<uint8_t>(),
2095                                    kModeManaged,
2096                                    kSecurityNone,
2097                                    false));
2098  ServiceRefPtr mock_service_generic(mock_service.get());
2099  mock_service->set_profile(profile0);
2100  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2101      .WillOnce(Return(WiFiServiceRefPtr()));
2102  EXPECT_CALL(*wifi_provider_, GetService(_, _)).WillOnce(Return(mock_service));
2103  EXPECT_CALL(*profile0, UpdateService(mock_service_generic))
2104      .WillOnce(Return(true));
2105  Error error;
2106  ServiceRefPtr service =
2107      manager()->ConfigureServiceForProfile(kProfileName0, args, &error);
2108  EXPECT_TRUE(error.IsSuccess());
2109  EXPECT_EQ(mock_service.get(), service.get());
2110  mock_service->set_profile(nullptr);  // Breaks reference cycle.
2111}
2112
2113TEST_F(ManagerTest, ConfigureServiceForProfileMatchingServiceByGUID) {
2114  scoped_refptr<MockService> mock_service(
2115      new NiceMock<MockService>(control_interface(),
2116                                dispatcher(),
2117                                metrics(),
2118                                manager()));
2119  const string kGUID = "a guid";
2120  mock_service->SetGuid(kGUID, nullptr);
2121  manager()->RegisterService(mock_service);
2122  ServiceRefPtr mock_service_generic(mock_service.get());
2123
2124  const string kProfileName = "profile";
2125  scoped_refptr<MockProfile> profile(
2126      AddNamedMockProfileToManager(manager(), kProfileName));
2127  mock_service->set_profile(profile);
2128
2129  EXPECT_CALL(*mock_service, technology())
2130     .WillOnce(Return(Technology::kCellular))
2131     .WillOnce(Return(Technology::kWifi));
2132
2133  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _)).Times(0);
2134  EXPECT_CALL(*wifi_provider_, GetService(_, _)).Times(0);
2135  EXPECT_CALL(*profile, AdoptService(mock_service_generic)).Times(0);
2136
2137  KeyValueStore args;
2138  args.SetString(kTypeProperty, kTypeWifi);
2139  args.SetString(kGuidProperty, kGUID);
2140
2141  // The first attempt should fail because the service reports a technology
2142  // other than "WiFi".
2143  {
2144    Error error;
2145    ServiceRefPtr service =
2146        manager()->ConfigureServiceForProfile(kProfileName, args, &error);
2147    EXPECT_EQ(nullptr, service.get());
2148    EXPECT_EQ(Error::kNotSupported, error.type());
2149    EXPECT_EQ("This GUID matches a non-wifi service", error.message());
2150  }
2151
2152  EXPECT_CALL(*mock_service, Configure(_, _)).Times(1);
2153  EXPECT_CALL(*profile, UpdateService(mock_service_generic)).Times(1);
2154
2155  {
2156    Error error;
2157    ServiceRefPtr service =
2158        manager()->ConfigureServiceForProfile(kProfileName, args, &error);
2159    EXPECT_TRUE(error.IsSuccess());
2160    EXPECT_EQ(mock_service.get(), service.get());
2161    EXPECT_EQ(profile.get(), service->profile().get());
2162  }
2163  mock_service->set_profile(nullptr);  // Breaks reference cycle.
2164}
2165
2166TEST_F(ManagerTest, ConfigureServiceForProfileMatchingServiceAndProfile) {
2167  const string kProfileName = "profile";
2168  scoped_refptr<MockProfile> profile(
2169      AddNamedMockProfileToManager(manager(), kProfileName));
2170
2171  scoped_refptr<MockWiFiService> mock_service(
2172      new NiceMock<MockWiFiService>(control_interface(),
2173                                    dispatcher(),
2174                                    metrics(),
2175                                    manager(),
2176                                    wifi_provider_,
2177                                    vector<uint8_t>(),
2178                                    kModeManaged,
2179                                    kSecurityNone,
2180                                    false));
2181  mock_service->set_profile(profile);
2182  ServiceRefPtr mock_service_generic(mock_service.get());
2183
2184  KeyValueStore args;
2185  args.SetString(kTypeProperty, kTypeWifi);
2186  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2187      .WillOnce(Return(mock_service));
2188  EXPECT_CALL(*wifi_provider_, GetService(_, _)).Times(0);
2189  EXPECT_CALL(*profile, AdoptService(mock_service_generic)).Times(0);
2190  EXPECT_CALL(*mock_service, Configure(_, _)).Times(1);
2191  EXPECT_CALL(*profile, UpdateService(mock_service_generic)).Times(1);
2192
2193  Error error;
2194  ServiceRefPtr service =
2195      manager()->ConfigureServiceForProfile(kProfileName, args, &error);
2196  EXPECT_TRUE(error.IsSuccess());
2197  EXPECT_EQ(mock_service.get(), service.get());
2198  EXPECT_EQ(profile.get(), service->profile().get());
2199  mock_service->set_profile(nullptr);  // Breaks reference cycle.
2200}
2201
2202TEST_F(ManagerTest, ConfigureServiceForProfileMatchingServiceEphemeralProfile) {
2203  const string kProfileName = "profile";
2204  scoped_refptr<MockProfile> profile(
2205      AddNamedMockProfileToManager(manager(), kProfileName));
2206
2207  scoped_refptr<MockWiFiService> mock_service(
2208      new NiceMock<MockWiFiService>(control_interface(),
2209                                    dispatcher(),
2210                                    metrics(),
2211                                    manager(),
2212                                    wifi_provider_,
2213                                    vector<uint8_t>(),
2214                                    kModeManaged,
2215                                    kSecurityNone,
2216                                    false));
2217  mock_service->set_profile(GetEphemeralProfile(manager()));
2218  ServiceRefPtr mock_service_generic(mock_service.get());
2219
2220  KeyValueStore args;
2221  args.SetString(kTypeProperty, kTypeWifi);
2222  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2223      .WillOnce(Return(mock_service));
2224  EXPECT_CALL(*wifi_provider_, GetService(_, _)).Times(0);
2225  EXPECT_CALL(*mock_service, Configure(_, _)).Times(1);
2226  EXPECT_CALL(*profile, UpdateService(mock_service_generic)).Times(1);
2227
2228  Error error;
2229  ServiceRefPtr service =
2230      manager()->ConfigureServiceForProfile(kProfileName, args, &error);
2231  EXPECT_TRUE(error.IsSuccess());
2232  EXPECT_EQ(mock_service.get(), service.get());
2233  EXPECT_EQ(profile.get(), service->profile().get());
2234  mock_service->set_profile(nullptr);  // Breaks reference cycle.
2235}
2236
2237TEST_F(ManagerTest, ConfigureServiceForProfileMatchingServicePrecedingProfile) {
2238  const string kProfileName0 = "profile0";
2239  scoped_refptr<MockProfile> profile0(
2240      AddNamedMockProfileToManager(manager(), kProfileName0));
2241  const string kProfileName1 = "profile1";
2242  scoped_refptr<MockProfile> profile1(
2243      AddNamedMockProfileToManager(manager(), kProfileName1));
2244
2245  scoped_refptr<MockWiFiService> mock_service(
2246      new NiceMock<MockWiFiService>(control_interface(),
2247                                    dispatcher(),
2248                                    metrics(),
2249                                    manager(),
2250                                    wifi_provider_,
2251                                    vector<uint8_t>(),
2252                                    kModeManaged,
2253                                    kSecurityNone,
2254                                    false));
2255  manager()->RegisterService(mock_service);
2256  mock_service->set_profile(profile0);
2257  ServiceRefPtr mock_service_generic(mock_service.get());
2258
2259  KeyValueStore args;
2260  args.SetString(kTypeProperty, kTypeWifi);
2261  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2262      .WillOnce(Return(mock_service));
2263  EXPECT_CALL(*wifi_provider_, GetService(_, _)).Times(0);
2264  EXPECT_CALL(*profile0, AbandonService(_)).Times(0);
2265  EXPECT_CALL(*profile1, AdoptService(_)).Times(0);
2266  // This happens once to make the service loadable for the ConfigureService
2267  // below, and a second time after the service is modified.
2268  EXPECT_CALL(*profile1, ConfigureService(mock_service_generic)).Times(0);
2269  EXPECT_CALL(*wifi_provider_, CreateTemporaryService(_, _)).Times(0);
2270  EXPECT_CALL(*mock_service, Configure(_, _)).Times(1);
2271  EXPECT_CALL(*profile1, UpdateService(mock_service_generic)).Times(1);
2272
2273  Error error;
2274  ServiceRefPtr service =
2275      manager()->ConfigureServiceForProfile(kProfileName1, args, &error);
2276  EXPECT_TRUE(error.IsSuccess());
2277  EXPECT_EQ(mock_service.get(), service.get());
2278  mock_service->set_profile(nullptr);  // Breaks reference cycle.
2279}
2280
2281TEST_F(ManagerTest,
2282       ConfigureServiceForProfileMatchingServiceProceedingProfile) {
2283  const string kProfileName0 = "profile0";
2284  scoped_refptr<MockProfile> profile0(
2285      AddNamedMockProfileToManager(manager(), kProfileName0));
2286  const string kProfileName1 = "profile1";
2287  scoped_refptr<MockProfile> profile1(
2288      AddNamedMockProfileToManager(manager(), kProfileName1));
2289
2290  scoped_refptr<MockWiFiService> matching_service(
2291      new StrictMock<MockWiFiService>(control_interface(),
2292                                      dispatcher(),
2293                                      metrics(),
2294                                      manager(),
2295                                      wifi_provider_,
2296                                      vector<uint8_t>(),
2297                                      kModeManaged,
2298                                      kSecurityNone,
2299                                      false));
2300  matching_service->set_profile(profile1);
2301
2302  // We need to get rid of our reference to this mock service as soon
2303  // as Manager::ConfigureServiceForProfile() takes a reference in its
2304  // call to WiFiProvider::CreateTemporaryService().  This way the
2305  // latter function can keep a DCHECK(service->HasOneRef() even in
2306  // unit tests.
2307  temp_mock_service_ =
2308      new NiceMock<MockWiFiService>(control_interface(),
2309                                    dispatcher(),
2310                                    metrics(),
2311                                    manager(),
2312                                    wifi_provider_,
2313                                    vector<uint8_t>(),
2314                                    kModeManaged,
2315                                    kSecurityNone,
2316                                    false);
2317
2318  // Only hold a pointer here so we don't affect the refcount.
2319  MockWiFiService* mock_service_ptr = temp_mock_service_.get();
2320
2321  KeyValueStore args;
2322  args.SetString(kTypeProperty, kTypeWifi);
2323  EXPECT_CALL(*wifi_provider_, FindSimilarService(_, _))
2324      .WillOnce(Return(matching_service));
2325  EXPECT_CALL(*wifi_provider_, GetService(_, _)).Times(0);
2326  EXPECT_CALL(*profile1, AbandonService(_)).Times(0);
2327  EXPECT_CALL(*profile0, AdoptService(_)).Times(0);
2328  EXPECT_CALL(*wifi_provider_, CreateTemporaryService(_, _))
2329      .WillOnce(InvokeWithoutArgs(this, &ManagerTest::ReleaseTempMockService));
2330  EXPECT_CALL(*profile0, ConfigureService(IsRefPtrTo(mock_service_ptr)))
2331      .Times(1);
2332  EXPECT_CALL(*mock_service_ptr, Configure(_, _)).Times(1);
2333  EXPECT_CALL(*profile0, UpdateService(IsRefPtrTo(mock_service_ptr))).Times(1);
2334
2335  Error error;
2336  ServiceRefPtr service =
2337      manager()->ConfigureServiceForProfile(kProfileName0, args, &error);
2338  EXPECT_TRUE(error.IsSuccess());
2339  EXPECT_EQ(nullptr, service.get());
2340  EXPECT_EQ(profile1.get(), matching_service->profile().get());
2341}
2342
2343#if defined(__BRILLO__)
2344TEST_F(ManagerTest, SetupApModeInterface) {
2345  const string kApInterfaceName = "Test-Interface";
2346  string ap_interface;
2347  Error error;
2348
2349  // Failed to setup AP mode interface.
2350  EXPECT_CALL(wifi_driver_hal_, SetupApModeInterface()).WillOnce(Return(""));
2351  EXPECT_FALSE(
2352      manager()->SetupApModeInterface(&ap_interface, &error));
2353  Mock::VerifyAndClearExpectations(&wifi_driver_hal_);
2354  EXPECT_TRUE(error.IsFailure());
2355  EXPECT_EQ("Failed to setup AP mode interface", error.message());
2356
2357  // AP mode interface setup succeed.
2358  error.Reset();
2359  EXPECT_CALL(wifi_driver_hal_, SetupApModeInterface())
2360      .WillOnce(Return(kApInterfaceName));
2361  EXPECT_TRUE(
2362      manager()->SetupApModeInterface(&ap_interface, &error));
2363  Mock::VerifyAndClearExpectations(&wifi_driver_hal_);
2364  Mock::VerifyAndClearExpectations(control_interface());
2365  EXPECT_TRUE(error.IsSuccess());
2366  EXPECT_EQ(kApInterfaceName, ap_interface);
2367}
2368
2369TEST_F(ManagerTest, SetupStationModeInterface) {
2370  const string kStationInterfaceName = "Test-Interface";
2371  string station_interface;
2372  Error error;
2373
2374  // Failed to setup station mode interface.
2375  EXPECT_CALL(wifi_driver_hal_, SetupStationModeInterface())
2376      .WillOnce(Return(""));
2377  EXPECT_FALSE(
2378      manager()->SetupStationModeInterface(&station_interface, &error));
2379  Mock::VerifyAndClearExpectations(&wifi_driver_hal_);
2380  EXPECT_TRUE(error.IsFailure());
2381  EXPECT_EQ("Failed to setup station mode interface", error.message());
2382
2383  // Station mode interface setup succeed.
2384  error.Reset();
2385  EXPECT_CALL(wifi_driver_hal_, SetupStationModeInterface())
2386      .WillOnce(Return(kStationInterfaceName));
2387  EXPECT_TRUE(
2388      manager()->SetupStationModeInterface(&station_interface, &error));
2389  Mock::VerifyAndClearExpectations(&wifi_driver_hal_);
2390  EXPECT_TRUE(error.IsSuccess());
2391  EXPECT_EQ(kStationInterfaceName, station_interface);
2392}
2393
2394TEST_F(ManagerTest, OnApModeSetterVanished) {
2395  const string kStationInterfaceName = "Test-Interface";
2396
2397  EXPECT_CALL(wifi_driver_hal_, SetupStationModeInterface())
2398      .WillOnce(Return(kStationInterfaceName));
2399  manager()->OnApModeSetterVanished();
2400  Mock::VerifyAndClearExpectations(&wifi_driver_hal_);
2401}
2402#endif  // __BRILLO__
2403#endif  // DISABLE_WIFI
2404
2405TEST_F(ManagerTest, FindMatchingService) {
2406  KeyValueStore args;
2407  {
2408    Error error;
2409    ServiceRefPtr service = manager()->FindMatchingService(args, &error);
2410    EXPECT_EQ(Error::kNotFound, error.type());
2411  }
2412
2413  scoped_refptr<MockService> mock_service0(
2414      new NiceMock<MockService>(control_interface(),
2415                                dispatcher(),
2416                                metrics(),
2417                                manager()));
2418  scoped_refptr<MockService> mock_service1(
2419      new NiceMock<MockService>(control_interface(),
2420                                dispatcher(),
2421                                metrics(),
2422                                manager()));
2423  manager()->RegisterService(mock_service0);
2424  manager()->RegisterService(mock_service1);
2425  EXPECT_CALL(*mock_service0, DoPropertiesMatch(_))
2426      .WillOnce(Return(true))
2427      .WillRepeatedly(Return(false));
2428  {
2429    Error error;
2430    EXPECT_EQ(mock_service0, manager()->FindMatchingService(args, &error));
2431    EXPECT_TRUE(error.IsSuccess());
2432  }
2433  EXPECT_CALL(*mock_service1, DoPropertiesMatch(_))
2434      .WillOnce(Return(true))
2435      .WillRepeatedly(Return(false));
2436  {
2437    Error error;
2438    EXPECT_EQ(mock_service1, manager()->FindMatchingService(args, &error));
2439    EXPECT_TRUE(error.IsSuccess());
2440  }
2441  {
2442    Error error;
2443    EXPECT_FALSE(manager()->FindMatchingService(args, &error));
2444    EXPECT_EQ(Error::kNotFound, error.type());
2445  }
2446}
2447
2448TEST_F(ManagerTest, TechnologyOrder) {
2449  // If the Manager is not running, setting the technology order should not
2450  // lauch a service sorting task.
2451  SetRunning(false);
2452  Error error;
2453  manager()->SetTechnologyOrder("vpn,ethernet,wifi,wimax,cellular", &error);
2454  ASSERT_TRUE(error.IsSuccess());
2455  EXPECT_FALSE(IsSortServicesTaskPending());
2456  EXPECT_THAT(GetTechnologyOrder(), ElementsAre(Technology::kVPN,
2457                                                Technology::kEthernet,
2458                                                Technology::kWifi,
2459                                                Technology::kWiMax,
2460                                                Technology::kCellular));
2461
2462  SetRunning(true);
2463  manager()->SetTechnologyOrder(string(kTypeEthernet) + "," + string(kTypeWifi),
2464                                &error);
2465  EXPECT_TRUE(IsSortServicesTaskPending());
2466  ASSERT_TRUE(error.IsSuccess());
2467  EXPECT_EQ(manager()->GetTechnologyOrder(),
2468            string(kTypeEthernet) + "," + string(kTypeWifi));
2469
2470  manager()->SetTechnologyOrder(string(kTypeEthernet) + "x," +
2471                                string(kTypeWifi), &error);
2472  ASSERT_FALSE(error.IsSuccess());
2473  EXPECT_EQ(Error::kInvalidArguments, error.type());
2474  EXPECT_EQ(string(kTypeEthernet) + "," + string(kTypeWifi),
2475            manager()->GetTechnologyOrder());
2476}
2477
2478TEST_F(ManagerTest, ConnectionStatusCheck) {
2479  // Setup mock metrics and service.
2480  MockMetrics mock_metrics(dispatcher());
2481  SetMetrics(&mock_metrics);
2482  scoped_refptr<MockService> mock_service = new NiceMock<MockService>(
2483      control_interface(), dispatcher(), metrics(), manager());
2484  manager()->RegisterService(mock_service);
2485
2486  // Device not connected.
2487  EXPECT_CALL(*mock_service.get(), IsConnected())
2488      .WillOnce(Return(false));
2489  EXPECT_CALL(mock_metrics,
2490      NotifyDeviceConnectionStatus(Metrics::kConnectionStatusOffline));
2491  manager()->ConnectionStatusCheck();
2492
2493  // Device connected, but not online.
2494  EXPECT_CALL(*mock_service.get(), IsConnected())
2495      .WillOnce(Return(true));
2496  EXPECT_CALL(*mock_service.get(), IsOnline())
2497      .WillOnce(Return(false));
2498  EXPECT_CALL(mock_metrics,
2499      NotifyDeviceConnectionStatus(Metrics::kConnectionStatusOnline)).Times(0);
2500  EXPECT_CALL(mock_metrics,
2501      NotifyDeviceConnectionStatus(Metrics::kConnectionStatusConnected));
2502  manager()->ConnectionStatusCheck();
2503
2504  // Device connected and online.
2505  EXPECT_CALL(*mock_service.get(), IsConnected())
2506      .WillOnce(Return(true));
2507  EXPECT_CALL(*mock_service.get(), IsOnline())
2508      .WillOnce(Return(true));
2509  EXPECT_CALL(mock_metrics,
2510      NotifyDeviceConnectionStatus(Metrics::kConnectionStatusOnline));
2511  EXPECT_CALL(mock_metrics,
2512      NotifyDeviceConnectionStatus(Metrics::kConnectionStatusConnected));
2513  manager()->ConnectionStatusCheck();
2514}
2515
2516TEST_F(ManagerTest, DevicePresenceStatusCheck) {
2517  // Setup mock metrics and service.
2518  MockMetrics mock_metrics(dispatcher());
2519  SetMetrics(&mock_metrics);
2520
2521  manager()->RegisterDevice(mock_devices_[0]);
2522  manager()->RegisterDevice(mock_devices_[1]);
2523  manager()->RegisterDevice(mock_devices_[2]);
2524  manager()->RegisterDevice(mock_devices_[3]);
2525
2526  ON_CALL(*mock_devices_[0].get(), technology())
2527      .WillByDefault(Return(Technology::kEthernet));
2528  ON_CALL(*mock_devices_[1].get(), technology())
2529      .WillByDefault(Return(Technology::kWifi));
2530  ON_CALL(*mock_devices_[2].get(), technology())
2531      .WillByDefault(Return(Technology::kCellular));
2532  ON_CALL(*mock_devices_[3].get(), technology())
2533      .WillByDefault(Return(Technology::kWifi));
2534
2535  EXPECT_CALL(mock_metrics,
2536      NotifyDevicePresenceStatus(Technology::kEthernet, true));
2537  EXPECT_CALL(mock_metrics,
2538      NotifyDevicePresenceStatus(Technology::kWifi, true));
2539  EXPECT_CALL(mock_metrics,
2540      NotifyDevicePresenceStatus(Technology::kWiMax, false));
2541  EXPECT_CALL(mock_metrics,
2542      NotifyDevicePresenceStatus(Technology::kCellular, true));
2543  manager()->DevicePresenceStatusCheck();
2544}
2545
2546TEST_F(ManagerTest, SortServicesWithConnection) {
2547  MockMetrics mock_metrics(dispatcher());
2548  SetMetrics(&mock_metrics);
2549
2550  scoped_refptr<MockService> mock_service0(
2551      new NiceMock<MockService>(control_interface(),
2552                                dispatcher(),
2553                                metrics(),
2554                                manager()));
2555  scoped_refptr<MockService> mock_service1(
2556      new NiceMock<MockService>(control_interface(),
2557                                dispatcher(),
2558                                metrics(),
2559                                manager()));
2560
2561  scoped_refptr<MockConnection> mock_connection0(
2562      new NiceMock<MockConnection>(device_info_.get()));
2563  scoped_refptr<MockConnection> mock_connection1(
2564      new NiceMock<MockConnection>(device_info_.get()));
2565
2566  // A single registered Service, without a connection.  The
2567  // DefaultService should be nullptr.  If a change notification is
2568  // generated, it should reference kNullPath.
2569  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2570  EXPECT_CALL(*manager_adaptor_,
2571              EmitRpcIdentifierChanged(
2572                  kDefaultServiceProperty,
2573                  control_interface()->NullRPCIdentifier()))
2574      .Times(AnyNumber());
2575  manager()->RegisterService(mock_service0);
2576  CompleteServiceSort();
2577
2578  // Adding another Service, also without a connection, does not
2579  // change DefaultService.  Furthermore, we do not send a change
2580  // notification for DefaultService.
2581  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2582  EXPECT_CALL(*manager_adaptor_,
2583              EmitRpcIdentifierChanged(kDefaultServiceProperty, _))
2584      .Times(0);
2585  manager()->RegisterService(mock_service1);
2586  CompleteServiceSort();
2587
2588  // An explicit sort doesn't change anything, and does not emit a
2589  // change notification for DefaultService.
2590  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2591  EXPECT_CALL(*manager_adaptor_,
2592              EmitRpcIdentifierChanged(kDefaultServiceProperty, _))
2593      .Times(0);
2594  manager()->SortServicesTask();
2595  EXPECT_TRUE(ServiceOrderIs(mock_service0, mock_service1));
2596
2597  // Re-ordering the unconnected Services doesn't change
2598  // DefaultService, and (hence) does not emit a change notification
2599  // for DefaultService.
2600  mock_service1->SetPriority(1, nullptr);
2601  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2602  EXPECT_CALL(*manager_adaptor_,
2603              EmitRpcIdentifierChanged(kDefaultServiceProperty, _))
2604      .Times(0);
2605  manager()->SortServicesTask();
2606  EXPECT_TRUE(ServiceOrderIs(mock_service1, mock_service0));
2607
2608  // Re-ordering the unconnected Services doesn't change
2609  // DefaultService, and (hence) does not emit a change notification
2610  // for DefaultService.
2611  mock_service1->SetPriority(0, nullptr);
2612  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2613  EXPECT_CALL(*manager_adaptor_,
2614              EmitRpcIdentifierChanged(kDefaultServiceProperty, _))
2615      .Times(0);
2616  manager()->SortServicesTask();
2617  EXPECT_TRUE(ServiceOrderIs(mock_service0, mock_service1));
2618
2619  mock_service0->set_mock_connection(mock_connection0);
2620  mock_service1->set_mock_connection(mock_connection1);
2621
2622  // If both Services have Connections, the DefaultService follows
2623  // from ServiceOrderIs.  We notify others of the change in
2624  // DefaultService.
2625  EXPECT_CALL(*mock_connection0.get(), SetIsDefault(true));
2626  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(mock_service0.get()));
2627  EXPECT_CALL(*manager_adaptor_,
2628              EmitRpcIdentifierChanged(kDefaultServiceProperty, _));
2629  manager()->SortServicesTask();
2630  EXPECT_TRUE(ServiceOrderIs(mock_service0, mock_service1));
2631
2632  ServiceWatcher service_watcher;
2633  int tag =
2634      manager()->RegisterDefaultServiceCallback(
2635          Bind(&ServiceWatcher::OnDefaultServiceChanged,
2636               service_watcher.AsWeakPtr()));
2637  EXPECT_EQ(1, tag);
2638
2639  // Changing the ordering causes the DefaultService to change, and
2640  // appropriate notifications are sent.
2641  mock_service1->SetPriority(1, nullptr);
2642  EXPECT_CALL(*mock_connection0.get(), SetIsDefault(false));
2643  EXPECT_CALL(*mock_connection1.get(), SetIsDefault(true));
2644  EXPECT_CALL(service_watcher, OnDefaultServiceChanged(_));
2645  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(mock_service1.get()));
2646  EXPECT_CALL(*manager_adaptor_,
2647              EmitRpcIdentifierChanged(kDefaultServiceProperty, _));
2648  manager()->SortServicesTask();
2649  EXPECT_TRUE(ServiceOrderIs(mock_service1, mock_service0));
2650
2651  // Deregistering a DefaultServiceCallback works as expected.  (Later
2652  // code causes DefaultService changes, but we see no further calls
2653  // to |service_watcher|.)
2654  manager()->DeregisterDefaultServiceCallback(tag);
2655  EXPECT_CALL(service_watcher, OnDefaultServiceChanged(_)).Times(0);
2656
2657  // Deregistering the current DefaultService causes the other Service
2658  // to become default.  Appropriate notifications are sent.
2659  EXPECT_CALL(*mock_connection0.get(), SetIsDefault(true));
2660  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(mock_service0.get()));
2661  EXPECT_CALL(*manager_adaptor_,
2662              EmitRpcIdentifierChanged(kDefaultServiceProperty, _));
2663  mock_service1->set_mock_connection(nullptr);  // So DeregisterService works.
2664  manager()->DeregisterService(mock_service1);
2665  CompleteServiceSort();
2666
2667  // Deregistering the only Service causes the DefaultService to become
2668  // nullptr.  Appropriate notifications are sent.
2669  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2670  EXPECT_CALL(*manager_adaptor_,
2671              EmitRpcIdentifierChanged(kDefaultServiceProperty, _));
2672  mock_service0->set_mock_connection(nullptr);  // So DeregisterService works.
2673  manager()->DeregisterService(mock_service0);
2674  CompleteServiceSort();
2675
2676  // An explicit sort doesn't change anything, and does not generate
2677  // an external notification.
2678  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2679  EXPECT_CALL(*manager_adaptor_,
2680              EmitRpcIdentifierChanged(kDefaultServiceProperty, _)).Times(0);
2681  manager()->SortServicesTask();
2682}
2683
2684TEST_F(ManagerTest, NotifyDefaultServiceChanged) {
2685  EXPECT_EQ(0, manager()->default_service_callback_tag_);
2686  EXPECT_TRUE(manager()->default_service_callbacks_.empty());
2687
2688  MockMetrics mock_metrics(dispatcher());
2689  SetMetrics(&mock_metrics);
2690
2691  scoped_refptr<MockService> mock_service(
2692      new NiceMock<MockService>(
2693          control_interface(), dispatcher(), metrics(), manager()));
2694  ServiceRefPtr service = mock_service;
2695  ServiceRefPtr null_service;
2696
2697  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2698  manager()->NotifyDefaultServiceChanged(null_service);
2699
2700  ServiceWatcher service_watcher1;
2701  ServiceWatcher service_watcher2;
2702  int tag1 =
2703      manager()->RegisterDefaultServiceCallback(
2704          Bind(&ServiceWatcher::OnDefaultServiceChanged,
2705               service_watcher1.AsWeakPtr()));
2706  EXPECT_EQ(1, tag1);
2707  int tag2 =
2708      manager()->RegisterDefaultServiceCallback(
2709          Bind(&ServiceWatcher::OnDefaultServiceChanged,
2710               service_watcher2.AsWeakPtr()));
2711  EXPECT_EQ(2, tag2);
2712
2713  EXPECT_CALL(service_watcher1, OnDefaultServiceChanged(null_service));
2714  EXPECT_CALL(service_watcher2, OnDefaultServiceChanged(null_service));
2715  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(nullptr));
2716  manager()->NotifyDefaultServiceChanged(null_service);
2717
2718  EXPECT_CALL(service_watcher1, OnDefaultServiceChanged(service));
2719  EXPECT_CALL(service_watcher2, OnDefaultServiceChanged(service));
2720  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(service.get()));
2721  manager()->NotifyDefaultServiceChanged(mock_service);
2722
2723  manager()->DeregisterDefaultServiceCallback(tag1);
2724  EXPECT_CALL(service_watcher1, OnDefaultServiceChanged(_)).Times(0);
2725  EXPECT_CALL(service_watcher2, OnDefaultServiceChanged(service));
2726  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(service.get()));
2727  manager()->NotifyDefaultServiceChanged(mock_service);
2728  EXPECT_EQ(1, manager()->default_service_callbacks_.size());
2729
2730  manager()->DeregisterDefaultServiceCallback(tag2);
2731  EXPECT_CALL(service_watcher2, OnDefaultServiceChanged(_)).Times(0);
2732  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(service.get()));
2733  manager()->NotifyDefaultServiceChanged(mock_service);
2734
2735  EXPECT_EQ(2, manager()->default_service_callback_tag_);
2736  EXPECT_TRUE(manager()->default_service_callbacks_.empty());
2737}
2738
2739TEST_F(ManagerTest, ReportServicesOnSameNetwork) {
2740  int connection_id1 = 100;
2741  int connection_id2 = 200;
2742  scoped_refptr<MockService> mock_service1 =
2743      new NiceMock<MockService>(control_interface(), dispatcher(),
2744                                metrics(), manager());
2745  mock_service1->set_connection_id(connection_id1);
2746  scoped_refptr<MockService> mock_service2 =
2747      new NiceMock<MockService>(control_interface(), dispatcher(),
2748                                metrics(), manager());
2749  mock_service2->set_connection_id(connection_id1);
2750  scoped_refptr<MockService> mock_service3 =
2751      new NiceMock<MockService>(control_interface(), dispatcher(),
2752                                metrics(), manager());
2753  mock_service3->set_connection_id(connection_id2);
2754
2755  manager()->RegisterService(mock_service1);
2756  manager()->RegisterService(mock_service2);
2757  manager()->RegisterService(mock_service3);
2758
2759  EXPECT_CALL(*metrics(), NotifyServicesOnSameNetwork(2));
2760  manager()->ReportServicesOnSameNetwork(connection_id1);
2761
2762  EXPECT_CALL(*metrics(), NotifyServicesOnSameNetwork(1));
2763  manager()->ReportServicesOnSameNetwork(connection_id2);
2764}
2765
2766TEST_F(ManagerTest, AvailableTechnologies) {
2767  mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
2768                                                   dispatcher(),
2769                                                   metrics(),
2770                                                   manager(),
2771                                                   "null4",
2772                                                   "addr4",
2773                                                   0));
2774  manager()->RegisterDevice(mock_devices_[0]);
2775  manager()->RegisterDevice(mock_devices_[1]);
2776  manager()->RegisterDevice(mock_devices_[2]);
2777  manager()->RegisterDevice(mock_devices_[3]);
2778
2779  ON_CALL(*mock_devices_[0].get(), technology())
2780      .WillByDefault(Return(Technology::kEthernet));
2781  ON_CALL(*mock_devices_[1].get(), technology())
2782      .WillByDefault(Return(Technology::kWifi));
2783  ON_CALL(*mock_devices_[2].get(), technology())
2784      .WillByDefault(Return(Technology::kCellular));
2785  ON_CALL(*mock_devices_[3].get(), technology())
2786      .WillByDefault(Return(Technology::kWifi));
2787
2788  set<string> expected_technologies;
2789  expected_technologies.insert(Technology::NameFromIdentifier(
2790      Technology::kEthernet));
2791  expected_technologies.insert(Technology::NameFromIdentifier(
2792      Technology::kWifi));
2793  expected_technologies.insert(Technology::NameFromIdentifier(
2794      Technology::kCellular));
2795  Error error;
2796  vector<string> technologies = manager()->AvailableTechnologies(&error);
2797
2798  EXPECT_THAT(set<string>(technologies.begin(), technologies.end()),
2799              ContainerEq(expected_technologies));
2800}
2801
2802TEST_F(ManagerTest, ConnectedTechnologies) {
2803  scoped_refptr<MockService> connected_service1(
2804      new NiceMock<MockService>(control_interface(),
2805                                dispatcher(),
2806                                metrics(),
2807                                manager()));
2808  scoped_refptr<MockService> connected_service2(
2809      new NiceMock<MockService>(control_interface(),
2810                                dispatcher(),
2811                                metrics(),
2812                                manager()));
2813  scoped_refptr<MockService> disconnected_service1(
2814      new NiceMock<MockService>(control_interface(),
2815                                dispatcher(),
2816                                metrics(),
2817                                manager()));
2818  scoped_refptr<MockService> disconnected_service2(
2819      new NiceMock<MockService>(control_interface(),
2820                                dispatcher(),
2821                                metrics(),
2822                                manager()));
2823
2824  ON_CALL(*connected_service1.get(), IsConnected())
2825      .WillByDefault(Return(true));
2826  ON_CALL(*connected_service2.get(), IsConnected())
2827      .WillByDefault(Return(true));
2828
2829  manager()->RegisterService(connected_service1);
2830  manager()->RegisterService(connected_service2);
2831  manager()->RegisterService(disconnected_service1);
2832  manager()->RegisterService(disconnected_service2);
2833
2834  manager()->RegisterDevice(mock_devices_[0]);
2835  manager()->RegisterDevice(mock_devices_[1]);
2836  manager()->RegisterDevice(mock_devices_[2]);
2837  manager()->RegisterDevice(mock_devices_[3]);
2838
2839  ON_CALL(*mock_devices_[0].get(), technology())
2840      .WillByDefault(Return(Technology::kEthernet));
2841  ON_CALL(*mock_devices_[1].get(), technology())
2842      .WillByDefault(Return(Technology::kWifi));
2843  ON_CALL(*mock_devices_[2].get(), technology())
2844      .WillByDefault(Return(Technology::kCellular));
2845  ON_CALL(*mock_devices_[3].get(), technology())
2846      .WillByDefault(Return(Technology::kWifi));
2847
2848  mock_devices_[0]->SelectService(connected_service1);
2849  mock_devices_[1]->SelectService(disconnected_service1);
2850  mock_devices_[2]->SelectService(disconnected_service2);
2851  mock_devices_[3]->SelectService(connected_service2);
2852
2853  set<string> expected_technologies;
2854  expected_technologies.insert(Technology::NameFromIdentifier(
2855      Technology::kEthernet));
2856  expected_technologies.insert(Technology::NameFromIdentifier(
2857      Technology::kWifi));
2858  Error error;
2859
2860  vector<string> technologies = manager()->ConnectedTechnologies(&error);
2861  EXPECT_THAT(set<string>(technologies.begin(), technologies.end()),
2862              ContainerEq(expected_technologies));
2863}
2864
2865TEST_F(ManagerTest, DefaultTechnology) {
2866  scoped_refptr<MockService> connected_service(
2867      new NiceMock<MockService>(control_interface(),
2868                                dispatcher(),
2869                                metrics(),
2870                                manager()));
2871  scoped_refptr<MockService> disconnected_service(
2872      new NiceMock<MockService>(control_interface(),
2873                                dispatcher(),
2874                                metrics(),
2875                                manager()));
2876
2877  // Connected. WiFi.
2878  ON_CALL(*connected_service.get(), IsConnected())
2879      .WillByDefault(Return(true));
2880  ON_CALL(*connected_service.get(), state())
2881      .WillByDefault(Return(Service::kStateConnected));
2882  ON_CALL(*connected_service.get(), technology())
2883      .WillByDefault(Return(Technology::kWifi));
2884
2885  // Disconnected. Ethernet.
2886  ON_CALL(*disconnected_service.get(), technology())
2887      .WillByDefault(Return(Technology::kEthernet));
2888
2889  manager()->RegisterService(disconnected_service);
2890  CompleteServiceSort();
2891  Error error;
2892  EXPECT_THAT(manager()->DefaultTechnology(&error), StrEq(""));
2893
2894
2895  manager()->RegisterService(connected_service);
2896  CompleteServiceSort();
2897  // Connected service should be brought to the front now.
2898  string expected_technology =
2899      Technology::NameFromIdentifier(Technology::kWifi);
2900  EXPECT_THAT(manager()->DefaultTechnology(&error), StrEq(expected_technology));
2901}
2902
2903TEST_F(ManagerTest, Stop) {
2904  scoped_refptr<MockProfile> profile(
2905      new NiceMock<MockProfile>(
2906          control_interface(), metrics(), manager(), ""));
2907  AdoptProfile(manager(), profile);
2908  scoped_refptr<MockService> service(
2909      new NiceMock<MockService>(control_interface(),
2910                                dispatcher(),
2911                                metrics(),
2912                                manager()));
2913  manager()->RegisterService(service);
2914  manager()->RegisterDevice(mock_devices_[0]);
2915  SetPowerManager();
2916  EXPECT_TRUE(manager()->power_manager());
2917  EXPECT_CALL(*profile.get(),
2918              UpdateDevice(DeviceRefPtr(mock_devices_[0].get())))
2919      .WillOnce(Return(true));
2920  EXPECT_CALL(*mock_devices_[0].get(), SetEnabled(false));
2921#if !defined(DISABLE_WIFI)
2922  EXPECT_CALL(*profile.get(), UpdateWiFiProvider(_)).WillOnce(Return(true));
2923#endif  // DISABLE_WIFI
2924  EXPECT_CALL(*profile.get(), Save()).WillOnce(Return(true));
2925  EXPECT_CALL(*service.get(), Disconnect(_, HasSubstr("Stop"))).Times(1);
2926  manager()->Stop();
2927  EXPECT_FALSE(manager()->power_manager());
2928}
2929
2930TEST_F(ManagerTest, UpdateServiceConnected) {
2931  scoped_refptr<MockService> mock_service(
2932      new NiceMock<MockService>(control_interface(),
2933                                dispatcher(),
2934                                metrics(),
2935                                manager()));
2936  manager()->RegisterService(mock_service);
2937  EXPECT_FALSE(mock_service->retain_auto_connect());
2938  EXPECT_FALSE(mock_service->auto_connect());
2939
2940  EXPECT_CALL(*mock_service.get(), IsConnected())
2941      .WillRepeatedly(Return(true));
2942  EXPECT_CALL(*mock_service.get(), EnableAndRetainAutoConnect());
2943  manager()->UpdateService(mock_service);
2944}
2945
2946TEST_F(ManagerTest, UpdateServiceConnectedPersistAutoConnect) {
2947  // This tests the case where the user connects to a service that is
2948  // currently associated with a profile.  We want to make sure that the
2949  // auto_connect flag is set and that the is saved to the current profile.
2950  scoped_refptr<MockService> mock_service(
2951      new NiceMock<MockService>(control_interface(),
2952                                dispatcher(),
2953                                metrics(),
2954                                manager()));
2955  manager()->RegisterService(mock_service);
2956  EXPECT_FALSE(mock_service->retain_auto_connect());
2957  EXPECT_FALSE(mock_service->auto_connect());
2958
2959  scoped_refptr<MockProfile> profile(
2960      new MockProfile(
2961          control_interface(), metrics(), manager(), ""));
2962
2963  mock_service->set_profile(profile);
2964  EXPECT_CALL(*mock_service, IsConnected())
2965      .WillRepeatedly(Return(true));
2966  EXPECT_CALL(*profile,
2967              UpdateService(static_cast<ServiceRefPtr>(mock_service)));
2968  EXPECT_CALL(*mock_service.get(), EnableAndRetainAutoConnect());
2969  manager()->UpdateService(mock_service);
2970  // This releases the ref on the mock profile.
2971  mock_service->set_profile(nullptr);
2972}
2973
2974TEST_F(ManagerTest, UpdateServiceLogging) {
2975  ScopedMockLog log;
2976  MockServiceRefPtr mock_service(
2977      new NiceMock<MockService>(control_interface(),
2978                                dispatcher(),
2979                                metrics(),
2980                                manager()));
2981  string updated_message = base::StringPrintf(
2982      "Service %s updated;", mock_service->unique_name().c_str());
2983
2984  // An idle service should not create a log message by default.
2985  EXPECT_CALL(*mock_service.get(), state())
2986      .WillRepeatedly(Return(Service::kStateIdle));
2987  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr(updated_message)))
2988      .Times(0);
2989  manager()->RegisterService(mock_service);
2990  CompleteServiceSort();
2991  manager()->UpdateService(mock_service);
2992  CompleteServiceSort();
2993  Mock::VerifyAndClearExpectations(mock_service.get());
2994  Mock::VerifyAndClearExpectations(&log);
2995
2996  // A service leaving the idle state should create a log message.
2997  EXPECT_CALL(*mock_service.get(), state())
2998      .WillRepeatedly(Return(Service::kStateAssociating));
2999  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr(updated_message)))
3000      .Times(1);
3001  manager()->UpdateService(mock_service.get());
3002  CompleteServiceSort();
3003  Mock::VerifyAndClearExpectations(&log);
3004
3005  // A service in a non-idle state should not create a log message if its
3006  // state did not change.
3007  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr(updated_message)))
3008      .Times(0);
3009  manager()->UpdateService(mock_service);
3010  CompleteServiceSort();
3011  Mock::VerifyAndClearExpectations(mock_service.get());
3012  Mock::VerifyAndClearExpectations(&log);
3013
3014  // A service transitioning between two non-idle states should create
3015  // a log message.
3016  EXPECT_CALL(*mock_service.get(), state())
3017      .WillRepeatedly(Return(Service::kStateConnected));
3018  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr(updated_message)))
3019      .Times(1);
3020  manager()->UpdateService(mock_service.get());
3021  CompleteServiceSort();
3022  Mock::VerifyAndClearExpectations(mock_service.get());
3023  Mock::VerifyAndClearExpectations(&log);
3024
3025  // A service transitioning from a non-idle state to idle should create
3026  // a log message.
3027  EXPECT_CALL(*mock_service.get(), state())
3028      .WillRepeatedly(Return(Service::kStateIdle));
3029  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr(updated_message)))
3030      .Times(1);
3031  manager()->UpdateService(mock_service.get());
3032  CompleteServiceSort();
3033}
3034
3035TEST_F(ManagerTest, SaveSuccessfulService) {
3036  scoped_refptr<MockProfile> profile(
3037      new StrictMock<MockProfile>(
3038          control_interface(), metrics(), manager(), ""));
3039  AdoptProfile(manager(), profile);
3040  scoped_refptr<MockService> service(
3041      new NiceMock<MockService>(control_interface(),
3042                                dispatcher(),
3043                                metrics(),
3044                                manager()));
3045
3046  // Re-cast this back to a ServiceRefPtr, so EXPECT arguments work correctly.
3047  ServiceRefPtr expect_service(service.get());
3048
3049  EXPECT_CALL(*profile.get(), ConfigureService(expect_service))
3050      .WillOnce(Return(false));
3051  manager()->RegisterService(service);
3052
3053  EXPECT_CALL(*service.get(), state())
3054      .WillRepeatedly(Return(Service::kStateConnected));
3055  EXPECT_CALL(*service.get(), IsConnected())
3056      .WillRepeatedly(Return(true));
3057  EXPECT_CALL(*profile.get(), AdoptService(expect_service))
3058      .WillOnce(Return(true));
3059  manager()->UpdateService(service);
3060}
3061
3062TEST_F(ManagerTest, UpdateDevice) {
3063  MockProfile* profile0 =
3064      new MockProfile(control_interface(), metrics(), manager(), "");
3065  MockProfile* profile1 =
3066      new MockProfile(control_interface(), metrics(), manager(), "");
3067  MockProfile* profile2 =
3068      new MockProfile(control_interface(), metrics(), manager(), "");
3069  AdoptProfile(manager(), profile0);  // Passes ownership.
3070  AdoptProfile(manager(), profile1);  // Passes ownership.
3071  AdoptProfile(manager(), profile2);  // Passes ownership.
3072  DeviceRefPtr device_ref(mock_devices_[0].get());
3073  EXPECT_CALL(*profile0, UpdateDevice(device_ref)).Times(0);
3074  EXPECT_CALL(*profile1, UpdateDevice(device_ref)).WillOnce(Return(true));
3075  EXPECT_CALL(*profile2, UpdateDevice(device_ref)).WillOnce(Return(false));
3076  manager()->UpdateDevice(mock_devices_[0]);
3077}
3078
3079TEST_F(ManagerTest, EnumerateProfiles) {
3080  vector<string> profile_paths;
3081  for (size_t i = 0; i < 10; i++) {
3082    scoped_refptr<MockProfile> profile(
3083      new StrictMock<MockProfile>(
3084          control_interface(), metrics(), manager(), ""));
3085    profile_paths.push_back(base::StringPrintf("/profile/%zd", i));
3086    EXPECT_CALL(*profile.get(), GetRpcIdentifier())
3087        .WillOnce(Return(profile_paths.back()));
3088    AdoptProfile(manager(), profile);
3089  }
3090
3091  Error error;
3092  vector<string> returned_paths = manager()->EnumerateProfiles(&error);
3093  EXPECT_TRUE(error.IsSuccess());
3094  EXPECT_EQ(profile_paths.size(), returned_paths.size());
3095  for (size_t i = 0; i < profile_paths.size(); i++) {
3096    EXPECT_EQ(profile_paths[i], returned_paths[i]);
3097  }
3098}
3099
3100TEST_F(ManagerTest, EnumerateServiceInnerDevices) {
3101  MockServiceRefPtr service1 = new NiceMock<MockService>(control_interface(),
3102                                                         dispatcher(),
3103                                                         metrics(),
3104                                                         manager());
3105  MockServiceRefPtr service2 = new NiceMock<MockService>(control_interface(),
3106                                                         dispatcher(),
3107                                                         metrics(),
3108                                                         manager());
3109  const string kDeviceRpcID = "/rpc/";
3110  manager()->RegisterService(service1);
3111  manager()->RegisterService(service2);
3112  EXPECT_CALL(*service1.get(), GetInnerDeviceRpcIdentifier())
3113      .WillRepeatedly(Return(kDeviceRpcID));
3114  EXPECT_CALL(*service2.get(), GetInnerDeviceRpcIdentifier())
3115      .WillRepeatedly(Return(""));
3116  Error error;
3117  EXPECT_EQ(vector<string>{kDeviceRpcID}, manager()->EnumerateDevices(&error));
3118  EXPECT_TRUE(error.IsSuccess());
3119}
3120
3121TEST_F(ManagerTest, AutoConnectOnRegister) {
3122  MockServiceRefPtr service = MakeAutoConnectableService();
3123  EXPECT_CALL(*service.get(), AutoConnect());
3124  manager()->RegisterService(service);
3125  dispatcher()->DispatchPendingEvents();
3126}
3127
3128TEST_F(ManagerTest, AutoConnectOnUpdate) {
3129  MockServiceRefPtr service1 = MakeAutoConnectableService();
3130  service1->SetPriority(1, nullptr);
3131  MockServiceRefPtr service2 = MakeAutoConnectableService();
3132  service2->SetPriority(2, nullptr);
3133  manager()->RegisterService(service1);
3134  manager()->RegisterService(service2);
3135  dispatcher()->DispatchPendingEvents();
3136
3137  EXPECT_CALL(*service1.get(), AutoConnect());
3138  EXPECT_CALL(*service2.get(), state())
3139      .WillRepeatedly(Return(Service::kStateFailure));
3140  EXPECT_CALL(*service2.get(), IsFailed())
3141      .WillRepeatedly(Return(true));
3142  EXPECT_CALL(*service2.get(), IsConnected())
3143      .WillRepeatedly(Return(false));
3144  manager()->UpdateService(service2);
3145  dispatcher()->DispatchPendingEvents();
3146}
3147
3148TEST_F(ManagerTest, AutoConnectOnDeregister) {
3149  MockServiceRefPtr service1 = MakeAutoConnectableService();
3150  service1->SetPriority(1, nullptr);
3151  MockServiceRefPtr service2 = MakeAutoConnectableService();
3152  service2->SetPriority(2, nullptr);
3153  manager()->RegisterService(service1);
3154  manager()->RegisterService(service2);
3155  dispatcher()->DispatchPendingEvents();
3156
3157  EXPECT_CALL(*service1.get(), AutoConnect());
3158  manager()->DeregisterService(service2);
3159  dispatcher()->DispatchPendingEvents();
3160}
3161
3162TEST_F(ManagerTest, AutoConnectOnSuspending) {
3163  MockServiceRefPtr service = MakeAutoConnectableService();
3164  SetSuspending(true);
3165  SetPowerManager();
3166  EXPECT_CALL(*service, AutoConnect()).Times(0);
3167  manager()->RegisterService(service);
3168  dispatcher()->DispatchPendingEvents();
3169}
3170
3171TEST_F(ManagerTest, AutoConnectOnNotSuspending) {
3172  MockServiceRefPtr service = MakeAutoConnectableService();
3173  SetSuspending(false);
3174  SetPowerManager();
3175  EXPECT_CALL(*service, AutoConnect());
3176  manager()->RegisterService(service);
3177  dispatcher()->DispatchPendingEvents();
3178}
3179
3180TEST_F(ManagerTest, AutoConnectWhileNotRunning) {
3181  SetRunning(false);
3182  MockServiceRefPtr service = MakeAutoConnectableService();
3183  EXPECT_CALL(*service, AutoConnect()).Times(0);
3184  manager()->RegisterService(service);
3185  dispatcher()->DispatchPendingEvents();
3186}
3187
3188TEST_F(ManagerTest, Suspend) {
3189  MockServiceRefPtr service = MakeAutoConnectableService();
3190  SetPowerManager();
3191  EXPECT_CALL(*service, AutoConnect());
3192  manager()->RegisterService(service);
3193  manager()->RegisterDevice(mock_devices_[0]);
3194  dispatcher()->DispatchPendingEvents();
3195
3196  EXPECT_CALL(*mock_devices_[0], OnBeforeSuspend(_));
3197  OnSuspendImminent();
3198  EXPECT_CALL(*service, AutoConnect()).Times(0);
3199  dispatcher()->DispatchPendingEvents();
3200  Mock::VerifyAndClearExpectations(mock_devices_[0].get());
3201
3202  EXPECT_CALL(*mock_devices_[0], OnAfterResume());
3203  OnSuspendDone();
3204  EXPECT_CALL(*service, AutoConnect());
3205  dispatcher()->DispatchPendingEvents();
3206  Mock::VerifyAndClearExpectations(mock_devices_[0].get());
3207}
3208
3209TEST_F(ManagerTest, AddTerminationAction) {
3210  EXPECT_TRUE(GetTerminationActions()->IsEmpty());
3211  manager()->AddTerminationAction("action1", base::Closure());
3212  EXPECT_FALSE(GetTerminationActions()->IsEmpty());
3213  manager()->AddTerminationAction("action2", base::Closure());
3214}
3215
3216TEST_F(ManagerTest, RemoveTerminationAction) {
3217  const char kKey1[] = "action1";
3218  const char kKey2[] = "action2";
3219
3220  // Removing an action when the hook table is empty.
3221  EXPECT_TRUE(GetTerminationActions()->IsEmpty());
3222  manager()->RemoveTerminationAction("unknown");
3223
3224  // Fill hook table with two items.
3225  manager()->AddTerminationAction(kKey1, base::Closure());
3226  EXPECT_FALSE(GetTerminationActions()->IsEmpty());
3227  manager()->AddTerminationAction(kKey2, base::Closure());
3228
3229  // Removing an action that ends up with a non-empty hook table.
3230  manager()->RemoveTerminationAction(kKey1);
3231  EXPECT_FALSE(GetTerminationActions()->IsEmpty());
3232
3233  // Removing the last action.
3234  manager()->RemoveTerminationAction(kKey2);
3235  EXPECT_TRUE(GetTerminationActions()->IsEmpty());
3236}
3237
3238TEST_F(ManagerTest, RunTerminationActions) {
3239  TerminationActionTest test_action;
3240  const string kActionName = "action";
3241
3242  EXPECT_CALL(test_action, Done(_));
3243  manager()->RunTerminationActions(Bind(&TerminationActionTest::Done,
3244                                        test_action.AsWeakPtr()));
3245
3246  manager()->AddTerminationAction(TerminationActionTest::kActionName,
3247                                  Bind(&TerminationActionTest::Action,
3248                                       test_action.AsWeakPtr()));
3249  test_action.set_manager(manager());
3250  EXPECT_CALL(test_action, Done(_));
3251  manager()->RunTerminationActions(Bind(&TerminationActionTest::Done,
3252                                        test_action.AsWeakPtr()));
3253}
3254
3255TEST_F(ManagerTest, OnSuspendImminentDevicesPresent) {
3256  EXPECT_CALL(*mock_devices_[0].get(), OnBeforeSuspend(_));
3257  EXPECT_CALL(*mock_devices_[1].get(), OnBeforeSuspend(_));
3258  EXPECT_CALL(*mock_devices_[2].get(), OnBeforeSuspend(_));
3259  manager()->RegisterDevice(mock_devices_[0]);
3260  manager()->RegisterDevice(mock_devices_[1]);
3261  manager()->RegisterDevice(mock_devices_[2]);
3262  SetPowerManager();
3263  OnSuspendImminent();
3264}
3265
3266TEST_F(ManagerTest, OnSuspendImminentNoDevicesPresent) {
3267  EXPECT_CALL(*power_manager_, ReportSuspendReadiness());
3268  SetPowerManager();
3269  OnSuspendImminent();
3270}
3271
3272TEST_F(ManagerTest, OnDarkSuspendImminentDevicesPresent) {
3273  EXPECT_CALL(*mock_devices_[0].get(), OnDarkResume(_));
3274  EXPECT_CALL(*mock_devices_[1].get(), OnDarkResume(_));
3275  EXPECT_CALL(*mock_devices_[2].get(), OnDarkResume(_));
3276  manager()->RegisterDevice(mock_devices_[0]);
3277  manager()->RegisterDevice(mock_devices_[1]);
3278  manager()->RegisterDevice(mock_devices_[2]);
3279  SetPowerManager();
3280  OnDarkSuspendImminent();
3281}
3282
3283TEST_F(ManagerTest, OnDarkSuspendImminentNoDevicesPresent) {
3284  EXPECT_CALL(*power_manager_, ReportDarkSuspendReadiness());
3285  SetPowerManager();
3286  OnDarkSuspendImminent();
3287}
3288
3289TEST_F(ManagerTest, OnSuspendActionsComplete) {
3290  Error error;
3291  EXPECT_CALL(*power_manager_, ReportSuspendReadiness());
3292  SetPowerManager();
3293  OnSuspendActionsComplete(error);
3294}
3295
3296TEST_F(ManagerTest, RecheckPortal) {
3297  EXPECT_CALL(*mock_devices_[0].get(), RequestPortalDetection())
3298      .WillOnce(Return(false));
3299  EXPECT_CALL(*mock_devices_[1].get(), RequestPortalDetection())
3300      .WillOnce(Return(true));
3301  EXPECT_CALL(*mock_devices_[2].get(), RequestPortalDetection())
3302      .Times(0);
3303
3304  manager()->RegisterDevice(mock_devices_[0]);
3305  manager()->RegisterDevice(mock_devices_[1]);
3306  manager()->RegisterDevice(mock_devices_[2]);
3307
3308  manager()->RecheckPortal(nullptr);
3309}
3310
3311TEST_F(ManagerTest, RecheckPortalOnService) {
3312  MockServiceRefPtr service = new NiceMock<MockService>(control_interface(),
3313                                                        dispatcher(),
3314                                                        metrics(),
3315                                                        manager());
3316  EXPECT_CALL(*mock_devices_[0].get(),
3317              IsConnectedToService(IsRefPtrTo(service)))
3318      .WillOnce(Return(false));
3319  EXPECT_CALL(*mock_devices_[1].get(),
3320              IsConnectedToService(IsRefPtrTo(service)))
3321      .WillOnce(Return(true));
3322  EXPECT_CALL(*mock_devices_[1].get(), RestartPortalDetection())
3323      .WillOnce(Return(true));
3324  EXPECT_CALL(*mock_devices_[2].get(), IsConnectedToService(_))
3325      .Times(0);
3326
3327  manager()->RegisterDevice(mock_devices_[0]);
3328  manager()->RegisterDevice(mock_devices_[1]);
3329  manager()->RegisterDevice(mock_devices_[2]);
3330
3331  manager()->RecheckPortalOnService(service);
3332}
3333
3334TEST_F(ManagerTest, GetDefaultService) {
3335  EXPECT_FALSE(manager()->GetDefaultService().get());
3336  EXPECT_EQ(control_interface()->NullRPCIdentifier(),
3337            GetDefaultServiceRpcIdentifier());
3338
3339  scoped_refptr<MockService> mock_service(
3340      new NiceMock<MockService>(control_interface(),
3341                                dispatcher(),
3342                                metrics(),
3343                                manager()));
3344
3345  manager()->RegisterService(mock_service);
3346  EXPECT_FALSE(manager()->GetDefaultService().get());
3347  EXPECT_EQ(control_interface()->NullRPCIdentifier(),
3348            GetDefaultServiceRpcIdentifier());
3349
3350  scoped_refptr<MockConnection> mock_connection(
3351      new NiceMock<MockConnection>(device_info_.get()));
3352  mock_service->set_mock_connection(mock_connection);
3353  EXPECT_EQ(mock_service.get(), manager()->GetDefaultService().get());
3354  EXPECT_EQ(mock_service->GetRpcIdentifier(), GetDefaultServiceRpcIdentifier());
3355
3356  mock_service->set_mock_connection(nullptr);
3357  manager()->DeregisterService(mock_service);
3358}
3359
3360TEST_F(ManagerTest, GetServiceWithGUID) {
3361  scoped_refptr<MockService> mock_service0(
3362      new NiceMock<MockService>(control_interface(),
3363                                dispatcher(),
3364                                metrics(),
3365                                manager()));
3366
3367  scoped_refptr<MockService> mock_service1(
3368      new NiceMock<MockService>(control_interface(),
3369                                dispatcher(),
3370                                metrics(),
3371                                manager()));
3372
3373  EXPECT_CALL(*mock_service0.get(), Configure(_, _))
3374      .Times(0);
3375  EXPECT_CALL(*mock_service1.get(), Configure(_, _))
3376      .Times(0);
3377
3378  manager()->RegisterService(mock_service0);
3379  manager()->RegisterService(mock_service1);
3380
3381  const string kGUID0 = "GUID0";
3382  const string kGUID1 = "GUID1";
3383
3384  {
3385    Error error;
3386    ServiceRefPtr service = manager()->GetServiceWithGUID(kGUID0, &error);
3387    EXPECT_FALSE(error.IsSuccess());
3388    EXPECT_FALSE(service);
3389  }
3390
3391  KeyValueStore args;
3392  args.SetString(kGuidProperty, kGUID1);
3393
3394  {
3395    Error error;
3396    ServiceRefPtr service = manager()->GetService(args, &error);
3397    EXPECT_EQ(Error::kInvalidArguments, error.type());
3398    EXPECT_FALSE(service);
3399  }
3400
3401  mock_service0->SetGuid(kGUID0, nullptr);
3402  mock_service1->SetGuid(kGUID1, nullptr);
3403
3404  {
3405    Error error;
3406    ServiceRefPtr service = manager()->GetServiceWithGUID(kGUID0, &error);
3407    EXPECT_TRUE(error.IsSuccess());
3408    EXPECT_EQ(mock_service0.get(), service.get());
3409  }
3410
3411  {
3412    Error error;
3413    EXPECT_CALL(*mock_service1.get(), Configure(_, &error))
3414        .Times(1);
3415    ServiceRefPtr service = manager()->GetService(args, &error);
3416    EXPECT_TRUE(error.IsSuccess());
3417    EXPECT_EQ(mock_service1.get(), service.get());
3418  }
3419
3420  manager()->DeregisterService(mock_service0);
3421  manager()->DeregisterService(mock_service1);
3422}
3423
3424
3425TEST_F(ManagerTest, CalculateStateOffline) {
3426  EXPECT_FALSE(manager()->IsConnected());
3427  EXPECT_EQ("offline", manager()->CalculateState(nullptr));
3428
3429  MockMetrics mock_metrics(dispatcher());
3430  SetMetrics(&mock_metrics);
3431  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(_))
3432      .Times(AnyNumber());
3433  scoped_refptr<MockService> mock_service0(
3434      new NiceMock<MockService>(control_interface(),
3435                                dispatcher(),
3436                                metrics(),
3437                                manager()));
3438
3439  scoped_refptr<MockService> mock_service1(
3440      new NiceMock<MockService>(control_interface(),
3441                                dispatcher(),
3442                                metrics(),
3443                                manager()));
3444
3445  EXPECT_CALL(*mock_service0.get(), IsConnected())
3446      .WillRepeatedly(Return(false));
3447  EXPECT_CALL(*mock_service1.get(), IsConnected())
3448      .WillRepeatedly(Return(false));
3449
3450  manager()->RegisterService(mock_service0);
3451  manager()->RegisterService(mock_service1);
3452
3453  EXPECT_FALSE(manager()->IsConnected());
3454  EXPECT_EQ("offline", manager()->CalculateState(nullptr));
3455
3456  manager()->DeregisterService(mock_service0);
3457  manager()->DeregisterService(mock_service1);
3458}
3459
3460TEST_F(ManagerTest, CalculateStateOnline) {
3461  MockMetrics mock_metrics(dispatcher());
3462  SetMetrics(&mock_metrics);
3463  EXPECT_CALL(mock_metrics, NotifyDefaultServiceChanged(_))
3464      .Times(AnyNumber());
3465  scoped_refptr<MockService> mock_service0(
3466      new NiceMock<MockService>(control_interface(),
3467                                dispatcher(),
3468                                metrics(),
3469                                manager()));
3470
3471  scoped_refptr<MockService> mock_service1(
3472      new NiceMock<MockService>(control_interface(),
3473                                dispatcher(),
3474                                metrics(),
3475                                manager()));
3476
3477  EXPECT_CALL(*mock_service0.get(), IsConnected())
3478      .WillRepeatedly(Return(false));
3479  EXPECT_CALL(*mock_service1.get(), IsConnected())
3480      .WillRepeatedly(Return(true));
3481  EXPECT_CALL(*mock_service0.get(), state())
3482      .WillRepeatedly(Return(Service::kStateIdle));
3483  EXPECT_CALL(*mock_service1.get(), state())
3484      .WillRepeatedly(Return(Service::kStateConnected));
3485
3486  manager()->RegisterService(mock_service0);
3487  manager()->RegisterService(mock_service1);
3488  CompleteServiceSort();
3489
3490  EXPECT_TRUE(manager()->IsConnected());
3491  EXPECT_EQ("online", manager()->CalculateState(nullptr));
3492
3493  manager()->DeregisterService(mock_service0);
3494  manager()->DeregisterService(mock_service1);
3495}
3496
3497TEST_F(ManagerTest, RefreshConnectionState) {
3498  EXPECT_CALL(*manager_adaptor_,
3499              EmitStringChanged(kConnectionStateProperty, kStateIdle));
3500  EXPECT_CALL(*upstart_, NotifyDisconnected());
3501  EXPECT_CALL(*upstart_, NotifyConnected()).Times(0);
3502  RefreshConnectionState();
3503  Mock::VerifyAndClearExpectations(manager_adaptor_);
3504  Mock::VerifyAndClearExpectations(upstart_);
3505
3506  scoped_refptr<MockService> mock_service(
3507      new NiceMock<MockService>(control_interface(),
3508                                dispatcher(),
3509                                metrics(),
3510                                manager()));
3511  EXPECT_CALL(*manager_adaptor_,
3512              EmitStringChanged(kConnectionStateProperty, _)).Times(0);
3513  EXPECT_CALL(*upstart_, NotifyDisconnected()).Times(0);
3514  EXPECT_CALL(*upstart_, NotifyConnected());
3515  manager()->RegisterService(mock_service);
3516  RefreshConnectionState();
3517
3518  scoped_refptr<MockConnection> mock_connection(
3519      new NiceMock<MockConnection>(device_info_.get()));
3520  mock_service->set_mock_connection(mock_connection);
3521  EXPECT_CALL(*mock_service, state())
3522      .WillOnce(Return(Service::kStateIdle));
3523  RefreshConnectionState();
3524
3525  Mock::VerifyAndClearExpectations(manager_adaptor_);
3526  EXPECT_CALL(*mock_service, state())
3527      .WillOnce(Return(Service::kStatePortal));
3528  EXPECT_CALL(*mock_service, IsConnected())
3529      .WillOnce(Return(true));
3530  EXPECT_CALL(*manager_adaptor_,
3531              EmitStringChanged(kConnectionStateProperty, kStatePortal));
3532  RefreshConnectionState();
3533  Mock::VerifyAndClearExpectations(manager_adaptor_);
3534  Mock::VerifyAndClearExpectations(upstart_);
3535
3536  mock_service->set_mock_connection(nullptr);
3537  manager()->DeregisterService(mock_service);
3538
3539  EXPECT_CALL(*manager_adaptor_,
3540              EmitStringChanged(kConnectionStateProperty, kStateIdle));
3541  EXPECT_CALL(*upstart_, NotifyDisconnected());
3542  EXPECT_CALL(*upstart_, NotifyConnected()).Times(0);
3543  RefreshConnectionState();
3544}
3545
3546TEST_F(ManagerTest, StartupPortalList) {
3547  // Simulate loading value from the default profile.
3548  const string kProfileValue("wifi,vpn");
3549  manager()->props_.check_portal_list = kProfileValue;
3550
3551  EXPECT_EQ(kProfileValue, manager()->GetCheckPortalList(nullptr));
3552  EXPECT_TRUE(manager()->IsPortalDetectionEnabled(Technology::kWifi));
3553  EXPECT_FALSE(manager()->IsPortalDetectionEnabled(Technology::kCellular));
3554
3555  const string kStartupValue("cellular,ethernet");
3556  manager()->SetStartupPortalList(kStartupValue);
3557  // Ensure profile value is not overwritten, so when we save the default
3558  // profile, the correct value will still be written.
3559  EXPECT_EQ(kProfileValue, manager()->props_.check_portal_list);
3560
3561  // However we should read back a different list.
3562  EXPECT_EQ(kStartupValue, manager()->GetCheckPortalList(nullptr));
3563  EXPECT_FALSE(manager()->IsPortalDetectionEnabled(Technology::kWifi));
3564  EXPECT_TRUE(manager()->IsPortalDetectionEnabled(Technology::kCellular));
3565
3566  const string kRuntimeValue("ppp");
3567  // Setting a runtime value over the control API should overwrite both
3568  // the profile value and what we read back.
3569  Error error;
3570  manager()->mutable_store()->SetStringProperty(
3571      kCheckPortalListProperty,
3572      kRuntimeValue,
3573      &error);
3574  ASSERT_TRUE(error.IsSuccess());
3575  EXPECT_EQ(kRuntimeValue, manager()->GetCheckPortalList(nullptr));
3576  EXPECT_EQ(kRuntimeValue, manager()->props_.check_portal_list);
3577  EXPECT_FALSE(manager()->IsPortalDetectionEnabled(Technology::kCellular));
3578  EXPECT_TRUE(manager()->IsPortalDetectionEnabled(Technology::kPPP));
3579}
3580
3581TEST_F(ManagerTest, LinkMonitorEnabled) {
3582  const string kEnabledTechnologies("wifi,vpn");
3583  manager()->props_.link_monitor_technologies = kEnabledTechnologies;
3584  EXPECT_TRUE(manager()->IsTechnologyLinkMonitorEnabled(Technology::kWifi));
3585  EXPECT_FALSE(
3586      manager()->IsTechnologyLinkMonitorEnabled(Technology::kCellular));
3587}
3588
3589TEST_F(ManagerTest, IsTechnologyAutoConnectDisabled) {
3590  const string kNoAutoConnectTechnologies("wifi,cellular");
3591  manager()->props_.no_auto_connect_technologies = kNoAutoConnectTechnologies;
3592  EXPECT_TRUE(manager()->IsTechnologyAutoConnectDisabled(Technology::kWifi));
3593  EXPECT_TRUE(
3594      manager()->IsTechnologyAutoConnectDisabled(Technology::kCellular));
3595  EXPECT_FALSE(
3596      manager()->IsTechnologyAutoConnectDisabled(Technology::kEthernet));
3597}
3598
3599TEST_F(ManagerTest, SetEnabledStateForTechnologyPersistentCheck) {
3600  Error error(Error::kOperationInitiated);
3601  DisableTechnologyReplyHandler disable_technology_reply_handler;
3602  ResultCallback disable_technology_callback(
3603      Bind(&DisableTechnologyReplyHandler::ReportResult,
3604           disable_technology_reply_handler.AsWeakPtr()));
3605  EXPECT_CALL(disable_technology_reply_handler, ReportResult(_)).Times(0);
3606  EXPECT_CALL(*mock_devices_[0], SetEnabledPersistent(false, _, _));
3607
3608  ON_CALL(*mock_devices_[0], technology())
3609      .WillByDefault(Return(Technology::kEthernet));
3610  manager()->RegisterDevice(mock_devices_[0]);
3611  manager()->SetEnabledStateForTechnology(kTypeEthernet, false, true,
3612                                          &error, disable_technology_callback);
3613
3614  EXPECT_CALL(*mock_devices_[0], SetEnabledNonPersistent(false, _, _));
3615  manager()->SetEnabledStateForTechnology(kTypeEthernet, false, false,
3616                                          &error, disable_technology_callback);
3617}
3618
3619TEST_F(ManagerTest, SetEnabledStateForTechnology) {
3620  Error error(Error::kOperationInitiated);
3621  DisableTechnologyReplyHandler disable_technology_reply_handler;
3622  ResultCallback disable_technology_callback(
3623      Bind(&DisableTechnologyReplyHandler::ReportResult,
3624           disable_technology_reply_handler.AsWeakPtr()));
3625  EXPECT_CALL(disable_technology_reply_handler, ReportResult(_)).Times(0);
3626
3627  manager()->SetEnabledStateForTechnology(kTypeEthernet, false, true,
3628                                          &error, disable_technology_callback);
3629  EXPECT_TRUE(error.IsSuccess());
3630
3631  ON_CALL(*mock_devices_[0], technology())
3632      .WillByDefault(Return(Technology::kEthernet));
3633  ON_CALL(*mock_devices_[1], technology())
3634      .WillByDefault(Return(Technology::kCellular));
3635  ON_CALL(*mock_devices_[2], technology())
3636      .WillByDefault(Return(Technology::kCellular));
3637
3638  manager()->RegisterDevice(mock_devices_[0]);
3639  manager()->RegisterDevice(mock_devices_[1]);
3640
3641  // Ethernet Device is disabled, so disable succeeds immediately.
3642  EXPECT_CALL(*mock_devices_[0], SetEnabledPersistent(false, _, _))
3643      .WillOnce(WithArg<1>(Invoke(SetErrorSuccess)));
3644  error.Populate(Error::kOperationInitiated);
3645  manager()->SetEnabledStateForTechnology(kTypeEthernet, false, true,
3646                                          &error, disable_technology_callback);
3647  EXPECT_TRUE(error.IsSuccess());
3648
3649  // Ethernet Device is enabled, and mock doesn't change error from
3650  // kOperationInitiated, so expect disable to say operation in progress.
3651  EXPECT_CALL(*mock_devices_[0], SetEnabledPersistent(false, _, _));
3652  mock_devices_[0]->enabled_ = true;
3653  error.Populate(Error::kOperationInitiated);
3654  manager()->SetEnabledStateForTechnology(kTypeEthernet, false, true,
3655                                          &error, disable_technology_callback);
3656  EXPECT_TRUE(error.IsOngoing());
3657
3658  // Ethernet Device is disabled, and mock doesn't change error from
3659  // kOperationInitiated, so expect enable to say operation in progress.
3660  EXPECT_CALL(*mock_devices_[0], SetEnabledPersistent(true, _, _));
3661  mock_devices_[0]->enabled_ = false;
3662  error.Populate(Error::kOperationInitiated);
3663  manager()->SetEnabledStateForTechnology(kTypeEthernet, true, true,
3664                                          &error, disable_technology_callback);
3665  EXPECT_TRUE(error.IsOngoing());
3666
3667  // Cellular Device is enabled, but disable failed.
3668  EXPECT_CALL(*mock_devices_[1], SetEnabledPersistent(false, _, _))
3669      .WillOnce(WithArg<1>(Invoke(SetErrorPermissionDenied)));
3670  mock_devices_[1]->enabled_ = true;
3671  error.Populate(Error::kOperationInitiated);
3672  manager()->SetEnabledStateForTechnology(kTypeCellular, false, true,
3673                                          &error, disable_technology_callback);
3674  EXPECT_EQ(Error::kPermissionDenied, error.type());
3675
3676  // Multiple Cellular Devices in enabled state. Should indicate IsOngoing
3677  // if one is in progress (even if the other completed immediately).
3678  manager()->RegisterDevice(mock_devices_[2]);
3679  EXPECT_CALL(*mock_devices_[1], SetEnabledPersistent(false, _, _))
3680      .WillOnce(WithArg<1>(Invoke(SetErrorPermissionDenied)));
3681  EXPECT_CALL(*mock_devices_[2], SetEnabledPersistent(false, _, _));
3682  mock_devices_[1]->enabled_ = true;
3683  mock_devices_[2]->enabled_ = true;
3684  error.Populate(Error::kOperationInitiated);
3685  manager()->SetEnabledStateForTechnology(kTypeCellular, false, true,
3686                                          &error, disable_technology_callback);
3687  EXPECT_TRUE(error.IsOngoing());
3688
3689  // ...and order doesn't matter.
3690  EXPECT_CALL(*mock_devices_[1], SetEnabledPersistent(false, _, _));
3691  EXPECT_CALL(*mock_devices_[2], SetEnabledPersistent(false, _, _))
3692      .WillOnce(WithArg<1>(Invoke(SetErrorPermissionDenied)));
3693  mock_devices_[1]->enabled_ = true;
3694  mock_devices_[2]->enabled_ = true;
3695  error.Populate(Error::kOperationInitiated);
3696  manager()->SetEnabledStateForTechnology(kTypeCellular, false, true,
3697                                          &error, disable_technology_callback);
3698  EXPECT_TRUE(error.IsOngoing());
3699  Mock::VerifyAndClearExpectations(&disable_technology_reply_handler);
3700
3701  // Multiple Cellular Devices in enabled state. Even if all disable
3702  // operations complete asynchronously, we only get one call to the
3703  // DisableTechnologyReplyHandler::ReportResult.
3704  ResultCallback device1_result_callback;
3705  ResultCallback device2_result_callback;
3706  EXPECT_CALL(*mock_devices_[1], SetEnabledPersistent(false, _, _))
3707      .WillOnce(SaveArg<2>(&device1_result_callback));
3708  EXPECT_CALL(*mock_devices_[2], SetEnabledPersistent(false, _, _))
3709      .WillOnce(DoAll(WithArg<1>(Invoke(SetErrorPermissionDenied)),
3710                      SaveArg<2>(&device2_result_callback)));
3711  EXPECT_CALL(disable_technology_reply_handler, ReportResult(_));
3712  mock_devices_[1]->enabled_ = true;
3713  mock_devices_[2]->enabled_ = true;
3714  error.Populate(Error::kOperationInitiated);
3715  manager()->SetEnabledStateForTechnology(kTypeCellular, false, true,
3716                                          &error, disable_technology_callback);
3717  EXPECT_TRUE(error.IsOngoing());
3718  device1_result_callback.Run(Error(Error::kSuccess));
3719  device2_result_callback.Run(Error(Error::kSuccess));
3720}
3721
3722TEST_F(ManagerTest, IgnoredSearchList) {
3723  std::unique_ptr<MockResolver> resolver(new StrictMock<MockResolver>());
3724  vector<string> ignored_paths;
3725  SetResolver(resolver.get());
3726
3727  const string kIgnored0 = "chromium.org";
3728  ignored_paths.push_back(kIgnored0);
3729  EXPECT_CALL(*resolver.get(), set_ignored_search_list(ignored_paths));
3730  SetIgnoredDNSSearchPaths(kIgnored0, nullptr);
3731  EXPECT_EQ(kIgnored0, GetIgnoredDNSSearchPaths());
3732
3733  const string kIgnored1 = "google.com";
3734  const string kIgnoredSum = kIgnored0 + "," + kIgnored1;
3735  ignored_paths.push_back(kIgnored1);
3736  EXPECT_CALL(*resolver.get(), set_ignored_search_list(ignored_paths));
3737  SetIgnoredDNSSearchPaths(kIgnoredSum, nullptr);
3738  EXPECT_EQ(kIgnoredSum, GetIgnoredDNSSearchPaths());
3739
3740  ignored_paths.clear();
3741  EXPECT_CALL(*resolver.get(), set_ignored_search_list(ignored_paths));
3742  SetIgnoredDNSSearchPaths("", nullptr);
3743  EXPECT_EQ("", GetIgnoredDNSSearchPaths());
3744
3745  SetResolver(Resolver::GetInstance());
3746}
3747
3748TEST_F(ManagerTest, ServiceStateChangeEmitsServices) {
3749  // Test to make sure that every service state-change causes the
3750  // Manager to emit a new service list.
3751  scoped_refptr<MockService> mock_service(
3752      new NiceMock<MockService>(control_interface(),
3753                                dispatcher(),
3754                                metrics(),
3755                                manager()));
3756  EXPECT_CALL(*mock_service, state())
3757      .WillRepeatedly(Return(Service::kStateIdle));
3758
3759  manager()->RegisterService(mock_service);
3760  EXPECT_CALL(
3761      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3762          kServiceCompleteListProperty, _)).Times(1);
3763  EXPECT_CALL(
3764      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3765          kServicesProperty, _)).Times(1);
3766  EXPECT_CALL(
3767      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3768          kServiceWatchListProperty, _)).Times(1);
3769  CompleteServiceSort();
3770
3771  Mock::VerifyAndClearExpectations(manager_adaptor_);
3772  EXPECT_CALL(
3773      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3774          kServiceCompleteListProperty, _)).Times(1);
3775  EXPECT_CALL(
3776      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3777          kServicesProperty, _)).Times(1);
3778  EXPECT_CALL(
3779      *manager_adaptor_, EmitRpcIdentifierArrayChanged(
3780          kServiceWatchListProperty, _)).Times(1);
3781  manager()->UpdateService(mock_service.get());
3782  CompleteServiceSort();
3783
3784  manager()->DeregisterService(mock_service);
3785}
3786
3787TEST_F(ManagerTest, EnumerateServices) {
3788  scoped_refptr<MockService> mock_service(
3789      new NiceMock<MockService>(control_interface(),
3790                                dispatcher(),
3791                                metrics(),
3792                                manager()));
3793  manager()->RegisterService(mock_service);
3794
3795  EXPECT_CALL(*mock_service, state())
3796      .WillRepeatedly(Return(Service::kStateConnected));
3797  EXPECT_CALL(*mock_service, IsVisible())
3798      .WillRepeatedly(Return(false));
3799  EXPECT_TRUE(EnumerateAvailableServices().empty());
3800  EXPECT_TRUE(EnumerateWatchedServices().empty());
3801
3802  EXPECT_CALL(*mock_service, state())
3803      .WillRepeatedly(Return(Service::kStateIdle));
3804  EXPECT_TRUE(EnumerateAvailableServices().empty());
3805  EXPECT_TRUE(EnumerateWatchedServices().empty());
3806
3807  EXPECT_CALL(*mock_service, IsVisible())
3808      .WillRepeatedly(Return(true));
3809  Service::ConnectState unwatched_states[] = {
3810      Service::kStateUnknown,
3811      Service::kStateIdle,
3812      Service::kStateFailure
3813  };
3814  for (size_t i = 0; i < arraysize(unwatched_states); ++i) {
3815    EXPECT_CALL(*mock_service, state())
3816        .WillRepeatedly(Return(unwatched_states[i]));
3817    EXPECT_FALSE(EnumerateAvailableServices().empty());
3818    EXPECT_TRUE(EnumerateWatchedServices().empty());
3819  }
3820
3821  Service::ConnectState watched_states[] = {
3822      Service::kStateAssociating,
3823      Service::kStateConfiguring,
3824      Service::kStateConnected,
3825      Service::kStatePortal,
3826      Service::kStateOnline
3827  };
3828  for (size_t i = 0; i < arraysize(watched_states); ++i) {
3829    EXPECT_CALL(*mock_service, state())
3830        .WillRepeatedly(Return(watched_states[i]));
3831    EXPECT_FALSE(EnumerateAvailableServices().empty());
3832    EXPECT_FALSE(EnumerateWatchedServices().empty());
3833  }
3834
3835  manager()->DeregisterService(mock_service);
3836}
3837
3838TEST_F(ManagerTest, ConnectToBestServices) {
3839  scoped_refptr<MockService> wifi_service0(
3840      new NiceMock<MockService>(control_interface(),
3841                                dispatcher(),
3842                                metrics(),
3843                                manager()));
3844  EXPECT_CALL(*wifi_service0.get(), state())
3845      .WillRepeatedly(Return(Service::kStateIdle));
3846  EXPECT_CALL(*wifi_service0.get(), IsConnected())
3847      .WillRepeatedly(Return(false));
3848  wifi_service0->SetConnectable(true);
3849  wifi_service0->SetAutoConnect(true);
3850  wifi_service0->SetSecurity(Service::kCryptoAes, true, true);
3851  EXPECT_CALL(*wifi_service0.get(), technology())
3852      .WillRepeatedly(Return(Technology::kWifi));
3853  EXPECT_CALL(*wifi_service0.get(), IsVisible())
3854      .WillRepeatedly(Return(false));
3855  EXPECT_CALL(*wifi_service0.get(), explicitly_disconnected())
3856      .WillRepeatedly(Return(false));
3857
3858  scoped_refptr<MockService> wifi_service1(
3859      new NiceMock<MockService>(control_interface(),
3860                                dispatcher(),
3861                                metrics(),
3862                                manager()));
3863  EXPECT_CALL(*wifi_service1.get(), state())
3864      .WillRepeatedly(Return(Service::kStateIdle));
3865  EXPECT_CALL(*wifi_service1.get(), IsVisible())
3866      .WillRepeatedly(Return(true));
3867  EXPECT_CALL(*wifi_service1.get(), IsConnected())
3868      .WillRepeatedly(Return(false));
3869  wifi_service1->SetAutoConnect(true);
3870  wifi_service1->SetConnectable(true);
3871  wifi_service1->SetSecurity(Service::kCryptoRc4, true, true);
3872  EXPECT_CALL(*wifi_service1.get(), technology())
3873      .WillRepeatedly(Return(Technology::kWifi));
3874  EXPECT_CALL(*wifi_service1.get(), explicitly_disconnected())
3875      .WillRepeatedly(Return(false));
3876
3877  scoped_refptr<MockService> wifi_service2(
3878      new NiceMock<MockService>(control_interface(),
3879                                dispatcher(),
3880                                metrics(),
3881                                manager()));
3882  EXPECT_CALL(*wifi_service2.get(), state())
3883      .WillRepeatedly(Return(Service::kStateConnected));
3884  EXPECT_CALL(*wifi_service2.get(), IsConnected())
3885      .WillRepeatedly(Return(true));
3886  EXPECT_CALL(*wifi_service2.get(), IsVisible())
3887      .WillRepeatedly(Return(true));
3888  wifi_service2->SetAutoConnect(true);
3889  wifi_service2->SetConnectable(true);
3890  wifi_service2->SetSecurity(Service::kCryptoNone, false, false);
3891  EXPECT_CALL(*wifi_service2.get(), technology())
3892      .WillRepeatedly(Return(Technology::kWifi));
3893  EXPECT_CALL(*wifi_service2.get(), explicitly_disconnected())
3894      .WillRepeatedly(Return(false));
3895
3896  manager()->RegisterService(wifi_service0);
3897  manager()->RegisterService(wifi_service1);
3898  manager()->RegisterService(wifi_service2);
3899
3900  CompleteServiceSort();
3901  EXPECT_TRUE(ServiceOrderIs(wifi_service2, wifi_service0));
3902
3903  scoped_refptr<MockService> cell_service(
3904      new NiceMock<MockService>(control_interface(),
3905                                dispatcher(),
3906                                metrics(),
3907                                manager()));
3908
3909  EXPECT_CALL(*cell_service.get(), state())
3910      .WillRepeatedly(Return(Service::kStateIdle));
3911  EXPECT_CALL(*cell_service.get(), IsConnected())
3912      .WillRepeatedly(Return(false));
3913  EXPECT_CALL(*cell_service.get(), IsVisible())
3914      .WillRepeatedly(Return(true));
3915  cell_service->SetAutoConnect(true);
3916  cell_service->SetConnectable(true);
3917  EXPECT_CALL(*cell_service.get(), technology())
3918      .WillRepeatedly(Return(Technology::kCellular));
3919  EXPECT_CALL(*cell_service.get(), explicitly_disconnected())
3920      .WillRepeatedly(Return(true));
3921  manager()->RegisterService(cell_service);
3922
3923  scoped_refptr<MockService> wimax_service(
3924      new NiceMock<MockService>(control_interface(),
3925                                dispatcher(),
3926                                metrics(),
3927                                manager()));
3928
3929  EXPECT_CALL(*wimax_service.get(), state())
3930      .WillRepeatedly(Return(Service::kStateConnected));
3931  EXPECT_CALL(*wimax_service.get(), IsConnected())
3932      .WillRepeatedly(Return(true));
3933  EXPECT_CALL(*wimax_service.get(), IsVisible())
3934      .WillRepeatedly(Return(true));
3935  wimax_service->SetAutoConnect(true);
3936  wimax_service->SetConnectable(true);
3937  EXPECT_CALL(*wimax_service.get(), technology())
3938      .WillRepeatedly(Return(Technology::kWiMax));
3939  EXPECT_CALL(*wimax_service.get(), explicitly_disconnected())
3940      .WillRepeatedly(Return(false));
3941  manager()->RegisterService(wimax_service);
3942
3943  scoped_refptr<MockService> vpn_service(
3944      new NiceMock<MockService>(control_interface(),
3945                                dispatcher(),
3946                                metrics(),
3947                                manager()));
3948
3949  EXPECT_CALL(*vpn_service.get(), state())
3950      .WillRepeatedly(Return(Service::kStateIdle));
3951  EXPECT_CALL(*vpn_service.get(), IsConnected())
3952      .WillRepeatedly(Return(false));
3953  EXPECT_CALL(*vpn_service.get(), IsVisible())
3954      .WillRepeatedly(Return(true));
3955  wifi_service2->SetAutoConnect(false);
3956  vpn_service->SetConnectable(true);
3957  EXPECT_CALL(*vpn_service.get(), technology())
3958      .WillRepeatedly(Return(Technology::kVPN));
3959  manager()->RegisterService(vpn_service);
3960
3961  // The connected services should be at the top.
3962  EXPECT_TRUE(ServiceOrderIs(wifi_service2, wimax_service));
3963
3964  EXPECT_CALL(*wifi_service0.get(), Connect(_, _)).Times(0);  // Not visible.
3965  EXPECT_CALL(*wifi_service1.get(), Connect(_, _));
3966  EXPECT_CALL(*wifi_service2.get(), Connect(_, _)).Times(0);  // Lower prio.
3967  EXPECT_CALL(*cell_service.get(), Connect(_, _))
3968      .Times(0);  // Explicitly disconnected.
3969  EXPECT_CALL(*wimax_service.get(), Connect(_, _)).Times(0);  // Is connected.
3970  EXPECT_CALL(*vpn_service.get(), Connect(_, _)).Times(0);  // Not autoconnect.
3971
3972  manager()->ConnectToBestServices(nullptr);
3973  dispatcher()->DispatchPendingEvents();
3974
3975  // After this operation, since the Connect calls above are mocked and
3976  // no actual state changes have occurred, we should expect that the
3977  // service sorting order will not have changed.
3978  EXPECT_TRUE(ServiceOrderIs(wifi_service2, wimax_service));
3979}
3980
3981TEST_F(ManagerTest, CreateConnectivityReport) {
3982  // Add devices
3983  // WiFi
3984  auto wifi_device = make_scoped_refptr(
3985       new NiceMock<MockDevice>(control_interface(),
3986                                dispatcher(),
3987                                metrics(),
3988                                manager(),
3989                                "null",
3990                                "addr",
3991                                0));
3992  manager()->RegisterDevice(wifi_device);
3993  // Cell
3994  auto cell_device = make_scoped_refptr(
3995      new NiceMock<MockDevice>(control_interface(),
3996                               dispatcher(),
3997                               metrics(),
3998                               manager(),
3999                               "null",
4000                               "addr",
4001                               1));
4002  manager()->RegisterDevice(cell_device);
4003  // WiMax
4004  auto wimax_device = make_scoped_refptr(
4005      new NiceMock<MockDevice>(control_interface(),
4006                               dispatcher(),
4007                               metrics(),
4008                               manager(),
4009                               "null",
4010                               "addr",
4011                               2));
4012  manager()->RegisterDevice(wimax_device);
4013  // Ethernet
4014  auto eth_device = make_scoped_refptr(
4015      new NiceMock<MockDevice>(control_interface(),
4016                               dispatcher(),
4017                               metrics(),
4018                               manager(),
4019                               "null",
4020                               "addr",
4021                               3));
4022  manager()->RegisterDevice(eth_device);
4023  // VPN Device -- base device for a service that will not be connected
4024  auto vpn_device = make_scoped_refptr(
4025      new NiceMock<MockDevice>(control_interface(),
4026                               dispatcher(),
4027                               metrics(),
4028                               manager(),
4029                               "null",
4030                               "addr",
4031                               4));
4032  manager()->RegisterDevice(vpn_device);
4033
4034  // Add service for multiple devices
4035  // WiFi
4036  MockServiceRefPtr wifi_service =
4037      new NiceMock<MockService>(control_interface(),
4038                                dispatcher(),
4039                                metrics(),
4040                                manager());
4041  manager()->RegisterService(wifi_service);
4042  EXPECT_CALL(*wifi_service.get(), state())
4043      .WillRepeatedly(Return(Service::kStateConnected));
4044  EXPECT_CALL(*wifi_service.get(), IsConnected())
4045      .WillRepeatedly(Return(true));
4046  EXPECT_CALL(*wifi_device.get(),
4047              IsConnectedToService(_)).WillRepeatedly(Return(false));
4048  EXPECT_CALL(*wifi_device.get(),
4049              IsConnectedToService(IsRefPtrTo(wifi_service)))
4050      .WillRepeatedly(Return(true));
4051
4052  // Cell
4053  MockServiceRefPtr cell_service =
4054      new NiceMock<MockService>(control_interface(),
4055                                dispatcher(),
4056                                metrics(),
4057                                manager());
4058  manager()->RegisterService(cell_service);
4059  EXPECT_CALL(*cell_service.get(), state())
4060      .WillRepeatedly(Return(Service::kStateConnected));
4061  EXPECT_CALL(*cell_service.get(), IsConnected())
4062      .WillRepeatedly(Return(true));
4063  EXPECT_CALL(*cell_device.get(),
4064              IsConnectedToService(_)).WillRepeatedly(Return(false));
4065  EXPECT_CALL(*cell_device.get(),
4066              IsConnectedToService(IsRefPtrTo(cell_service)))
4067      .WillRepeatedly(Return(true));
4068
4069  // WiMax
4070  MockServiceRefPtr wimax_service =
4071      new NiceMock<MockService>(control_interface(),
4072                                dispatcher(),
4073                                metrics(),
4074                                manager());
4075  manager()->RegisterService(wimax_service);
4076  EXPECT_CALL(*wimax_service.get(), state())
4077      .WillRepeatedly(Return(Service::kStateConnected));
4078  EXPECT_CALL(*wimax_service.get(), IsConnected())
4079      .WillRepeatedly(Return(true));
4080
4081  EXPECT_CALL(*wimax_device.get(),
4082              IsConnectedToService(_)).WillRepeatedly(Return(false));
4083  EXPECT_CALL(*wimax_device.get(),
4084              IsConnectedToService(IsRefPtrTo(wimax_service)))
4085      .WillRepeatedly(Return(true));
4086
4087  // Ethernet
4088  MockServiceRefPtr eth_service =
4089      new NiceMock<MockService>(control_interface(),
4090                                dispatcher(),
4091                                metrics(),
4092                                manager());
4093  manager()->RegisterService(eth_service);
4094  EXPECT_CALL(*eth_service.get(), state())
4095      .WillRepeatedly(Return(Service::kStateConnected));
4096  EXPECT_CALL(*eth_service.get(), IsConnected())
4097      .WillRepeatedly(Return(true));
4098  EXPECT_CALL(*eth_device.get(),
4099              IsConnectedToService(_)).WillRepeatedly(Return(false));
4100  EXPECT_CALL(*eth_device.get(),
4101              IsConnectedToService(IsRefPtrTo(eth_service)))
4102      .WillRepeatedly(Return(true));
4103
4104  // VPN: Service exists but is not connected and will not trigger a
4105  // connectivity report.
4106  MockServiceRefPtr vpn_service =
4107      new NiceMock<MockService>(control_interface(),
4108                                dispatcher(),
4109                                metrics(),
4110                                manager());
4111  manager()->RegisterService(vpn_service);
4112  EXPECT_CALL(*vpn_service.get(), state())
4113      .WillRepeatedly(Return(Service::kStateIdle));
4114  EXPECT_CALL(*vpn_service.get(), IsConnected())
4115      .WillRepeatedly(Return(false));
4116
4117  EXPECT_CALL(*wifi_device.get(), StartConnectivityTest())
4118      .WillOnce(Return(true));
4119  EXPECT_CALL(*cell_device.get(), StartConnectivityTest())
4120      .WillOnce(Return(true));
4121  EXPECT_CALL(*wimax_device.get(), StartConnectivityTest())
4122      .WillOnce(Return(true));
4123  EXPECT_CALL(*eth_device.get(), StartConnectivityTest())
4124      .WillOnce(Return(true));
4125  EXPECT_CALL(*vpn_device.get(), StartConnectivityTest()).Times(0);
4126  manager()->CreateConnectivityReport(nullptr);
4127  dispatcher()->DispatchPendingEvents();
4128}
4129
4130#if !defined(DISABLE_WIFI)
4131TEST_F(ManagerTest, VerifyWhenNotConnected) {
4132  const string kFakeCertificate("fake cert");
4133  const string kFakePublicKey("fake public key");
4134  const string kFakeNonce("fake public key");
4135  const string kFakeSignedData("fake signed data");
4136  const string kFakeUdn("fake udn");
4137  const vector<uint8_t> kSSID(10, 87);
4138  const string kConfiguredSSID("AConfiguredDestination");
4139  const vector<uint8_t> kConfiguredSSIDVector(kConfiguredSSID.begin(),
4140                                              kConfiguredSSID.end());
4141  const string kConfiguredBSSID("aa:bb:aa:bb:aa:bb");
4142  scoped_refptr<MockWiFiService> mock_destination(
4143      new NiceMock<MockWiFiService>(control_interface(), dispatcher(),
4144                                    metrics(), manager(), wifi_provider_,
4145                                    kSSID, "", "none", false));
4146  // Register this service, but don't mark it as connected.
4147  manager()->RegisterService(mock_destination);
4148  // Verify that if we're not connected to anything, verification fails.
4149  {
4150    LOG(INFO) << "Can't verify if not connected.";
4151    EXPECT_CALL(*crypto_util_proxy_,
4152                VerifyDestination(_, _, _, _, _, _, _, _, _)).Times(0);
4153    Error error(Error::kOperationInitiated);
4154    manager()->VerifyDestination(kFakeCertificate, kFakePublicKey, kFakeNonce,
4155                                 kFakeSignedData, kFakeUdn, "", "",
4156                                 ResultBoolCallback(), &error);
4157    EXPECT_TRUE(error.IsFailure());
4158    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4159  }
4160  {
4161    // However, if the destination is already configured, we might be
4162    // connected to it via something other than WiFi, and we shouldn't
4163    // enforce the WiFi check.
4164    EXPECT_CALL(*crypto_util_proxy_,
4165                VerifyDestination(kFakeCertificate, kFakePublicKey, kFakeNonce,
4166                                  kFakeSignedData, kFakeUdn,
4167                                  kConfiguredSSIDVector, kConfiguredBSSID,
4168                                  _, _)).Times(1).WillOnce(Return(true));
4169    Error error(Error::kOperationInitiated);
4170    manager()->VerifyDestination(kFakeCertificate, kFakePublicKey, kFakeNonce,
4171                                 kFakeSignedData, kFakeUdn, kConfiguredSSID,
4172                                 kConfiguredBSSID, ResultBoolCallback(),
4173                                 &error);
4174    EXPECT_FALSE(error.IsFailure());
4175    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4176  }
4177}
4178
4179TEST_F(ManagerTest, VerifyDestination) {
4180  const string kFakeCertificate("fake cert");
4181  const string kFakePublicKey("fake public key");
4182  const string kFakeNonce("fake public key");
4183  const string kFakeSignedData("fake signed data");
4184  const string kFakeUdn("fake udn");
4185  const char kSSIDStr[] = "fake ssid";
4186  const vector<uint8_t> kSSID(kSSIDStr, kSSIDStr + arraysize(kSSIDStr));
4187  const string kConfiguredSSID("AConfiguredDestination");
4188  const vector<uint8_t> kConfiguredSSIDVector(kConfiguredSSID.begin(),
4189                                              kConfiguredSSID.end());
4190  const string kConfiguredBSSID("aa:bb:aa:bb:aa:bb");
4191  const string kFakeData("muffin man");
4192  scoped_refptr<MockWiFiService> mock_destination(
4193      new NiceMock<MockWiFiService>(control_interface(),
4194                                    dispatcher(),
4195                                    metrics(),
4196                                    manager(),
4197                                    wifi_provider_,
4198                                    kSSID,
4199                                    "",
4200                                    "none",
4201                                    false));
4202  manager()->RegisterService(mock_destination);
4203  // Making the service look online will let service lookup in
4204  // VerifyDestinatoin succeed.
4205  EXPECT_CALL(*mock_destination.get(), IsConnected())
4206      .WillRepeatedly(Return(true));
4207  StrictMock<DestinationVerificationTest> dv_test;
4208
4209  // Lead off by verifying that the basic VerifyDestination flow works.
4210  {
4211    LOG(INFO) << "Basic VerifyDestination flow.";
4212    ResultBoolCallback passed_down_callback;
4213    EXPECT_CALL(*crypto_util_proxy_, VerifyDestination(kFakeCertificate,
4214                                                       kFakePublicKey,
4215                                                       kFakeNonce,
4216                                                       kFakeSignedData,
4217                                                       kFakeUdn,
4218                                                       kSSID,
4219                                                       _,
4220                                                       _,
4221                                                       _))
4222        .Times(1)
4223        .WillOnce(DoAll(SaveArg<7>(&passed_down_callback), Return(true)));
4224    // Ask the manager to verify the current destination.  This should look
4225    // up our previously registered service, and pass some metadata about
4226    // that service down to the CryptoUtilProxy to verify.
4227    Error error(Error::kOperationInitiated);
4228    ResultBoolCallback cb = Bind(
4229        &DestinationVerificationTest::ResultBoolCallbackStub,
4230        dv_test.AsWeakPtr());
4231    manager()->VerifyDestination(kFakeCertificate,
4232                                 kFakePublicKey,
4233                                 kFakeNonce,
4234                                 kFakeSignedData,
4235                                 kFakeUdn,
4236                                 // Ask to be verified against that service.
4237                                 "", "",
4238                                 cb,
4239                                 &error);
4240    // We assert here, because if the operation is not ongoing, it is
4241    // inconsistent with shim behavior to call the callback anyway.
4242    ASSERT_TRUE(error.IsOngoing());
4243    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4244    EXPECT_CALL(dv_test, ResultBoolCallbackStub(_, true)).Times(1);
4245    // Call the callback passed into the CryptoUtilProxy, which
4246    // should find its way into the callback passed into the manager.
4247    // In real code, that callback passed into the manager is from the
4248    // DBus adaptor.
4249    Error e;
4250    passed_down_callback.Run(e, true);
4251    Mock::VerifyAndClearExpectations(&dv_test);
4252  }
4253
4254  // Now for a slightly more complex variant.  When we encrypt data,
4255  // we do the same verification step but monkey with the callback to
4256  // link ourselves to an encrypt step afterward.
4257  {
4258    LOG(INFO) << "Basic VerifyAndEncryptData";
4259    ResultBoolCallback passed_down_callback;
4260    EXPECT_CALL(*crypto_util_proxy_, VerifyDestination(kFakeCertificate,
4261                                                       kFakePublicKey,
4262                                                       kFakeNonce,
4263                                                       kFakeSignedData,
4264                                                       kFakeUdn,
4265                                                       kSSID,
4266                                                       _,
4267                                                       _,
4268                                                       _))
4269        .WillOnce(DoAll(SaveArg<7>(&passed_down_callback), Return(true)));
4270
4271    Error error(Error::kOperationInitiated);
4272    ResultStringCallback cb = Bind(
4273        &DestinationVerificationTest::ResultStringCallbackStub,
4274        dv_test.AsWeakPtr());
4275    manager()->VerifyAndEncryptData(kFakeCertificate,
4276                                    kFakePublicKey,
4277                                    kFakeNonce,
4278                                    kFakeSignedData,
4279                                    kFakeUdn,
4280                                    "", "",
4281                                    kFakeData,
4282                                    cb,
4283                                    &error);
4284    ASSERT_TRUE(error.IsOngoing());
4285    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4286    // Now, if we call that passed down callback, we should see encrypt being
4287    // called.
4288    ResultStringCallback second_passed_down_callback;
4289    EXPECT_CALL(*crypto_util_proxy_, EncryptData(kFakePublicKey,
4290                                                 kFakeData,
4291                                                 _,
4292                                                 _))
4293        .Times(1)
4294        .WillOnce(DoAll(SaveArg<2>(&second_passed_down_callback),
4295                        Return(true)));
4296    Error e;
4297    passed_down_callback.Run(e, true);
4298    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4299    EXPECT_CALL(dv_test, ResultStringCallbackStub(_, _)).Times(1);
4300    // And if we call the second passed down callback, we should see the
4301    // original function we passed down to VerifyDestination getting called.
4302    e.Reset();
4303    second_passed_down_callback.Run(e, "");
4304    Mock::VerifyAndClearExpectations(&dv_test);
4305  }
4306
4307  // If verification fails on the way to trying to encrypt, we should ditch
4308  // without calling encrypt at all.
4309  {
4310    LOG(INFO) << "Failed VerifyAndEncryptData";
4311    ResultBoolCallback passed_down_callback;
4312    EXPECT_CALL(*crypto_util_proxy_, VerifyDestination(kFakeCertificate,
4313                                                       kFakePublicKey,
4314                                                       kFakeNonce,
4315                                                       kFakeSignedData,
4316                                                       kFakeUdn,
4317                                                       kSSID,
4318                                                       _,
4319                                                       _,
4320                                                       _))
4321        .WillOnce(DoAll(SaveArg<7>(&passed_down_callback), Return(true)));
4322
4323    Error error(Error::kOperationInitiated);
4324    ResultStringCallback cb = Bind(
4325        &DestinationVerificationTest::ResultStringCallbackStub,
4326        dv_test.AsWeakPtr());
4327    manager()->VerifyAndEncryptData(kFakeCertificate,
4328                                    kFakePublicKey,
4329                                    kFakeNonce,
4330                                    kFakeSignedData,
4331                                    kFakeUdn,
4332                                    "", "",
4333                                    kFakeData,
4334                                    cb,
4335                                    &error);
4336    ASSERT_TRUE(error.IsOngoing());
4337    Mock::VerifyAndClearExpectations(crypto_util_proxy_);
4338    Error e(Error::kOperationFailed);
4339    EXPECT_CALL(*crypto_util_proxy_, EncryptData(_, _, _, _)).Times(0);
4340    // Although we're ditching, this callback is what cleans up the pending
4341    // DBus call.
4342    EXPECT_CALL(dv_test, ResultStringCallbackStub(_, string(""))).Times(1);
4343    passed_down_callback.Run(e, false);
4344    Mock::VerifyAndClearExpectations(&dv_test);
4345  }
4346}
4347#endif  // DISABLE_WIFI
4348
4349TEST_F(ManagerTest, IsProfileBefore) {
4350  scoped_refptr<MockProfile> profile0(
4351      new NiceMock<MockProfile>(
4352          control_interface(), metrics(), manager(), ""));
4353  scoped_refptr<MockProfile> profile1(
4354      new NiceMock<MockProfile>(
4355          control_interface(), metrics(), manager(), ""));
4356
4357  AdoptProfile(manager(), profile0);
4358  AdoptProfile(manager(), profile1);  // profile1 is after profile0.
4359  EXPECT_TRUE(manager()->IsProfileBefore(profile0, profile1));
4360  EXPECT_FALSE(manager()->IsProfileBefore(profile1, profile0));
4361
4362  // A few abnormal cases, but it's good to track their behavior.
4363  scoped_refptr<MockProfile> profile2(
4364      new NiceMock<MockProfile>(
4365          control_interface(), metrics(), manager(), ""));
4366  EXPECT_TRUE(manager()->IsProfileBefore(profile0, profile2));
4367  EXPECT_TRUE(manager()->IsProfileBefore(profile1, profile2));
4368  EXPECT_FALSE(manager()->IsProfileBefore(profile2, profile0));
4369  EXPECT_FALSE(manager()->IsProfileBefore(profile2, profile1));
4370}
4371
4372TEST_F(ManagerTest, GetLoadableProfileEntriesForService) {
4373  MockStore storage0;
4374  MockStore storage1;
4375  MockStore storage2;
4376
4377  scoped_refptr<MockProfile> profile0(
4378      new NiceMock<MockProfile>(
4379          control_interface(), metrics(), manager(), ""));
4380  scoped_refptr<MockProfile> profile1(
4381      new NiceMock<MockProfile>(
4382          control_interface(), metrics(), manager(), ""));
4383  scoped_refptr<MockProfile> profile2(
4384      new NiceMock<MockProfile>(
4385          control_interface(), metrics(), manager(), ""));
4386
4387  AdoptProfile(manager(), profile0);
4388  AdoptProfile(manager(), profile1);
4389  AdoptProfile(manager(), profile2);
4390
4391  scoped_refptr<MockService> service(
4392      new NiceMock<MockService>(control_interface(),
4393                                dispatcher(),
4394                                metrics(),
4395                                manager()));
4396
4397  EXPECT_CALL(*profile0, GetConstStorage()).WillOnce(Return(&storage0));
4398  EXPECT_CALL(*profile1, GetConstStorage()).WillOnce(Return(&storage1));
4399  EXPECT_CALL(*profile2, GetConstStorage()).WillOnce(Return(&storage2));
4400
4401  const string kEntry0("aluminum_crutch");
4402  const string kEntry2("rehashed_faces");
4403
4404  EXPECT_CALL(*service, GetLoadableStorageIdentifier(Ref(storage0)))
4405      .WillOnce(Return(kEntry0));
4406  EXPECT_CALL(*service, GetLoadableStorageIdentifier(Ref(storage1)))
4407      .WillOnce(Return(""));
4408  EXPECT_CALL(*service, GetLoadableStorageIdentifier(Ref(storage2)))
4409      .WillOnce(Return(kEntry2));
4410
4411  const string kProfileRpc0("service_station");
4412  const string kProfileRpc2("crystal_tiaras");
4413
4414  EXPECT_CALL(*profile0, GetRpcIdentifier()).WillOnce(Return(kProfileRpc0));
4415  EXPECT_CALL(*profile1, GetRpcIdentifier()).Times(0);
4416  EXPECT_CALL(*profile2, GetRpcIdentifier()).WillOnce(Return(kProfileRpc2));
4417
4418  map<string, string> entries =
4419      manager()->GetLoadableProfileEntriesForService(service);
4420  EXPECT_EQ(2, entries.size());
4421  EXPECT_TRUE(ContainsKey(entries, kProfileRpc0));
4422  EXPECT_TRUE(ContainsKey(entries, kProfileRpc2));
4423  EXPECT_EQ(kEntry0, entries[kProfileRpc0]);
4424  EXPECT_EQ(kEntry2, entries[kProfileRpc2]);
4425}
4426
4427#if !defined(DISABLE_WIFI)
4428TEST_F(ManagerTest, InitializeProfilesInformsProviders) {
4429  ScopedTempDir temp_dir;
4430  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
4431  Manager manager(control_interface(),
4432                  dispatcher(),
4433                  metrics(),
4434                  run_path(),
4435                  storage_path(),
4436                  temp_dir.path().value());
4437  // Can't use |wifi_provider_|, because it's owned by the Manager
4438  // object in the fixture.
4439  MockWiFiProvider* wifi_provider = new NiceMock<MockWiFiProvider>();
4440  manager.wifi_provider_.reset(wifi_provider);  // pass ownership
4441  manager.UpdateProviderMapping();
4442  // Give manager a valid place to write the user profile list.
4443  manager.user_profile_list_path_ = temp_dir.path().Append("user_profile_list");
4444
4445  // With no user profiles, the WiFiProvider should be called once
4446  // (for the default profile).
4447  EXPECT_CALL(*wifi_provider, CreateServicesFromProfile(_));
4448  manager.InitializeProfiles();
4449  Mock::VerifyAndClearExpectations(wifi_provider);
4450
4451  // With |n| user profiles, the WiFiProvider should be called |n+1|
4452  // times. First, create 2 user profiles...
4453  const char kProfile0[] = "~user/profile0";
4454  const char kProfile1[] = "~user/profile1";
4455  string profile_rpc_path;
4456  Error error;
4457  ASSERT_TRUE(base::CreateDirectory(temp_dir.path().Append("user")));
4458  manager.CreateProfile(kProfile0, &profile_rpc_path, &error);
4459  manager.PushProfile(kProfile0, &profile_rpc_path, &error);
4460  manager.CreateProfile(kProfile1, &profile_rpc_path, &error);
4461  manager.PushProfile(kProfile1, &profile_rpc_path, &error);
4462
4463  // ... then reset manager state ...
4464  manager.profiles_.clear();
4465
4466  // ...then check that the WiFiProvider is notified about all three
4467  // profiles (one default, two user).
4468  EXPECT_CALL(*wifi_provider, CreateServicesFromProfile(_)).Times(3);
4469  manager.InitializeProfiles();
4470  Mock::VerifyAndClearExpectations(wifi_provider);
4471}
4472#endif  // DISABLE_WIFI
4473
4474TEST_F(ManagerTest, InitializeProfilesHandlesDefaults) {
4475  ScopedTempDir temp_dir;
4476  std::unique_ptr<Manager> manager;
4477  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
4478
4479  // Instantiate a Manager with empty persistent storage. Check that
4480  // defaults are set.
4481  //
4482  // Note that we use the same directory for default and user profiles.
4483  // This doesn't affect the test results, because we don't push a
4484  // user profile.
4485  manager.reset(new Manager(control_interface(),
4486                            dispatcher(),
4487                            metrics(),
4488                            run_path(),
4489                            temp_dir.path().value(),
4490                            temp_dir.path().value()));
4491  manager->InitializeProfiles();
4492  EXPECT_EQ(PortalDetector::kDefaultCheckPortalList,
4493            manager->props_.check_portal_list);
4494  EXPECT_EQ(Resolver::kDefaultIgnoredSearchList,
4495            manager->props_.ignored_dns_search_paths);
4496  EXPECT_EQ(LinkMonitor::kDefaultLinkMonitorTechnologies,
4497            manager->props_.link_monitor_technologies);
4498  EXPECT_EQ(ConnectivityTrial::kDefaultURL,
4499            manager->props_.portal_url);
4500  EXPECT_EQ(PortalDetector::kDefaultCheckIntervalSeconds,
4501            manager->props_.portal_check_interval_seconds);
4502
4503  // Change one of the settings.
4504  static const string kCustomCheckPortalList = "fiber0";
4505  Error error;
4506  manager->SetCheckPortalList(kCustomCheckPortalList, &error);
4507  manager->profiles_[0]->Save();
4508
4509  // Instantiate a new manager. It should have our settings for
4510  // check_portal_list, rather than the default.
4511  manager.reset(new Manager(control_interface(),
4512                            dispatcher(),
4513                            metrics(),
4514                            run_path(),
4515                            temp_dir.path().value(),
4516                            temp_dir.path().value()));
4517  manager->InitializeProfiles();
4518  EXPECT_EQ(kCustomCheckPortalList, manager->props_.check_portal_list);
4519
4520  // If we clear the persistent storage, we again get the default value.
4521  ASSERT_TRUE(temp_dir.Delete());
4522  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
4523  manager.reset(new Manager(control_interface(),
4524                            dispatcher(),
4525                            metrics(),
4526                            run_path(),
4527                            temp_dir.path().value(),
4528                            temp_dir.path().value()));
4529  manager->InitializeProfiles();
4530  EXPECT_EQ(PortalDetector::kDefaultCheckPortalList,
4531            manager->props_.check_portal_list);
4532}
4533
4534TEST_F(ManagerTest, ProfileStackChangeLogging) {
4535  ScopedTempDir temp_dir;
4536  std::unique_ptr<Manager> manager;
4537  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
4538  manager.reset(new Manager(control_interface(),
4539                            dispatcher(),
4540                            metrics(),
4541                            run_path(),
4542                            temp_dir.path().value(),
4543                            temp_dir.path().value()));
4544
4545  ScopedMockLog log;
4546  EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
4547  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("1 profile(s)")));
4548  manager->InitializeProfiles();
4549
4550  const char kProfile0[] = "~user/profile0";
4551  const char kProfile1[] = "~user/profile1";
4552  const char kProfile2[] = "~user/profile2";
4553  ASSERT_TRUE(base::CreateDirectory(temp_dir.path().Append("user")));
4554  TestCreateProfile(manager.get(), kProfile0);
4555  TestCreateProfile(manager.get(), kProfile1);
4556  TestCreateProfile(manager.get(), kProfile2);
4557
4558  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("2 profile(s)")));
4559  TestPushProfile(manager.get(), kProfile0);
4560
4561  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("3 profile(s)")));
4562  TestInsertUserProfile(manager.get(), kProfile1, "not-so-random-string");
4563
4564  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("4 profile(s)")));
4565  TestInsertUserProfile(manager.get(), kProfile2, "very-random-string");
4566
4567  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("3 profile(s)")));
4568  TestPopProfile(manager.get(), kProfile2);
4569
4570  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("2 profile(s)")));
4571  TestPopAnyProfile(manager.get());
4572
4573  EXPECT_CALL(log, Log(logging::LOG_INFO, _, HasSubstr("1 profile(s)")));
4574  TestPopAllUserProfiles(manager.get());
4575}
4576
4577// Custom property setters should return false, and make no changes, if
4578// the new value is the same as the old value.
4579TEST_F(ManagerTest, CustomSetterNoopChange) {
4580  // SetCheckPortalList
4581  {
4582    static const string kCheckPortalList = "weird-device,weirder-device";
4583    Error error;
4584    // Set to known value.
4585    EXPECT_TRUE(SetCheckPortalList(kCheckPortalList, &error));
4586    EXPECT_TRUE(error.IsSuccess());
4587    // Set to same value.
4588    EXPECT_FALSE(SetCheckPortalList(kCheckPortalList, &error));
4589    EXPECT_TRUE(error.IsSuccess());
4590  }
4591
4592  // SetIgnoredDNSSearchPaths
4593  {
4594    NiceMock<MockResolver> resolver;
4595    static const string kIgnoredPaths = "example.com,example.org";
4596    Error error;
4597    SetResolver(&resolver);
4598    // Set to known value.
4599    EXPECT_CALL(resolver, set_ignored_search_list(_));
4600    EXPECT_TRUE(SetIgnoredDNSSearchPaths(kIgnoredPaths, &error));
4601    EXPECT_TRUE(error.IsSuccess());
4602    Mock::VerifyAndClearExpectations(&resolver);
4603    // Set to same value.
4604    EXPECT_CALL(resolver, set_ignored_search_list(_)).Times(0);
4605    EXPECT_FALSE(SetIgnoredDNSSearchPaths(kIgnoredPaths, &error));
4606    EXPECT_TRUE(error.IsSuccess());
4607    Mock::VerifyAndClearExpectations(&resolver);
4608  }
4609}
4610
4611TEST_F(ManagerTest, GeoLocation) {
4612  EXPECT_TRUE(manager()->GetNetworksForGeolocation().empty());
4613
4614  auto device = make_scoped_refptr(new NiceMock<MockDevice>(control_interface(),
4615                                                            dispatcher(),
4616                                                            metrics(),
4617                                                            manager(),
4618                                                            "null",
4619                                                            "addr",
4620                                                            0));
4621
4622  // Manager should ignore gelocation info from technologies it does not know.
4623  EXPECT_CALL(*device, technology())
4624      .Times(AtLeast(1))
4625      .WillRepeatedly(Return(Technology::kEthernet));
4626  EXPECT_CALL(*device, GetGeolocationObjects()).Times(0);
4627  manager()->OnDeviceGeolocationInfoUpdated(device);
4628  Mock::VerifyAndClearExpectations(device.get());
4629  EXPECT_TRUE(manager()->GetNetworksForGeolocation().empty());
4630
4631  // Manager should add WiFi geolocation info.
4632  EXPECT_CALL(*device, technology())
4633      .Times(AtLeast(1))
4634      .WillRepeatedly(Return(Technology::kWifi));
4635  EXPECT_CALL(*device, GetGeolocationObjects())
4636      .WillOnce(Return(vector<GeolocationInfo>()));
4637  manager()->OnDeviceGeolocationInfoUpdated(device);
4638  Mock::VerifyAndClearExpectations(device.get());
4639  auto location_infos = manager()->GetNetworksForGeolocation();
4640  EXPECT_EQ(1, location_infos.size());
4641  EXPECT_TRUE(ContainsKey(location_infos, kGeoWifiAccessPointsProperty));
4642
4643  // Manager should inclusively add cellular info.
4644  EXPECT_CALL(*device, technology())
4645      .Times(AtLeast(1))
4646      .WillRepeatedly(Return(Technology::kCellular));
4647  EXPECT_CALL(*device, GetGeolocationObjects())
4648      .WillOnce(Return(vector<GeolocationInfo>()));
4649  manager()->OnDeviceGeolocationInfoUpdated(device);
4650  location_infos = manager()->GetNetworksForGeolocation();
4651  EXPECT_EQ(2, location_infos.size());
4652  EXPECT_TRUE(ContainsKey(location_infos, kGeoWifiAccessPointsProperty));
4653  EXPECT_TRUE(ContainsKey(location_infos, kGeoCellTowersProperty));
4654}
4655
4656TEST_F(ManagerTest, IsWifiIdle) {
4657  // No registered service.
4658  EXPECT_FALSE(manager()->IsWifiIdle());
4659
4660  scoped_refptr<MockService> wifi_service(new MockService(control_interface(),
4661                                                          dispatcher(),
4662                                                          metrics(),
4663                                                          manager()));
4664
4665  scoped_refptr<MockService> cell_service(new MockService(control_interface(),
4666                                                          dispatcher(),
4667                                                          metrics(),
4668                                                          manager()));
4669
4670  manager()->RegisterService(wifi_service);
4671  manager()->RegisterService(cell_service);
4672
4673  EXPECT_CALL(*wifi_service.get(), technology())
4674      .WillRepeatedly(Return(Technology::kWifi));
4675  EXPECT_CALL(*cell_service.get(), technology())
4676      .WillRepeatedly(Return(Technology::kCellular));
4677
4678  // Cellular is connected.
4679  EXPECT_CALL(*cell_service.get(), IsConnected())
4680      .WillRepeatedly(Return(true));
4681  manager()->UpdateService(cell_service);
4682
4683  // No wifi connection attempt.
4684  EXPECT_CALL(*wifi_service.get(), IsConnecting())
4685      .WillRepeatedly(Return(false));
4686  EXPECT_CALL(*wifi_service.get(), IsConnected())
4687      .WillRepeatedly(Return(false));
4688  manager()->UpdateService(wifi_service);
4689  EXPECT_TRUE(manager()->IsWifiIdle());
4690
4691  // Attempt wifi connection.
4692  Mock::VerifyAndClearExpectations(wifi_service.get());
4693  EXPECT_CALL(*wifi_service.get(), technology())
4694      .WillRepeatedly(Return(Technology::kWifi));
4695  EXPECT_CALL(*wifi_service.get(), IsConnecting())
4696      .WillRepeatedly(Return(true));
4697  EXPECT_CALL(*wifi_service.get(), IsConnected())
4698      .WillRepeatedly(Return(false));
4699  manager()->UpdateService(wifi_service);
4700  EXPECT_FALSE(manager()->IsWifiIdle());
4701
4702  // wifi connected.
4703  Mock::VerifyAndClearExpectations(wifi_service.get());
4704  EXPECT_CALL(*wifi_service.get(), technology())
4705      .WillRepeatedly(Return(Technology::kWifi));
4706  EXPECT_CALL(*wifi_service.get(), IsConnecting())
4707      .WillRepeatedly(Return(false));
4708  EXPECT_CALL(*wifi_service.get(), IsConnected())
4709      .WillRepeatedly(Return(true));
4710  manager()->UpdateService(wifi_service);
4711  EXPECT_FALSE(manager()->IsWifiIdle());
4712}
4713
4714TEST_F(ManagerTest, DetectMultiHomedDevices) {
4715  vector<scoped_refptr<MockConnection>> mock_connections;
4716  vector<ConnectionRefPtr> device_connections;
4717  mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
4718                                                   dispatcher(),
4719                                                   metrics(),
4720                                                   manager(),
4721                                                   "null4",
4722                                                   "addr4",
4723                                                   0));
4724  mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
4725                                                   dispatcher(),
4726                                                   metrics(),
4727                                                   manager(),
4728                                                   "null5",
4729                                                   "addr5",
4730                                                   0));
4731  for (const auto& device : mock_devices_) {
4732    manager()->RegisterDevice(device);
4733    mock_connections.emplace_back(
4734        new NiceMock<MockConnection>(device_info_.get()));
4735    device_connections.emplace_back(mock_connections.back());
4736  }
4737  EXPECT_CALL(*mock_connections[1], GetSubnetName()).WillOnce(Return("1"));
4738  EXPECT_CALL(*mock_connections[2], GetSubnetName()).WillOnce(Return("2"));
4739  EXPECT_CALL(*mock_connections[3], GetSubnetName()).WillOnce(Return("1"));
4740  EXPECT_CALL(*mock_connections[4], GetSubnetName()).WillOnce(Return(""));
4741  EXPECT_CALL(*mock_connections[5], GetSubnetName()).WillOnce(Return(""));
4742
4743  // Do not assign a connection to mock_devices_[0].
4744  EXPECT_CALL(*mock_devices_[1], connection())
4745      .WillRepeatedly(ReturnRef(device_connections[1]));
4746  EXPECT_CALL(*mock_devices_[2], connection())
4747      .WillRepeatedly(ReturnRef(device_connections[2]));
4748  EXPECT_CALL(*mock_devices_[3], connection())
4749      .WillRepeatedly(ReturnRef(device_connections[3]));
4750  EXPECT_CALL(*mock_devices_[4], connection())
4751      .WillRepeatedly(ReturnRef(device_connections[4]));
4752  EXPECT_CALL(*mock_devices_[5], connection())
4753      .WillRepeatedly(ReturnRef(device_connections[5]));
4754
4755  EXPECT_CALL(*mock_devices_[0], SetIsMultiHomed(false));
4756  EXPECT_CALL(*mock_devices_[1], SetIsMultiHomed(true));
4757  EXPECT_CALL(*mock_devices_[2], SetIsMultiHomed(false));
4758  EXPECT_CALL(*mock_devices_[3], SetIsMultiHomed(true));
4759  EXPECT_CALL(*mock_devices_[4], SetIsMultiHomed(false));
4760  EXPECT_CALL(*mock_devices_[5], SetIsMultiHomed(false));
4761  manager()->DetectMultiHomedDevices();
4762}
4763
4764TEST_F(ManagerTest, IsTechnologyProhibited) {
4765  // Test initial state.
4766  EXPECT_EQ("", manager()->props_.prohibited_technologies);
4767  EXPECT_FALSE(manager()->IsTechnologyProhibited(Technology::kWiMax));
4768  EXPECT_FALSE(manager()->IsTechnologyProhibited(Technology::kVPN));
4769
4770  Error smoke_error;
4771  EXPECT_FALSE(manager()->SetProhibitedTechnologies("smoke_signal",
4772                                                    &smoke_error));
4773  EXPECT_EQ(Error::kInvalidArguments, smoke_error.type());
4774
4775  ON_CALL(*mock_devices_[0], technology())
4776      .WillByDefault(Return(Technology::kVPN));
4777  ON_CALL(*mock_devices_[1], technology())
4778      .WillByDefault(Return(Technology::kWiMax));
4779  ON_CALL(*mock_devices_[2], technology())
4780      .WillByDefault(Return(Technology::kWifi));
4781
4782  manager()->RegisterDevice(mock_devices_[0]);
4783  manager()->RegisterDevice(mock_devices_[1]);
4784  manager()->RegisterDevice(mock_devices_[2]);
4785
4786  // Registered devices of prohibited technology types should be disabled.
4787  EXPECT_CALL(*mock_devices_[0], SetEnabledNonPersistent(false, _, _));
4788  EXPECT_CALL(*mock_devices_[1], SetEnabledNonPersistent(false, _, _));
4789  EXPECT_CALL(*mock_devices_[2], SetEnabledNonPersistent(false, _, _)).Times(0);
4790  Error error;
4791  manager()->SetProhibitedTechnologies("wimax,vpn", &error);
4792  EXPECT_TRUE(manager()->IsTechnologyProhibited(Technology::kVPN));
4793  EXPECT_TRUE(manager()->IsTechnologyProhibited(Technology::kWiMax));
4794  EXPECT_FALSE(manager()->IsTechnologyProhibited(Technology::kWifi));
4795  Mock::VerifyAndClearExpectations(mock_devices_[0].get());
4796  Mock::VerifyAndClearExpectations(mock_devices_[1].get());
4797  Mock::VerifyAndClearExpectations(mock_devices_[2].get());
4798
4799  // Newly registered devices should be disabled.
4800  mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
4801                                                   dispatcher(),
4802                                                   metrics(),
4803                                                   manager(),
4804                                                   "null4",
4805                                                   "addr4",
4806                                                   0));
4807  mock_devices_.push_back(new NiceMock<MockDevice>(control_interface(),
4808                                                   dispatcher(),
4809                                                   metrics(),
4810                                                   manager(),
4811                                                   "null5",
4812                                                   "addr5",
4813                                                   0));
4814  ON_CALL(*mock_devices_[3], technology())
4815      .WillByDefault(Return(Technology::kVPN));
4816  ON_CALL(*mock_devices_[4], technology())
4817      .WillByDefault(Return(Technology::kWiMax));
4818  ON_CALL(*mock_devices_[5], technology())
4819      .WillByDefault(Return(Technology::kWifi));
4820
4821  EXPECT_CALL(*mock_devices_[3], SetEnabledNonPersistent(false, _, _));
4822  EXPECT_CALL(*mock_devices_[4], SetEnabledNonPersistent(false, _, _));
4823  EXPECT_CALL(*mock_devices_[5], SetEnabledPersistent(false, _, _)).Times(0);
4824
4825  manager()->RegisterDevice(mock_devices_[3]);
4826  manager()->RegisterDevice(mock_devices_[4]);
4827  manager()->RegisterDevice(mock_devices_[5]);
4828  Mock::VerifyAndClearExpectations(mock_devices_[3].get());
4829  Mock::VerifyAndClearExpectations(mock_devices_[4].get());
4830  Mock::VerifyAndClearExpectations(mock_devices_[5].get());
4831
4832  // Calls to enable a non-prohibited technology should succeed.
4833  Error enable_error(Error::kOperationInitiated);
4834  DisableTechnologyReplyHandler technology_reply_handler;
4835  ResultCallback enable_technology_callback(
4836      Bind(&DisableTechnologyReplyHandler::ReportResult,
4837           technology_reply_handler.AsWeakPtr()));
4838  EXPECT_CALL(*mock_devices_[2], SetEnabledPersistent(true, _, _));
4839  EXPECT_CALL(*mock_devices_[5], SetEnabledPersistent(true, _, _));
4840  manager()->SetEnabledStateForTechnology(
4841      "wifi", true, true, &enable_error, enable_technology_callback);
4842  EXPECT_EQ(Error::kOperationInitiated, enable_error.type());
4843
4844  // Calls to enable a prohibited technology should fail.
4845  Error enable_prohibited_error(Error::kOperationInitiated);
4846  EXPECT_CALL(*mock_devices_[0], SetEnabledPersistent(true, _, _)).Times(0);
4847  EXPECT_CALL(*mock_devices_[3], SetEnabledPersistent(true, _, _)).Times(0);
4848  manager()->SetEnabledStateForTechnology(
4849      "vpn", true, true, &enable_prohibited_error, enable_technology_callback);
4850  EXPECT_EQ(Error::kPermissionDenied, enable_prohibited_error.type());
4851}
4852
4853TEST_F(ManagerTest, ClaimBlacklistedDevice) {
4854  const string kClaimerName = "test_claimer";
4855  const string kDeviceName = "test_device";
4856
4857  // Set blacklisted devices.
4858  vector<string> blacklisted_devices = { kDeviceName };
4859  manager()->SetBlacklistedDevices(blacklisted_devices);
4860
4861  Error error;
4862  manager()->ClaimDevice(kClaimerName, kDeviceName, &error);
4863  EXPECT_TRUE(error.IsFailure());
4864  EXPECT_EQ("Not allowed to claim unmanaged device", error.message());
4865  // Verify device claimer is not created.
4866  EXPECT_EQ(nullptr, manager()->device_claimer_.get());
4867}
4868
4869TEST_F(ManagerTest, ReleaseBlacklistedDevice) {
4870  const string kClaimerName = "test_claimer";
4871  const string kDeviceName = "test_device";
4872
4873  // Set blacklisted devices.
4874  vector<string> blacklisted_devices = { kDeviceName };
4875  manager()->SetBlacklistedDevices(blacklisted_devices);
4876
4877  Error error;
4878  bool claimer_removed;
4879  manager()->ReleaseDevice(kClaimerName, kDeviceName, &claimer_removed, &error);
4880  EXPECT_TRUE(error.IsFailure());
4881  EXPECT_FALSE(claimer_removed);
4882  EXPECT_EQ("Not allowed to release unmanaged device", error.message());
4883}
4884
4885TEST_F(ManagerTest, BlacklistedDeviceIsNotManaged) {
4886  const string kDeviceName = "test_device";
4887
4888  vector<string> blacklisted_devices = { kDeviceName };
4889  manager()->SetBlacklistedDevices(blacklisted_devices);
4890  EXPECT_FALSE(manager()->DeviceManagementAllowed(kDeviceName));
4891}
4892
4893TEST_F(ManagerTest, NonBlacklistedDeviceIsManaged) {
4894  const string kDeviceName = "test_device";
4895
4896  vector<string> blacklisted_devices = { "other_device" };
4897  manager()->SetBlacklistedDevices(blacklisted_devices);
4898  EXPECT_TRUE(manager()->DeviceManagementAllowed(kDeviceName));
4899}
4900
4901TEST_F(ManagerTest, WhitelistedDeviceIsManaged) {
4902  const string kDeviceName = "test_device";
4903
4904  vector<string> whitelisted_devices = { kDeviceName };
4905  manager()->SetWhitelistedDevices(whitelisted_devices);
4906  EXPECT_TRUE(manager()->DeviceManagementAllowed(kDeviceName));
4907}
4908
4909TEST_F(ManagerTest, NonWhitelistedDeviceIsNotManaged) {
4910  const string kDeviceName = "test_device";
4911
4912  vector<string> whitelisted_devices = { "other_device" };
4913  manager()->SetWhitelistedDevices(whitelisted_devices);
4914  EXPECT_FALSE(manager()->DeviceManagementAllowed(kDeviceName));
4915}
4916
4917TEST_F(ManagerTest, DevicesIsManagedByDefault) {
4918  EXPECT_TRUE(manager()->DeviceManagementAllowed("test_device"));
4919}
4920
4921TEST_F(ManagerTest, ClaimDeviceWithoutClaimer) {
4922  const char kClaimerName[] = "test_claimer1";
4923  const char kDeviceName[] = "test_device";
4924
4925  // Claim device when device claimer doesn't exist yet.
4926  Error error;
4927  manager()->ClaimDevice(kClaimerName, kDeviceName, &error);
4928  EXPECT_TRUE(error.IsSuccess());
4929  EXPECT_TRUE(manager()->device_info()->IsDeviceBlackListed(kDeviceName));
4930  // Verify device claimer is created.
4931  EXPECT_NE(nullptr, manager()->device_claimer_.get());
4932}
4933
4934TEST_F(ManagerTest, ClaimDeviceWithClaimer) {
4935  const char kClaimer1Name[] = "test_claimer1";
4936  const char kClaimer2Name[] = "test_claimer2";
4937  const char kDeviceName[] = "test_device";
4938
4939  // Setup device claimer.
4940  MockDeviceClaimer* device_claimer = new MockDeviceClaimer(kClaimer1Name);
4941  SetDeviceClaimer(device_claimer);
4942
4943  // Claim device with empty string name.
4944  const char kEmptyDeviceNameError[] = "Empty device name";
4945  Error error;
4946  manager()->ClaimDevice(kClaimer1Name, "", &error);
4947  EXPECT_EQ(string(kEmptyDeviceNameError), error.message());
4948
4949  // Device claim succeed.
4950  error.Reset();
4951  EXPECT_CALL(*device_claimer, Claim(kDeviceName, _)).WillOnce(Return(true));
4952  manager()->ClaimDevice(kClaimer1Name, kDeviceName, &error);
4953  EXPECT_EQ(Error::kSuccess, error.type());
4954  Mock::VerifyAndClearExpectations(device_claimer);
4955
4956  // Claimer mismatch, current implementation only allows one claimer at a time.
4957  const char kInvalidClaimerError[] =
4958      "Invalid claimer name test_claimer2. Claimer test_claimer1 already exist";
4959  error.Reset();
4960  EXPECT_CALL(*device_claimer, Claim(_, _)).Times(0);
4961  manager()->ClaimDevice(kClaimer2Name, kDeviceName, &error);
4962  EXPECT_EQ(string(kInvalidClaimerError), error.message());
4963}
4964
4965TEST_F(ManagerTest, ClaimRegisteredDevice) {
4966  const char kClaimerName[] = "test_claimer";
4967
4968  // Setup device claimer.
4969  MockDeviceClaimer* device_claimer = new MockDeviceClaimer(kClaimerName);
4970  SetDeviceClaimer(device_claimer);
4971
4972  // Register a device to manager.
4973  ON_CALL(*mock_devices_[0].get(), technology())
4974      .WillByDefault(Return(Technology::kWifi));
4975  manager()->RegisterDevice(mock_devices_[0]);
4976  // Verify device is registered.
4977  EXPECT_TRUE(IsDeviceRegistered(mock_devices_[0], Technology::kWifi));
4978
4979  // Claim the registered device.
4980  Error error;
4981  EXPECT_CALL(*device_claimer, Claim(mock_devices_[0]->link_name(), _))
4982      .WillOnce(Return(true));
4983  manager()->ClaimDevice(kClaimerName, mock_devices_[0]->link_name(), &error);
4984  EXPECT_EQ(Error::kSuccess, error.type());
4985  Mock::VerifyAndClearExpectations(device_claimer);
4986
4987  // Expect device to not be registered anymore.
4988  EXPECT_FALSE(IsDeviceRegistered(mock_devices_[0], Technology::kWifi));
4989}
4990
4991TEST_F(ManagerTest, ReleaseDevice) {
4992  const char kClaimerName[] = "test_claimer";
4993  const char kWrongClaimerName[] = "test_claimer1";
4994  const char kDeviceName[] = "test_device";
4995
4996  // Release device without claimer.
4997  const char kNoClaimerError[] = "Device claimer doesn't exist";
4998  Error error;
4999  bool claimer_removed;
5000  manager()->ReleaseDevice(kClaimerName, kDeviceName, &claimer_removed, &error);
5001  EXPECT_EQ(string(kNoClaimerError), error.message());
5002  EXPECT_FALSE(claimer_removed);
5003
5004  // Setup device claimer.
5005  MockDeviceClaimer* device_claimer = new MockDeviceClaimer(kClaimerName);
5006  SetDeviceClaimer(device_claimer);
5007
5008  // Release device from wrong claimer.
5009  const char kClaimerMismatchError[] =
5010      "Invalid claimer name test_claimer1. Claimer test_claimer already exist";
5011  error.Reset();
5012  manager()->ReleaseDevice(kWrongClaimerName, kDeviceName, &claimer_removed,
5013                           &error);
5014  EXPECT_EQ(string(kClaimerMismatchError), error.message());
5015  EXPECT_FALSE(claimer_removed);
5016
5017  // Release one of multiple device from a non-default claimer.
5018  error.Reset();
5019  EXPECT_CALL(*device_claimer, Release(kDeviceName, &error))
5020      .WillOnce(Return(true));
5021  EXPECT_CALL(*device_claimer, default_claimer()).WillOnce(Return(false));
5022  EXPECT_CALL(*device_claimer, DevicesClaimed()).WillOnce(Return(true));
5023  manager()->ReleaseDevice(kClaimerName, kDeviceName, &claimer_removed, &error);
5024  Mock::VerifyAndClearExpectations(device_claimer);
5025  EXPECT_TRUE(error.IsSuccess());
5026  EXPECT_FALSE(claimer_removed);
5027
5028  // Release a device with default claimer. Claimer should not be resetted.
5029  error.Reset();
5030  EXPECT_CALL(*device_claimer, Release(kDeviceName, &error))
5031      .WillOnce(Return(true));
5032  EXPECT_CALL(*device_claimer, default_claimer()).WillOnce(Return(true));
5033  EXPECT_CALL(*device_claimer, DevicesClaimed()).Times(0);
5034  manager()->ReleaseDevice(kClaimerName, kDeviceName, &claimer_removed, &error);
5035  Mock::VerifyAndClearExpectations(device_claimer);
5036  EXPECT_TRUE(error.IsSuccess());
5037  EXPECT_FALSE(claimer_removed);
5038  EXPECT_NE(nullptr, manager()->device_claimer_.get());
5039
5040  // Release last device with non-default claimer. Claimer should be resetted.
5041  error.Reset();
5042  EXPECT_CALL(*device_claimer, Release(kDeviceName, &error))
5043      .WillOnce(Return(true));
5044  EXPECT_CALL(*device_claimer, default_claimer()).WillOnce(Return(false));
5045  EXPECT_CALL(*device_claimer, DevicesClaimed()).WillOnce(Return(false));
5046  manager()->ReleaseDevice(kClaimerName, kDeviceName, &claimer_removed, &error);
5047  Mock::VerifyAndClearExpectations(device_claimer);
5048  EXPECT_TRUE(error.IsSuccess());
5049  EXPECT_TRUE(claimer_removed);
5050  EXPECT_EQ(nullptr, manager()->device_claimer_.get());
5051}
5052
5053TEST_F(ManagerTest, GetEnabledDeviceWithTechnology) {
5054  auto ethernet_device = mock_devices_[0];
5055  auto wifi_device = mock_devices_[1];
5056  auto cellular_device = mock_devices_[2];
5057  ON_CALL(*ethernet_device.get(), technology())
5058      .WillByDefault(Return(Technology::kEthernet));
5059  ON_CALL(*wifi_device.get(), technology())
5060      .WillByDefault(Return(Technology::kWifi));
5061  ON_CALL(*cellular_device.get(), technology())
5062      .WillByDefault(Return(Technology::kCellular));
5063  ethernet_device->enabled_ = true;
5064  wifi_device->enabled_ = true;
5065  cellular_device->enabled_ = true;
5066
5067  manager()->RegisterDevice(ethernet_device);
5068  manager()->RegisterDevice(wifi_device);
5069  manager()->RegisterDevice(cellular_device);
5070
5071  EXPECT_EQ(ethernet_device,
5072            manager()->GetEnabledDeviceWithTechnology(Technology::kEthernet));
5073  EXPECT_EQ(wifi_device,
5074            manager()->GetEnabledDeviceWithTechnology(Technology::kWifi));
5075  EXPECT_EQ(cellular_device,
5076            manager()->GetEnabledDeviceWithTechnology(Technology::kCellular));
5077}
5078
5079TEST_F(ManagerTest, GetEnabledDeviceByLinkName) {
5080  auto ethernet_device = mock_devices_[0];
5081  auto wifi_device = mock_devices_[1];
5082  auto disabled_wifi_device = mock_devices_[2];
5083  ON_CALL(*ethernet_device.get(), technology())
5084      .WillByDefault(Return(Technology::kEthernet));
5085  ON_CALL(*wifi_device.get(), technology())
5086      .WillByDefault(Return(Technology::kWifi));
5087  ON_CALL(*disabled_wifi_device.get(), technology())
5088      .WillByDefault(Return(Technology::kWifi));
5089  ethernet_device->enabled_ = true;
5090  wifi_device->enabled_ = true;
5091  disabled_wifi_device->enabled_ = false;
5092
5093  manager()->RegisterDevice(ethernet_device);
5094  manager()->RegisterDevice(wifi_device);
5095
5096  EXPECT_EQ(ethernet_device,
5097            manager()->GetEnabledDeviceByLinkName(
5098                ethernet_device->link_name()));
5099  EXPECT_EQ(wifi_device,
5100            manager()->GetEnabledDeviceByLinkName(wifi_device->link_name()));
5101  EXPECT_EQ(nullptr,
5102            manager()->GetEnabledDeviceByLinkName(
5103                disabled_wifi_device->link_name()));
5104}
5105
5106TEST_F(ManagerTest, AcceptHostnameFrom) {
5107  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth0"));
5108  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth1"));
5109  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5110
5111  manager()->SetAcceptHostnameFrom("eth0");
5112  EXPECT_TRUE(manager()->ShouldAcceptHostnameFrom("eth0"));
5113  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth1"));
5114  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5115
5116  manager()->SetAcceptHostnameFrom("eth1");
5117  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth0"));
5118  EXPECT_TRUE(manager()->ShouldAcceptHostnameFrom("eth1"));
5119  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5120
5121  manager()->SetAcceptHostnameFrom("eth*");
5122  EXPECT_TRUE(manager()->ShouldAcceptHostnameFrom("eth0"));
5123  EXPECT_TRUE(manager()->ShouldAcceptHostnameFrom("eth1"));
5124  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5125
5126  manager()->SetAcceptHostnameFrom("wlan*");
5127  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth0"));
5128  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth1"));
5129  EXPECT_TRUE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5130
5131  manager()->SetAcceptHostnameFrom("ether*");
5132  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth0"));
5133  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("eth1"));
5134  EXPECT_FALSE(manager()->ShouldAcceptHostnameFrom("wlan0"));
5135}
5136
5137TEST_F(ManagerTest, DHCPv6EnabledDevices) {
5138  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("eth0"));
5139  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("eth1"));
5140  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("wlan0"));
5141
5142  vector<string> enabled_devices;
5143  enabled_devices.push_back("eth0");
5144  manager()->SetDHCPv6EnabledDevices(enabled_devices);
5145  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("eth0"));
5146  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("eth1"));
5147  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("wlan0"));
5148
5149  enabled_devices.push_back("eth1");
5150  manager()->SetDHCPv6EnabledDevices(enabled_devices);
5151  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("eth0"));
5152  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("eth1"));
5153  EXPECT_FALSE(manager()->IsDHCPv6EnabledForDevice("wlan0"));
5154
5155  enabled_devices.push_back("wlan0");
5156  manager()->SetDHCPv6EnabledDevices(enabled_devices);
5157  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("eth0"));
5158  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("eth1"));
5159  EXPECT_TRUE(manager()->IsDHCPv6EnabledForDevice("wlan0"));
5160}
5161
5162TEST_F(ManagerTest, FilterPrependDNSServersByFamily) {
5163  const struct {
5164    IPAddress::Family family;
5165    string prepend_value;
5166    vector<string> output_list;
5167  } expectations[] = {
5168    {IPAddress::kFamilyIPv4, "", {}},
5169    {IPAddress::kFamilyIPv4, "8.8.8.8", {"8.8.8.8"}},
5170    {IPAddress::kFamilyIPv4, "8.8.8.8,2001:4860:4860::8888", {"8.8.8.8"}},
5171    {IPAddress::kFamilyIPv4, "2001:4860:4860::8844", {}},
5172    {IPAddress::kFamilyIPv6, "", {}},
5173    {IPAddress::kFamilyIPv6, "8.8.8.8", {}},
5174    {IPAddress::kFamilyIPv6, "2001:4860:4860::8844",
5175        {"2001:4860:4860::8844"}},
5176    {IPAddress::kFamilyIPv6, "8.8.8.8,2001:4860:4860::8888",
5177        {"2001:4860:4860::8888"}}
5178  };
5179
5180  for (const auto& expectation : expectations) {
5181    manager()->SetPrependDNSServers(expectation.prepend_value);
5182    auto dns_servers =
5183        manager()->FilterPrependDNSServersByFamily(expectation.family);
5184    EXPECT_EQ(expectation.output_list, dns_servers);
5185  }
5186}
5187
5188}  // namespace shill
5189