Home | History | Annotate | Download | only in wifi
      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/wifi/wifi_provider.h"
     18 
     19 #include <map>
     20 #include <set>
     21 #include <string>
     22 #include <vector>
     23 
     24 #include <base/format_macros.h>
     25 #include <base/strings/string_number_conversions.h>
     26 #include <base/strings/string_util.h>
     27 #include <base/strings/stringprintf.h>
     28 #if defined(__ANDROID__)
     29 #include <dbus/service_constants.h>
     30 #else
     31 #include <chromeos/dbus/service_constants.h>
     32 #endif  // __ANDROID__
     33 #include <gtest/gtest.h>
     34 
     35 #include "shill/mock_event_dispatcher.h"
     36 #include "shill/mock_manager.h"
     37 #include "shill/mock_metrics.h"
     38 #include "shill/mock_profile.h"
     39 #include "shill/mock_store.h"
     40 #include "shill/net/ieee80211.h"
     41 #include "shill/net/mock_time.h"
     42 #include "shill/nice_mock_control.h"
     43 #include "shill/supplicant/wpa_supplicant.h"
     44 #include "shill/technology.h"
     45 #include "shill/wifi/mock_wifi_service.h"
     46 #include "shill/wifi/wifi_endpoint.h"
     47 
     48 using base::StringPrintf;
     49 using std::map;
     50 using std::set;
     51 using std::string;
     52 using std::vector;
     53 using ::testing::_;
     54 using ::testing::AnyNumber;
     55 using ::testing::ContainerEq;
     56 using ::testing::Eq;
     57 using ::testing::Invoke;
     58 using ::testing::Mock;
     59 using ::testing::NiceMock;
     60 using ::testing::Return;
     61 using ::testing::SetArgumentPointee;
     62 using ::testing::StartsWith;
     63 using ::testing::StrictMock;
     64 
     65 namespace shill {
     66 
     67 namespace {
     68 
     69 const time_t kFirstWeek = 50;
     70 const char kIllegalDayProfile[] = "IllegalDay";
     71 const time_t kSecondsPerWeek = 60 * 60 * 24 * 7;
     72 const time_t kTestDays = 20;
     73 
     74 }  // namespace
     75 
     76 class WiFiProviderTest : public testing::Test {
     77  public:
     78   WiFiProviderTest()
     79       : metrics_(nullptr),
     80         manager_(&control_, &dispatcher_, &metrics_),
     81         provider_(&control_, &dispatcher_, &metrics_, &manager_),
     82         default_profile_(
     83             new NiceMock<MockProfile>(
     84                 &control_, &metrics_, &manager_, "default")),
     85         user_profile_(
     86             new NiceMock<MockProfile>(&control_, &metrics_, &manager_, "user")),
     87         storage_entry_index_(0) {
     88     provider_.time_ = &time_;
     89 
     90     string freq_string = StringPrintf("%s%d", WiFiProvider::kStorageFrequencies,
     91                                       0);
     92     profile_frequency_data_[freq_string].push_back(
     93         base::StringPrintf("@%" PRIu64, static_cast<uint64_t>(kFirstWeek)));
     94     profile_frequency_data_[freq_string].push_back("5001:1");
     95     profile_frequency_data_[freq_string].push_back("5002:2");
     96 
     97     freq_string = StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 1);
     98     profile_frequency_data_[freq_string].push_back(
     99         base::StringPrintf("@%" PRIu64, static_cast<uint64_t>(kFirstWeek) + 1));
    100     // Overlap one entry with previous block.
    101     profile_frequency_data_[freq_string].push_back("5001:1");
    102     profile_frequency_data_[freq_string].push_back("6001:1");
    103     profile_frequency_data_[freq_string].push_back("6002:2");
    104 
    105     freq_string = StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 2);
    106     profile_frequency_data_[freq_string].push_back(
    107         base::StringPrintf("@%" PRIu64, static_cast<uint64_t>(kFirstWeek) + 2));
    108     profile_frequency_data_[freq_string].push_back("7001:1");
    109     profile_frequency_data_[freq_string].push_back("7002:2");
    110 
    111     profile_frequency_data_[kIllegalDayProfile].push_back("7001:1");
    112     profile_frequency_data_[kIllegalDayProfile].push_back("7002:2");
    113   }
    114 
    115   virtual ~WiFiProviderTest() {}
    116 
    117   virtual void SetUp() {
    118     EXPECT_CALL(*default_profile_, IsDefault()).WillRepeatedly(Return(true));
    119     EXPECT_CALL(*default_profile_, GetStorage())
    120         .WillRepeatedly(Return(&default_profile_storage_));
    121     EXPECT_CALL(*default_profile_, GetConstStorage())
    122         .WillRepeatedly(Return(&default_profile_storage_));
    123 
    124     EXPECT_CALL(*user_profile_, IsDefault()).WillRepeatedly(Return(false));
    125     EXPECT_CALL(*user_profile_, GetStorage())
    126         .WillRepeatedly(Return(&user_profile_storage_));
    127     EXPECT_CALL(*user_profile_, GetConstStorage())
    128         .WillRepeatedly(Return(&user_profile_storage_));
    129 
    130     // Default expectations for UMA metrics. Individual test cases
    131     // will override these, by adding later expectations.
    132     EXPECT_CALL(metrics_, SendToUMA(
    133         Metrics::kMetricRememberedWiFiNetworkCount,
    134         _,
    135         Metrics::kMetricRememberedWiFiNetworkCountMin,
    136         Metrics::kMetricRememberedWiFiNetworkCountMax,
    137         Metrics::kMetricRememberedWiFiNetworkCountNumBuckets))
    138         .Times(AnyNumber());
    139     EXPECT_CALL(metrics_, SendToUMA(
    140         StartsWith("Network.Shill.WiFi.RememberedPrivateNetworkCount."),
    141         _,
    142         Metrics::kMetricRememberedWiFiNetworkCountMin,
    143         Metrics::kMetricRememberedWiFiNetworkCountMax,
    144         Metrics::kMetricRememberedWiFiNetworkCountNumBuckets))
    145         .Times(AnyNumber());
    146     EXPECT_CALL(metrics_, SendToUMA(
    147         StartsWith("Network.Shill.WiFi.RememberedSharedNetworkCount."),
    148         _,
    149         Metrics::kMetricRememberedWiFiNetworkCountMin,
    150         Metrics::kMetricRememberedWiFiNetworkCountMax,
    151         Metrics::kMetricRememberedWiFiNetworkCountNumBuckets))
    152         .Times(AnyNumber());
    153   }
    154 
    155   bool GetStringList(const std::string& /*group*/,
    156                      const std::string& key,
    157                      std::vector<std::string>* value) {
    158     if (!value) {
    159       return false;
    160     }
    161     if (ContainsKey(profile_frequency_data_, key)) {
    162       *value = profile_frequency_data_[key];
    163       return true;
    164     }
    165     return false;
    166   }
    167 
    168   bool GetIllegalDayStringList(const std::string& /*group*/,
    169                                const std::string& key,
    170                                std::vector<std::string>* value) {
    171     if (!value) {
    172       return false;
    173     }
    174     if (ContainsKey(profile_frequency_data_, key)) {
    175       *value = profile_frequency_data_[kIllegalDayProfile];
    176       return true;
    177     }
    178     return false;
    179   }
    180 
    181   // Used by mock invocations of RegisterService() to maintain the side-effect
    182   // of assigning a profile to |service|.
    183   void BindServiceToDefaultProfile(const ServiceRefPtr& service) {
    184     service->set_profile(default_profile_);
    185   }
    186   void BindServiceToUserProfile(const ServiceRefPtr& service) {
    187     service->set_profile(user_profile_);
    188   }
    189 
    190  protected:
    191   typedef scoped_refptr<MockWiFiService> MockWiFiServiceRefPtr;
    192 
    193   void CreateServicesFromProfile(Profile* profile) {
    194     provider_.CreateServicesFromProfile(profile);
    195   }
    196 
    197   void LoadAndFixupServiceEntries(Profile* profile) {
    198     provider_.LoadAndFixupServiceEntries(profile);
    199   }
    200 
    201   void Save() {
    202     provider_.Save(&default_profile_storage_);
    203   }
    204 
    205   const vector<WiFiServiceRefPtr> GetServices() {
    206     return provider_.services_;
    207   }
    208 
    209   const WiFiProvider::EndpointServiceMap& GetServiceByEndpoint() {
    210     return provider_.service_by_endpoint_;
    211   }
    212 
    213   bool GetRunning() {
    214     return provider_.running_;
    215   }
    216 
    217   void AddStringParameterToStorage(MockStore* storage,
    218                                    const string& id,
    219                                    const string& key,
    220                                    const string& value) {
    221     EXPECT_CALL(*storage, GetString(id, key, _))
    222         .WillRepeatedly(DoAll(SetArgumentPointee<2>(value),
    223                               Return(true)));
    224   }
    225 
    226   // Adds service to profile's storage. But does not set profile on the Service.
    227   string AddServiceToProfileStorage(Profile* profile,
    228                                     const char* ssid,
    229                                     const char* mode,
    230                                     const char* security,
    231                                     bool is_hidden,
    232                                     bool provide_hidden) {
    233     string id = base::StringPrintf("entry_%d", storage_entry_index_);
    234     auto profile_storage = static_cast<MockStore*>(profile->GetStorage());
    235     EXPECT_CALL(*profile_storage, GetString(id, _, _))
    236         .WillRepeatedly(Return(false));
    237     AddStringParameterToStorage(
    238         profile_storage, id, WiFiService::kStorageType, kTypeWifi);
    239     if (ssid) {
    240       const string ssid_string(ssid);
    241       const string hex_ssid(
    242           base::HexEncode(ssid_string.data(), ssid_string.size()));
    243       AddStringParameterToStorage(
    244           profile_storage, id, WiFiService::kStorageSSID, hex_ssid);
    245     }
    246     if (mode) {
    247       AddStringParameterToStorage(
    248           profile_storage, id, WiFiService::kStorageMode, mode);
    249     }
    250     if (security) {
    251       AddStringParameterToStorage(
    252           profile_storage, id, WiFiService::kStorageSecurity, security);
    253     }
    254     if (provide_hidden) {
    255       EXPECT_CALL(*profile_storage, GetBool(id, kWifiHiddenSsid, _))
    256           .WillRepeatedly(
    257               DoAll(SetArgumentPointee<2>(is_hidden), Return(true)));
    258     } else {
    259       EXPECT_CALL(*profile_storage, GetBool(id, kWifiHiddenSsid, _))
    260           .WillRepeatedly(Return(false));
    261     }
    262     storage_entry_index_++;
    263     return id;
    264   }
    265 
    266   void SetServiceParameters(const char* ssid,
    267                             const char* mode,
    268                             const char* security_class,
    269                             bool is_hidden,
    270                             bool provide_hidden,
    271                             KeyValueStore* args) {
    272     args->SetString(kTypeProperty, kTypeWifi);
    273     if (ssid) {
    274       // TODO(pstew): When Chrome switches to using kWifiHexSsid primarily for
    275       // GetService and friends, we should switch to doing so here ourselves.
    276       args->SetString(kSSIDProperty, ssid);
    277     }
    278     if (mode) {
    279       args->SetString(kModeProperty, mode);
    280     }
    281     if (security_class) {
    282       args->SetString(kSecurityClassProperty, security_class);
    283     }
    284     if (provide_hidden) {
    285       args->SetBool(kWifiHiddenSsid, is_hidden);
    286     }
    287   }
    288 
    289   ServiceRefPtr CreateTemporaryService(const char* ssid,
    290                                        const char* mode,
    291                                        const char* security,
    292                                        bool is_hidden,
    293                                        bool provide_hidden,
    294                                        Error* error) {
    295     KeyValueStore args;
    296     SetServiceParameters(
    297         ssid, mode, security, is_hidden, provide_hidden, &args);
    298     return provider_.CreateTemporaryService(args, error);
    299   }
    300 
    301   WiFiServiceRefPtr GetService(const char* ssid,
    302                                const char* mode,
    303                                const char* security_class,
    304                                bool is_hidden,
    305                                bool provide_hidden,
    306                                Error* error) {
    307     KeyValueStore args;
    308     SetServiceParameters(
    309         ssid, mode, security_class, is_hidden, provide_hidden, &args);
    310     return provider_.GetWiFiService(args, error);
    311   }
    312 
    313   WiFiServiceRefPtr GetWiFiService(const KeyValueStore& args, Error* error) {
    314     return provider_.GetWiFiService(args, error);
    315   }
    316 
    317   WiFiServiceRefPtr FindService(const vector<uint8_t>& ssid,
    318                                 const string& mode,
    319                                 const string& security) {
    320     return provider_.FindService(ssid, mode, security);
    321   }
    322   WiFiEndpointRefPtr MakeEndpoint(const string& ssid, const string& bssid,
    323                                   uint16_t frequency, int16_t signal_dbm) {
    324     return WiFiEndpoint::MakeOpenEndpoint(
    325         nullptr, nullptr, ssid, bssid,
    326         WPASupplicant::kNetworkModeInfrastructure, frequency, signal_dbm);
    327   }
    328   MockWiFiServiceRefPtr AddMockService(const vector<uint8_t>& ssid,
    329                                        const string& mode,
    330                                        const string& security,
    331                                        bool hidden_ssid) {
    332     MockWiFiServiceRefPtr service = new MockWiFiService(
    333         &control_,
    334         &dispatcher_,
    335         &metrics_,
    336         &manager_,
    337         &provider_,
    338         ssid,
    339         mode,
    340         security,
    341         hidden_ssid);
    342     provider_.services_.push_back(service);
    343     return service;
    344   }
    345   void AddEndpointToService(WiFiServiceRefPtr service,
    346                             const WiFiEndpointConstRefPtr& endpoint) {
    347     provider_.service_by_endpoint_[endpoint.get()] = service;
    348   }
    349 
    350   void BuildFreqCountStrings(vector<string>* strings) {
    351     // NOTE: These strings match the frequencies in |BuildFreqCountMap|.  They
    352     // are also provided, here, in sorted order to match the frequency map
    353     // (iterators for which will provide them in frequency-sorted order).
    354     static const char* kStrings[] = {
    355       "@20", "5180:14", "5240:16", "5745:7", "5765:4", "5785:14", "5805:5"
    356     };
    357     if (!strings) {
    358       LOG(ERROR) << "NULL |strings|.";
    359       return;
    360     }
    361     for (size_t i = 0; i < arraysize(kStrings); ++i) {
    362       (*strings).push_back(kStrings[i]);
    363     }
    364   }
    365 
    366   void BuildFreqCountMap(WiFiProvider::ConnectFrequencyMap* frequencies) {
    367     // NOTE: These structures match the strings in |BuildFreqCountStrings|.
    368     static const struct FreqCount {
    369       uint16_t freq;
    370       int64_t count;
    371     } kConnectFreq[] = {
    372       {5180, 14},
    373       {5240, 16},
    374       {5745, 7},
    375       {5765, 4},
    376       {5785, 14},
    377       {5805, 5}
    378     };
    379     if (!frequencies) {
    380       LOG(ERROR) << "NULL |frequencies|.";
    381       return;
    382     }
    383     for (size_t i = 0; i < arraysize(kConnectFreq); ++i) {
    384       (*frequencies)[kConnectFreq[i].freq] = kConnectFreq[i].count;
    385     }
    386   }
    387 
    388   void LoadConnectCountByFrequency(time_t today_seconds) {
    389     provider_.time_ = &time_;
    390     EXPECT_CALL(time_, GetSecondsSinceEpoch()).WillOnce(Return(today_seconds));
    391     const string kGroupId =
    392         StringPrintf("%s_0_0_%s_%s", kTypeWifi, kModeManaged, kSecurityNone);
    393     EXPECT_CALL(default_profile_storage_,
    394                 GetString(kGroupId, _, _)).WillRepeatedly(Return(true));
    395     set<string> groups;
    396     groups.insert(kGroupId);
    397     EXPECT_CALL(default_profile_storage_, GetGroups()).WillOnce(Return(groups));
    398     // Provide data for block[0] through block[2] (block[3] is empty).
    399     EXPECT_CALL(
    400         default_profile_storage_,
    401         GetStringList(
    402             WiFiProvider::kStorageId,
    403             StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 0), _)).
    404         WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
    405     EXPECT_CALL(
    406         default_profile_storage_,
    407         GetStringList(
    408             WiFiProvider::kStorageId,
    409             StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 1), _)).
    410         WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
    411     EXPECT_CALL(
    412         default_profile_storage_,
    413         GetStringList(
    414             WiFiProvider::kStorageId,
    415             StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 2), _)).
    416         WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
    417     EXPECT_CALL(
    418         default_profile_storage_,
    419         GetStringList(
    420             WiFiProvider::kStorageId,
    421             StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 3), _)).
    422         WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
    423 
    424     LoadAndFixupServiceEntries(default_profile_.get());
    425   }
    426 
    427   map<string, vector<string>> profile_frequency_data_;
    428   NiceMockControl control_;
    429   MockEventDispatcher dispatcher_;
    430   MockMetrics metrics_;
    431   MockTime time_;
    432   StrictMock<MockManager> manager_;
    433   WiFiProvider provider_;
    434   scoped_refptr<MockProfile> default_profile_;
    435   scoped_refptr<MockProfile> user_profile_;
    436   StrictMock<MockStore> default_profile_storage_;
    437   StrictMock<MockStore> user_profile_storage_;
    438   int storage_entry_index_;  // shared across profiles
    439 };
    440 
    441 MATCHER(TypeWiFiPropertyMatch, "") {
    442   return arg.properties().size() == 1 &&
    443       arg.LookupString(kTypeProperty, "") == kTypeWifi;
    444 }
    445 
    446 MATCHER_P(RefPtrMatch, ref, "") {
    447   return ref.get() == arg.get();
    448 }
    449 
    450 TEST_F(WiFiProviderTest, Start) {
    451   // Doesn't do anything really.  Just testing for no crash.
    452   EXPECT_TRUE(GetServices().empty());
    453   EXPECT_FALSE(GetRunning());
    454   provider_.Start();
    455   EXPECT_TRUE(GetServices().empty());
    456   EXPECT_TRUE(GetRunning());
    457   EXPECT_TRUE(GetServiceByEndpoint().empty());
    458   EXPECT_FALSE(provider_.disable_vht());
    459 }
    460 
    461 TEST_F(WiFiProviderTest, Stop) {
    462   MockWiFiServiceRefPtr service0 = AddMockService(vector<uint8_t>(1, '0'),
    463                                                   kModeManaged,
    464                                                   kSecurityNone,
    465                                                   false);
    466   MockWiFiServiceRefPtr service1 = AddMockService(vector<uint8_t>(1, '1'),
    467                                                   kModeManaged,
    468                                                   kSecurityNone,
    469                                                   false);
    470   WiFiEndpointRefPtr endpoint = MakeEndpoint("", "00:00:00:00:00:00", 0, 0);
    471   AddEndpointToService(service0, endpoint);
    472 
    473   EXPECT_EQ(2, GetServices().size());
    474   EXPECT_FALSE(GetServiceByEndpoint().empty());
    475   EXPECT_CALL(*service0, ResetWiFi()).Times(1);
    476   EXPECT_CALL(*service1, ResetWiFi()).Times(1);
    477   EXPECT_CALL(manager_, DeregisterService(RefPtrMatch(service0))).Times(1);
    478   EXPECT_CALL(manager_, DeregisterService(RefPtrMatch(service1))).Times(1);
    479   provider_.Stop();
    480   // Verify now, so it's clear that this happened as a result of the call
    481   // above, and not anything in the destructor(s).
    482   Mock::VerifyAndClearExpectations(service0.get());
    483   Mock::VerifyAndClearExpectations(service1.get());
    484   Mock::VerifyAndClearExpectations(&manager_);
    485   EXPECT_TRUE(GetServices().empty());
    486   EXPECT_TRUE(GetServiceByEndpoint().empty());
    487 }
    488 
    489 TEST_F(WiFiProviderTest, CreateServicesFromProfileWithNoGroups) {
    490   EXPECT_CALL(default_profile_storage_,
    491               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    492       .WillOnce(Return(set<string>()));
    493   EXPECT_CALL(metrics_, SendToUMA(
    494       Metrics::kMetricRememberedWiFiNetworkCount,
    495       0,
    496       Metrics::kMetricRememberedWiFiNetworkCountMin,
    497       Metrics::kMetricRememberedWiFiNetworkCountMax,
    498       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    499   CreateServicesFromProfile(default_profile_.get());
    500   EXPECT_TRUE(GetServices().empty());
    501 }
    502 
    503 TEST_F(WiFiProviderTest, CreateServicesFromProfileMissingSSID) {
    504   set<string> groups;
    505   groups.insert(
    506       AddServiceToProfileStorage(
    507           default_profile_.get(), nullptr, kModeManaged, kSecurityNone, false,
    508           true));
    509   EXPECT_CALL(default_profile_storage_,
    510               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    511       .WillRepeatedly(Return(groups));
    512   EXPECT_CALL(metrics_, SendToUMA(
    513       Metrics::kMetricRememberedWiFiNetworkCount,
    514       0,
    515       Metrics::kMetricRememberedWiFiNetworkCountMin,
    516       Metrics::kMetricRememberedWiFiNetworkCountMax,
    517       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    518   CreateServicesFromProfile(default_profile_.get());
    519   EXPECT_TRUE(GetServices().empty());
    520 }
    521 
    522 TEST_F(WiFiProviderTest, CreateServicesFromProfileEmptySSID) {
    523   set<string> groups;
    524   groups.insert(
    525       AddServiceToProfileStorage(
    526           default_profile_.get(), "", kModeManaged, kSecurityNone, false,
    527           true));
    528   EXPECT_CALL(default_profile_storage_,
    529               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    530       .WillRepeatedly(Return(groups));
    531   EXPECT_CALL(metrics_, SendToUMA(
    532       Metrics::kMetricRememberedWiFiNetworkCount,
    533       0,
    534       Metrics::kMetricRememberedWiFiNetworkCountMin,
    535       Metrics::kMetricRememberedWiFiNetworkCountMax,
    536       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    537   CreateServicesFromProfile(default_profile_.get());
    538   EXPECT_TRUE(GetServices().empty());
    539 }
    540 
    541 TEST_F(WiFiProviderTest, CreateServicesFromProfileMissingMode) {
    542   set<string> groups;
    543   groups.insert(
    544       AddServiceToProfileStorage(
    545           default_profile_.get(), "foo", nullptr, kSecurityNone, false, true));
    546   EXPECT_CALL(default_profile_storage_,
    547               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    548       .WillRepeatedly(Return(groups));
    549   EXPECT_CALL(metrics_, SendToUMA(
    550       Metrics::kMetricRememberedWiFiNetworkCount,
    551       0,
    552       Metrics::kMetricRememberedWiFiNetworkCountMin,
    553       Metrics::kMetricRememberedWiFiNetworkCountMax,
    554       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    555   CreateServicesFromProfile(default_profile_.get());
    556   EXPECT_TRUE(GetServices().empty());
    557 }
    558 
    559 TEST_F(WiFiProviderTest, CreateServicesFromProfileEmptyMode) {
    560   set<string> groups;
    561   groups.insert(
    562       AddServiceToProfileStorage(
    563           default_profile_.get(), "foo", "", kSecurityNone, false, true));
    564   EXPECT_CALL(default_profile_storage_,
    565               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    566       .WillRepeatedly(Return(groups));
    567   EXPECT_CALL(metrics_, SendToUMA(
    568       Metrics::kMetricRememberedWiFiNetworkCount,
    569       0,
    570       Metrics::kMetricRememberedWiFiNetworkCountMin,
    571       Metrics::kMetricRememberedWiFiNetworkCountMax,
    572       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    573   CreateServicesFromProfile(default_profile_.get());
    574   EXPECT_TRUE(GetServices().empty());
    575 }
    576 
    577 TEST_F(WiFiProviderTest, CreateServicesFromProfileMissingSecurity) {
    578   set<string> groups;
    579   groups.insert(
    580       AddServiceToProfileStorage(
    581           default_profile_.get(), "foo", kModeManaged, nullptr, false, true));
    582   EXPECT_CALL(default_profile_storage_,
    583               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    584       .WillRepeatedly(Return(groups));
    585   EXPECT_CALL(metrics_, SendToUMA(
    586       Metrics::kMetricRememberedWiFiNetworkCount,
    587       0,
    588       Metrics::kMetricRememberedWiFiNetworkCountMin,
    589       Metrics::kMetricRememberedWiFiNetworkCountMax,
    590       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    591   CreateServicesFromProfile(default_profile_.get());
    592   EXPECT_TRUE(GetServices().empty());
    593 }
    594 
    595 TEST_F(WiFiProviderTest, CreateServicesFromProfileEmptySecurity) {
    596   set<string> groups;
    597   groups.insert(
    598       AddServiceToProfileStorage(
    599           default_profile_.get(), "foo", kModeManaged, "", false, true));
    600   EXPECT_CALL(default_profile_storage_,
    601               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    602       .WillRepeatedly(Return(groups));
    603   EXPECT_CALL(metrics_, SendToUMA(
    604       Metrics::kMetricRememberedWiFiNetworkCount,
    605       0,
    606       Metrics::kMetricRememberedWiFiNetworkCountMin,
    607       Metrics::kMetricRememberedWiFiNetworkCountMax,
    608       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    609   CreateServicesFromProfile(default_profile_.get());
    610   EXPECT_TRUE(GetServices().empty());
    611 }
    612 
    613 TEST_F(WiFiProviderTest, CreateServicesFromProfileMissingHidden) {
    614   set<string> groups;
    615   groups.insert(
    616       AddServiceToProfileStorage(
    617           default_profile_.get(), "foo", kModeManaged, kSecurityNone, false,
    618           false));
    619   EXPECT_CALL(default_profile_storage_,
    620               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    621       .WillRepeatedly(Return(groups));
    622   EXPECT_CALL(metrics_, SendToUMA(
    623       Metrics::kMetricRememberedWiFiNetworkCount,
    624       0,
    625       Metrics::kMetricRememberedWiFiNetworkCountMin,
    626       Metrics::kMetricRememberedWiFiNetworkCountMax,
    627       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    628   CreateServicesFromProfile(default_profile_.get());
    629   EXPECT_TRUE(GetServices().empty());
    630 }
    631 
    632 TEST_F(WiFiProviderTest, CreateServicesFromProfileSingle) {
    633   set<string> groups;
    634   string kSSID("foo");
    635   groups.insert(
    636       AddServiceToProfileStorage(
    637           default_profile_.get(),
    638           kSSID.c_str(), kModeManaged, kSecurityNone, false, true));
    639   EXPECT_CALL(default_profile_storage_,
    640               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    641       .WillRepeatedly(Return(groups));
    642   EXPECT_CALL(manager_, RegisterService(_))
    643       .WillOnce(Invoke(this, &WiFiProviderTest::BindServiceToDefaultProfile));
    644   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    645   EXPECT_CALL(metrics_, SendToUMA(
    646       Metrics::kMetricRememberedWiFiNetworkCount,
    647       1,
    648       Metrics::kMetricRememberedWiFiNetworkCountMin,
    649       Metrics::kMetricRememberedWiFiNetworkCountMax,
    650       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets)).Times(2);
    651   CreateServicesFromProfile(default_profile_.get());
    652   Mock::VerifyAndClearExpectations(&manager_);
    653   EXPECT_EQ(1, GetServices().size());
    654 
    655   const WiFiServiceRefPtr service = GetServices().front();
    656   const string service_ssid(service->ssid().begin(), service->ssid().end());
    657   EXPECT_EQ(kSSID, service_ssid);
    658   EXPECT_EQ(kModeManaged, service->mode());
    659   EXPECT_TRUE(service->IsSecurityMatch(kSecurityNone));
    660 
    661   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
    662   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    663   CreateServicesFromProfile(default_profile_.get());
    664   EXPECT_EQ(1, GetServices().size());
    665 }
    666 
    667 TEST_F(WiFiProviderTest, CreateServicesFromProfileHiddenButConnected) {
    668   set<string> groups;
    669   string kSSID("foo");
    670   groups.insert(
    671       AddServiceToProfileStorage(
    672           default_profile_.get(),
    673           kSSID.c_str(), kModeManaged, kSecurityNone, true, true));
    674   EXPECT_CALL(default_profile_storage_,
    675               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    676       .WillRepeatedly(Return(groups));
    677   EXPECT_CALL(manager_, RegisterService(_))
    678       .WillOnce(Invoke(this, &WiFiProviderTest::BindServiceToDefaultProfile));
    679   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    680   EXPECT_CALL(manager_, IsTechnologyConnected(Technology::kWifi))
    681       .WillOnce(Return(true));
    682   EXPECT_CALL(manager_, RequestScan(_, _, _)).Times(0);
    683   EXPECT_CALL(metrics_, SendToUMA(
    684       Metrics::kMetricRememberedWiFiNetworkCount,
    685       1,
    686       Metrics::kMetricRememberedWiFiNetworkCountMin,
    687       Metrics::kMetricRememberedWiFiNetworkCountMax,
    688       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets)).Times(2);
    689   CreateServicesFromProfile(default_profile_.get());
    690   Mock::VerifyAndClearExpectations(&manager_);
    691 
    692   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
    693   EXPECT_CALL(manager_, IsTechnologyConnected(_)).Times(0);
    694   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    695   CreateServicesFromProfile(default_profile_.get());
    696 }
    697 
    698 TEST_F(WiFiProviderTest, CreateServicesFromProfileHiddenNotConnected) {
    699   set<string> groups;
    700   string kSSID("foo");
    701   groups.insert(AddServiceToProfileStorage(default_profile_.get(),
    702       kSSID.c_str(), kModeManaged, kSecurityNone, true, true));
    703   EXPECT_CALL(default_profile_storage_,
    704               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    705       .WillRepeatedly(Return(groups));
    706   EXPECT_CALL(manager_, RegisterService(_))
    707       .WillOnce(Invoke(this, &WiFiProviderTest::BindServiceToDefaultProfile));
    708   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    709   EXPECT_CALL(manager_, IsTechnologyConnected(Technology::kWifi))
    710       .WillOnce(Return(false));
    711   EXPECT_CALL(manager_, RequestScan(Device::kProgressiveScan,
    712                                     kTypeWifi, _)).Times(1);
    713   EXPECT_CALL(metrics_, SendToUMA(
    714       Metrics::kMetricRememberedWiFiNetworkCount,
    715       1,
    716       Metrics::kMetricRememberedWiFiNetworkCountMin,
    717       Metrics::kMetricRememberedWiFiNetworkCountMax,
    718       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets)).Times(2);
    719   CreateServicesFromProfile(default_profile_.get());
    720   Mock::VerifyAndClearExpectations(&manager_);
    721 
    722   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
    723   EXPECT_CALL(manager_, IsTechnologyConnected(_)).Times(0);
    724   EXPECT_CALL(manager_, RequestScan(_, _, _)).Times(0);
    725   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    726   CreateServicesFromProfile(default_profile_.get());
    727 }
    728 
    729 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfileNonWiFi) {
    730   const string kEntryName("name");
    731   auto profile_storage =
    732       static_cast<MockStore*>(default_profile_->GetStorage());
    733   EXPECT_CALL(*profile_storage,
    734               GetString(kEntryName, WiFiService::kStorageType, _))
    735       .WillOnce(Return(false));
    736   Error error;
    737   EXPECT_EQ(nullptr,
    738             provider_.CreateTemporaryServiceFromProfile(
    739                 default_profile_, kEntryName, &error));
    740   EXPECT_FALSE(error.IsSuccess());
    741   EXPECT_THAT(error.message(),
    742               StartsWith("Unspecified or invalid network type"));
    743 }
    744 
    745 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfileMissingSSID) {
    746   string entry_name = AddServiceToProfileStorage(
    747           default_profile_.get(), nullptr, kModeManaged, kSecurityNone, false,
    748           true);
    749   Error error;
    750   EXPECT_EQ(nullptr,
    751             provider_.CreateTemporaryServiceFromProfile(
    752                 default_profile_, entry_name, &error));
    753   EXPECT_FALSE(error.IsSuccess());
    754   EXPECT_THAT(error.message(), StartsWith("Unspecified or invalid SSID"));
    755 }
    756 
    757 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfileMissingMode) {
    758   string entry_name = AddServiceToProfileStorage(
    759       default_profile_.get(), "foo", "", kSecurityNone, false, true);
    760 
    761   Error error;
    762   EXPECT_EQ(nullptr,
    763             provider_.CreateTemporaryServiceFromProfile(
    764                 default_profile_, entry_name, &error));
    765   EXPECT_FALSE(error.IsSuccess());
    766   EXPECT_THAT(error.message(), StartsWith("Network mode not specified"));
    767 }
    768 
    769 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfileMissingSecurity) {
    770   string entry_name = AddServiceToProfileStorage(
    771       default_profile_.get(), "foo", kModeManaged, "", false, true);
    772 
    773   Error error;
    774   EXPECT_EQ(nullptr,
    775             provider_.CreateTemporaryServiceFromProfile(
    776                 default_profile_, entry_name, &error));
    777   EXPECT_FALSE(error.IsSuccess());
    778   EXPECT_THAT(error.message(),
    779               StartsWith("Unspecified or invalid security mode"));
    780 }
    781 
    782 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfileMissingHidden) {
    783   string entry_name = AddServiceToProfileStorage(
    784       default_profile_.get(), "foo", kModeManaged, kSecurityNone, false, false);
    785 
    786   Error error;
    787   EXPECT_EQ(nullptr,
    788             provider_.CreateTemporaryServiceFromProfile(
    789                 default_profile_, entry_name, &error));
    790   EXPECT_FALSE(error.IsSuccess());
    791   EXPECT_THAT(error.message(),
    792               StartsWith("Hidden SSID not specified"));
    793 }
    794 
    795 TEST_F(WiFiProviderTest, CreateTemporaryServiceFromProfile) {
    796   string entry_name = AddServiceToProfileStorage(
    797       default_profile_.get(), "foo", kModeManaged, kSecurityNone, false, true);
    798 
    799   Error error;
    800   EXPECT_NE(nullptr,
    801             provider_.CreateTemporaryServiceFromProfile(
    802                 default_profile_, entry_name, &error));
    803   EXPECT_TRUE(error.IsSuccess());
    804 }
    805 
    806 TEST_F(WiFiProviderTest, CreateTwoServices) {
    807   set<string> groups;
    808   groups.insert(
    809       AddServiceToProfileStorage(
    810           default_profile_.get(), "foo", kModeManaged, kSecurityNone, false,
    811           true));
    812   groups.insert(
    813       AddServiceToProfileStorage(
    814           default_profile_.get(), "bar", kModeManaged, kSecurityNone, true,
    815           true));
    816   EXPECT_CALL(default_profile_storage_,
    817               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    818       .WillRepeatedly(Return(groups));
    819   EXPECT_CALL(manager_, RegisterService(_))
    820       .Times(2)
    821       .WillRepeatedly(
    822           Invoke(this, &WiFiProviderTest::BindServiceToDefaultProfile));
    823   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    824   EXPECT_CALL(manager_, IsTechnologyConnected(Technology::kWifi))
    825       .WillOnce(Return(true));
    826   EXPECT_CALL(manager_, RequestScan(_, kTypeWifi, _)).Times(0);
    827   EXPECT_CALL(metrics_, SendToUMA(
    828       Metrics::kMetricRememberedWiFiNetworkCount,
    829       2,
    830       Metrics::kMetricRememberedWiFiNetworkCountMin,
    831       Metrics::kMetricRememberedWiFiNetworkCountMax,
    832       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    833   CreateServicesFromProfile(default_profile_.get());
    834   Mock::VerifyAndClearExpectations(&manager_);
    835 
    836   EXPECT_EQ(2, GetServices().size());
    837 }
    838 
    839 TEST_F(WiFiProviderTest, ServiceSourceStats) {
    840   set<string> default_profile_groups;
    841   default_profile_groups.insert(
    842       AddServiceToProfileStorage(
    843           default_profile_.get(), "foo", kModeManaged, kSecurityWpa, false,
    844           true));
    845   EXPECT_CALL(default_profile_storage_,
    846               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    847       .WillRepeatedly(Return(default_profile_groups));
    848   EXPECT_CALL(manager_, RegisterService(_))
    849       .WillOnce(Invoke(this, &WiFiProviderTest::BindServiceToDefaultProfile));
    850   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    851   // Processing default profile does not generate UMA metrics.
    852   EXPECT_CALL(metrics_, SendToUMA(
    853       StartsWith("Network.Shill.WiFi.RememberedSystemNetworkCount."),
    854       _, _, _, _))
    855       .Times(0);
    856   EXPECT_CALL(metrics_, SendToUMA(
    857       StartsWith("Network.Shill.WiFi.RememberedUserNetworkCount."),
    858       _, _, _, _))
    859       .Times(0);
    860   CreateServicesFromProfile(default_profile_.get());
    861   Mock::VerifyAndClearExpectations(&manager_);
    862 
    863   set<string> user_profile_groups;
    864   user_profile_groups.insert(
    865       AddServiceToProfileStorage(
    866           user_profile_.get(), "bar", kModeManaged, kSecurityRsn, false, true));
    867   EXPECT_CALL(user_profile_storage_,
    868               GetGroupsWithProperties(TypeWiFiPropertyMatch()))
    869       .WillRepeatedly(Return(user_profile_groups));
    870   EXPECT_CALL(manager_, RegisterService(_))
    871       .WillOnce(Invoke(this, &WiFiProviderTest::BindServiceToUserProfile));
    872   EXPECT_CALL(manager_, IsServiceEphemeral(_)).WillRepeatedly(Return(false));
    873   // Processing user profile generates metrics for both, default profile,
    874   // and user profile.
    875   EXPECT_CALL(metrics_, SendToUMA(
    876       StartsWith("Network.Shill.WiFi.RememberedSystemNetworkCount."),
    877       0,
    878       Metrics::kMetricRememberedWiFiNetworkCountMin,
    879       Metrics::kMetricRememberedWiFiNetworkCountMax,
    880       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets))
    881       .Times(3);  // none, wep, 802.1x
    882   EXPECT_CALL(metrics_, SendToUMA(
    883       StartsWith("Network.Shill.WiFi.RememberedUserNetworkCount."),
    884       0,
    885       Metrics::kMetricRememberedWiFiNetworkCountMin,
    886       Metrics::kMetricRememberedWiFiNetworkCountMax,
    887       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets))
    888       .Times(3);  // none, wep, 802.1x
    889   EXPECT_CALL(metrics_, SendToUMA(
    890       StartsWith("Network.Shill.WiFi.RememberedSystemNetworkCount.psk"),
    891       1,
    892       Metrics::kMetricRememberedWiFiNetworkCountMin,
    893       Metrics::kMetricRememberedWiFiNetworkCountMax,
    894       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    895   EXPECT_CALL(metrics_, SendToUMA(
    896       StartsWith("Network.Shill.WiFi.RememberedUserNetworkCount.psk"),
    897       1,
    898       Metrics::kMetricRememberedWiFiNetworkCountMin,
    899       Metrics::kMetricRememberedWiFiNetworkCountMax,
    900       Metrics::kMetricRememberedWiFiNetworkCountNumBuckets));
    901   CreateServicesFromProfile(user_profile_.get());
    902 }
    903 
    904 TEST_F(WiFiProviderTest, GetServiceEmptyMode) {
    905   Error error;
    906   EXPECT_FALSE(GetService("foo", "", kSecurityNone,
    907                           false, false, &error).get());
    908   EXPECT_EQ(Error::kNotSupported, error.type());
    909 }
    910 
    911 TEST_F(WiFiProviderTest, GetServiceNoMode) {
    912   Error error;
    913   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
    914   EXPECT_TRUE(GetService("foo", nullptr, kSecurityNone,
    915                           false, false, &error).get());
    916   EXPECT_TRUE(error.IsSuccess());
    917 }
    918 
    919 TEST_F(WiFiProviderTest, GetServiceBadMode) {
    920   Error error;
    921   EXPECT_FALSE(GetService("foo", "BogoMesh",
    922                           kSecurityNone,
    923                           false, false, &error).get());
    924   EXPECT_EQ(Error::kNotSupported, error.type());
    925   EXPECT_EQ("service mode is unsupported", error.message());
    926 }
    927 
    928 TEST_F(WiFiProviderTest, GetServiceNoSSID) {
    929   Error error;
    930   EXPECT_FALSE(GetService(nullptr, kModeManaged,
    931                           kSecurityNone, false, false,
    932                           &error).get());
    933   EXPECT_EQ(Error::kInvalidArguments, error.type());
    934   EXPECT_EQ("must specify SSID", error.message());
    935 }
    936 
    937 TEST_F(WiFiProviderTest, GetServiceEmptySSID) {
    938   Error error;
    939   EXPECT_FALSE(GetService("", kModeManaged,
    940                           kSecurityNone, false, false,
    941                           &error).get());
    942   EXPECT_EQ(Error::kInvalidNetworkName, error.type());
    943   EXPECT_EQ("SSID is too short", error.message());
    944 }
    945 
    946 TEST_F(WiFiProviderTest, GetServiceLongSSID) {
    947   Error error;
    948   string ssid(IEEE_80211::kMaxSSIDLen + 1, '0');
    949   EXPECT_FALSE(GetService(ssid.c_str(), kModeManaged,
    950                           kSecurityNone, false, false,
    951                           &error).get());
    952   EXPECT_EQ(Error::kInvalidNetworkName, error.type());
    953   EXPECT_EQ("SSID is too long", error.message());
    954 }
    955 
    956 TEST_F(WiFiProviderTest, GetServiceJustLongEnoughSSID) {
    957   Error error;
    958   string ssid(IEEE_80211::kMaxSSIDLen, '0');
    959   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
    960   EXPECT_TRUE(GetService(ssid.c_str(), kModeManaged,
    961                          kSecurityNone, false, false,
    962                          &error));
    963   EXPECT_TRUE(error.IsSuccess());
    964 }
    965 
    966 TEST_F(WiFiProviderTest, GetServiceBadSecurityClass) {
    967   Error error;
    968   EXPECT_FALSE(GetService("foo", kModeManaged,
    969                           kSecurityRsn, false, false,
    970                           &error));
    971   EXPECT_EQ(Error::kNotSupported, error.type());
    972   EXPECT_EQ("security class is unsupported", error.message());
    973 }
    974 
    975 TEST_F(WiFiProviderTest, GetServiceMinimal) {
    976   Error error;
    977   const string kSSID("foo");
    978   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
    979   WiFiServiceRefPtr service = GetService(kSSID.c_str(), kModeManaged,
    980                                          nullptr, false, false, &error);
    981   EXPECT_TRUE(service.get());
    982   EXPECT_TRUE(error.IsSuccess());
    983   const string service_ssid(service->ssid().begin(), service->ssid().end());
    984   EXPECT_EQ(kSSID, service_ssid);
    985   EXPECT_EQ(kModeManaged, service->mode());
    986 
    987   // These two should be set to their default values if not specified.
    988   EXPECT_TRUE(service->IsSecurityMatch(kSecurityNone));
    989   EXPECT_TRUE(service->hidden_ssid());
    990 }
    991 
    992 TEST_F(WiFiProviderTest, GetServiceFullySpecified) {
    993   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
    994   const string kSSID("bar");
    995   Error error;
    996   WiFiServiceRefPtr service0 = GetService(
    997       kSSID.c_str(), kModeManaged, kSecurityPsk, false, true, &error);
    998   Mock::VerifyAndClearExpectations(&manager_);
    999   EXPECT_TRUE(error.IsSuccess());
   1000   const string service_ssid(service0->ssid().begin(), service0->ssid().end());
   1001   EXPECT_EQ(kSSID, service_ssid);
   1002   EXPECT_EQ(kModeManaged, service0->mode());
   1003   EXPECT_TRUE(service0->IsSecurityMatch(kSecurityPsk));
   1004   EXPECT_FALSE(service0->hidden_ssid());
   1005 
   1006   // Getting the same service parameters (even with a different hidden
   1007   // parameter) should return the same service.
   1008   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1009   WiFiServiceRefPtr service1 =
   1010       GetService(kSSID.c_str(), kModeManaged, kSecurityPsk, true, true, &error);
   1011   Mock::VerifyAndClearExpectations(&manager_);
   1012   EXPECT_EQ(service0.get(), service1.get());
   1013   EXPECT_EQ(1, GetServices().size());
   1014 
   1015   // Getting the same ssid with different other parameters should return
   1016   // a different service.
   1017   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1018   WiFiServiceRefPtr service2 = GetService(
   1019       kSSID.c_str(), kModeManaged, kSecurityNone, true, true, &error);
   1020   Mock::VerifyAndClearExpectations(&manager_);
   1021   EXPECT_NE(service0.get(), service2.get());
   1022   EXPECT_EQ(2, GetServices().size());
   1023 }
   1024 
   1025 TEST_F(WiFiProviderTest, GetServiceByHexSsid) {
   1026   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1027   const string kSSID("bar");
   1028   const string kHexSsid(base::HexEncode(kSSID.c_str(), kSSID.length()));
   1029 
   1030   KeyValueStore args;
   1031   args.SetString(kTypeProperty, kTypeWifi);
   1032   args.SetString(kWifiHexSsid, kHexSsid);
   1033   args.SetString(kSecurityProperty, kSecurityPsk);
   1034   args.SetBool(kWifiHiddenSsid, false);
   1035 
   1036   Error error;
   1037   WiFiServiceRefPtr service = GetWiFiService(args, &error);
   1038   Mock::VerifyAndClearExpectations(&manager_);
   1039   EXPECT_TRUE(error.IsSuccess());
   1040   const string service_ssid(service->ssid().begin(), service->ssid().end());
   1041   EXPECT_EQ(kSSID, service_ssid);
   1042   EXPECT_EQ(kModeManaged, service->mode());
   1043   EXPECT_TRUE(service->IsSecurityMatch(kSecurityPsk));
   1044   EXPECT_FALSE(service->hidden_ssid());
   1045 
   1046 
   1047   // While here, make sure FindSimilarService also supports kWifiHexSsid.
   1048   Error find_error;
   1049   ServiceRefPtr find_service = provider_.FindSimilarService(args, &find_error);
   1050   EXPECT_TRUE(find_error.IsSuccess());
   1051   EXPECT_EQ(service.get(), find_service.get());
   1052 }
   1053 
   1054 TEST_F(WiFiProviderTest, GetServiceWithSecurityAndSecurityClassMismatched) {
   1055   const string kSSID("bar");
   1056   KeyValueStore args;
   1057   args.SetString(kTypeProperty, kTypeWifi);
   1058   args.SetString(kSSIDProperty, kSSID);
   1059   args.SetString(kSecurityProperty, kSecurityRsn);
   1060   args.SetString(kSecurityClassProperty, kSecurityPsk);
   1061   args.SetBool(kWifiHiddenSsid, false);
   1062 
   1063   Error error;
   1064   WiFiServiceRefPtr service;
   1065   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1066   service = GetWiFiService(args, &error);
   1067   EXPECT_FALSE(error.IsSuccess());
   1068 }
   1069 
   1070 TEST_F(WiFiProviderTest, GetServiceWithSecurityAndSecurityClassMatching) {
   1071   const string kSSID("bar");
   1072   KeyValueStore args;
   1073   args.SetString(kTypeProperty, kTypeWifi);
   1074   args.SetString(kSSIDProperty, kSSID);
   1075   args.SetString(kSecurityProperty, kSecurityPsk);
   1076   args.SetString(kSecurityClassProperty, kSecurityPsk);
   1077   args.SetBool(kWifiHiddenSsid, false);
   1078 
   1079   Error error;
   1080   WiFiServiceRefPtr service;
   1081   EXPECT_CALL(manager_, RegisterService(_));
   1082   service = GetWiFiService(args, &error);
   1083   EXPECT_TRUE(error.IsSuccess());
   1084 }
   1085 
   1086 TEST_F(WiFiProviderTest,
   1087        GetServiceWithSecurityAndSecurityClassMatchingButInvalidClass) {
   1088   const string kSSID("bar");
   1089   KeyValueStore args;
   1090   args.SetString(kTypeProperty, kTypeWifi);
   1091   args.SetString(kSSIDProperty, kSSID);
   1092   args.SetString(kSecurityProperty, kSecurityRsn);
   1093   args.SetString(kSecurityClassProperty, kSecurityRsn);
   1094   args.SetBool(kWifiHiddenSsid, false);
   1095   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1096 
   1097   Error error;
   1098   WiFiServiceRefPtr service = GetWiFiService(args, &error);
   1099   Mock::VerifyAndClearExpectations(&manager_);
   1100   EXPECT_FALSE(error.IsSuccess());
   1101 }
   1102 
   1103 TEST_F(WiFiProviderTest, GetServiceBadSecurity) {
   1104   const string kSSID("bar");
   1105   KeyValueStore args;
   1106   args.SetString(kTypeProperty, kTypeWifi);
   1107   args.SetString(kSSIDProperty, kSSID);
   1108   args.SetString(kSecurityProperty, "pig-80211");
   1109   args.SetBool(kWifiHiddenSsid, false);
   1110 
   1111   Error error;
   1112   WiFiServiceRefPtr service;
   1113   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1114   service = GetWiFiService(args, &error);
   1115   EXPECT_FALSE(error.IsSuccess());
   1116   EXPECT_EQ(Error::kNotSupported, error.type());
   1117   EXPECT_EQ("security mode is unsupported", error.message());
   1118 }
   1119 
   1120 TEST_F(WiFiProviderTest, FindSimilarService) {
   1121   // Since CreateTemporyService uses exactly the same validation as
   1122   // GetService, don't bother with testing invalid parameters.
   1123   const string kSSID("foo");
   1124   KeyValueStore args;
   1125   SetServiceParameters(
   1126       kSSID.c_str(), kModeManaged, kSecurityNone,
   1127       true, true, &args);
   1128   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1129   Error get_service_error;
   1130   WiFiServiceRefPtr service = GetWiFiService(args, &get_service_error);
   1131   EXPECT_EQ(1, GetServices().size());
   1132 
   1133   {
   1134     Error error;
   1135     ServiceRefPtr find_service = provider_.FindSimilarService(args, &error);
   1136     EXPECT_EQ(service.get(), find_service.get());
   1137     EXPECT_TRUE(error.IsSuccess());
   1138   }
   1139 
   1140   args.SetBool(kWifiHiddenSsid, false);
   1141 
   1142   {
   1143     Error error;
   1144     ServiceRefPtr find_service = provider_.FindSimilarService(args, &error);
   1145     EXPECT_EQ(service.get(), find_service.get());
   1146     EXPECT_TRUE(error.IsSuccess());
   1147   }
   1148 
   1149   args.SetString(kSecurityClassProperty, kSecurityPsk);
   1150 
   1151   {
   1152     Error error;
   1153     ServiceRefPtr find_service = provider_.FindSimilarService(args, &error);
   1154     EXPECT_EQ(nullptr, find_service.get());
   1155     EXPECT_EQ(Error::kNotFound, error.type());
   1156   }
   1157 }
   1158 
   1159 TEST_F(WiFiProviderTest, CreateTemporaryService) {
   1160   // Since CreateTemporyService uses exactly the same validation as
   1161   // GetService, don't bother with testing invalid parameters.
   1162   const string kSSID("foo");
   1163   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1164   Error error;
   1165   WiFiServiceRefPtr service0 = GetService(
   1166       kSSID.c_str(), kModeManaged, kSecurityNone, true, true, &error);
   1167   EXPECT_EQ(1, GetServices().size());
   1168   Mock::VerifyAndClearExpectations(&manager_);
   1169 
   1170   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1171   ServiceRefPtr service1 =
   1172       CreateTemporaryService(kSSID.c_str(), kModeManaged,
   1173                              kSecurityNone, true, true, &error);
   1174 
   1175   // Test that a new service was created, but not registered with the
   1176   // manager or added to the provider's service list.
   1177   EXPECT_EQ(1, GetServices().size());
   1178   EXPECT_TRUE(service0 != service1);
   1179   EXPECT_TRUE(service1->HasOneRef());
   1180 }
   1181 
   1182 TEST_F(WiFiProviderTest, FindServiceWPA) {
   1183   const string kSSID("an_ssid");
   1184   Error error;
   1185   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1186   KeyValueStore args;
   1187   SetServiceParameters(
   1188       kSSID.c_str(), kModeManaged, nullptr, false, false, &args);
   1189   args.SetString(kSecurityProperty, kSecurityRsn);
   1190   WiFiServiceRefPtr service = GetWiFiService(args, &error);
   1191   ASSERT_TRUE(service);
   1192   const vector<uint8_t> ssid_bytes(kSSID.begin(), kSSID.end());
   1193   WiFiServiceRefPtr wpa_service(FindService(ssid_bytes, kModeManaged,
   1194                                             kSecurityWpa));
   1195   EXPECT_TRUE(wpa_service);
   1196   EXPECT_EQ(service.get(), wpa_service.get());
   1197   WiFiServiceRefPtr rsn_service(FindService(ssid_bytes, kModeManaged,
   1198                                             kSecurityRsn));
   1199   EXPECT_TRUE(rsn_service.get());
   1200   EXPECT_EQ(service.get(), rsn_service.get());
   1201   WiFiServiceRefPtr psk_service(FindService(ssid_bytes, kModeManaged,
   1202                                             kSecurityPsk));
   1203   EXPECT_EQ(service.get(), psk_service.get());
   1204   WiFiServiceRefPtr wep_service(FindService(ssid_bytes, kModeManaged,
   1205                                             kSecurityWep));
   1206   EXPECT_TRUE(service.get() != wep_service.get());
   1207   EXPECT_EQ(nullptr, wep_service.get());
   1208 }
   1209 
   1210 TEST_F(WiFiProviderTest, FindServiceForEndpoint) {
   1211   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1212   Error error;
   1213   const string kSSID("an_ssid");
   1214   WiFiServiceRefPtr service = GetService(
   1215       kSSID.c_str(), kModeManaged, kSecurityNone, false, true, &error);
   1216   ASSERT_TRUE(service);
   1217   WiFiEndpointRefPtr endpoint = MakeEndpoint(kSSID, "00:00:00:00:00:00", 0, 0);
   1218   WiFiServiceRefPtr endpoint_service =
   1219       provider_.FindServiceForEndpoint(endpoint);
   1220   // Just because a matching service exists, we shouldn't necessarily have
   1221   // it returned.  We will test that this function returns the correct
   1222   // service if the endpoint is added below.
   1223   EXPECT_EQ(nullptr, endpoint_service.get());
   1224 }
   1225 
   1226 TEST_F(WiFiProviderTest, OnEndpointAdded) {
   1227   provider_.Start();
   1228   const string ssid0("an_ssid");
   1229   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1230   EXPECT_FALSE(FindService(ssid0_bytes, kModeManaged,
   1231                            kSecurityNone));
   1232   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1233   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1234   EXPECT_CALL(manager_, UpdateService(_)).Times(1);
   1235   provider_.OnEndpointAdded(endpoint0);
   1236   Mock::VerifyAndClearExpectations(&manager_);
   1237   EXPECT_EQ(1, GetServices().size());
   1238   WiFiServiceRefPtr service0(FindService(ssid0_bytes, kModeManaged,
   1239                                          kSecurityNone));
   1240   EXPECT_TRUE(service0);
   1241   EXPECT_TRUE(service0->HasEndpoints());
   1242   EXPECT_EQ(1, GetServiceByEndpoint().size());
   1243   WiFiServiceRefPtr endpoint_service =
   1244       provider_.FindServiceForEndpoint(endpoint0);
   1245   EXPECT_EQ(service0.get(), endpoint_service.get());
   1246 
   1247   WiFiEndpointRefPtr endpoint1 = MakeEndpoint(ssid0, "00:00:00:00:00:01", 0, 0);
   1248   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1249   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1250   provider_.OnEndpointAdded(endpoint1);
   1251   Mock::VerifyAndClearExpectations(&manager_);
   1252   EXPECT_EQ(1, GetServices().size());
   1253 
   1254   const string ssid1("another_ssid");
   1255   const vector<uint8_t> ssid1_bytes(ssid1.begin(), ssid1.end());
   1256   EXPECT_FALSE(FindService(ssid1_bytes, kModeManaged,
   1257                            kSecurityNone));
   1258   WiFiEndpointRefPtr endpoint2 = MakeEndpoint(ssid1, "00:00:00:00:00:02",
   1259                                               0, 0);
   1260   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1261   EXPECT_CALL(manager_, UpdateService(_)).Times(1);
   1262   provider_.OnEndpointAdded(endpoint2);
   1263   Mock::VerifyAndClearExpectations(&manager_);
   1264   EXPECT_EQ(2, GetServices().size());
   1265 
   1266   WiFiServiceRefPtr service1(FindService(ssid1_bytes, kModeManaged,
   1267                                          kSecurityNone));
   1268   EXPECT_TRUE(service1);
   1269   EXPECT_TRUE(service1->HasEndpoints());
   1270   EXPECT_TRUE(service1 != service0);
   1271 }
   1272 
   1273 TEST_F(WiFiProviderTest, OnEndpointAddedWithSecurity) {
   1274   provider_.Start();
   1275   const string ssid0("an_ssid");
   1276   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1277   EXPECT_FALSE(FindService(ssid0_bytes, kModeManaged,
   1278                            kSecurityNone));
   1279   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1280   endpoint0->set_security_mode(kSecurityRsn);
   1281   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1282   EXPECT_CALL(manager_, UpdateService(_)).Times(1);
   1283   provider_.OnEndpointAdded(endpoint0);
   1284   Mock::VerifyAndClearExpectations(&manager_);
   1285   EXPECT_EQ(1, GetServices().size());
   1286   WiFiServiceRefPtr service0(FindService(ssid0_bytes, kModeManaged,
   1287                                          kSecurityWpa));
   1288   EXPECT_TRUE(service0);
   1289   EXPECT_TRUE(service0->HasEndpoints());
   1290   EXPECT_EQ(kSecurityPsk, service0->security_);
   1291 
   1292   WiFiEndpointRefPtr endpoint1 = MakeEndpoint(ssid0, "00:00:00:00:00:01", 0, 0);
   1293   endpoint1->set_security_mode(kSecurityWpa);
   1294   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1295   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1296   provider_.OnEndpointAdded(endpoint1);
   1297   Mock::VerifyAndClearExpectations(&manager_);
   1298   EXPECT_EQ(1, GetServices().size());
   1299 
   1300   const string ssid1("another_ssid");
   1301   const vector<uint8_t> ssid1_bytes(ssid1.begin(), ssid1.end());
   1302   EXPECT_FALSE(FindService(ssid1_bytes, kModeManaged,
   1303                            kSecurityNone));
   1304   WiFiEndpointRefPtr endpoint2 = MakeEndpoint(ssid1, "00:00:00:00:00:02", 0, 0);
   1305   endpoint2->set_security_mode(kSecurityWpa);
   1306   EXPECT_CALL(manager_, RegisterService(_)).Times(1);
   1307   EXPECT_CALL(manager_, UpdateService(_)).Times(1);
   1308   provider_.OnEndpointAdded(endpoint2);
   1309   Mock::VerifyAndClearExpectations(&manager_);
   1310   EXPECT_EQ(2, GetServices().size());
   1311 
   1312   WiFiServiceRefPtr service1(FindService(ssid1_bytes, kModeManaged,
   1313                                          kSecurityRsn));
   1314   EXPECT_TRUE(service1);
   1315   EXPECT_TRUE(service1->HasEndpoints());
   1316   EXPECT_EQ(kSecurityPsk, service1->security_);
   1317   EXPECT_TRUE(service1 != service0);
   1318 }
   1319 
   1320 TEST_F(WiFiProviderTest, OnEndpointAddedWhileStopped) {
   1321   // If we don't call provider_.Start(), OnEndpointAdded should have no effect.
   1322   const string ssid("an_ssid");
   1323   WiFiEndpointRefPtr endpoint = MakeEndpoint(ssid, "00:00:00:00:00:00", 0, 0);
   1324   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1325   EXPECT_CALL(manager_, UpdateService(_)).Times(0);
   1326   provider_.OnEndpointAdded(endpoint);
   1327   EXPECT_TRUE(GetServices().empty());
   1328 }
   1329 
   1330 TEST_F(WiFiProviderTest, OnEndpointAddedToMockService) {
   1331   // The previous test allowed the provider to create its own "real"
   1332   // WiFiServices, which hides some of what we can test with mock
   1333   // services.  Re-do an add-endpoint operation by seeding the provider
   1334   // with a mock service.
   1335   provider_.Start();
   1336   const string ssid0("an_ssid");
   1337   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1338   MockWiFiServiceRefPtr service0 = AddMockService(ssid0_bytes,
   1339                                                   kModeManaged,
   1340                                                   kSecurityNone,
   1341                                                   false);
   1342   const string ssid1("another_ssid");
   1343   const vector<uint8_t> ssid1_bytes(ssid1.begin(), ssid1.end());
   1344   MockWiFiServiceRefPtr service1 = AddMockService(ssid1_bytes,
   1345                                                   kModeManaged,
   1346                                                   kSecurityNone,
   1347                                                   false);
   1348   EXPECT_EQ(service0.get(), FindService(ssid0_bytes,
   1349                                         kModeManaged,
   1350                                         kSecurityNone).get());
   1351   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1352   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1353   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1354   EXPECT_CALL(*service0, AddEndpoint(RefPtrMatch(endpoint0))).Times(1);
   1355   EXPECT_CALL(*service1, AddEndpoint(_)).Times(0);
   1356   provider_.OnEndpointAdded(endpoint0);
   1357   Mock::VerifyAndClearExpectations(&manager_);
   1358   Mock::VerifyAndClearExpectations(service0.get());
   1359   Mock::VerifyAndClearExpectations(service1.get());
   1360 
   1361   WiFiEndpointRefPtr endpoint1 = MakeEndpoint(ssid0, "00:00:00:00:00:01", 0, 0);
   1362   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1363   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1364   EXPECT_CALL(*service0, AddEndpoint(RefPtrMatch(endpoint1))).Times(1);
   1365   EXPECT_CALL(*service1, AddEndpoint(_)).Times(0);
   1366   provider_.OnEndpointAdded(endpoint1);
   1367   Mock::VerifyAndClearExpectations(&manager_);
   1368   Mock::VerifyAndClearExpectations(service0.get());
   1369   Mock::VerifyAndClearExpectations(service1.get());
   1370 
   1371   WiFiEndpointRefPtr endpoint2 = MakeEndpoint(ssid1, "00:00:00:00:00:02", 0, 0);
   1372   EXPECT_CALL(manager_, RegisterService(_)).Times(0);
   1373   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service1))).Times(1);
   1374   EXPECT_CALL(*service0, AddEndpoint(_)).Times(0);
   1375   EXPECT_CALL(*service1, AddEndpoint(RefPtrMatch(endpoint2))).Times(1);
   1376   provider_.OnEndpointAdded(endpoint2);
   1377 }
   1378 
   1379 TEST_F(WiFiProviderTest, OnEndpointRemoved) {
   1380   provider_.Start();
   1381   const string ssid0("an_ssid");
   1382   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1383   MockWiFiServiceRefPtr service0 = AddMockService(ssid0_bytes,
   1384                                                   kModeManaged,
   1385                                                   kSecurityNone,
   1386                                                   false);
   1387   const string ssid1("another_ssid");
   1388   const vector<uint8_t> ssid1_bytes(ssid1.begin(), ssid1.end());
   1389   MockWiFiServiceRefPtr service1 = AddMockService(ssid1_bytes,
   1390                                                   kModeManaged,
   1391                                                   kSecurityNone,
   1392                                                   false);
   1393   EXPECT_EQ(2, GetServices().size());
   1394 
   1395   // Remove the last endpoint of a non-remembered service.
   1396   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1397   AddEndpointToService(service0, endpoint0);
   1398   EXPECT_EQ(1, GetServiceByEndpoint().size());
   1399 
   1400   EXPECT_CALL(*service0, RemoveEndpoint(RefPtrMatch(endpoint0))).Times(1);
   1401   EXPECT_CALL(*service1, RemoveEndpoint(_)).Times(0);
   1402   EXPECT_CALL(*service0, HasEndpoints()).WillOnce(Return(false));
   1403   EXPECT_CALL(*service0, IsRemembered()).WillOnce(Return(false));
   1404   EXPECT_CALL(*service0, ResetWiFi()).Times(1);
   1405   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(0);
   1406   EXPECT_CALL(manager_, DeregisterService(RefPtrMatch(service0))).Times(1);
   1407   provider_.OnEndpointRemoved(endpoint0);
   1408   // Verify now, so it's clear that this happened as a result of the call
   1409   // above, and not anything in the destructor(s).
   1410   Mock::VerifyAndClearExpectations(&manager_);
   1411   Mock::VerifyAndClearExpectations(service0.get());
   1412   Mock::VerifyAndClearExpectations(service1.get());
   1413   EXPECT_EQ(1, GetServices().size());
   1414   EXPECT_EQ(service1.get(), GetServices().front().get());
   1415   EXPECT_TRUE(GetServiceByEndpoint().empty());
   1416 }
   1417 
   1418 TEST_F(WiFiProviderTest, OnEndpointRemovedButHasEndpoints) {
   1419   provider_.Start();
   1420   const string ssid0("an_ssid");
   1421   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1422   MockWiFiServiceRefPtr service0 = AddMockService(ssid0_bytes,
   1423                                                   kModeManaged,
   1424                                                   kSecurityNone,
   1425                                                   false);
   1426   EXPECT_EQ(1, GetServices().size());
   1427 
   1428   // Remove an endpoint of a non-remembered service.
   1429   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1430   AddEndpointToService(service0, endpoint0);
   1431   EXPECT_EQ(1, GetServiceByEndpoint().size());
   1432 
   1433   EXPECT_CALL(*service0, RemoveEndpoint(RefPtrMatch(endpoint0))).Times(1);
   1434   EXPECT_CALL(*service0, HasEndpoints()).WillOnce(Return(true));
   1435   EXPECT_CALL(*service0, IsRemembered()).WillRepeatedly(Return(false));
   1436   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1437   EXPECT_CALL(*service0, ResetWiFi()).Times(0);
   1438   EXPECT_CALL(manager_, DeregisterService(_)).Times(0);
   1439   provider_.OnEndpointRemoved(endpoint0);
   1440   // Verify now, so it's clear that this happened as a result of the call
   1441   // above, and not anything in the destructor(s).
   1442   Mock::VerifyAndClearExpectations(&manager_);
   1443   Mock::VerifyAndClearExpectations(service0.get());
   1444   EXPECT_EQ(1, GetServices().size());
   1445   EXPECT_TRUE(GetServiceByEndpoint().empty());
   1446 }
   1447 
   1448 TEST_F(WiFiProviderTest, OnEndpointRemovedButIsRemembered) {
   1449   provider_.Start();
   1450   const string ssid0("an_ssid");
   1451   const vector<uint8_t> ssid0_bytes(ssid0.begin(), ssid0.end());
   1452   MockWiFiServiceRefPtr service0 = AddMockService(ssid0_bytes,
   1453                                                   kModeManaged,
   1454                                                   kSecurityNone,
   1455                                                   false);
   1456   EXPECT_EQ(1, GetServices().size());
   1457 
   1458   // Remove the last endpoint of a remembered service.
   1459   WiFiEndpointRefPtr endpoint0 = MakeEndpoint(ssid0, "00:00:00:00:00:00", 0, 0);
   1460   AddEndpointToService(service0, endpoint0);
   1461   EXPECT_EQ(1, GetServiceByEndpoint().size());
   1462 
   1463   EXPECT_CALL(*service0, RemoveEndpoint(RefPtrMatch(endpoint0))).Times(1);
   1464   EXPECT_CALL(*service0, HasEndpoints()).WillRepeatedly(Return(false));
   1465   EXPECT_CALL(*service0, IsRemembered()).WillOnce(Return(true));
   1466   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(service0))).Times(1);
   1467   EXPECT_CALL(*service0, ResetWiFi()).Times(0);
   1468   EXPECT_CALL(manager_, DeregisterService(_)).Times(0);
   1469   provider_.OnEndpointRemoved(endpoint0);
   1470   // Verify now, so it's clear that this happened as a result of the call
   1471   // above, and not anything in the destructor(s).
   1472   Mock::VerifyAndClearExpectations(&manager_);
   1473   Mock::VerifyAndClearExpectations(service0.get());
   1474   EXPECT_EQ(1, GetServices().size());
   1475   EXPECT_TRUE(GetServiceByEndpoint().empty());
   1476 }
   1477 
   1478 TEST_F(WiFiProviderTest, OnEndpointRemovedWhileStopped) {
   1479   // If we don't call provider_.Start(), OnEndpointRemoved should not
   1480   // cause a crash even if a service matching the endpoint does not exist.
   1481   const string ssid("an_ssid");
   1482   WiFiEndpointRefPtr endpoint = MakeEndpoint(ssid, "00:00:00:00:00:00", 0, 0);
   1483   provider_.OnEndpointRemoved(endpoint);
   1484 }
   1485 
   1486 TEST_F(WiFiProviderTest, OnEndpointUpdated) {
   1487   provider_.Start();
   1488 
   1489   // Create an endpoint and associate it with a mock service.
   1490   const string ssid("an_ssid");
   1491   WiFiEndpointRefPtr endpoint = MakeEndpoint(ssid, "00:00:00:00:00:00", 0, 0);
   1492 
   1493   const vector<uint8_t> ssid_bytes(ssid.begin(), ssid.end());
   1494   MockWiFiServiceRefPtr open_service = AddMockService(ssid_bytes,
   1495                                                       kModeManaged,
   1496                                                       kSecurityNone,
   1497                                                       false);
   1498   EXPECT_CALL(*open_service, AddEndpoint(RefPtrMatch(endpoint)));
   1499   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(open_service)));
   1500   provider_.OnEndpointAdded(endpoint);
   1501   Mock::VerifyAndClearExpectations(open_service.get());
   1502 
   1503   // WiFiProvider is running and endpoint matches this service.
   1504   EXPECT_CALL(*open_service, NotifyEndpointUpdated(RefPtrMatch(endpoint)));
   1505   EXPECT_CALL(*open_service, AddEndpoint(_)).Times(0);
   1506   provider_.OnEndpointUpdated(endpoint);
   1507   Mock::VerifyAndClearExpectations(open_service.get());
   1508 
   1509   // If the endpoint is changed in a way that causes it to match a different
   1510   // service, the provider should transfer the endpoint from one service to
   1511   // the other.
   1512   MockWiFiServiceRefPtr rsn_service = AddMockService(ssid_bytes,
   1513                                                      kModeManaged,
   1514                                                      kSecurityRsn,
   1515                                                      false);
   1516   EXPECT_CALL(*open_service, RemoveEndpoint(RefPtrMatch(endpoint)));
   1517   // We are playing out a scenario where the open service is not removed
   1518   // since it still claims to have more endpoints remaining.
   1519   EXPECT_CALL(*open_service, HasEndpoints()).WillOnce(Return(true));
   1520   EXPECT_CALL(*rsn_service, AddEndpoint(RefPtrMatch(endpoint)));
   1521   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(open_service)));
   1522   EXPECT_CALL(manager_, UpdateService(RefPtrMatch(rsn_service)));
   1523   endpoint->set_security_mode(kSecurityRsn);
   1524   provider_.OnEndpointUpdated(endpoint);
   1525 }
   1526 
   1527 TEST_F(WiFiProviderTest, OnEndpointUpdatedWhileStopped) {
   1528   // If we don't call provider_.Start(), OnEndpointUpdated should not
   1529   // cause a crash even if a service matching the endpoint does not exist.
   1530   const string ssid("an_ssid");
   1531   WiFiEndpointRefPtr endpoint = MakeEndpoint(ssid, "00:00:00:00:00:00", 0, 0);
   1532   provider_.OnEndpointUpdated(endpoint);
   1533 }
   1534 
   1535 TEST_F(WiFiProviderTest, OnServiceUnloaded) {
   1536   // This function should never unregister services itself -- the Manager
   1537   // will automatically deregister the service if OnServiceUnloaded()
   1538   // returns true (via WiFiService::Unload()).
   1539   EXPECT_CALL(manager_, DeregisterService(_)).Times(0);
   1540 
   1541   MockWiFiServiceRefPtr service = AddMockService(vector<uint8_t>(1, '0'),
   1542                                                  kModeManaged,
   1543                                                  kSecurityNone,
   1544                                                  false);
   1545   EXPECT_EQ(1, GetServices().size());
   1546   EXPECT_CALL(*service, HasEndpoints()).WillOnce(Return(true));
   1547   EXPECT_CALL(*service, ResetWiFi()).Times(0);
   1548   EXPECT_FALSE(provider_.OnServiceUnloaded(service));
   1549   EXPECT_EQ(1, GetServices().size());
   1550   Mock::VerifyAndClearExpectations(service.get());
   1551 
   1552   EXPECT_CALL(*service, HasEndpoints()).WillOnce(Return(false));
   1553   EXPECT_CALL(*service, ResetWiFi()).Times(1);
   1554   EXPECT_TRUE(provider_.OnServiceUnloaded(service));
   1555   // Verify now, so it's clear that this happened as a result of the call
   1556   // above, and not anything in the destructor(s).
   1557   Mock::VerifyAndClearExpectations(service.get());
   1558   EXPECT_TRUE(GetServices().empty());
   1559 
   1560   Mock::VerifyAndClearExpectations(&manager_);
   1561 }
   1562 
   1563 TEST_F(WiFiProviderTest, LoadAndFixupServiceEntriesDefaultProfile) {
   1564   // We test LoadAndFixupServiceEntries indirectly since it calls a static
   1565   // method in WiFiService.
   1566   EXPECT_CALL(metrics_, SendEnumToUMA(
   1567       "Network.Shill.Wifi.ServiceFixupEntries",
   1568       Metrics::kMetricServiceFixupDefaultProfile,
   1569       Metrics::kMetricServiceFixupMax)).Times(1);
   1570   EXPECT_CALL(default_profile_storage_, Flush()).Times(1);
   1571   const string kGroupId =
   1572       StringPrintf("%s_0_0_%s_%s", kTypeWifi, kModeManaged, kSecurityNone);
   1573   EXPECT_CALL(default_profile_storage_,
   1574               GetString(kGroupId, _, _)).WillRepeatedly(Return(false));
   1575   EXPECT_CALL(default_profile_storage_,
   1576               SetString(kGroupId, _, _)).WillRepeatedly(Return(true));
   1577   set<string> groups;
   1578   groups.insert(kGroupId);
   1579   EXPECT_CALL(default_profile_storage_, GetGroups())
   1580       .WillRepeatedly(Return(groups));
   1581   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1582       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 0), _)).
   1583       WillOnce(Return(true));
   1584   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1585       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 1), _)).
   1586       WillOnce(Return(true));
   1587   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1588       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 2), _)).
   1589       WillOnce(Return(true));
   1590   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1591       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 3), _)).
   1592       WillOnce(Return(false));
   1593   LoadAndFixupServiceEntries(default_profile_.get());
   1594 }
   1595 
   1596 TEST_F(WiFiProviderTest, LoadAndFixupServiceEntriesUserProfile) {
   1597   EXPECT_CALL(metrics_, SendEnumToUMA(
   1598       "Network.Shill.Wifi.ServiceFixupEntries",
   1599       Metrics::kMetricServiceFixupUserProfile,
   1600       Metrics::kMetricServiceFixupMax)).Times(1);
   1601   EXPECT_CALL(user_profile_storage_, Flush()).Times(1);
   1602   const string kGroupId =
   1603       StringPrintf("%s_0_0_%s_%s", kTypeWifi, kModeManaged, kSecurityNone);
   1604   EXPECT_CALL(user_profile_storage_,
   1605               GetString(kGroupId, _, _)).WillRepeatedly(Return(false));
   1606   EXPECT_CALL(user_profile_storage_,
   1607               SetString(kGroupId, _, _)).WillRepeatedly(Return(true));
   1608   set<string> groups;
   1609   groups.insert(kGroupId);
   1610   EXPECT_CALL(user_profile_storage_, GetGroups())
   1611       .WillRepeatedly(Return(groups));
   1612   EXPECT_CALL(user_profile_storage_, GetStringList(_, _, _)).Times(0);
   1613   LoadAndFixupServiceEntries(user_profile_.get());
   1614 }
   1615 
   1616 TEST_F(WiFiProviderTest, LoadAndFixupServiceEntriesNothingToDo) {
   1617   EXPECT_CALL(metrics_, SendEnumToUMA(_, _, _)).Times(0);
   1618   EXPECT_CALL(default_profile_storage_, Flush()).Times(0);
   1619   const string kGroupId =
   1620       StringPrintf("%s_0_0_%s_%s", kTypeWifi, kModeManaged, kSecurityNone);
   1621   EXPECT_CALL(default_profile_storage_,
   1622               GetString(kGroupId, _, _)).WillRepeatedly(Return(true));
   1623   set<string> groups;
   1624   groups.insert(kGroupId);
   1625   EXPECT_CALL(default_profile_storage_, GetGroups()).WillOnce(Return(groups));
   1626   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1627       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 0), _)).
   1628       WillOnce(Return(true));
   1629   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1630       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 1), _)).
   1631       WillOnce(Return(true));
   1632   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1633       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 2), _)).
   1634       WillOnce(Return(true));
   1635   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1636       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 3), _)).
   1637       WillOnce(Return(false));
   1638   LoadAndFixupServiceEntries(default_profile_.get());
   1639 }
   1640 
   1641 TEST_F(WiFiProviderTest, GetHiddenSSIDList) {
   1642   EXPECT_TRUE(provider_.GetHiddenSSIDList().empty());
   1643   const vector<uint8_t> ssid0(1, '0');
   1644   AddMockService(ssid0, kModeManaged, kSecurityNone, false);
   1645   EXPECT_TRUE(provider_.GetHiddenSSIDList().empty());
   1646 
   1647   const vector<uint8_t> ssid1(1, '1');
   1648   MockWiFiServiceRefPtr service1 = AddMockService(ssid1,
   1649                                                   kModeManaged,
   1650                                                   kSecurityNone,
   1651                                                   true);
   1652   EXPECT_CALL(*service1, IsRemembered()).WillRepeatedly(Return(false));
   1653   EXPECT_TRUE(provider_.GetHiddenSSIDList().empty());
   1654 
   1655   const vector<uint8_t> ssid2(1, '2');
   1656   MockWiFiServiceRefPtr service2 = AddMockService(ssid2,
   1657                                                   kModeManaged,
   1658                                                   kSecurityNone,
   1659                                                   true);
   1660   EXPECT_CALL(*service2, IsRemembered()).WillRepeatedly(Return(true));
   1661   ByteArrays ssid_list = provider_.GetHiddenSSIDList();
   1662 
   1663   EXPECT_EQ(1, ssid_list.size());
   1664   EXPECT_TRUE(ssid_list[0] == ssid2);
   1665 
   1666   const vector<uint8_t> ssid3(1, '3');
   1667   MockWiFiServiceRefPtr service3 = AddMockService(ssid3,
   1668                                                   kModeManaged,
   1669                                                   kSecurityNone,
   1670                                                   false);
   1671   EXPECT_CALL(*service2, IsRemembered()).WillRepeatedly(Return(true));
   1672 
   1673   ssid_list = provider_.GetHiddenSSIDList();
   1674   EXPECT_EQ(1, ssid_list.size());
   1675   EXPECT_TRUE(ssid_list[0] == ssid2);
   1676 
   1677   const vector<uint8_t> ssid4(1, '4');
   1678   MockWiFiServiceRefPtr service4 = AddMockService(ssid4,
   1679                                                   kModeManaged,
   1680                                                   kSecurityNone,
   1681                                                   true);
   1682   EXPECT_CALL(*service4, IsRemembered()).WillRepeatedly(Return(true));
   1683 
   1684   ssid_list = provider_.GetHiddenSSIDList();
   1685   EXPECT_EQ(2, ssid_list.size());
   1686   EXPECT_TRUE(ssid_list[0] == ssid2);
   1687   EXPECT_TRUE(ssid_list[1] == ssid4);
   1688 }
   1689 
   1690 TEST_F(WiFiProviderTest, StringListToFrequencyMap) {
   1691   vector<string> strings;
   1692   BuildFreqCountStrings(&strings);
   1693   WiFiProvider::ConnectFrequencyMap frequencies_result;
   1694   time_t days = WiFiProvider::StringListToFrequencyMap(strings,
   1695                                                        &frequencies_result);
   1696 
   1697   WiFiProvider::ConnectFrequencyMap frequencies_expect;
   1698   BuildFreqCountMap(&frequencies_expect);
   1699   EXPECT_THAT(frequencies_result, ContainerEq(frequencies_expect));
   1700   EXPECT_EQ(days, kTestDays);
   1701 }
   1702 
   1703 TEST_F(WiFiProviderTest, StringListToFrequencyMapEmpty) {
   1704   vector<string> strings;
   1705   strings.push_back("@50");
   1706   WiFiProvider::ConnectFrequencyMap frequencies_result;
   1707   time_t days = WiFiProvider::StringListToFrequencyMap(strings,
   1708                                                        &frequencies_result);
   1709   EXPECT_TRUE(frequencies_result.empty());
   1710   EXPECT_EQ(days, 50);
   1711 }
   1712 
   1713 TEST_F(WiFiProviderTest, FrequencyMapToStringList) {
   1714   WiFiProvider::ConnectFrequencyMap frequencies;
   1715   BuildFreqCountMap(&frequencies);
   1716   vector<string> strings_result;
   1717   WiFiProvider::FrequencyMapToStringList(kTestDays, frequencies,
   1718                                          &strings_result);
   1719 
   1720   vector<string> strings_expect;
   1721   BuildFreqCountStrings(&strings_expect);
   1722   EXPECT_THAT(strings_result, ContainerEq(strings_expect));
   1723 }
   1724 
   1725 TEST_F(WiFiProviderTest, FrequencyMapToStringListEmpty) {
   1726   WiFiProvider::ConnectFrequencyMap frequencies;
   1727   vector<string> strings_result;
   1728   WiFiProvider::FrequencyMapToStringList(kTestDays, frequencies,
   1729                                          &strings_result);
   1730   EXPECT_EQ(1, strings_result.size());
   1731   EXPECT_EQ(*strings_result.begin(), "@20");
   1732 }
   1733 
   1734 TEST_F(WiFiProviderTest, FrequencyMapBasicAging) {
   1735   const time_t kThisWeek = kFirstWeek +
   1736       WiFiProvider::kWeeksToKeepFrequencyCounts - 1;
   1737   LoadConnectCountByFrequency(kThisWeek * kSecondsPerWeek);
   1738 
   1739   // Make sure we have data for all 3 blocks.
   1740   WiFiProvider::ConnectFrequencyMap expected;
   1741   expected[5001] = 2;
   1742   expected[5002] = 2;
   1743   expected[6001] = 1;
   1744   expected[6002] = 2;
   1745   expected[7001] = 1;
   1746   expected[7002] = 2;
   1747   EXPECT_THAT(provider_.connect_count_by_frequency_, ContainerEq(expected));
   1748 
   1749   // And, then, make sure we output the expected blocks of data.
   1750   EXPECT_CALL(
   1751       default_profile_storage_,
   1752       SetStringList(WiFiProvider::kStorageId, _,
   1753                     Eq(profile_frequency_data_[
   1754                         StringPrintf(
   1755                             "%s%d", WiFiProvider::kStorageFrequencies, 0)])));
   1756   EXPECT_CALL(
   1757       default_profile_storage_,
   1758       SetStringList(WiFiProvider::kStorageId, _,
   1759                     Eq(profile_frequency_data_[
   1760                         StringPrintf(
   1761                             "%s%d", WiFiProvider::kStorageFrequencies, 1)])));
   1762   EXPECT_CALL(
   1763       default_profile_storage_,
   1764       SetStringList(WiFiProvider::kStorageId, _,
   1765                     Eq(profile_frequency_data_[
   1766                         StringPrintf(
   1767                             "%s%d", WiFiProvider::kStorageFrequencies, 2)])));
   1768   vector<string> frequencies;
   1769   frequencies.push_back(base::StringPrintf("@%" PRIu64,
   1770                                            static_cast<uint64_t>(kThisWeek)));
   1771   EXPECT_CALL(
   1772       default_profile_storage_,
   1773       SetStringList(WiFiProvider::kStorageId, _, Eq(frequencies))).Times(0);
   1774   Save();
   1775 }
   1776 
   1777 TEST_F(WiFiProviderTest, FrequencyMapAgingIllegalDay) {
   1778   provider_.time_ = &time_;
   1779   const time_t kThisWeek = kFirstWeek +
   1780       WiFiProvider::kWeeksToKeepFrequencyCounts - 1;
   1781   const time_t kThisWeekSeconds = kThisWeek * kSecondsPerWeek;
   1782   EXPECT_CALL(time_, GetSecondsSinceEpoch()).WillOnce(Return(kThisWeekSeconds));
   1783   const string kGroupId =
   1784       StringPrintf("%s_0_0_%s_%s", kTypeWifi, kModeManaged, kSecurityNone);
   1785   EXPECT_CALL(default_profile_storage_,
   1786               GetString(kGroupId, _, _)).WillRepeatedly(Return(true));
   1787   set<string> groups;
   1788   groups.insert(kGroupId);
   1789   // Instead of block[1], return a block without the date.
   1790   EXPECT_CALL(default_profile_storage_, GetGroups()).WillOnce(Return(groups));
   1791   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1792       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 0), _)).
   1793       WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
   1794   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1795       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 1), _)).
   1796       WillOnce(Invoke(this, &WiFiProviderTest::GetIllegalDayStringList));
   1797   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1798       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 2), _)).
   1799       WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
   1800   EXPECT_CALL(default_profile_storage_, GetStringList(WiFiProvider::kStorageId,
   1801       StringPrintf("%s%d", WiFiProvider::kStorageFrequencies, 3), _)).
   1802       WillOnce(Invoke(this, &WiFiProviderTest::GetStringList));
   1803 
   1804   LoadAndFixupServiceEntries(default_profile_.get());
   1805 
   1806   // Verify that the received information only includes block[0] and block[2].
   1807   WiFiProvider::ConnectFrequencyMap expected;
   1808   expected[5001] = 1;
   1809   expected[5002] = 2;
   1810   expected[7001] = 1;
   1811   expected[7002] = 2;
   1812   EXPECT_THAT(provider_.connect_count_by_frequency_, ContainerEq(expected));
   1813 
   1814   // And, then, make sure we output the expected blocks of data.
   1815   EXPECT_CALL(
   1816       default_profile_storage_,
   1817       SetStringList(WiFiProvider::kStorageId, _,
   1818                     Eq(profile_frequency_data_[
   1819                         StringPrintf(
   1820                             "%s%d", WiFiProvider::kStorageFrequencies, 0)])));
   1821   EXPECT_CALL(
   1822       default_profile_storage_,
   1823       SetStringList(WiFiProvider::kStorageId, _,
   1824                     Eq(profile_frequency_data_[
   1825                         StringPrintf(
   1826                             "%s%d", WiFiProvider::kStorageFrequencies, 1)]))).
   1827       Times(0);
   1828   EXPECT_CALL(
   1829       default_profile_storage_,
   1830       SetStringList(WiFiProvider::kStorageId, _,
   1831                     Eq(profile_frequency_data_[
   1832                         StringPrintf(
   1833                             "%s%d", WiFiProvider::kStorageFrequencies, 2)])));
   1834   vector<string> frequencies;
   1835   frequencies.push_back(base::StringPrintf("@%" PRIu64,
   1836                                            static_cast<uint64_t>(kThisWeek)));
   1837   EXPECT_CALL(default_profile_storage_,
   1838               SetStringList(WiFiProvider::kStorageId, _, Eq(frequencies)))
   1839       .Times(0);
   1840   Save();
   1841 }
   1842 
   1843 TEST_F(WiFiProviderTest, IncrementConnectCount) {
   1844   const time_t kThisWeek = kFirstWeek +
   1845       WiFiProvider::kWeeksToKeepFrequencyCounts - 1;
   1846   const time_t kThisWeekSeconds = kThisWeek * kSecondsPerWeek;
   1847   LoadConnectCountByFrequency(kThisWeekSeconds);
   1848 
   1849   EXPECT_CALL(time_, GetSecondsSinceEpoch()).WillOnce(Return(kThisWeekSeconds));
   1850   EXPECT_CALL(manager_, UpdateWiFiProvider());
   1851   EXPECT_CALL(metrics_, SendToUMA(Metrics::kMetricFrequenciesConnectedEver,
   1852                                   _, _, _, _));
   1853   time_t newest_week_at_start =
   1854       provider_.connect_count_by_frequency_dated_.crbegin()->first;
   1855   provider_.IncrementConnectCount(6002);
   1856 
   1857   // Make sure we have data for all 3 blocks.
   1858   WiFiProvider::ConnectFrequencyMap expected;
   1859   expected[5001] = 2;
   1860   expected[5002] = 2;
   1861   expected[6001] = 1;
   1862   expected[6002] = 3;
   1863   expected[7001] = 1;
   1864   expected[7002] = 2;
   1865   EXPECT_THAT(provider_.connect_count_by_frequency_, ContainerEq(expected));
   1866   // Make sure we didn't delete the oldest block.
   1867   EXPECT_TRUE(ContainsKey(provider_.connect_count_by_frequency_dated_,
   1868                           kFirstWeek));
   1869   // Make sure we didn't create a new block.
   1870   time_t newest_week_at_end =
   1871       provider_.connect_count_by_frequency_dated_.crbegin()->first;
   1872   EXPECT_EQ(newest_week_at_start, newest_week_at_end);
   1873 }
   1874 
   1875 TEST_F(WiFiProviderTest, IncrementConnectCountCreateNew) {
   1876   time_t this_week = kFirstWeek + WiFiProvider::kWeeksToKeepFrequencyCounts - 1;
   1877   LoadConnectCountByFrequency(this_week * kSecondsPerWeek);
   1878 
   1879   this_week += 2;
   1880   EXPECT_CALL(time_, GetSecondsSinceEpoch()).
   1881       WillOnce(Return(this_week * kSecondsPerWeek));
   1882   EXPECT_CALL(manager_, UpdateWiFiProvider());
   1883   EXPECT_CALL(metrics_, SendToUMA(Metrics::kMetricFrequenciesConnectedEver,
   1884                                   _, _, _, _));
   1885   time_t newest_week_at_start =
   1886       provider_.connect_count_by_frequency_dated_.crbegin()->first;
   1887   provider_.IncrementConnectCount(6001);
   1888 
   1889   // Make sure we have data for newest 2 blocks (only).
   1890   WiFiProvider::ConnectFrequencyMap expected;
   1891   expected[5001] = 1;
   1892   expected[6001] = 2;
   1893   expected[6002] = 2;
   1894   expected[7001] = 1;
   1895   expected[7002] = 2;
   1896   EXPECT_THAT(provider_.connect_count_by_frequency_, ContainerEq(expected));
   1897   // Verify that the oldest block is gone.
   1898   EXPECT_FALSE(ContainsKey(provider_.connect_count_by_frequency_dated_,
   1899                            kFirstWeek));
   1900   // Make sure we created a new block and that it is for the current week.
   1901   time_t newest_week_at_end =
   1902       provider_.connect_count_by_frequency_dated_.crbegin()->first;
   1903   EXPECT_NE(newest_week_at_start, newest_week_at_end);
   1904   EXPECT_TRUE(ContainsKey(provider_.connect_count_by_frequency_dated_,
   1905                           this_week));
   1906 }
   1907 
   1908 TEST_F(WiFiProviderTest, ReportAutoConnectableServices) {
   1909   MockWiFiServiceRefPtr service0 = AddMockService(vector<uint8_t>(1, '0'),
   1910                                                   kModeManaged,
   1911                                                   kSecurityNone,
   1912                                                   false);
   1913   MockWiFiServiceRefPtr service1 = AddMockService(vector<uint8_t>(1, '1'),
   1914                                                   kModeManaged,
   1915                                                   kSecurityNone,
   1916                                                   false);
   1917   service0->EnableAndRetainAutoConnect();
   1918   service0->SetConnectable(true);
   1919   service1->EnableAndRetainAutoConnect();
   1920   service1->SetConnectable(true);
   1921 
   1922   EXPECT_CALL(*service0, IsAutoConnectable(_))
   1923       .WillOnce(Return(true))
   1924       .WillOnce(Return(false));
   1925   EXPECT_CALL(*service1, IsAutoConnectable(_))
   1926       .WillRepeatedly(Return(false));
   1927 
   1928   // With 1 auto connectable service.
   1929   EXPECT_CALL(metrics_, NotifyWifiAutoConnectableServices(1));
   1930   provider_.ReportAutoConnectableServices();
   1931 
   1932   // With no auto connectable service.
   1933   EXPECT_CALL(metrics_, NotifyWifiAutoConnectableServices(_)).Times(0);
   1934   provider_.ReportAutoConnectableServices();
   1935 }
   1936 
   1937 TEST_F(WiFiProviderTest, NumAutoConnectableServices) {
   1938   MockWiFiServiceRefPtr service0 = AddMockService(
   1939       vector<uint8_t>(1, '0'), kModeManaged, kSecurityNone, false);
   1940   MockWiFiServiceRefPtr service1 = AddMockService(
   1941       vector<uint8_t>(1, '1'), kModeManaged, kSecurityNone, false);
   1942   service0->EnableAndRetainAutoConnect();
   1943   service0->SetConnectable(true);
   1944   service1->EnableAndRetainAutoConnect();
   1945   service1->SetConnectable(true);
   1946 
   1947   EXPECT_CALL(*service0, IsAutoConnectable(_))
   1948       .WillOnce(Return(true))
   1949       .WillOnce(Return(false));
   1950   EXPECT_CALL(*service1, IsAutoConnectable(_)).WillRepeatedly(Return(true));
   1951 
   1952   // 2 auto-connectable services.
   1953   EXPECT_EQ(2, provider_.NumAutoConnectableServices());
   1954 
   1955   // 1 auto-connectable service.
   1956   EXPECT_EQ(1, provider_.NumAutoConnectableServices());
   1957 }
   1958 
   1959 TEST_F(WiFiProviderTest, GetSsidsConfiguredForAutoConnect) {
   1960   vector<uint8_t> ssid0(3, '0');
   1961   vector<uint8_t> ssid1(5, '1');
   1962   ByteString ssid0_bytes(ssid0);
   1963   ByteString ssid1_bytes(ssid1);
   1964   MockWiFiServiceRefPtr service0 =
   1965       AddMockService(ssid0, kModeManaged, kSecurityNone, false);
   1966   MockWiFiServiceRefPtr service1 =
   1967       AddMockService(ssid1, kModeManaged, kSecurityNone, false);
   1968   // 2 services configured for auto-connect.
   1969   service0->SetAutoConnect(true);
   1970   service1->SetAutoConnect(true);
   1971   vector<ByteString> service_list_0 =
   1972       provider_.GetSsidsConfiguredForAutoConnect();
   1973   EXPECT_EQ(2, service_list_0.size());
   1974   EXPECT_TRUE(ssid0_bytes.Equals(service_list_0[0]));
   1975   EXPECT_TRUE(ssid1_bytes.Equals(service_list_0[1]));
   1976 
   1977   // 1 service configured for auto-connect.
   1978   service0->SetAutoConnect(false);
   1979   service1->SetAutoConnect(true);
   1980   vector<ByteString> service_list_1 =
   1981       provider_.GetSsidsConfiguredForAutoConnect();
   1982   EXPECT_EQ(1, service_list_1.size());
   1983   EXPECT_TRUE(ssid1_bytes.Equals(service_list_1[0]));
   1984 }
   1985 
   1986 }  // namespace shill
   1987