Home | History | Annotate | Download | only in cellular
      1 //
      2 // Copyright (C) 2013 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/cellular/cellular.h"
     18 
     19 #include <sys/socket.h>
     20 #include <linux/if.h>  // NOLINT - Needs typedefs from sys/socket.h.
     21 #include <linux/netlink.h>
     22 
     23 #include <base/bind.h>
     24 #if defined(__ANDROID__)
     25 #include <dbus/service_constants.h>
     26 #else
     27 #include <chromeos/dbus/service_constants.h>
     28 #endif  // __ANDROID__
     29 
     30 #include "shill/cellular/cellular_bearer.h"
     31 #include "shill/cellular/cellular_capability_cdma.h"
     32 #include "shill/cellular/cellular_capability_classic.h"
     33 #include "shill/cellular/cellular_capability_gsm.h"
     34 #include "shill/cellular/cellular_capability_universal.h"
     35 #include "shill/cellular/cellular_service.h"
     36 #include "shill/cellular/mock_cellular_service.h"
     37 #include "shill/cellular/mock_mm1_modem_modem3gpp_proxy.h"
     38 #include "shill/cellular/mock_mm1_modem_proxy.h"
     39 #include "shill/cellular/mock_mm1_modem_simple_proxy.h"
     40 #include "shill/cellular/mock_mobile_operator_info.h"
     41 #include "shill/cellular/mock_modem_cdma_proxy.h"
     42 #include "shill/cellular/mock_modem_gsm_card_proxy.h"
     43 #include "shill/cellular/mock_modem_gsm_network_proxy.h"
     44 #include "shill/cellular/mock_modem_info.h"
     45 #include "shill/cellular/mock_modem_proxy.h"
     46 #include "shill/cellular/mock_modem_simple_proxy.h"
     47 #include "shill/dhcp/mock_dhcp_config.h"
     48 #include "shill/dhcp/mock_dhcp_provider.h"
     49 #include "shill/error.h"
     50 #include "shill/mock_adaptors.h"
     51 #include "shill/mock_control.h"
     52 #include "shill/mock_dbus_properties_proxy.h"
     53 #include "shill/mock_device_info.h"
     54 #include "shill/mock_external_task.h"
     55 #include "shill/mock_ppp_device.h"
     56 #include "shill/mock_ppp_device_factory.h"
     57 #include "shill/mock_process_manager.h"
     58 #include "shill/net/mock_rtnl_handler.h"
     59 #include "shill/property_store_unittest.h"
     60 #include "shill/rpc_task.h"  // for RpcTaskDelegate
     61 #include "shill/test_event_dispatcher.h"
     62 #include "shill/testing.h"
     63 
     64 // mm/mm-modem.h must be included after cellular_capability_universal.h
     65 // in order to allow MM_MODEM_CDMA_* to be defined properly.
     66 #include <mm/mm-modem.h>
     67 
     68 using base::Bind;
     69 using base::Unretained;
     70 using std::map;
     71 using std::string;
     72 using std::unique_ptr;
     73 using std::vector;
     74 using testing::_;
     75 using testing::AnyNumber;
     76 using testing::DoAll;
     77 using testing::Invoke;
     78 using testing::Mock;
     79 using testing::NiceMock;
     80 using testing::Return;
     81 using testing::ReturnRef;
     82 using testing::SaveArg;
     83 using testing::SetArgumentPointee;
     84 using testing::Unused;
     85 
     86 namespace shill {
     87 
     88 class CellularPropertyTest : public PropertyStoreTest {
     89  public:
     90   CellularPropertyTest()
     91       : modem_info_(control_interface(),
     92                     dispatcher(),
     93                     metrics(),
     94                     manager()),
     95         device_(new Cellular(&modem_info_,
     96                              "usb0",
     97                              "00:01:02:03:04:05",
     98                              3,
     99                              Cellular::kTypeCDMA,
    100                              "",
    101                              "")) {}
    102   virtual ~CellularPropertyTest() {}
    103 
    104  protected:
    105   MockModemInfo modem_info_;
    106   DeviceRefPtr device_;
    107 };
    108 
    109 TEST_F(CellularPropertyTest, Contains) {
    110   EXPECT_TRUE(device_->store().Contains(kNameProperty));
    111   EXPECT_FALSE(device_->store().Contains(""));
    112 }
    113 
    114 TEST_F(CellularPropertyTest, SetProperty) {
    115   {
    116     Error error;
    117     const bool allow_roaming = true;
    118     EXPECT_TRUE(device_->mutable_store()->SetAnyProperty(
    119         kCellularAllowRoamingProperty, allow_roaming, &error));
    120   }
    121   // Ensure that attempting to write a R/O property returns InvalidArgs error.
    122   {
    123     Error error;
    124     EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
    125         kAddressProperty, PropertyStoreTest::kStringV, &error));
    126     ASSERT_TRUE(error.IsFailure());  // name() may be invalid otherwise
    127     EXPECT_EQ(Error::kInvalidArguments, error.type());
    128   }
    129   {
    130     Error error;
    131     EXPECT_FALSE(device_->mutable_store()->SetAnyProperty(
    132         kCarrierProperty, PropertyStoreTest::kStringV, &error));
    133     ASSERT_TRUE(error.IsFailure());  // name() may be invalid otherwise
    134     EXPECT_EQ(Error::kInvalidArguments, error.type());
    135   }
    136 }
    137 
    138 class CellularTest : public testing::Test {
    139  public:
    140   CellularTest()
    141       : kHomeProviderCode("10001"),
    142         kHomeProviderCountry("us"),
    143         kHomeProviderName("HomeProviderName"),
    144         kServingOperatorCode("10002"),
    145         kServingOperatorCountry("ca"),
    146         kServingOperatorName("ServingOperatorName"),
    147         control_interface_(this),
    148         modem_info_(&control_interface_, &dispatcher_, nullptr, nullptr),
    149         device_info_(modem_info_.control_interface(), &dispatcher_,
    150                      modem_info_.metrics(), modem_info_.manager()),
    151         dhcp_config_(new MockDHCPConfig(modem_info_.control_interface(),
    152                                         kTestDeviceName)),
    153         create_gsm_card_proxy_from_factory_(false),
    154         mock_home_provider_info_(nullptr),
    155         mock_serving_operator_info_(nullptr),
    156         device_(new Cellular(&modem_info_,
    157                              kTestDeviceName,
    158                              kTestDeviceAddress,
    159                              3,
    160                              Cellular::kTypeGSM,
    161                              kDBusService,
    162                              kDBusPath)) {
    163     PopulateProxies();
    164     modem_info_.metrics()->RegisterDevice(device_->interface_index(),
    165                                           Technology::kCellular);
    166   }
    167 
    168   virtual void SetUp() {
    169     static_cast<Device*>(device_.get())->rtnl_handler_ = &rtnl_handler_;
    170     device_->set_dhcp_provider(&dhcp_provider_);
    171     device_->process_manager_ = &process_manager_;
    172     EXPECT_CALL(*modem_info_.mock_manager(), device_info())
    173         .WillRepeatedly(Return(&device_info_));
    174     EXPECT_CALL(*modem_info_.mock_manager(), DeregisterService(_))
    175         .Times(AnyNumber());
    176   }
    177 
    178   virtual void TearDown() {
    179     device_->DestroyIPConfig();
    180     device_->state_ = Cellular::kStateDisabled;
    181     device_->capability_->ReleaseProxies();
    182     device_->set_dhcp_provider(nullptr);
    183     // Break cycle between Cellular and CellularService.
    184     device_->service_ = nullptr;
    185     device_->SelectService(nullptr);
    186   }
    187 
    188   void PopulateProxies() {
    189     dbus_properties_proxy_.reset(new MockDBusPropertiesProxy());
    190     proxy_.reset(new MockModemProxy());
    191     simple_proxy_.reset(new MockModemSimpleProxy());
    192     cdma_proxy_.reset(new MockModemCDMAProxy());
    193     gsm_card_proxy_.reset(new MockModemGSMCardProxy());
    194     gsm_network_proxy_.reset(new MockModemGSMNetworkProxy());
    195     mm1_modem_3gpp_proxy_.reset(new mm1::MockModemModem3gppProxy());
    196     mm1_proxy_.reset(new mm1::MockModemProxy());
    197     mm1_simple_proxy_.reset(new mm1::MockModemSimpleProxy());
    198   }
    199 
    200   void SetMockMobileOperatorInfoObjects() {
    201     mock_home_provider_info_ =
    202         new MockMobileOperatorInfo(&dispatcher_, "HomeProvider");
    203     // Takes ownership.
    204     device_->set_home_provider_info(mock_home_provider_info_);
    205 
    206     mock_serving_operator_info_ =
    207         new MockMobileOperatorInfo(&dispatcher_, "ServingOperator");
    208     // Takes ownership.
    209     device_->set_serving_operator_info(mock_serving_operator_info_);
    210   }
    211 
    212   void InvokeEnable(bool enable, Error* error,
    213                     const ResultCallback& callback, int timeout) {
    214     callback.Run(Error());
    215   }
    216   void InvokeEnableReturningWrongState(
    217       bool enable, Error* error, const ResultCallback& callback, int timeout) {
    218     callback.Run(Error(Error::kWrongState));
    219   }
    220   void InvokeGetSignalQuality(Error* error,
    221                               const SignalQualityCallback& callback,
    222                               int timeout) {
    223     callback.Run(kStrength, Error());
    224   }
    225   void InvokeGetModemStatus(Error* error,
    226                             const KeyValueStoreCallback& callback,
    227                             int timeout) {
    228     KeyValueStore props;
    229     props.SetString("carrier", kTestCarrier);
    230     props.SetString("unknown-property", "irrelevant-value");
    231     callback.Run(props, Error());
    232   }
    233   void InvokeGetModemInfo(Error* error, const ModemInfoCallback& callback,
    234                             int timeout) {
    235     static const char kManufacturer[] = "Company";
    236     static const char kModelID[] = "Gobi 2000";
    237     static const char kHWRev[] = "A00B1234";
    238     callback.Run(kManufacturer, kModelID, kHWRev, Error());
    239   }
    240   void InvokeGetRegistrationState1X(Error* error,
    241                                     const RegistrationStateCallback& callback,
    242                                     int timeout) {
    243     callback.Run(MM_MODEM_CDMA_REGISTRATION_STATE_HOME,
    244                  MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN,
    245                  Error());
    246   }
    247   void InvokeGetIMEI(Error* error, const GSMIdentifierCallback& callback,
    248                      int timeout) {
    249     callback.Run(kIMEI, Error());
    250   }
    251   void InvokeGetIMSI(Error* error, const GSMIdentifierCallback& callback,
    252                      int timeout) {
    253     callback.Run(kIMSI, Error());
    254   }
    255   void InvokeGetMSISDN(Error* error, const GSMIdentifierCallback& callback,
    256                        int timeout) {
    257     callback.Run(kMSISDN, Error());
    258   }
    259   void InvokeGetSPN(Error* error, const GSMIdentifierCallback& callback,
    260                     int timeout) {
    261     callback.Run(kTestCarrierSPN, Error());
    262   }
    263   void InvokeGetRegistrationInfo(Error* error,
    264                                  const RegistrationInfoCallback& callback,
    265                                  int timeout) {
    266     static const char kNetworkID[] = "22803";
    267     callback.Run(MM_MODEM_GSM_NETWORK_REG_STATUS_ROAMING,
    268                  kNetworkID, kTestCarrier, Error());
    269   }
    270   void InvokeRegister(const string& network_id,
    271                       Error* error,
    272                       const ResultCallback& callback,
    273                       int timeout) {
    274     callback.Run(Error());
    275   }
    276   void InvokeGetRegistrationState(Error* error,
    277                                   const RegistrationStateCallback& callback,
    278                                   int timeout) {
    279     callback.Run(MM_MODEM_CDMA_REGISTRATION_STATE_REGISTERED,
    280                  MM_MODEM_CDMA_REGISTRATION_STATE_HOME,
    281                  Error());
    282   }
    283   void InvokeGetRegistrationStateUnregistered(
    284       Error* error,
    285       const RegistrationStateCallback& callback,
    286       int timeout) {
    287     callback.Run(MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN,
    288                  MM_MODEM_CDMA_REGISTRATION_STATE_UNKNOWN,
    289                  Error());
    290   }
    291   void InvokeConnect(KeyValueStore props, Error* error,
    292                      const ResultCallback& callback, int timeout) {
    293     EXPECT_EQ(Service::kStateAssociating, device_->service_->state());
    294     callback.Run(Error());
    295   }
    296   void InvokeConnectFail(KeyValueStore props, Error* error,
    297                          const ResultCallback& callback, int timeout) {
    298     EXPECT_EQ(Service::kStateAssociating, device_->service_->state());
    299     callback.Run(Error(Error::kNotOnHomeNetwork));
    300   }
    301   void InvokeConnectFailNoService(KeyValueStore props, Error* error,
    302                                   const ResultCallback& callback, int timeout) {
    303     device_->service_ = nullptr;
    304     callback.Run(Error(Error::kNotOnHomeNetwork));
    305   }
    306   void InvokeConnectSuccessNoService(KeyValueStore props, Error* error,
    307                                      const ResultCallback& callback,
    308                                      int timeout) {
    309     device_->service_ = nullptr;
    310     callback.Run(Error());
    311   }
    312   void InvokeDisconnect(Error* error, const ResultCallback& callback,
    313                         int timeout) {
    314     if (!callback.is_null())
    315       callback.Run(Error());
    316   }
    317   void InvokeDisconnectFail(Error* error, const ResultCallback& callback,
    318                             int timeout) {
    319     error->Populate(Error::kOperationFailed);
    320     if (!callback.is_null())
    321       callback.Run(*error);
    322   }
    323   void InvokeDisconnectMM1(const string& bearer, Error* error,
    324                            const ResultCallback& callback, int timeout) {
    325     if (!callback.is_null())
    326       callback.Run(Error());
    327   }
    328   void InvokeSetPowerState(const uint32_t& power_state,
    329                            Error* error,
    330                            const ResultCallback& callback,
    331                            int timeout) {
    332     callback.Run(Error());
    333   }
    334   void ExpectCdmaStartModem(string network_technology) {
    335     if (!device_->IsUnderlyingDeviceEnabled())
    336       EXPECT_CALL(*proxy_,
    337                   Enable(true, _, _, CellularCapability::kTimeoutEnable))
    338           .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
    339     EXPECT_CALL(*simple_proxy_,
    340                 GetModemStatus(_, _, CellularCapability::kTimeoutDefault))
    341         .WillOnce(Invoke(this, &CellularTest::InvokeGetModemStatus));
    342     EXPECT_CALL(*proxy_,
    343                 GetModemInfo(_, _, CellularCapability::kTimeoutDefault))
    344         .WillOnce(Invoke(this, &CellularTest::InvokeGetModemInfo));
    345     if (network_technology == kNetworkTechnology1Xrtt)
    346       EXPECT_CALL(*cdma_proxy_, GetRegistrationState(nullptr, _, _))
    347           .WillOnce(Invoke(this, &CellularTest::InvokeGetRegistrationState1X));
    348     else
    349       EXPECT_CALL(*cdma_proxy_, GetRegistrationState(nullptr, _, _))
    350           .WillOnce(Invoke(this, &CellularTest::InvokeGetRegistrationState));
    351     EXPECT_CALL(*cdma_proxy_, GetSignalQuality(nullptr, _, _))
    352         .Times(2)
    353         .WillRepeatedly(Invoke(this, &CellularTest::InvokeGetSignalQuality));
    354     EXPECT_CALL(*this, TestCallback(IsSuccess()));
    355     EXPECT_CALL(*modem_info_.mock_manager(), RegisterService(_));
    356   }
    357 
    358   void ExpectDisconnectCapabilityUniversal() {
    359     SetCellularType(Cellular::kTypeUniversal);
    360     device_->state_ = Cellular::kStateConnected;
    361     EXPECT_CALL(*mm1_simple_proxy_, Disconnect(_, _, _, _))
    362         .WillOnce(Invoke(this, &CellularTest::InvokeDisconnectMM1));
    363     GetCapabilityUniversal()->modem_simple_proxy_.reset(
    364         mm1_simple_proxy_.release());
    365   }
    366 
    367   void VerifyDisconnect() {
    368     EXPECT_EQ(Cellular::kStateRegistered, device_->state_);
    369   }
    370 
    371   void StartPPP(int pid) {
    372     EXPECT_CALL(process_manager_, StartProcess(_, _, _, _, _, _))
    373         .WillOnce(Return(pid));
    374     device_->StartPPP("fake_serial_device");
    375     EXPECT_FALSE(device_->ipconfig());  // No DHCP client.
    376     EXPECT_FALSE(device_->selected_service());
    377     EXPECT_FALSE(device_->is_ppp_authenticating_);
    378     EXPECT_NE(nullptr, device_->ppp_task_);
    379     Mock::VerifyAndClearExpectations(&process_manager_);
    380   }
    381 
    382   void FakeUpConnectedPPP() {
    383     const char kInterfaceName[] = "fake-ppp-device";
    384     const int kInterfaceIndex = -1;
    385     auto mock_ppp_device = make_scoped_refptr(
    386         new MockPPPDevice(modem_info_.control_interface(), nullptr, nullptr,
    387                           nullptr, kInterfaceName, kInterfaceIndex));
    388     device_->ppp_device_ = mock_ppp_device;
    389     device_->state_ = Cellular::kStateConnected;
    390   }
    391 
    392   void ExpectPPPStopped() {
    393     auto mock_ppp_device =
    394         static_cast<MockPPPDevice*>(device_->ppp_device_.get());
    395     EXPECT_CALL(*mock_ppp_device, DropConnection());
    396   }
    397 
    398   void VerifyPPPStopped() {
    399     EXPECT_EQ(nullptr, device_->ppp_task_);
    400     EXPECT_FALSE(device_->ppp_device_);
    401   }
    402 
    403   void SetCommonOnAfterResumeExpectations() {
    404     EXPECT_CALL(*dbus_properties_proxy_, GetAll(_))
    405         .WillRepeatedly(Return(KeyValueStore()));
    406     EXPECT_CALL(*mm1_proxy_, set_state_changed_callback(_)).Times(AnyNumber());
    407     EXPECT_CALL(*modem_info_.mock_metrics(), NotifyDeviceScanStarted(_))
    408         .Times(AnyNumber());
    409     EXPECT_CALL(*modem_info_.mock_manager(), UpdateEnabledTechnologies())
    410         .Times(AnyNumber());
    411     EXPECT_CALL(*static_cast<DeviceMockAdaptor*>(device_->adaptor()),
    412                 EmitBoolChanged(_, _)).Times(AnyNumber());
    413   }
    414 
    415   mm1::MockModemProxy* SetupOnAfterResume() {
    416     SetCellularType(Cellular::kTypeUniversal);
    417     SetCommonOnAfterResumeExpectations();
    418     return mm1_proxy_.get();  // Before the capability snags it.
    419   }
    420 
    421   void VerifyOperatorMap(const Stringmap& operator_map,
    422                          const string& code,
    423                          const string& name,
    424                          const string& country) {
    425     Stringmap::const_iterator it;
    426     Stringmap::const_iterator endit = operator_map.end();
    427 
    428     it = operator_map.find(kOperatorCodeKey);
    429     if (code == "") {
    430       EXPECT_EQ(endit, it);
    431     } else {
    432       ASSERT_NE(endit, it);
    433       EXPECT_EQ(code, it->second);
    434     }
    435     it = operator_map.find(kOperatorNameKey);
    436     if (name == "") {
    437       EXPECT_EQ(endit, it);
    438     } else {
    439       ASSERT_NE(endit, it);
    440       EXPECT_EQ(name, it->second);
    441     }
    442     it = operator_map.find(kOperatorCountryKey);
    443     if (country == "") {
    444       EXPECT_EQ(endit, it);
    445     } else {
    446       ASSERT_NE(endit, it);
    447       EXPECT_EQ(country, it->second);
    448     }
    449   }
    450 
    451   MOCK_METHOD1(TestCallback, void(const Error& error));
    452 
    453  protected:
    454   static const char kTestDeviceName[];
    455   static const char kTestDeviceAddress[];
    456   static const char kDBusService[];
    457   static const char kDBusPath[];
    458   static const char kTestCarrier[];
    459   static const char kTestCarrierSPN[];
    460   static const char kMEID[];
    461   static const char kIMEI[];
    462   static const char kIMSI[];
    463   static const char kMSISDN[];
    464   static const char kTestMobileProviderDBPath[];
    465   static const Stringmaps kTestNetworksGSM;
    466   static const Stringmaps kTestNetworksCellular;
    467   static const int kStrength;
    468 
    469   // Must be std::string so that we can safely ReturnRef.
    470   const string kHomeProviderCode;
    471   const string kHomeProviderCountry;
    472   const string kHomeProviderName;
    473   const string kServingOperatorCode;
    474   const string kServingOperatorCountry;
    475   const string kServingOperatorName;
    476 
    477   class TestControl : public MockControl {
    478    public:
    479     explicit TestControl(CellularTest* test) : test_(test) {}
    480 
    481     virtual DBusPropertiesProxyInterface* CreateDBusPropertiesProxy(
    482         const std::string& path,
    483         const std::string& service) {
    484       CHECK(test_->dbus_properties_proxy_);
    485       return test_->dbus_properties_proxy_.release();
    486     }
    487 
    488     virtual ModemProxyInterface* CreateModemProxy(
    489         const string& /*path*/,
    490         const string& /*service*/) {
    491       CHECK(test_->proxy_);
    492       return test_->proxy_.release();
    493     }
    494 
    495     virtual ModemSimpleProxyInterface* CreateModemSimpleProxy(
    496         const string& /*path*/,
    497         const string& /*service*/) {
    498       CHECK(test_->simple_proxy_);
    499       return test_->simple_proxy_.release();
    500     }
    501 
    502     virtual ModemCDMAProxyInterface* CreateModemCDMAProxy(
    503         const string& /*path*/,
    504         const string& /*service*/) {
    505       CHECK(test_->cdma_proxy_);
    506       return test_->cdma_proxy_.release();
    507     }
    508 
    509     virtual ModemGSMCardProxyInterface* CreateModemGSMCardProxy(
    510         const string& /*path*/,
    511         const string& /*service*/) {
    512       // TODO(benchan): This code conditionally returns a nullptr to avoid
    513       // CellularCapabilityGSM::InitProperties (and thus
    514       // CellularCapabilityGSM::GetIMSI) from being called during the
    515       // construction. Remove this workaround after refactoring the tests.
    516       CHECK(!test_->create_gsm_card_proxy_from_factory_ ||
    517             test_->gsm_card_proxy_);
    518       return test_->create_gsm_card_proxy_from_factory_ ?
    519           test_->gsm_card_proxy_.release() : nullptr;
    520     }
    521 
    522     virtual ModemGSMNetworkProxyInterface* CreateModemGSMNetworkProxy(
    523         const string& /*path*/,
    524         const string& /*service*/) {
    525       CHECK(test_->gsm_network_proxy_);
    526       return test_->gsm_network_proxy_.release();
    527     }
    528 
    529     virtual mm1::ModemModem3gppProxyInterface* CreateMM1ModemModem3gppProxy(
    530       const std::string& path,
    531       const std::string& service) {
    532       CHECK(test_->mm1_modem_3gpp_proxy_);
    533       return test_->mm1_modem_3gpp_proxy_.release();
    534     }
    535 
    536     virtual mm1::ModemProxyInterface* CreateMM1ModemProxy(
    537       const std::string& path,
    538       const std::string& service) {
    539       CHECK(test_->mm1_proxy_);
    540       return test_->mm1_proxy_.release();
    541     }
    542 
    543     virtual mm1::ModemSimpleProxyInterface* CreateMM1ModemSimpleProxy(
    544         const string& /*path*/,
    545         const string& /*service*/) {
    546       CHECK(test_->mm1_simple_proxy_);
    547       return test_->mm1_simple_proxy_.release();
    548     }
    549 
    550    private:
    551     CellularTest* test_;
    552   };
    553   void StartRTNLHandler();
    554   void StopRTNLHandler();
    555 
    556   void AllowCreateGSMCardProxyFromFactory() {
    557     create_gsm_card_proxy_from_factory_ = true;
    558   }
    559 
    560   void SetCellularType(Cellular::Type type) {
    561     device_->InitCapability(type);
    562   }
    563 
    564   CellularCapabilityClassic* GetCapabilityClassic() {
    565     return static_cast<CellularCapabilityClassic*>(
    566         device_->capability_.get());
    567   }
    568 
    569   CellularCapabilityCDMA* GetCapabilityCDMA() {
    570     return static_cast<CellularCapabilityCDMA*>(device_->capability_.get());
    571   }
    572 
    573   CellularCapabilityGSM* GetCapabilityGSM() {
    574     return static_cast<CellularCapabilityGSM*>(device_->capability_.get());
    575   }
    576 
    577   CellularCapabilityUniversal* GetCapabilityUniversal() {
    578     return static_cast<CellularCapabilityUniversal*>(
    579         device_->capability_.get());
    580   }
    581 
    582   // Different tests simulate a cellular service being set using a real /mock
    583   // service.
    584   CellularService* SetService() {
    585     device_->service_ = new CellularService(&modem_info_, device_);
    586     return device_->service_.get();
    587   }
    588   MockCellularService* SetMockService() {
    589     device_->service_ = new MockCellularService(&modem_info_, device_);
    590     return static_cast<MockCellularService*>(device_->service_.get());
    591   }
    592 
    593   void set_enabled_persistent(bool new_value) {
    594     device_->enabled_persistent_ = new_value;
    595   }
    596 
    597   void SetCapabilityUniversalActiveBearer(unique_ptr<CellularBearer> bearer) {
    598     SetCellularType(Cellular::kTypeUniversal);
    599     CellularCapabilityUniversal* capability = GetCapabilityUniversal();
    600     capability->active_bearer_ = std::move(bearer);
    601   }
    602 
    603   EventDispatcherForTest dispatcher_;
    604   TestControl control_interface_;
    605   MockModemInfo modem_info_;
    606   MockDeviceInfo device_info_;
    607   MockProcessManager process_manager_;
    608   NiceMock<MockRTNLHandler> rtnl_handler_;
    609 
    610   MockDHCPProvider dhcp_provider_;
    611   scoped_refptr<MockDHCPConfig> dhcp_config_;
    612 
    613   bool create_gsm_card_proxy_from_factory_;
    614   unique_ptr<MockDBusPropertiesProxy> dbus_properties_proxy_;
    615   unique_ptr<MockModemProxy> proxy_;
    616   unique_ptr<MockModemSimpleProxy> simple_proxy_;
    617   unique_ptr<MockModemCDMAProxy> cdma_proxy_;
    618   unique_ptr<MockModemGSMCardProxy> gsm_card_proxy_;
    619   unique_ptr<MockModemGSMNetworkProxy> gsm_network_proxy_;
    620   unique_ptr<mm1::MockModemModem3gppProxy> mm1_modem_3gpp_proxy_;
    621   unique_ptr<mm1::MockModemProxy> mm1_proxy_;
    622   unique_ptr<mm1::MockModemSimpleProxy> mm1_simple_proxy_;
    623   MockMobileOperatorInfo* mock_home_provider_info_;
    624   MockMobileOperatorInfo* mock_serving_operator_info_;
    625   CellularRefPtr device_;
    626 };
    627 
    628 const char CellularTest::kTestDeviceName[] = "usb0";
    629 const char CellularTest::kTestDeviceAddress[] = "00:01:02:03:04:05";
    630 const char CellularTest::kDBusService[] = "org.chromium.ModemManager";
    631 const char CellularTest::kDBusPath[] = "/org/chromium/ModemManager/Gobi/0";
    632 const char CellularTest::kTestCarrier[] = "The Cellular Carrier";
    633 const char CellularTest::kTestCarrierSPN[] = "Home Provider";
    634 const char CellularTest::kMEID[] = "01234567EF8901";
    635 const char CellularTest::kIMEI[] = "987654321098765";
    636 const char CellularTest::kIMSI[] = "123456789012345";
    637 const char CellularTest::kMSISDN[] = "12345678901";
    638 const char CellularTest::kTestMobileProviderDBPath[] =
    639     "provider_db_unittest.bfd";
    640 const Stringmaps CellularTest::kTestNetworksGSM =
    641     {{{CellularCapabilityGSM::kNetworkPropertyStatus, "1"},
    642       {CellularCapabilityGSM::kNetworkPropertyID, "0000"},
    643       {CellularCapabilityGSM::kNetworkPropertyLongName, "some_long_name"},
    644       {CellularCapabilityGSM::kNetworkPropertyShortName, "short"}}};
    645 const Stringmaps CellularTest::kTestNetworksCellular =
    646     {{{kStatusProperty, "available"},
    647       {kNetworkIdProperty, "0000"},
    648       {kLongNameProperty, "some_long_name"},
    649       {kShortNameProperty, "short"}}};
    650 const int CellularTest::kStrength = 90;
    651 
    652 TEST_F(CellularTest, GetStateString) {
    653   EXPECT_EQ("CellularStateDisabled",
    654             Cellular::GetStateString(Cellular::kStateDisabled));
    655   EXPECT_EQ("CellularStateEnabled",
    656             Cellular::GetStateString(Cellular::kStateEnabled));
    657   EXPECT_EQ("CellularStateRegistered",
    658             Cellular::GetStateString(Cellular::kStateRegistered));
    659   EXPECT_EQ("CellularStateConnected",
    660             Cellular::GetStateString(Cellular::kStateConnected));
    661   EXPECT_EQ("CellularStateLinked",
    662             Cellular::GetStateString(Cellular::kStateLinked));
    663 }
    664 
    665 TEST_F(CellularTest, GetModemStateString) {
    666   EXPECT_EQ("CellularModemStateFailed",
    667             Cellular::GetModemStateString(Cellular::kModemStateFailed));
    668   EXPECT_EQ("CellularModemStateUnknown",
    669             Cellular::GetModemStateString(Cellular::kModemStateUnknown));
    670   EXPECT_EQ("CellularModemStateInitializing",
    671             Cellular::GetModemStateString(Cellular::kModemStateInitializing));
    672   EXPECT_EQ("CellularModemStateLocked",
    673             Cellular::GetModemStateString(Cellular::kModemStateLocked));
    674   EXPECT_EQ("CellularModemStateDisabled",
    675             Cellular::GetModemStateString(Cellular::kModemStateDisabled));
    676   EXPECT_EQ("CellularModemStateDisabling",
    677             Cellular::GetModemStateString(Cellular::kModemStateDisabling));
    678   EXPECT_EQ("CellularModemStateEnabling",
    679             Cellular::GetModemStateString(Cellular::kModemStateEnabling));
    680   EXPECT_EQ("CellularModemStateEnabled",
    681             Cellular::GetModemStateString(Cellular::kModemStateEnabled));
    682   EXPECT_EQ("CellularModemStateSearching",
    683             Cellular::GetModemStateString(Cellular::kModemStateSearching));
    684   EXPECT_EQ("CellularModemStateRegistered",
    685             Cellular::GetModemStateString(Cellular::kModemStateRegistered));
    686   EXPECT_EQ("CellularModemStateDisconnecting",
    687             Cellular::GetModemStateString(Cellular::kModemStateDisconnecting));
    688   EXPECT_EQ("CellularModemStateConnecting",
    689             Cellular::GetModemStateString(Cellular::kModemStateConnecting));
    690   EXPECT_EQ("CellularModemStateConnected",
    691             Cellular::GetModemStateString(Cellular::kModemStateConnected));
    692 }
    693 
    694 TEST_F(CellularTest, StartCDMARegister) {
    695   SetCellularType(Cellular::kTypeCDMA);
    696   ExpectCdmaStartModem(kNetworkTechnology1Xrtt);
    697   EXPECT_CALL(*cdma_proxy_, MEID()).WillOnce(Return(kMEID));
    698   Error error;
    699   device_->Start(&error, Bind(&CellularTest::TestCallback, Unretained(this)));
    700   dispatcher_.DispatchPendingEvents();
    701   EXPECT_EQ(kMEID, device_->meid());
    702   EXPECT_EQ(kTestCarrier, device_->carrier());
    703   EXPECT_EQ(Cellular::kStateRegistered, device_->state_);
    704   ASSERT_TRUE(device_->service_.get());
    705   EXPECT_EQ(kNetworkTechnology1Xrtt, device_->service_->network_technology());
    706   EXPECT_EQ(kStrength, device_->service_->strength());
    707   EXPECT_EQ(kRoamingStateHome, device_->service_->roaming_state());
    708 }
    709 
    710 TEST_F(CellularTest, StartGSMRegister) {
    711   SetMockMobileOperatorInfoObjects();
    712   EXPECT_CALL(*proxy_, Enable(true, _, _, CellularCapability::kTimeoutEnable))
    713       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
    714   EXPECT_CALL(*gsm_card_proxy_,
    715               GetIMEI(_, _, CellularCapability::kTimeoutDefault))
    716       .WillOnce(Invoke(this, &CellularTest::InvokeGetIMEI));
    717   EXPECT_CALL(*gsm_card_proxy_,
    718               GetIMSI(_, _, CellularCapability::kTimeoutDefault))
    719       .WillOnce(Invoke(this, &CellularTest::InvokeGetIMSI));
    720   EXPECT_CALL(*gsm_card_proxy_,
    721               GetSPN(_, _, CellularCapability::kTimeoutDefault))
    722       .WillOnce(Invoke(this, &CellularTest::InvokeGetSPN));
    723   EXPECT_CALL(*gsm_card_proxy_,
    724               GetMSISDN(_, _, CellularCapability::kTimeoutDefault))
    725       .WillOnce(Invoke(this, &CellularTest::InvokeGetMSISDN));
    726   EXPECT_CALL(*gsm_network_proxy_, AccessTechnology())
    727       .WillOnce(Return(MM_MODEM_GSM_ACCESS_TECH_EDGE));
    728   EXPECT_CALL(*gsm_card_proxy_, EnabledFacilityLocks())
    729       .WillOnce(Return(MM_MODEM_GSM_FACILITY_SIM));
    730   EXPECT_CALL(*proxy_, GetModemInfo(_, _, CellularCapability::kTimeoutDefault))
    731       .WillOnce(Invoke(this, &CellularTest::InvokeGetModemInfo));
    732   EXPECT_CALL(*gsm_network_proxy_,
    733               GetRegistrationInfo(_, _, CellularCapability::kTimeoutDefault))
    734       .WillOnce(Invoke(this, &CellularTest::InvokeGetRegistrationInfo));
    735   EXPECT_CALL(*gsm_network_proxy_, GetSignalQuality(nullptr, _, _))
    736       .Times(2)
    737       .WillRepeatedly(Invoke(this,
    738                              &CellularTest::InvokeGetSignalQuality));
    739   EXPECT_CALL(*mock_serving_operator_info_, UpdateMCCMNC(_));
    740   EXPECT_CALL(*mock_serving_operator_info_, UpdateOperatorName(_));
    741   EXPECT_CALL(*this, TestCallback(IsSuccess()));
    742   EXPECT_CALL(*modem_info_.mock_manager(), RegisterService(_));
    743   AllowCreateGSMCardProxyFromFactory();
    744 
    745   Error error;
    746   device_->Start(&error, Bind(&CellularTest::TestCallback, Unretained(this)));
    747   EXPECT_TRUE(error.IsSuccess());
    748   dispatcher_.DispatchPendingEvents();
    749   EXPECT_EQ(kIMEI, device_->imei());
    750   EXPECT_EQ(kIMSI, device_->imsi());
    751   EXPECT_EQ(kTestCarrierSPN, GetCapabilityGSM()->spn_);
    752   EXPECT_EQ(kMSISDN, device_->mdn());
    753   EXPECT_EQ(Cellular::kStateRegistered, device_->state_);
    754   ASSERT_TRUE(device_->service_.get());
    755   EXPECT_EQ(kNetworkTechnologyEdge, device_->service_->network_technology());
    756   EXPECT_TRUE(GetCapabilityGSM()->sim_lock_status_.enabled);
    757   EXPECT_EQ(kStrength, device_->service_->strength());
    758   EXPECT_EQ(kRoamingStateRoaming, device_->service_->roaming_state());
    759 }
    760 
    761 TEST_F(CellularTest, StartConnected) {
    762   EXPECT_CALL(device_info_, GetFlags(device_->interface_index(), _))
    763       .WillOnce(Return(true));
    764   SetCellularType(Cellular::kTypeCDMA);
    765   device_->set_modem_state(Cellular::kModemStateConnected);
    766   device_->set_meid(kMEID);
    767   ExpectCdmaStartModem(kNetworkTechnologyEvdo);
    768   Error error;
    769   device_->Start(&error, Bind(&CellularTest::TestCallback, Unretained(this)));
    770   EXPECT_TRUE(error.IsSuccess());
    771   dispatcher_.DispatchPendingEvents();
    772   EXPECT_EQ(Cellular::kStateConnected, device_->state_);
    773 }
    774 
    775 TEST_F(CellularTest, StartLinked) {
    776   EXPECT_CALL(device_info_, GetFlags(device_->interface_index(), _))
    777       .WillOnce(DoAll(SetArgumentPointee<1>(IFF_UP), Return(true)));
    778   SetCellularType(Cellular::kTypeCDMA);
    779   device_->set_modem_state(Cellular::kModemStateConnected);
    780   device_->set_meid(kMEID);
    781   ExpectCdmaStartModem(kNetworkTechnologyEvdo);
    782   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kTestDeviceName, _, _, _))
    783       .WillOnce(Return(dhcp_config_));
    784   EXPECT_CALL(*dhcp_config_, RequestIP()).WillOnce(Return(true));
    785   EXPECT_CALL(*modem_info_.mock_manager(), UpdateService(_)).Times(3);
    786   Error error;
    787   device_->Start(&error, Bind(&CellularTest::TestCallback, Unretained(this)));
    788   EXPECT_TRUE(error.IsSuccess());
    789   dispatcher_.DispatchPendingEvents();
    790   EXPECT_EQ(Cellular::kStateLinked, device_->state_);
    791   EXPECT_EQ(Service::kStateConfiguring, device_->service_->state());
    792   device_->SelectService(nullptr);
    793 }
    794 
    795 TEST_F(CellularTest, FriendlyServiceName) {
    796   // Test that the name created for the service is sensible under different
    797   // scenarios w.r.t. information about the mobile network operator.
    798   SetMockMobileOperatorInfoObjects();
    799   CHECK(mock_home_provider_info_);
    800   CHECK(mock_serving_operator_info_);
    801 
    802   SetCellularType(Cellular::kTypeCDMA);
    803   // We are not testing the behaviour of capabilities here.
    804   device_->mobile_operator_info_observer_->set_capability(nullptr);
    805 
    806   // (1) Service created, MNO not known => Default name.
    807   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    808       .WillRepeatedly(Return(false));
    809   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    810       .WillRepeatedly(Return(false));
    811   device_->CreateService();
    812   // Compare substrings explicitly using EXPECT_EQ for better error message.
    813   size_t prefix_len = strlen(Cellular::kGenericServiceNamePrefix);
    814   EXPECT_EQ(Cellular::kGenericServiceNamePrefix,
    815             device_->service_->friendly_name().substr(0, prefix_len));
    816   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    817   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    818   device_->DestroyService();
    819 
    820   // (2) Service created, then home provider determined => Name provided by
    821   //     home provider.
    822   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    823       .WillRepeatedly(Return(false));
    824   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    825       .WillRepeatedly(Return(false));
    826   device_->CreateService();
    827   // Now emulate an event for updated home provider information.
    828   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    829   mock_home_provider_info_->SetEmptyDefaultsForProperties();
    830   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    831       .WillRepeatedly(Return(true));
    832   EXPECT_CALL(*mock_home_provider_info_, operator_name())
    833       .WillRepeatedly(ReturnRef(kHomeProviderName));
    834   device_->mobile_operator_info_observer_->OnOperatorChanged();
    835   EXPECT_EQ(kHomeProviderName, device_->service_->friendly_name());
    836   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    837   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    838   device_->DestroyService();
    839 
    840   // (3) Service created, then serving operator determined => Name provided by
    841   //     serving operator.
    842   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    843       .WillRepeatedly(Return(false));
    844   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    845       .WillRepeatedly(Return(false));
    846   device_->CreateService();
    847   // Now emulate an event for updated serving operator information.
    848   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    849   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
    850   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    851       .WillRepeatedly(Return(true));
    852   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
    853       .WillRepeatedly(ReturnRef(kServingOperatorName));
    854   device_->mobile_operator_info_observer_->OnOperatorChanged();
    855   EXPECT_EQ(kServingOperatorName, device_->service_->friendly_name());
    856   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    857   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    858   device_->DestroyService();
    859 
    860   // (4) Service created, then home provider determined, then serving operator
    861   // determined => final name is serving operator.
    862   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    863       .WillRepeatedly(Return(false));
    864   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    865       .WillRepeatedly(Return(false));
    866   device_->CreateService();
    867   // Now emulate an event for updated home provider information.
    868   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    869   mock_home_provider_info_->SetEmptyDefaultsForProperties();
    870   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    871       .WillRepeatedly(Return(true));
    872   EXPECT_CALL(*mock_home_provider_info_, operator_name())
    873       .WillRepeatedly(ReturnRef(kHomeProviderName));
    874   device_->mobile_operator_info_observer_->OnOperatorChanged();
    875   // Now emulate an event for updated serving operator information.
    876   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    877   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
    878   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    879       .WillRepeatedly(Return(true));
    880   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
    881       .WillRepeatedly(ReturnRef(kServingOperatorName));
    882   device_->mobile_operator_info_observer_->OnOperatorChanged();
    883   EXPECT_EQ(kServingOperatorName, device_->service_->friendly_name());
    884   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    885   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    886   device_->DestroyService();
    887 
    888   // (5) Service created, then serving operator determined, then home provider
    889   // determined => final name is serving operator.
    890   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    891       .WillRepeatedly(Return(false));
    892   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    893       .WillRepeatedly(Return(false));
    894   device_->CreateService();
    895   // Now emulate an event for updated serving operator information.
    896   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    897   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
    898   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    899       .WillRepeatedly(Return(true));
    900   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
    901       .WillRepeatedly(ReturnRef(kServingOperatorName));
    902   device_->mobile_operator_info_observer_->OnOperatorChanged();
    903   // Now emulate an event for updated home provider information.
    904   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    905   mock_home_provider_info_->SetEmptyDefaultsForProperties();
    906   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    907       .WillRepeatedly(Return(true));
    908   EXPECT_CALL(*mock_home_provider_info_, operator_name())
    909       .WillRepeatedly(ReturnRef(kHomeProviderName));
    910   device_->mobile_operator_info_observer_->OnOperatorChanged();
    911   EXPECT_EQ(kServingOperatorName, device_->service_->friendly_name());
    912   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    913   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    914   device_->DestroyService();
    915 
    916   // (6) Serving operator known, home provider known, and then service created
    917   //     => Name is serving operator.
    918   mock_home_provider_info_->SetEmptyDefaultsForProperties();
    919   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
    920   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    921       .WillRepeatedly(Return(true));
    922   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    923       .WillRepeatedly(Return(true));
    924   EXPECT_CALL(*mock_home_provider_info_, operator_name())
    925       .WillRepeatedly(ReturnRef(kHomeProviderName));
    926   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
    927       .WillRepeatedly(ReturnRef(kServingOperatorName));
    928   device_->CreateService();
    929   EXPECT_EQ(kServingOperatorName, device_->service_->friendly_name());
    930 }
    931 
    932 TEST_F(CellularTest, HomeProviderServingOperator) {
    933   // Test that the the home provider information is correctly updated under
    934   // different scenarios w.r.t. information about the mobile network operators.
    935   SetMockMobileOperatorInfoObjects();
    936   CHECK(mock_home_provider_info_);
    937   CHECK(mock_serving_operator_info_);
    938   Stringmap home_provider;
    939   Stringmap serving_operator;
    940 
    941 
    942   // (1) Neither home provider nor serving operator known.
    943   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    944       .WillRepeatedly(Return(false));
    945   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    946       .WillRepeatedly(Return(false));
    947 
    948   device_->CreateService();
    949 
    950   home_provider = device_->home_provider();
    951   VerifyOperatorMap(home_provider, "", "", "");
    952   serving_operator = device_->service_->serving_operator();
    953   VerifyOperatorMap(serving_operator, "", "", "");
    954   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    955   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    956   device_->DestroyService();
    957 
    958   // (2) serving operator known.
    959   // When home provider is not known, serving operator proxies in.
    960   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    961       .WillRepeatedly(Return(false));
    962   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
    963   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    964       .WillRepeatedly(Return(true));
    965   EXPECT_CALL(*mock_serving_operator_info_, mccmnc())
    966       .WillRepeatedly(ReturnRef(kServingOperatorCode));
    967   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
    968       .WillRepeatedly(ReturnRef(kServingOperatorName));
    969   EXPECT_CALL(*mock_serving_operator_info_, country())
    970       .WillRepeatedly(ReturnRef(kServingOperatorCountry));
    971 
    972   device_->CreateService();
    973 
    974   home_provider = device_->home_provider();
    975   VerifyOperatorMap(home_provider,
    976                     kServingOperatorCode,
    977                     kServingOperatorName,
    978                     kServingOperatorCountry);
    979   serving_operator = device_->service_->serving_operator();
    980   VerifyOperatorMap(serving_operator,
    981                     kServingOperatorCode,
    982                     kServingOperatorName,
    983                     kServingOperatorCountry);
    984   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
    985   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
    986   device_->DestroyService();
    987 
    988   // (3) home provider known.
    989   // When serving operator is not known, home provider proxies in.
    990   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
    991       .WillRepeatedly(Return(false));
    992   mock_home_provider_info_->SetEmptyDefaultsForProperties();
    993   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
    994       .WillRepeatedly(Return(true));
    995   EXPECT_CALL(*mock_home_provider_info_, mccmnc())
    996       .WillRepeatedly(ReturnRef(kHomeProviderCode));
    997   EXPECT_CALL(*mock_home_provider_info_, operator_name())
    998       .WillRepeatedly(ReturnRef(kHomeProviderName));
    999   EXPECT_CALL(*mock_home_provider_info_, country())
   1000       .WillRepeatedly(ReturnRef(kHomeProviderCountry));
   1001 
   1002   device_->CreateService();
   1003 
   1004   home_provider = device_->home_provider();
   1005   VerifyOperatorMap(home_provider,
   1006                     kHomeProviderCode,
   1007                     kHomeProviderName,
   1008                     kHomeProviderCountry);
   1009   serving_operator = device_->service_->serving_operator();
   1010   VerifyOperatorMap(serving_operator,
   1011                     kHomeProviderCode,
   1012                     kHomeProviderName,
   1013                     kHomeProviderCountry);
   1014   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
   1015   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
   1016   device_->DestroyService();
   1017 
   1018   // (4) Serving operator known, home provider known.
   1019   mock_home_provider_info_->SetEmptyDefaultsForProperties();
   1020   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
   1021       .WillRepeatedly(Return(true));
   1022   EXPECT_CALL(*mock_home_provider_info_, mccmnc())
   1023       .WillRepeatedly(ReturnRef(kHomeProviderCode));
   1024   EXPECT_CALL(*mock_home_provider_info_, operator_name())
   1025       .WillRepeatedly(ReturnRef(kHomeProviderName));
   1026   EXPECT_CALL(*mock_home_provider_info_, country())
   1027       .WillRepeatedly(ReturnRef(kHomeProviderCountry));
   1028   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
   1029   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
   1030       .WillRepeatedly(Return(true));
   1031   EXPECT_CALL(*mock_serving_operator_info_, mccmnc())
   1032       .WillRepeatedly(ReturnRef(kServingOperatorCode));
   1033   EXPECT_CALL(*mock_serving_operator_info_, operator_name())
   1034       .WillRepeatedly(ReturnRef(kServingOperatorName));
   1035   EXPECT_CALL(*mock_serving_operator_info_, country())
   1036       .WillRepeatedly(ReturnRef(kServingOperatorCountry));
   1037 
   1038   device_->CreateService();
   1039 
   1040   home_provider = device_->home_provider();
   1041   VerifyOperatorMap(home_provider,
   1042                     kHomeProviderCode,
   1043                     kHomeProviderName,
   1044                     kHomeProviderCountry);
   1045   serving_operator = device_->service_->serving_operator();
   1046   VerifyOperatorMap(serving_operator,
   1047                     kServingOperatorCode,
   1048                     kServingOperatorName,
   1049                     kServingOperatorCountry);
   1050 }
   1051 
   1052 static bool IllegalChar(char a) {
   1053   return !(isalnum(a) || a == '_');
   1054 }
   1055 
   1056 TEST_F(CellularTest, StorageIdentifier) {
   1057   // Test that the storage identifier name used by the service is sensible under
   1058   // different scenarios w.r.t. information about the mobile network operator.
   1059   SetMockMobileOperatorInfoObjects();
   1060   mock_home_provider_info_->SetEmptyDefaultsForProperties();
   1061   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
   1062   CHECK(mock_home_provider_info_);
   1063   CHECK(mock_serving_operator_info_);
   1064 
   1065   // See cellular_service.cc
   1066   string prefix = string(kTypeCellular) + "_" +
   1067                   string(kTestDeviceAddress) + "_";
   1068   // Service replaces ':' with '_'
   1069   std::replace_if(prefix.begin(), prefix.end(), &IllegalChar, '_');
   1070   const string kUuidHomeProvider = "uuidHomeProvider";
   1071   const string kUuidServingOperator = "uuidServingOperator";
   1072   const string kSimIdentifier = "12345123451234512345";
   1073 
   1074   SetCellularType(Cellular::kTypeCDMA);
   1075   // We are not testing the behaviour of capabilities here.
   1076   device_->mobile_operator_info_observer_->set_capability(nullptr);
   1077   ON_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
   1078       .WillByDefault(Return(false));
   1079 
   1080   // (1) Service created, both home provider and serving operator known =>
   1081   // home provider used.
   1082   mock_home_provider_info_->SetEmptyDefaultsForProperties();
   1083   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
   1084   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
   1085       .WillRepeatedly(Return(true));
   1086   EXPECT_CALL(*mock_home_provider_info_, uuid())
   1087       .WillRepeatedly(ReturnRef(kUuidHomeProvider));
   1088   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
   1089       .WillRepeatedly(Return(true));
   1090   EXPECT_CALL(*mock_serving_operator_info_, uuid())
   1091       .WillRepeatedly(ReturnRef(kUuidServingOperator));
   1092   device_->CreateService();
   1093   EXPECT_EQ(prefix + kUuidHomeProvider,
   1094             device_->service()->GetStorageIdentifier());
   1095   Mock::VerifyAndClearExpectations(mock_home_provider_info_);
   1096   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
   1097   device_->DestroyService();
   1098 
   1099   // Common expectation for following tests:
   1100   EXPECT_CALL(*mock_home_provider_info_, IsMobileNetworkOperatorKnown())
   1101       .WillRepeatedly(Return(false));
   1102 
   1103   // (2) Service created, no extra information => Default storage_id;
   1104   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
   1105       .WillRepeatedly(Return(false));
   1106   device_->CreateService();
   1107   EXPECT_EQ(prefix + device_->service()->friendly_name(),
   1108             device_->service()->GetStorageIdentifier());
   1109   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
   1110   device_->DestroyService();
   1111 
   1112   // (3) Service created, serving operator known, uuid known.
   1113   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
   1114   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
   1115       .WillRepeatedly(Return(true));
   1116   EXPECT_CALL(*mock_serving_operator_info_, uuid())
   1117       .WillRepeatedly(ReturnRef(kUuidServingOperator));
   1118   device_->CreateService();
   1119   EXPECT_EQ(prefix + kUuidServingOperator,
   1120             device_->service()->GetStorageIdentifier());
   1121   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
   1122   device_->DestroyService();
   1123 
   1124   // (4) Service created, serving operator known, uuid not known, iccid known.
   1125   mock_serving_operator_info_->SetEmptyDefaultsForProperties();
   1126   EXPECT_CALL(*mock_serving_operator_info_, IsMobileNetworkOperatorKnown())
   1127       .WillRepeatedly(Return(true));
   1128   device_->set_sim_identifier(kSimIdentifier);
   1129   device_->CreateService();
   1130   EXPECT_EQ(prefix + kSimIdentifier,
   1131             device_->service()->GetStorageIdentifier());
   1132   Mock::VerifyAndClearExpectations(mock_serving_operator_info_);
   1133   device_->DestroyService();
   1134 }
   1135 
   1136 namespace {
   1137 
   1138 MATCHER(ContainsPhoneNumber, "") {
   1139   return arg.ContainsString(
   1140       CellularCapabilityClassic::kConnectPropertyPhoneNumber);
   1141 }
   1142 
   1143 }  // namespace
   1144 
   1145 TEST_F(CellularTest, Connect) {
   1146   Error error;
   1147   EXPECT_CALL(device_info_, GetFlags(device_->interface_index(), _))
   1148       .Times(2)
   1149       .WillRepeatedly(Return(true));
   1150   device_->state_ = Cellular::kStateConnected;
   1151   device_->Connect(&error);
   1152   EXPECT_EQ(Error::kAlreadyConnected, error.type());
   1153   error.Populate(Error::kSuccess);
   1154 
   1155   device_->state_ = Cellular::kStateLinked;
   1156   device_->Connect(&error);
   1157   EXPECT_EQ(Error::kAlreadyConnected, error.type());
   1158 
   1159   device_->state_ = Cellular::kStateEnabled;
   1160   device_->Connect(&error);
   1161   EXPECT_EQ(Error::kNotRegistered, error.type());
   1162 
   1163   error.Reset();
   1164   device_->state_ = Cellular::kStateDisabled;
   1165   device_->Connect(&error);
   1166   EXPECT_EQ(Error::kNotRegistered, error.type());
   1167 
   1168   device_->state_ = Cellular::kStateRegistered;
   1169   SetService();
   1170 
   1171   device_->allow_roaming_ = false;
   1172   device_->service_->roaming_state_ = kRoamingStateRoaming;
   1173   device_->Connect(&error);
   1174   EXPECT_EQ(Error::kNotOnHomeNetwork, error.type());
   1175 
   1176   error.Populate(Error::kSuccess);
   1177   EXPECT_CALL(*simple_proxy_,
   1178               Connect(ContainsPhoneNumber(), _, _,
   1179                       CellularCapability::kTimeoutConnect))
   1180                 .Times(2)
   1181                 .WillRepeatedly(Invoke(this, &CellularTest::InvokeConnect));
   1182   GetCapabilityClassic()->simple_proxy_.reset(simple_proxy_.release());
   1183   device_->service_->roaming_state_ = kRoamingStateHome;
   1184   device_->state_ = Cellular::kStateRegistered;
   1185   device_->Connect(&error);
   1186   EXPECT_TRUE(error.IsSuccess());
   1187   dispatcher_.DispatchPendingEvents();
   1188   EXPECT_EQ(Cellular::kStateConnected, device_->state_);
   1189 
   1190   device_->allow_roaming_ = true;
   1191   device_->service_->roaming_state_ = kRoamingStateRoaming;
   1192   device_->state_ = Cellular::kStateRegistered;
   1193   device_->Connect(&error);
   1194   EXPECT_TRUE(error.IsSuccess());
   1195   dispatcher_.DispatchPendingEvents();
   1196   EXPECT_EQ(Cellular::kStateConnected, device_->state_);
   1197 }
   1198 
   1199 TEST_F(CellularTest, Disconnect) {
   1200   Error error;
   1201   device_->state_ = Cellular::kStateRegistered;
   1202   device_->Disconnect(&error, "in test");
   1203   EXPECT_EQ(Error::kNotConnected, error.type());
   1204   error.Reset();
   1205 
   1206   device_->state_ = Cellular::kStateConnected;
   1207   EXPECT_CALL(*proxy_,
   1208               Disconnect(_, _, CellularCapability::kTimeoutDisconnect))
   1209       .WillOnce(Invoke(this, &CellularTest::InvokeDisconnect));
   1210   GetCapabilityClassic()->proxy_.reset(proxy_.release());
   1211   device_->Disconnect(&error, "in test");
   1212   EXPECT_TRUE(error.IsSuccess());
   1213   EXPECT_EQ(Cellular::kStateRegistered, device_->state_);
   1214 }
   1215 
   1216 TEST_F(CellularTest, DisconnectFailure) {
   1217   // Test the case where the underlying modem state is set
   1218   // to disconnecting, but shill thinks it's still connected
   1219   Error error;
   1220   device_->state_ = Cellular::kStateConnected;
   1221   EXPECT_CALL(*proxy_,
   1222               Disconnect(_, _, CellularCapability::kTimeoutDisconnect))
   1223        .Times(2)
   1224        .WillRepeatedly(Invoke(this, &CellularTest::InvokeDisconnectFail));
   1225   GetCapabilityClassic()->proxy_.reset(proxy_.release());
   1226   device_->modem_state_ = Cellular::kModemStateDisconnecting;
   1227   device_->Disconnect(&error, "in test");
   1228   EXPECT_TRUE(error.IsFailure());
   1229   EXPECT_EQ(Cellular::kStateConnected, device_->state_);
   1230 
   1231   device_->modem_state_ = Cellular::kModemStateConnected;
   1232   device_->Disconnect(&error, "in test");
   1233   EXPECT_TRUE(error.IsFailure());
   1234   EXPECT_EQ(Cellular::kStateRegistered, device_->state_);
   1235 }
   1236 
   1237 TEST_F(CellularTest, ConnectFailure) {
   1238   SetCellularType(Cellular::kTypeCDMA);
   1239   device_->state_ = Cellular::kStateRegistered;
   1240   SetService();
   1241   ASSERT_EQ(Service::kStateIdle, device_->service_->state());
   1242   EXPECT_CALL(*simple_proxy_,
   1243               Connect(_, _, _, CellularCapability::kTimeoutConnect))
   1244                 .WillOnce(Invoke(this, &CellularTest::InvokeConnectFail));
   1245   GetCapabilityClassic()->simple_proxy_.reset(simple_proxy_.release());
   1246   Error error;
   1247   device_->Connect(&error);
   1248   EXPECT_EQ(Service::kStateFailure, device_->service_->state());
   1249 }
   1250 
   1251 TEST_F(CellularTest, ConnectFailureNoService) {
   1252   // Make sure we don't crash if the connect failed and there is no
   1253   // CellularService object.  This can happen if the modem is enabled and
   1254   // then quick disabled.
   1255   SetCellularType(Cellular::kTypeCDMA);
   1256   device_->state_ = Cellular::kStateRegistered;
   1257   SetService();
   1258   EXPECT_CALL(
   1259       *simple_proxy_,
   1260       Connect(_, _, _, CellularCapability::kTimeoutConnect))
   1261       .WillOnce(Invoke(this, &CellularTest::InvokeConnectFailNoService));
   1262   EXPECT_CALL(*modem_info_.mock_manager(), UpdateService(_));
   1263   GetCapabilityClassic()->simple_proxy_.reset(simple_proxy_.release());
   1264   Error error;
   1265   device_->Connect(&error);
   1266 }
   1267 
   1268 TEST_F(CellularTest, ConnectSuccessNoService) {
   1269   // Make sure we don't crash if the connect succeeds but the service was
   1270   // destroyed before the connect request completes.
   1271   SetCellularType(Cellular::kTypeCDMA);
   1272   device_->state_ = Cellular::kStateRegistered;
   1273   SetService();
   1274   EXPECT_CALL(
   1275       *simple_proxy_,
   1276       Connect(_, _, _, CellularCapability::kTimeoutConnect))
   1277       .WillOnce(Invoke(this, &CellularTest::InvokeConnectSuccessNoService));
   1278   EXPECT_CALL(*modem_info_.mock_manager(), UpdateService(_));
   1279   GetCapabilityClassic()->simple_proxy_.reset(simple_proxy_.release());
   1280   Error error;
   1281   device_->Connect(&error);
   1282 }
   1283 
   1284 TEST_F(CellularTest, LinkEventWontDestroyService) {
   1285   // If the network interface goes down, Cellular::LinkEvent should
   1286   // drop the connection but the service object should persist.
   1287   device_->state_ = Cellular::kStateLinked;
   1288   CellularService* service = SetService();
   1289   device_->LinkEvent(0, 0);  // flags doesn't contain IFF_UP
   1290   EXPECT_EQ(device_->state_, Cellular::kStateConnected);
   1291   EXPECT_EQ(device_->service_, service);
   1292 }
   1293 
   1294 TEST_F(CellularTest, UseNoArpGateway) {
   1295   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kTestDeviceName, _, false, _))
   1296       .WillOnce(Return(dhcp_config_));
   1297   device_->AcquireIPConfig();
   1298 }
   1299 
   1300 TEST_F(CellularTest, ModemStateChangeEnable) {
   1301   EXPECT_CALL(*simple_proxy_,
   1302               GetModemStatus(_, _, CellularCapability::kTimeoutDefault))
   1303       .WillOnce(Invoke(this, &CellularTest::InvokeGetModemStatus));
   1304   EXPECT_CALL(*cdma_proxy_, MEID()).WillOnce(Return(kMEID));
   1305   EXPECT_CALL(*proxy_,
   1306               GetModemInfo(_, _, CellularCapability::kTimeoutDefault))
   1307       .WillOnce(Invoke(this, &CellularTest::InvokeGetModemInfo));
   1308   EXPECT_CALL(*cdma_proxy_, GetRegistrationState(nullptr, _, _))
   1309       .WillOnce(Invoke(this,
   1310                        &CellularTest::InvokeGetRegistrationStateUnregistered));
   1311   EXPECT_CALL(*cdma_proxy_, GetSignalQuality(nullptr, _, _))
   1312       .WillOnce(Invoke(this, &CellularTest::InvokeGetSignalQuality));
   1313   EXPECT_CALL(*modem_info_.mock_manager(), UpdateEnabledTechnologies());
   1314   device_->state_ = Cellular::kStateDisabled;
   1315   device_->set_modem_state(Cellular::kModemStateDisabled);
   1316   SetCellularType(Cellular::kTypeCDMA);
   1317 
   1318   KeyValueStore props;
   1319   props.SetBool(CellularCapabilityClassic::kModemPropertyEnabled, true);
   1320   device_->OnPropertiesChanged(MM_MODEM_INTERFACE, props, vector<string>());
   1321   dispatcher_.DispatchPendingEvents();
   1322 
   1323   EXPECT_EQ(Cellular::kModemStateEnabled, device_->modem_state());
   1324   EXPECT_EQ(Cellular::kStateEnabled, device_->state());
   1325   EXPECT_TRUE(device_->enabled());
   1326 }
   1327 
   1328 TEST_F(CellularTest, ModemStateChangeDisable) {
   1329   EXPECT_CALL(*proxy_,
   1330               Disconnect(_, _, CellularCapability::kTimeoutDisconnect))
   1331       .WillOnce(Invoke(this, &CellularTest::InvokeDisconnect));
   1332   EXPECT_CALL(*proxy_,
   1333               Enable(false, _, _, CellularCapability::kTimeoutEnable))
   1334       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1335   EXPECT_CALL(*modem_info_.mock_manager(), UpdateEnabledTechnologies());
   1336   device_->enabled_ = true;
   1337   device_->enabled_pending_ = true;
   1338   device_->state_ = Cellular::kStateEnabled;
   1339   device_->set_modem_state(Cellular::kModemStateEnabled);
   1340   SetCellularType(Cellular::kTypeCDMA);
   1341   GetCapabilityClassic()->InitProxies();
   1342 
   1343   GetCapabilityClassic()->OnModemStateChangedSignal(kModemClassicStateEnabled,
   1344                                                     kModemClassicStateDisabled,
   1345                                                     0);
   1346   dispatcher_.DispatchPendingEvents();
   1347 
   1348   EXPECT_EQ(Cellular::kModemStateDisabled, device_->modem_state());
   1349   EXPECT_EQ(Cellular::kStateDisabled, device_->state());
   1350   EXPECT_FALSE(device_->enabled());
   1351 }
   1352 
   1353 TEST_F(CellularTest, ModemStateChangeStaleConnected) {
   1354   // Test to make sure that we ignore stale modem Connected state transitions.
   1355   // When a modem is asked to connect and before the connect completes, the
   1356   // modem is disabled, it may send a stale Connected state transition after
   1357   // it has been disabled.
   1358   AllowCreateGSMCardProxyFromFactory();
   1359   device_->state_ = Cellular::kStateDisabled;
   1360   device_->modem_state_ = Cellular::kModemStateEnabling;
   1361   device_->OnModemStateChanged(Cellular::kModemStateConnected);
   1362   dispatcher_.DispatchPendingEvents();
   1363   EXPECT_EQ(Cellular::kStateDisabled, device_->state());
   1364 }
   1365 
   1366 TEST_F(CellularTest, ModemStateChangeValidConnected) {
   1367   device_->state_ = Cellular::kStateEnabled;
   1368   device_->modem_state_ = Cellular::kModemStateConnecting;
   1369   SetService();
   1370   device_->OnModemStateChanged(Cellular::kModemStateConnected);
   1371   EXPECT_EQ(Cellular::kStateConnected, device_->state());
   1372 }
   1373 
   1374 TEST_F(CellularTest, ModemStateChangeLostRegistration) {
   1375   SetCellularType(Cellular::kTypeUniversal);
   1376   CellularCapabilityUniversal* capability = GetCapabilityUniversal();
   1377   capability->registration_state_ = MM_MODEM_3GPP_REGISTRATION_STATE_HOME;
   1378   EXPECT_TRUE(capability->IsRegistered());
   1379   device_->set_modem_state(Cellular::kModemStateRegistered);
   1380   device_->OnModemStateChanged(Cellular::kModemStateEnabled);
   1381   EXPECT_FALSE(capability->IsRegistered());
   1382 }
   1383 
   1384 TEST_F(CellularTest, StartModemCallback) {
   1385   EXPECT_CALL(*this, TestCallback(IsSuccess()));
   1386   EXPECT_EQ(device_->state_, Cellular::kStateDisabled);
   1387   device_->StartModemCallback(Bind(&CellularTest::TestCallback,
   1388                                    Unretained(this)),
   1389                               Error(Error::kSuccess));
   1390   EXPECT_EQ(device_->state_, Cellular::kStateEnabled);
   1391 }
   1392 
   1393 TEST_F(CellularTest, StartModemCallbackFail) {
   1394   EXPECT_CALL(*this, TestCallback(IsFailure()));
   1395   EXPECT_EQ(device_->state_, Cellular::kStateDisabled);
   1396   device_->StartModemCallback(Bind(&CellularTest::TestCallback,
   1397                                    Unretained(this)),
   1398                               Error(Error::kOperationFailed));
   1399   EXPECT_EQ(device_->state_, Cellular::kStateDisabled);
   1400 }
   1401 
   1402 TEST_F(CellularTest, StopModemCallback) {
   1403   EXPECT_CALL(*this, TestCallback(IsSuccess()));
   1404   SetMockService();
   1405   device_->StopModemCallback(Bind(&CellularTest::TestCallback,
   1406                                   Unretained(this)),
   1407                              Error(Error::kSuccess));
   1408   EXPECT_EQ(device_->state_, Cellular::kStateDisabled);
   1409   EXPECT_FALSE(device_->service_.get());
   1410 }
   1411 
   1412 TEST_F(CellularTest, StopModemCallbackFail) {
   1413   EXPECT_CALL(*this, TestCallback(IsFailure()));
   1414   SetMockService();
   1415   device_->StopModemCallback(Bind(&CellularTest::TestCallback,
   1416                                   Unretained(this)),
   1417                              Error(Error::kOperationFailed));
   1418   EXPECT_EQ(device_->state_, Cellular::kStateDisabled);
   1419   EXPECT_FALSE(device_->service_.get());
   1420 }
   1421 
   1422 TEST_F(CellularTest, SetAllowRoaming) {
   1423   EXPECT_FALSE(device_->allow_roaming_);
   1424   EXPECT_CALL(*modem_info_.mock_manager(), UpdateDevice(_));
   1425   Error error;
   1426   device_->SetAllowRoaming(true, &error);
   1427   EXPECT_TRUE(error.IsSuccess());
   1428   EXPECT_TRUE(device_->allow_roaming_);
   1429 }
   1430 
   1431 class TestRPCTaskDelegate :
   1432       public RPCTaskDelegate,
   1433       public base::SupportsWeakPtr<TestRPCTaskDelegate> {
   1434  public:
   1435   virtual void GetLogin(std::string* user, std::string* password) {}
   1436   virtual void Notify(const std::string& reason,
   1437                       const std::map<std::string, std::string>& dict) {}
   1438 };
   1439 
   1440 TEST_F(CellularTest, LinkEventUpWithPPP) {
   1441   // If PPP is running, don't run DHCP as well.
   1442   TestRPCTaskDelegate task_delegate;
   1443   base::Callback<void(pid_t, int)> death_callback;
   1444   unique_ptr<NiceMock<MockExternalTask>> mock_task(
   1445       new NiceMock<MockExternalTask>(modem_info_.control_interface(),
   1446                                      &process_manager_,
   1447                                      task_delegate.AsWeakPtr(),
   1448                                      death_callback));
   1449   EXPECT_CALL(*mock_task, OnDelete()).Times(AnyNumber());
   1450   device_->ppp_task_ = std::move(mock_task);
   1451   device_->state_ = Cellular::kStateConnected;
   1452   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kTestDeviceName, _, _, _))
   1453       .Times(0);
   1454   EXPECT_CALL(*dhcp_config_, RequestIP()).Times(0);
   1455   device_->LinkEvent(IFF_UP, 0);
   1456 }
   1457 
   1458 TEST_F(CellularTest, LinkEventUpWithoutPPP) {
   1459   // If PPP is not running, fire up DHCP.
   1460   device_->state_ = Cellular::kStateConnected;
   1461   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kTestDeviceName, _, _, _))
   1462       .WillOnce(Return(dhcp_config_));
   1463   EXPECT_CALL(*dhcp_config_, RequestIP());
   1464   EXPECT_CALL(*dhcp_config_, ReleaseIP(_)).Times(AnyNumber());
   1465   device_->LinkEvent(IFF_UP, 0);
   1466 }
   1467 
   1468 TEST_F(CellularTest, StartPPP) {
   1469   const int kPID = 234;
   1470   EXPECT_EQ(nullptr, device_->ppp_task_);
   1471   StartPPP(kPID);
   1472 }
   1473 
   1474 TEST_F(CellularTest, StartPPPAlreadyStarted) {
   1475   const int kPID = 234;
   1476   StartPPP(kPID);
   1477 
   1478   const int kPID2 = 235;
   1479   StartPPP(kPID2);
   1480 }
   1481 
   1482 TEST_F(CellularTest, StartPPPAfterEthernetUp) {
   1483   CellularService* service(SetService());
   1484   device_->state_ = Cellular::kStateLinked;
   1485   device_->set_ipconfig(dhcp_config_);
   1486   device_->SelectService(service);
   1487   EXPECT_CALL(*dhcp_config_, ReleaseIP(_))
   1488       .Times(AnyNumber())
   1489       .WillRepeatedly(Return(true));
   1490   const int kPID = 234;
   1491   EXPECT_EQ(nullptr, device_->ppp_task_);
   1492   StartPPP(kPID);
   1493   EXPECT_EQ(Cellular::kStateLinked, device_->state());
   1494 }
   1495 
   1496 TEST_F(CellularTest, GetLogin) {
   1497   // Doesn't crash when there is no service.
   1498   string username_to_pppd;
   1499   string password_to_pppd;
   1500   EXPECT_FALSE(device_->service());
   1501   device_->GetLogin(&username_to_pppd, &password_to_pppd);
   1502 
   1503   // Provides expected username and password in normal case.
   1504   const char kFakeUsername[] = "fake-user";
   1505   const char kFakePassword[] = "fake-password";
   1506   CellularService& service(*SetService());
   1507   service.ppp_username_ = kFakeUsername;
   1508   service.ppp_password_ = kFakePassword;
   1509   device_->GetLogin(&username_to_pppd, &password_to_pppd);
   1510 }
   1511 
   1512 TEST_F(CellularTest, Notify) {
   1513   // Common setup.
   1514   MockPPPDeviceFactory* ppp_device_factory =
   1515       MockPPPDeviceFactory::GetInstance();
   1516   const int kPID = 91;
   1517   device_->ppp_device_factory_ = ppp_device_factory;
   1518   SetMockService();
   1519   StartPPP(kPID);
   1520 
   1521   const map<string, string> kEmptyArgs;
   1522   device_->Notify(kPPPReasonAuthenticating, kEmptyArgs);
   1523   EXPECT_TRUE(device_->is_ppp_authenticating_);
   1524   device_->Notify(kPPPReasonAuthenticated, kEmptyArgs);
   1525   EXPECT_FALSE(device_->is_ppp_authenticating_);
   1526 
   1527   // Normal connect.
   1528   const string kInterfaceName("fake-device");
   1529   const int kInterfaceIndex = 1;
   1530   scoped_refptr<MockPPPDevice> ppp_device;
   1531   map<string, string> ppp_config;
   1532   ppp_device =
   1533       new MockPPPDevice(modem_info_.control_interface(), nullptr, nullptr,
   1534                         nullptr, kInterfaceName, kInterfaceIndex);
   1535   ppp_config[kPPPInterfaceName] = kInterfaceName;
   1536   EXPECT_CALL(device_info_, GetIndex(kInterfaceName))
   1537       .WillOnce(Return(kInterfaceIndex));
   1538   EXPECT_CALL(device_info_, RegisterDevice(_));
   1539   EXPECT_CALL(*ppp_device_factory,
   1540               CreatePPPDevice(_, _, _, _, kInterfaceName, kInterfaceIndex))
   1541       .WillOnce(Return(ppp_device.get()));
   1542   EXPECT_CALL(*ppp_device, SetEnabled(true));
   1543   EXPECT_CALL(*ppp_device, SelectService(_));
   1544   EXPECT_CALL(*ppp_device, UpdateIPConfigFromPPP(ppp_config, false));
   1545   device_->Notify(kPPPReasonConnect, ppp_config);
   1546   Mock::VerifyAndClearExpectations(&device_info_);
   1547   Mock::VerifyAndClearExpectations(ppp_device.get());
   1548 
   1549   // Re-connect on same network device: if pppd sends us multiple connect
   1550   // events, we behave sanely.
   1551   EXPECT_CALL(device_info_, GetIndex(kInterfaceName))
   1552       .WillOnce(Return(kInterfaceIndex));
   1553   EXPECT_CALL(*ppp_device, SetEnabled(true));
   1554   EXPECT_CALL(*ppp_device, SelectService(_));
   1555   EXPECT_CALL(*ppp_device, UpdateIPConfigFromPPP(ppp_config, false));
   1556   device_->Notify(kPPPReasonConnect, ppp_config);
   1557   Mock::VerifyAndClearExpectations(&device_info_);
   1558   Mock::VerifyAndClearExpectations(ppp_device.get());
   1559 
   1560   // Re-connect on new network device: if we still have the PPPDevice
   1561   // from a prior connect, this new connect should DTRT. This is
   1562   // probably an unlikely case.
   1563   const string kInterfaceName2("fake-device2");
   1564   const int kInterfaceIndex2 = 2;
   1565   scoped_refptr<MockPPPDevice> ppp_device2;
   1566   map<string, string> ppp_config2;
   1567   ppp_device2 =
   1568       new MockPPPDevice(modem_info_.control_interface(), nullptr, nullptr,
   1569                         nullptr, kInterfaceName2, kInterfaceIndex2);
   1570   ppp_config2[kPPPInterfaceName] = kInterfaceName2;
   1571   EXPECT_CALL(device_info_, GetIndex(kInterfaceName2))
   1572       .WillOnce(Return(kInterfaceIndex2));
   1573   EXPECT_CALL(device_info_,
   1574               RegisterDevice(static_cast<DeviceRefPtr>(ppp_device2)));
   1575   EXPECT_CALL(*ppp_device_factory,
   1576               CreatePPPDevice(_, _, _, _, kInterfaceName2, kInterfaceIndex2))
   1577       .WillOnce(Return(ppp_device2.get()));
   1578   EXPECT_CALL(*ppp_device, SelectService(ServiceRefPtr(nullptr)));
   1579   EXPECT_CALL(*ppp_device2, SetEnabled(true));
   1580   EXPECT_CALL(*ppp_device2, SelectService(_));
   1581   EXPECT_CALL(*ppp_device2, UpdateIPConfigFromPPP(ppp_config2, false));
   1582   device_->Notify(kPPPReasonConnect, ppp_config2);
   1583   Mock::VerifyAndClearExpectations(&device_info_);
   1584   Mock::VerifyAndClearExpectations(ppp_device.get());
   1585   Mock::VerifyAndClearExpectations(ppp_device2.get());
   1586 
   1587   // Disconnect should report unknown failure, since we had a
   1588   // Notify(kPPPReasonAuthenticated, ...).
   1589   EXPECT_CALL(*ppp_device2, SetServiceFailure(Service::kFailureUnknown));
   1590   device_->Notify(kPPPReasonDisconnect, kEmptyArgs);
   1591   EXPECT_EQ(nullptr, device_->ppp_task_);
   1592 
   1593   // |Cellular::ppp_task_| is destroyed on the task loop. Must dispatch once to
   1594   // cleanup.
   1595   dispatcher_.DispatchPendingEvents();
   1596 }
   1597 
   1598 TEST_F(CellularTest, PPPConnectionFailedBeforeAuth) {
   1599   // Test that we properly set Service state in the case where pppd
   1600   // disconnects before authenticating (as opposed to the Notify test,
   1601   // where pppd disconnects after connecting).
   1602   const int kPID = 52;
   1603   const map<string, string> kEmptyArgs;
   1604   MockCellularService* service = SetMockService();
   1605   StartPPP(kPID);
   1606 
   1607   ExpectDisconnectCapabilityUniversal();
   1608   EXPECT_CALL(*service, SetFailure(Service::kFailureUnknown));
   1609   device_->Notify(kPPPReasonDisconnect, kEmptyArgs);
   1610   EXPECT_EQ(nullptr, device_->ppp_task_);
   1611   VerifyDisconnect();
   1612 
   1613   // |Cellular::ppp_task_| is destroyed on the task loop. Must dispatch once to
   1614   // cleanup.
   1615   dispatcher_.DispatchPendingEvents();
   1616 }
   1617 
   1618 TEST_F(CellularTest, PPPConnectionFailedDuringAuth) {
   1619   // Test that we properly set Service state in the case where pppd
   1620   // disconnects during authentication (as opposed to the Notify test,
   1621   // where pppd disconnects after connecting).
   1622   const int kPID = 52;
   1623   const map<string, string> kEmptyArgs;
   1624   MockCellularService* service = SetMockService();
   1625   StartPPP(kPID);
   1626 
   1627   ExpectDisconnectCapabilityUniversal();
   1628   EXPECT_CALL(*service, SetFailure(Service::kFailurePPPAuth));
   1629   device_->Notify(kPPPReasonAuthenticating, kEmptyArgs);
   1630   device_->Notify(kPPPReasonDisconnect, kEmptyArgs);
   1631   EXPECT_EQ(nullptr, device_->ppp_task_);
   1632   VerifyDisconnect();
   1633 
   1634   // |Cellular::ppp_task_| is destroyed on the task loop. Must dispatch once to
   1635   // cleanup.
   1636   dispatcher_.DispatchPendingEvents();
   1637 }
   1638 
   1639 TEST_F(CellularTest, PPPConnectionFailedAfterAuth) {
   1640   // Test that we properly set Service state in the case where pppd
   1641   // disconnects after authenticating, but before connecting (as
   1642   // opposed to the Notify test, where pppd disconnects after
   1643   // connecting).
   1644   const int kPID = 52;
   1645   const map<string, string> kEmptyArgs;
   1646   MockCellularService* service = SetMockService();
   1647   StartPPP(kPID);
   1648 
   1649   EXPECT_CALL(*service, SetFailure(Service::kFailureUnknown));
   1650   ExpectDisconnectCapabilityUniversal();
   1651   device_->Notify(kPPPReasonAuthenticating, kEmptyArgs);
   1652   device_->Notify(kPPPReasonAuthenticated, kEmptyArgs);
   1653   device_->Notify(kPPPReasonDisconnect, kEmptyArgs);
   1654   EXPECT_EQ(nullptr, device_->ppp_task_);
   1655   VerifyDisconnect();
   1656 
   1657   // |Cellular::ppp_task_| is destroyed on the task loop. Must dispatch once to
   1658   // cleanup.
   1659   dispatcher_.DispatchPendingEvents();
   1660 }
   1661 
   1662 TEST_F(CellularTest, OnPPPDied) {
   1663   const int kPID = 1234;
   1664   const int kExitStatus = 5;
   1665   ExpectDisconnectCapabilityUniversal();
   1666   device_->OnPPPDied(kPID, kExitStatus);
   1667   VerifyDisconnect();
   1668 }
   1669 
   1670 TEST_F(CellularTest, OnPPPDiedCleanupDevice) {
   1671   // Test that OnPPPDied causes the ppp_device_ reference to be dropped.
   1672   const int kPID = 123;
   1673   const int kExitStatus = 5;
   1674   StartPPP(kPID);
   1675   FakeUpConnectedPPP();
   1676   ExpectDisconnectCapabilityUniversal();
   1677   device_->OnPPPDied(kPID, kExitStatus);
   1678   VerifyPPPStopped();
   1679 
   1680   // |Cellular::ppp_task_| is destroyed on the task loop. Must dispatch once to
   1681   // cleanup.
   1682   dispatcher_.DispatchPendingEvents();
   1683 }
   1684 
   1685 TEST_F(CellularTest, DropConnection) {
   1686   device_->set_ipconfig(dhcp_config_);
   1687   EXPECT_CALL(*dhcp_config_, ReleaseIP(_));
   1688   device_->DropConnection();
   1689   Mock::VerifyAndClearExpectations(dhcp_config_.get());  // verify before dtor
   1690   EXPECT_FALSE(device_->ipconfig());
   1691 }
   1692 
   1693 TEST_F(CellularTest, DropConnectionPPP) {
   1694   scoped_refptr<MockPPPDevice> ppp_device(
   1695       new MockPPPDevice(modem_info_.control_interface(),
   1696                         nullptr, nullptr, nullptr, "fake_ppp0", -1));
   1697   EXPECT_CALL(*ppp_device, DropConnection());
   1698   device_->ppp_device_ = ppp_device;
   1699   device_->DropConnection();
   1700 }
   1701 
   1702 TEST_F(CellularTest, ChangeServiceState) {
   1703   MockCellularService* service(SetMockService());
   1704   EXPECT_CALL(*service, SetState(_));
   1705   EXPECT_CALL(*service, SetFailure(_));
   1706   EXPECT_CALL(*service, SetFailureSilent(_));
   1707   ON_CALL(*service, state()).WillByDefault(Return(Service::kStateUnknown));
   1708 
   1709   // Without PPP, these should be handled by our selected_service().
   1710   device_->SelectService(service);
   1711   device_->SetServiceState(Service::kStateConfiguring);
   1712   device_->SetServiceFailure(Service::kFailurePPPAuth);
   1713   device_->SetServiceFailureSilent(Service::kFailureUnknown);
   1714   Mock::VerifyAndClearExpectations(service);  // before Cellular dtor
   1715 }
   1716 
   1717 TEST_F(CellularTest, ChangeServiceStatePPP) {
   1718   MockCellularService* service(SetMockService());
   1719   scoped_refptr<MockPPPDevice> ppp_device(
   1720       new MockPPPDevice(modem_info_.control_interface(),
   1721                         nullptr, nullptr, nullptr, "fake_ppp0", -1));
   1722   EXPECT_CALL(*ppp_device, SetServiceState(_));
   1723   EXPECT_CALL(*ppp_device, SetServiceFailure(_));
   1724   EXPECT_CALL(*ppp_device, SetServiceFailureSilent(_));
   1725   EXPECT_CALL(*service, SetState(_)).Times(0);
   1726   EXPECT_CALL(*service, SetFailure(_)).Times(0);
   1727   EXPECT_CALL(*service, SetFailureSilent(_)).Times(0);
   1728   device_->ppp_device_ = ppp_device;
   1729 
   1730   // With PPP, these should all be punted over to the |ppp_device|.
   1731   // Note in particular that Cellular does not manipulate |service| in
   1732   // this case.
   1733   device_->SetServiceState(Service::kStateConfiguring);
   1734   device_->SetServiceFailure(Service::kFailurePPPAuth);
   1735   device_->SetServiceFailureSilent(Service::kFailureUnknown);
   1736 }
   1737 
   1738 TEST_F(CellularTest, StopPPPOnDisconnect) {
   1739   const int kPID = 123;
   1740   Error error;
   1741   StartPPP(kPID);
   1742   FakeUpConnectedPPP();
   1743   ExpectPPPStopped();
   1744   device_->Disconnect(&error, "in test");
   1745   VerifyPPPStopped();
   1746 }
   1747 
   1748 TEST_F(CellularTest, StopPPPOnSuspend) {
   1749   const int kPID = 123;
   1750   StartPPP(kPID);
   1751   FakeUpConnectedPPP();
   1752   ExpectPPPStopped();
   1753   device_->OnBeforeSuspend(ResultCallback());
   1754   VerifyPPPStopped();
   1755 }
   1756 
   1757 TEST_F(CellularTest, OnAfterResumeDisabledWantDisabled) {
   1758   // The Device was disabled prior to resume, and the profile settings
   1759   // indicate that the device should be disabled. We should leave
   1760   // things alone.
   1761 
   1762   // Initial state.
   1763   mm1::MockModemProxy* mm1_proxy = SetupOnAfterResume();
   1764   set_enabled_persistent(false);
   1765   EXPECT_FALSE(device_->running());
   1766   EXPECT_FALSE(device_->enabled_persistent());
   1767   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1768 
   1769   // Resume, while device is disabled.
   1770   EXPECT_CALL(*mm1_proxy, Enable(_, _, _, _)).Times(0);
   1771   device_->OnAfterResume();
   1772   EXPECT_FALSE(device_->running());
   1773   EXPECT_FALSE(device_->enabled_persistent());
   1774   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1775 }
   1776 
   1777 TEST_F(CellularTest, OnAfterResumeDisableInProgressWantDisabled) {
   1778   // The Device was not disabled prior to resume, but the profile
   1779   // settings indicate that the device _should be_ disabled. Most
   1780   // likely, we started disabling the device, but that did not
   1781   // complete before we suspended. We should leave things alone.
   1782 
   1783   // Initial state.
   1784   mm1::MockModemProxy* mm1_proxy = SetupOnAfterResume();
   1785   Error error;
   1786   EXPECT_CALL(*mm1_proxy, Enable(true, _, _, _))
   1787       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1788   device_->SetEnabled(true);
   1789   EXPECT_TRUE(device_->running());
   1790   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1791 
   1792   // Start disable.
   1793   EXPECT_CALL(*modem_info_.mock_manager(), UpdateDevice(_));
   1794   device_->SetEnabledPersistent(false, &error, ResultCallback());
   1795   EXPECT_FALSE(device_->running());  // changes immediately
   1796   EXPECT_FALSE(device_->enabled_persistent());  // changes immediately
   1797   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);  // changes on completion
   1798 
   1799   // Resume, with disable still in progress.
   1800   device_->OnAfterResume();
   1801   EXPECT_FALSE(device_->running());
   1802   EXPECT_FALSE(device_->enabled_persistent());
   1803   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1804 
   1805   // Finish the disable operation.
   1806   EXPECT_CALL(*mm1_proxy, Enable(false, _, _, _))
   1807       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1808   EXPECT_CALL(*mm1_proxy, SetPowerState(_, _, _, _))
   1809       .WillOnce(Invoke(this, &CellularTest::InvokeSetPowerState));
   1810   dispatcher_.DispatchPendingEvents();
   1811   EXPECT_FALSE(device_->running());
   1812   EXPECT_FALSE(device_->enabled_persistent());
   1813   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1814 }
   1815 
   1816 TEST_F(CellularTest, OnAfterResumeDisableQueuedWantEnabled) {
   1817   // The Device was not disabled prior to resume, and the profile
   1818   // settings indicate that the device should be enabled. In
   1819   // particular, we went into suspend before we actually processed the
   1820   // task queued by CellularCapabilityUniversal::StopModem.
   1821   //
   1822   // This is unlikely, and a case where we fail to do the right thing.
   1823   // The tests exists to document this corner case, which we get wrong.
   1824 
   1825   // Initial state.
   1826   mm1::MockModemProxy* mm1_proxy = SetupOnAfterResume();
   1827   EXPECT_CALL(*mm1_proxy, Enable(true, _, _, _))
   1828       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1829   device_->SetEnabled(true);
   1830   EXPECT_TRUE(device_->running());
   1831   EXPECT_TRUE(device_->enabled_persistent());
   1832   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1833 
   1834   // Start disable.
   1835   device_->SetEnabled(false);
   1836   EXPECT_FALSE(device_->running());  // changes immediately
   1837   EXPECT_TRUE(device_->enabled_persistent());  // no change
   1838   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);  // changes on completion
   1839 
   1840   // Refresh proxies, since CellularCapabilityUniversal::StartModem wants
   1841   // new proxies. Also, stash away references for later.
   1842   PopulateProxies();
   1843   SetCommonOnAfterResumeExpectations();
   1844   mm1_proxy = mm1_proxy_.get();
   1845   auto dbus_properties_proxy = dbus_properties_proxy_.get();
   1846 
   1847   // Resume, with disable still in progress.
   1848   EXPECT_CALL(*mm1_proxy, Enable(true, _, _, _))
   1849       .WillOnce(Invoke(this, &CellularTest::InvokeEnableReturningWrongState));
   1850   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);  // disable still pending
   1851   device_->OnAfterResume();
   1852   EXPECT_TRUE(device_->running());  // changes immediately
   1853   EXPECT_TRUE(device_->enabled_persistent());  // no change
   1854   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);  // by OnAfterResume
   1855 
   1856   // Set up state that we need.
   1857   KeyValueStore modem_properties;
   1858   modem_properties.SetInt(MM_MODEM_PROPERTY_STATE,
   1859                           Cellular::kModemStateDisabled);
   1860 
   1861   // Let the disable complete.
   1862   EXPECT_CALL(*mm1_proxy, Enable(false, _, _, _))
   1863       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1864   EXPECT_CALL(*mm1_proxy, SetPowerState(_, _, _, _))
   1865       .WillOnce(Invoke(this, &CellularTest::InvokeSetPowerState));
   1866   EXPECT_CALL(*dbus_properties_proxy, GetAll(_))
   1867       .WillRepeatedly(Return(modem_properties));
   1868   dispatcher_.DispatchPendingEvents();
   1869   EXPECT_TRUE(device_->running());  // last changed by OnAfterResume
   1870   EXPECT_TRUE(device_->enabled_persistent());  // last changed by OnAfterResume
   1871   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1872 
   1873   // There's nothing queued up to restart the modem. Even though we
   1874   // want to be running, we're stuck in the disabled state.
   1875   dispatcher_.DispatchPendingEvents();
   1876   EXPECT_TRUE(device_->running());
   1877   EXPECT_TRUE(device_->enabled_persistent());
   1878   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1879 }
   1880 
   1881 TEST_F(CellularTest, OnAfterResumePowerDownInProgressWantEnabled) {
   1882   // The Device was not fully disabled prior to resume, and the
   1883   // profile settings indicate that the device should be enabled. In
   1884   // this case, we have disabled the device, but are waiting for the
   1885   // power-down (switch to low power) to complete.
   1886   //
   1887   // This test emulates the behavior of the Huawei E303 dongle, when
   1888   // Manager::kTerminationActionsTimeoutMilliseconds is 9500
   1889   // msec. (The dongle takes 10-11 seconds to go through the whole
   1890   // disable, power-down sequence).
   1891   //
   1892   // Eventually, the power-down would complete, and the device would
   1893   // be stuck in the disabled state. To counter-act that,
   1894   // OnAfterResume tries to enable the device now, even though the
   1895   // device is currently enabled.
   1896 
   1897   // Initial state.
   1898   mm1::MockModemProxy* mm1_proxy = SetupOnAfterResume();
   1899   EXPECT_CALL(*mm1_proxy, Enable(true, _, _, _))
   1900       .WillOnce(Invoke(this, &CellularTest::InvokeEnable));
   1901   device_->SetEnabled(true);
   1902   EXPECT_TRUE(device_->running());
   1903   EXPECT_TRUE(device_->enabled_persistent());
   1904   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1905 
   1906   // Start disable.
   1907   ResultCallback modem_proxy_enable_callback;
   1908   EXPECT_CALL(*mm1_proxy, Enable(false, _, _, _))
   1909       .WillOnce(SaveArg<2>(&modem_proxy_enable_callback));
   1910   device_->SetEnabled(false);
   1911   dispatcher_.DispatchPendingEvents();  // SetEnabled yields a deferred task
   1912   EXPECT_FALSE(device_->running());  // changes immediately
   1913   EXPECT_TRUE(device_->enabled_persistent());  // no change
   1914   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);  // changes on completion
   1915 
   1916   // Let the disable complete. That will trigger power-down.
   1917   //
   1918   // Note that, unlike for mm1_proxy->Enable, we don't save the
   1919   // callback for mm1_proxy->SetPowerState. We expect the callback not
   1920   // to be executed, as explained in the comment about having a fresh
   1921   // proxy OnAfterResume, below.
   1922   Error error;
   1923   ASSERT_TRUE(error.IsSuccess());
   1924   EXPECT_CALL(*mm1_proxy, SetPowerState(MM_MODEM_POWER_STATE_LOW, _, _, _))
   1925       .WillOnce(SetErrorTypeInArgument<1>(Error::kOperationInitiated));
   1926   modem_proxy_enable_callback.Run(error);
   1927 
   1928   // No response to power-down yet. It probably completed while the host
   1929   // was asleep, and so the reply from the modem was lost.
   1930 
   1931   // Refresh proxies, since CellularCapabilityUniversal::StartModem wants
   1932   // new proxies. Also, stash away references for later.
   1933   PopulateProxies();
   1934   SetCommonOnAfterResumeExpectations();
   1935   auto new_mm1_proxy = mm1_proxy_.get();
   1936   auto dbus_properties_proxy = dbus_properties_proxy_.get();
   1937 
   1938   // Resume.
   1939   ResultCallback new_callback;
   1940   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);  // disable still pending
   1941   EXPECT_CALL(*new_mm1_proxy, Enable(true, _, _, _))
   1942       .WillOnce(SaveArg<2>(&modem_proxy_enable_callback));
   1943   device_->OnAfterResume();
   1944   EXPECT_TRUE(device_->running());  // changes immediately
   1945   EXPECT_TRUE(device_->enabled_persistent());  // no change
   1946   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);  // by OnAfterResume
   1947 
   1948   // We should have a fresh proxy OnAfterResume. Otherwise, we may get
   1949   // confused when the SetPowerState call completes (either naturally,
   1950   // or via a time-out from dbus-c++).
   1951   //
   1952   // The pointers must differ, because the new proxy is constructed
   1953   // before the old one is destructed.
   1954   EXPECT_FALSE(new_mm1_proxy == mm1_proxy);
   1955 
   1956   // Set up state that we need.
   1957   KeyValueStore modem_properties;
   1958   modem_properties.SetInt(MM_MODEM_PROPERTY_STATE,
   1959                           Cellular::kModemStateEnabled);
   1960 
   1961   // Let the enable complete.
   1962   ASSERT_TRUE(error.IsSuccess());
   1963   EXPECT_CALL(*dbus_properties_proxy, GetAll(_))
   1964       .WillRepeatedly(Return(modem_properties));
   1965   ASSERT_TRUE(!modem_proxy_enable_callback.is_null());
   1966   modem_proxy_enable_callback.Run(error);
   1967   EXPECT_TRUE(device_->running());
   1968   EXPECT_TRUE(device_->enabled_persistent());
   1969   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1970 }
   1971 
   1972 TEST_F(CellularTest, OnAfterResumeDisabledWantEnabled) {
   1973   // This is the ideal case. The disable process completed before
   1974   // going into suspend.
   1975   mm1::MockModemProxy* mm1_proxy = SetupOnAfterResume();
   1976   EXPECT_FALSE(device_->running());
   1977   EXPECT_TRUE(device_->enabled_persistent());
   1978   EXPECT_EQ(Cellular::kStateDisabled, device_->state_);
   1979 
   1980   // Resume.
   1981   ResultCallback modem_proxy_enable_callback;
   1982   EXPECT_CALL(*mm1_proxy, Enable(true, _, _, _))
   1983       .WillOnce(SaveArg<2>(&modem_proxy_enable_callback));
   1984   device_->OnAfterResume();
   1985 
   1986   // Complete enable.
   1987   Error error;
   1988   ASSERT_TRUE(error.IsSuccess());
   1989   modem_proxy_enable_callback.Run(error);
   1990   EXPECT_TRUE(device_->running());
   1991   EXPECT_TRUE(device_->enabled_persistent());
   1992   EXPECT_EQ(Cellular::kStateEnabled, device_->state_);
   1993 }
   1994 
   1995 // Custom property setters should return false, and make no changes, if
   1996 // the new value is the same as the old value.
   1997 TEST_F(CellularTest, CustomSetterNoopChange) {
   1998   Error error;
   1999   EXPECT_FALSE(device_->allow_roaming_);
   2000   EXPECT_FALSE(device_->SetAllowRoaming(false, &error));
   2001   EXPECT_TRUE(error.IsSuccess());
   2002 }
   2003 
   2004 TEST_F(CellularTest, ScanImmediateFailure) {
   2005   Error error;
   2006 
   2007   device_->set_found_networks(kTestNetworksCellular);
   2008   EXPECT_FALSE(device_->scanning_);
   2009   // |InitProxies| must be called before calling any functions on the
   2010   // Capability*, to set up the modem proxies.
   2011   // Warning: The test loses all references to the proxies when |InitProxies| is
   2012   // called.
   2013   GetCapabilityGSM()->InitProxies();
   2014   device_->Scan(Device::kFullScan, &error, "");
   2015   EXPECT_TRUE(error.IsFailure());
   2016   EXPECT_FALSE(device_->scanning_);
   2017   EXPECT_EQ(kTestNetworksCellular, device_->found_networks());
   2018 }
   2019 
   2020 TEST_F(CellularTest, ScanAsynchronousFailure) {
   2021   Error error;
   2022   ScanResultsCallback results_callback;
   2023 
   2024   device_->set_found_networks(kTestNetworksCellular);
   2025   EXPECT_CALL(*gsm_network_proxy_, Scan(&error, _, _))
   2026       .WillOnce(DoAll(SetErrorTypeInArgument<0>(Error::kOperationInitiated),
   2027                       SaveArg<1>(&results_callback)));
   2028   EXPECT_FALSE(device_->scanning_);
   2029   // |InitProxies| must be called before calling any functions on the
   2030   // Capability*, to set up the modem proxies.
   2031   // Warning: The test loses all references to the proxies when |InitProxies| is
   2032   // called.
   2033   GetCapabilityGSM()->InitProxies();
   2034   device_->Scan(Device::kFullScan, &error, "");
   2035   EXPECT_TRUE(error.IsOngoing());
   2036   EXPECT_TRUE(device_->scanning_);
   2037 
   2038   // Asynchronously fail the scan.
   2039   error.Populate(Error::kOperationFailed);
   2040   results_callback.Run(kTestNetworksGSM, error);
   2041   EXPECT_FALSE(device_->scanning_);
   2042   EXPECT_TRUE(device_->found_networks().empty());
   2043 }
   2044 
   2045 TEST_F(CellularTest, ScanSuccess) {
   2046   Error error;
   2047   ScanResultsCallback results_callback;
   2048 
   2049   device_->clear_found_networks();
   2050   EXPECT_CALL(*gsm_network_proxy_, Scan(&error, _, _))
   2051       .WillOnce(DoAll(SetErrorTypeInArgument<0>(Error::kOperationInitiated),
   2052                       SaveArg<1>(&results_callback)));
   2053   EXPECT_FALSE(device_->scanning_);
   2054   // |InitProxies| must be called before calling any functions on the
   2055   // Capability*, to set up the modem proxies.
   2056   // Warning: The test loses all references to the proxies when |InitProxies| is
   2057   // called.
   2058   GetCapabilityGSM()->InitProxies();
   2059   device_->Scan(Device::kFullScan, &error, "");
   2060   EXPECT_TRUE(error.IsOngoing());
   2061   EXPECT_TRUE(device_->scanning_);
   2062 
   2063   // Successfully complete the scan.
   2064   const GSMScanResults gsm_results{};
   2065   error.Populate(Error::kSuccess);
   2066   results_callback.Run(kTestNetworksGSM, error);
   2067   EXPECT_FALSE(device_->scanning_);
   2068   EXPECT_EQ(kTestNetworksCellular, device_->found_networks());
   2069 }
   2070 
   2071 TEST_F(CellularTest, EstablishLinkDHCP) {
   2072   unique_ptr<CellularBearer> bearer(
   2073       new CellularBearer(&control_interface_, "", ""));
   2074   bearer->set_ipv4_config_method(IPConfig::kMethodDHCP);
   2075   SetCapabilityUniversalActiveBearer(std::move(bearer));
   2076   device_->state_ = Cellular::kStateConnected;
   2077 
   2078   MockCellularService* service = SetMockService();
   2079   ON_CALL(*service, state()).WillByDefault(Return(Service::kStateUnknown));
   2080 
   2081   EXPECT_CALL(device_info_, GetFlags(device_->interface_index(), _))
   2082       .WillOnce(DoAll(SetArgumentPointee<1>(IFF_UP), Return(true)));
   2083   EXPECT_CALL(dhcp_provider_, CreateIPv4Config(kTestDeviceName, _, _, _))
   2084       .WillOnce(Return(dhcp_config_));
   2085   EXPECT_CALL(*dhcp_config_, RequestIP()).WillOnce(Return(true));
   2086   EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
   2087   device_->EstablishLink();
   2088   EXPECT_EQ(service, device_->selected_service());
   2089   Mock::VerifyAndClearExpectations(service);  // before Cellular dtor
   2090 }
   2091 
   2092 TEST_F(CellularTest, EstablishLinkPPP) {
   2093   unique_ptr<CellularBearer> bearer(
   2094       new CellularBearer(&control_interface_, "", ""));
   2095   bearer->set_ipv4_config_method(IPConfig::kMethodPPP);
   2096   SetCapabilityUniversalActiveBearer(std::move(bearer));
   2097   device_->state_ = Cellular::kStateConnected;
   2098 
   2099   const int kPID = 123;
   2100   EXPECT_CALL(process_manager_, StartProcess(_, _, _, _, _, _))
   2101       .WillOnce(Return(kPID));
   2102   device_->EstablishLink();
   2103   EXPECT_FALSE(device_->ipconfig());  // No DHCP client.
   2104   EXPECT_FALSE(device_->selected_service());
   2105   EXPECT_FALSE(device_->is_ppp_authenticating_);
   2106   EXPECT_NE(nullptr, device_->ppp_task_);
   2107 }
   2108 
   2109 TEST_F(CellularTest, EstablishLinkStatic) {
   2110   IPAddress::Family kAddressFamily = IPAddress::kFamilyIPv4;
   2111   const char kAddress[] = "10.0.0.1";
   2112   const char kGateway[] = "10.0.0.254";
   2113   const int32_t kSubnetPrefix = 16;
   2114   const char* const kDNS[] = {"10.0.0.2", "8.8.4.4", "8.8.8.8"};
   2115 
   2116   unique_ptr<IPConfig::Properties> ipconfig_properties(
   2117       new IPConfig::Properties);
   2118   ipconfig_properties->address_family = kAddressFamily;
   2119   ipconfig_properties->address = kAddress;
   2120   ipconfig_properties->gateway = kGateway;
   2121   ipconfig_properties->subnet_prefix = kSubnetPrefix;
   2122   ipconfig_properties->dns_servers = vector<string>{kDNS[0], kDNS[1], kDNS[2]};
   2123 
   2124   unique_ptr<CellularBearer> bearer(
   2125       new CellularBearer(&control_interface_, "", ""));
   2126   bearer->set_ipv4_config_method(IPConfig::kMethodStatic);
   2127   bearer->set_ipv4_config_properties(std::move(ipconfig_properties));
   2128   SetCapabilityUniversalActiveBearer(std::move(bearer));
   2129   device_->state_ = Cellular::kStateConnected;
   2130 
   2131   MockCellularService* service = SetMockService();
   2132   ON_CALL(*service, state()).WillByDefault(Return(Service::kStateUnknown));
   2133 
   2134   EXPECT_CALL(device_info_, GetFlags(device_->interface_index(), _))
   2135       .WillOnce(DoAll(SetArgumentPointee<1>(IFF_UP), Return(true)));
   2136   EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
   2137   device_->EstablishLink();
   2138   EXPECT_EQ(service, device_->selected_service());
   2139   ASSERT_TRUE(device_->ipconfig());
   2140   EXPECT_EQ(kAddressFamily, device_->ipconfig()->properties().address_family);
   2141   EXPECT_EQ(kAddress, device_->ipconfig()->properties().address);
   2142   EXPECT_EQ(kGateway, device_->ipconfig()->properties().gateway);
   2143   EXPECT_EQ(kSubnetPrefix, device_->ipconfig()->properties().subnet_prefix);
   2144   ASSERT_EQ(3, device_->ipconfig()->properties().dns_servers.size());
   2145   EXPECT_EQ(kDNS[0], device_->ipconfig()->properties().dns_servers[0]);
   2146   EXPECT_EQ(kDNS[1], device_->ipconfig()->properties().dns_servers[1]);
   2147   EXPECT_EQ(kDNS[2], device_->ipconfig()->properties().dns_servers[2]);
   2148   Mock::VerifyAndClearExpectations(service);  // before Cellular dtor
   2149 }
   2150 
   2151 }  // namespace shill
   2152