blob: 1aa66ecf9cc8b09420d60ffe3dfb2caf36e34c85 [file] [log] [blame]
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Chris Masone853b81b2011-06-24 14:11:41 -07002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "shill/wifi.h"
6
mukesh agrawalf2f68a52011-09-01 12:15:48 -07007#include <linux/if.h>
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -07008#include <linux/netlink.h> // Needs typedefs from sys/socket.h.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07009#include <netinet/ether.h>
10#include <sys/socket.h>
mukesh agrawalf2f68a52011-09-01 12:15:48 -070011
Chris Masone853b81b2011-06-24 14:11:41 -070012#include <map>
13#include <string>
14#include <vector>
15
Darin Petkov60ceaf32012-10-18 10:36:01 +020016#include <base/file_util.h>
mukesh agrawal7ec71312011-11-10 02:08:26 +000017#include <base/memory/ref_counted.h>
mukesh agrawaldc42bb32011-07-28 10:40:26 -070018#include <base/memory/scoped_ptr.h>
Ben Chana0ddf462014-02-06 11:32:42 -080019#include <base/strings/string_number_conversions.h>
20#include <base/strings/string_split.h>
21#include <base/strings/string_util.h>
22#include <base/strings/stringprintf.h>
Chris Masone853b81b2011-06-24 14:11:41 -070023#include <chromeos/dbus/service_constants.h>
mukesh agrawal1830fa12011-09-26 14:31:40 -070024#include <dbus-c++/dbus.h>
Chris Masone853b81b2011-06-24 14:11:41 -070025
26#include "shill/dbus_adaptor.h"
Paul Stewart26b327e2011-10-19 11:38:09 -070027#include "shill/event_dispatcher.h"
Gaurav Shah6d2c72d2012-10-16 16:30:44 -070028#include "shill/geolocation_info.h"
mukesh agrawal8ede0522011-10-03 14:57:44 -070029#include "shill/ieee80211.h"
mukesh agrawal7a4e4002011-09-06 11:26:05 -070030#include "shill/key_value_store.h"
Christopher Wileyb691efd2012-08-09 13:51:51 -070031#include "shill/logging.h"
Chris Masone853b81b2011-06-24 14:11:41 -070032#include "shill/manager.h"
Wade Guthrie0cf3c982013-05-29 09:11:35 -070033#include "shill/mock_adaptors.h"
Ben Chan084faca2013-07-02 14:25:12 -070034#include "shill/mock_dbus_service_proxy.h"
Chris Masone853b81b2011-06-24 14:11:41 -070035#include "shill/mock_device.h"
mukesh agrawalc01f3982012-01-24 13:48:39 -080036#include "shill/mock_device_info.h"
mukesh agrawalf2f68a52011-09-01 12:15:48 -070037#include "shill/mock_dhcp_config.h"
38#include "shill/mock_dhcp_provider.h"
Paul Stewart11c224b2013-10-22 19:04:40 -070039#include "shill/mock_eap_credentials.h"
Paul Stewarte369ece2012-05-22 09:11:03 -070040#include "shill/mock_event_dispatcher.h"
Paul Stewart68735052014-02-11 09:16:09 -080041#include "shill/mock_ipconfig.h"
Paul Stewart3c508e12012-08-09 11:40:06 -070042#include "shill/mock_link_monitor.h"
mukesh agrawalcf24a242012-05-21 16:46:11 -070043#include "shill/mock_log.h"
Chris Masone2ae797d2011-08-23 20:41:00 -070044#include "shill/mock_manager.h"
Thieu Le3426c8f2012-01-11 17:35:11 -080045#include "shill/mock_metrics.h"
Wade Guthriebb9fca22013-04-10 17:21:42 -070046#include "shill/mock_netlink_manager.h"
Paul Stewart10ccbb32012-04-26 15:59:30 -070047#include "shill/mock_profile.h"
Ben Chanaf14d452014-02-04 17:31:55 -080048#include "shill/mock_proxy_factory.h"
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -070049#include "shill/mock_rtnl_handler.h"
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070050#include "shill/mock_scan_session.h"
Paul Stewarta41e38d2011-11-11 07:47:29 -080051#include "shill/mock_store.h"
mukesh agrawalb20776f2012-02-10 16:00:36 -080052#include "shill/mock_supplicant_bss_proxy.h"
Paul Stewart735eab52013-03-29 09:19:23 -070053#include "shill/mock_supplicant_eap_state_handler.h"
mukesh agrawal31950242011-07-14 11:53:38 -070054#include "shill/mock_supplicant_interface_proxy.h"
Paul Stewart835934a2012-12-06 19:27:09 -080055#include "shill/mock_supplicant_network_proxy.h"
mukesh agrawal31950242011-07-14 11:53:38 -070056#include "shill/mock_supplicant_process_proxy.h"
mukesh agrawal5c05b292012-03-07 10:12:52 -080057#include "shill/mock_time.h"
Paul Stewart3c504012013-01-17 17:49:58 -080058#include "shill/mock_wifi_provider.h"
mukesh agrawal7ec71312011-11-10 02:08:26 +000059#include "shill/mock_wifi_service.h"
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070060#include "shill/netlink_message_matchers.h"
mukesh agrawaldc42bb32011-07-28 10:40:26 -070061#include "shill/nice_mock_control.h"
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070062#include "shill/nl80211_message.h"
Chris Masone853b81b2011-06-24 14:11:41 -070063#include "shill/property_store_unittest.h"
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070064#include "shill/scan_session.h"
Paul Stewart85aea152013-01-22 09:31:56 -080065#include "shill/technology.h"
Ben Chanaf14d452014-02-04 17:31:55 -080066#include "shill/testing.h"
mukesh agrawal31950242011-07-14 11:53:38 -070067#include "shill/wifi_endpoint.h"
mukesh agrawal32399322011-09-01 10:53:43 -070068#include "shill/wifi_service.h"
Paul Stewartced6a0b2011-11-08 15:32:04 -080069#include "shill/wpa_supplicant.h"
Chris Masone853b81b2011-06-24 14:11:41 -070070
Albert Chaulk0e1cdea2013-02-27 15:32:55 -080071using base::FilePath;
Ben Chana0ddf462014-02-06 11:32:42 -080072using base::StringPrintf;
Chris Masone853b81b2011-06-24 14:11:41 -070073using std::map;
74using std::string;
75using std::vector;
76using ::testing::_;
mukesh agrawal31950242011-07-14 11:53:38 -070077using ::testing::AnyNumber;
Paul Stewart3c504012013-01-17 17:49:58 -080078using ::testing::AtLeast;
mukesh agrawal31950242011-07-14 11:53:38 -070079using ::testing::DefaultValue;
Paul Stewarta41e38d2011-11-11 07:47:29 -080080using ::testing::DoAll;
mukesh agrawalcf24a242012-05-21 16:46:11 -070081using ::testing::EndsWith;
Wade Guthrie0cf3c982013-05-29 09:11:35 -070082using ::testing::HasSubstr;
mukesh agrawal31950242011-07-14 11:53:38 -070083using ::testing::InSequence;
mukesh agrawalb20776f2012-02-10 16:00:36 -080084using ::testing::Invoke;
Paul Stewart549d44c2012-07-03 12:40:25 -070085using ::testing::InvokeWithoutArgs;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -070086using ::testing::MakeMatcher;
87using ::testing::Matcher;
88using ::testing::MatcherInterface;
89using ::testing::MatchResultListener;
mukesh agrawal7ec71312011-11-10 02:08:26 +000090using ::testing::Mock;
mukesh agrawaldc42bb32011-07-28 10:40:26 -070091using ::testing::NiceMock;
mukesh agrawald4dc0832013-03-25 14:38:26 -070092using ::testing::NotNull;
Paul Stewart11c224b2013-10-22 19:04:40 -070093using ::testing::Ref;
Chris Masone853b81b2011-06-24 14:11:41 -070094using ::testing::Return;
Ben Chanaf14d452014-02-04 17:31:55 -080095using ::testing::ReturnNew;
Prathmesh Prabhuba99b592013-04-17 15:13:14 -070096using ::testing::ReturnRef;
Gary Morainac1bdb42012-02-16 17:42:29 -080097using ::testing::SaveArg;
Paul Stewarta41e38d2011-11-11 07:47:29 -080098using ::testing::SetArgumentPointee;
99using ::testing::StrEq;
100using ::testing::StrictMock;
Chris Masone853b81b2011-06-24 14:11:41 -0700101using ::testing::Test;
mukesh agrawal31950242011-07-14 11:53:38 -0700102using ::testing::Throw;
mukesh agrawal8ede0522011-10-03 14:57:44 -0700103using ::testing::Values;
Chris Masone853b81b2011-06-24 14:11:41 -0700104
105namespace shill {
106
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700107namespace {
108
109const uint16_t kNl80211FamilyId = 0x13;
110const uint16_t kRandomScanFrequency1 = 5600;
111const uint16_t kRandomScanFrequency2 = 5560;
112const uint16_t kRandomScanFrequency3 = 2422;
Paul Stewartc67f0bd2013-12-06 12:14:50 -0800113const int kInterfaceIndex = 1234;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700114
115} // namespace
116
mukesh agrawal31950242011-07-14 11:53:38 -0700117class WiFiPropertyTest : public PropertyStoreTest {
Chris Masone853b81b2011-06-24 14:11:41 -0700118 public:
mukesh agrawal31950242011-07-14 11:53:38 -0700119 WiFiPropertyTest()
Thieu Le3426c8f2012-01-11 17:35:11 -0800120 : device_(new WiFi(control_interface(),
Paul Stewartc67f0bd2013-12-06 12:14:50 -0800121 NULL, NULL, manager(), "wifi", "", kInterfaceIndex)) {
Chris Masone853b81b2011-06-24 14:11:41 -0700122 }
mukesh agrawal31950242011-07-14 11:53:38 -0700123 virtual ~WiFiPropertyTest() {}
Chris Masone853b81b2011-06-24 14:11:41 -0700124
125 protected:
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800126 WiFiRefPtr device_;
Chris Masone853b81b2011-06-24 14:11:41 -0700127};
128
mukesh agrawal31950242011-07-14 11:53:38 -0700129TEST_F(WiFiPropertyTest, Contains) {
Ben Chanf024ef42013-09-20 14:21:38 -0700130 EXPECT_TRUE(device_->store().Contains(kNameProperty));
mukesh agrawalde29fa82011-09-16 16:16:36 -0700131 EXPECT_FALSE(device_->store().Contains(""));
Chris Masone853b81b2011-06-24 14:11:41 -0700132}
133
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800134TEST_F(WiFiPropertyTest, SetProperty) {
Chris Masonea8a2c252011-06-27 22:16:30 -0700135 {
136 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800137 EXPECT_TRUE(DBusAdaptor::SetProperty(
mukesh agrawalde29fa82011-09-16 16:16:36 -0700138 device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700139 kBgscanSignalThresholdProperty,
Chris Masonea8a2c252011-06-27 22:16:30 -0700140 PropertyStoreTest::kInt32V,
141 &error));
142 }
143 {
144 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800145 EXPECT_TRUE(DBusAdaptor::SetProperty(device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700146 kScanIntervalProperty,
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800147 PropertyStoreTest::kUint16V,
148 &error));
Chris Masonea8a2c252011-06-27 22:16:30 -0700149 }
Chris Masone853b81b2011-06-24 14:11:41 -0700150 // Ensure that an attempt to write a R/O property returns InvalidArgs error.
Chris Masonea8a2c252011-06-27 22:16:30 -0700151 {
152 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800153 EXPECT_FALSE(DBusAdaptor::SetProperty(device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700154 kScanningProperty,
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800155 PropertyStoreTest::kBoolV,
156 &error));
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700157 ASSERT_TRUE(error.is_set()); // name() may be invalid otherwise
Chris Masone9d779932011-08-25 16:33:41 -0700158 EXPECT_EQ(invalid_args(), error.name());
Chris Masonea8a2c252011-06-27 22:16:30 -0700159 }
Chris Masone853b81b2011-06-24 14:11:41 -0700160
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800161 {
162 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800163 EXPECT_TRUE(DBusAdaptor::SetProperty(
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800164 device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700165 kBgscanMethodProperty,
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800166 DBusAdaptor::StringToVariant(
Paul Stewart0654ece2013-03-26 15:21:26 -0700167 WPASupplicant::kNetworkBgscanMethodSimple),
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800168 &error));
169 }
170
171 {
172 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800173 EXPECT_FALSE(DBusAdaptor::SetProperty(
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800174 device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700175 kBgscanMethodProperty,
mukesh agrawal4d0401c2012-01-06 16:05:31 -0800176 DBusAdaptor::StringToVariant("not a real scan method"),
177 &error));
178 }
179}
180
Darin Petkov4a66cc52012-06-15 10:08:29 +0200181TEST_F(WiFiPropertyTest, BgscanMethodProperty) {
Paul Stewart0654ece2013-03-26 15:21:26 -0700182 EXPECT_NE(WPASupplicant::kNetworkBgscanMethodLearn,
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800183 WiFi::kDefaultBgscanMethod);
Darin Petkov4a66cc52012-06-15 10:08:29 +0200184 EXPECT_TRUE(device_->bgscan_method_.empty());
185
186 string method;
Paul Stewarte6e8e492013-01-17 11:00:50 -0800187 Error unused_error;
188 EXPECT_TRUE(device_->store().GetStringProperty(
Ben Chanf024ef42013-09-20 14:21:38 -0700189 kBgscanMethodProperty, &method, &unused_error));
Darin Petkov4a66cc52012-06-15 10:08:29 +0200190 EXPECT_EQ(WiFi::kDefaultBgscanMethod, method);
Paul Stewart0654ece2013-03-26 15:21:26 -0700191 EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodSimple, method);
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800192
193 ::DBus::Error error;
mukesh agrawal6bb9e7c2012-01-30 14:57:54 -0800194 EXPECT_TRUE(DBusAdaptor::SetProperty(
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800195 device_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700196 kBgscanMethodProperty,
197 DBusAdaptor::StringToVariant(WPASupplicant::kNetworkBgscanMethodLearn),
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800198 &error));
Paul Stewart0654ece2013-03-26 15:21:26 -0700199 EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodLearn, device_->bgscan_method_);
Paul Stewarte6e8e492013-01-17 11:00:50 -0800200 EXPECT_TRUE(device_->store().GetStringProperty(
Ben Chanf024ef42013-09-20 14:21:38 -0700201 kBgscanMethodProperty, &method, &unused_error));
Paul Stewart0654ece2013-03-26 15:21:26 -0700202 EXPECT_EQ(WPASupplicant::kNetworkBgscanMethodLearn, method);
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800203
204 EXPECT_TRUE(DBusAdaptor::ClearProperty(
Ben Chanf024ef42013-09-20 14:21:38 -0700205 device_->mutable_store(), kBgscanMethodProperty, &error));
Paul Stewarte6e8e492013-01-17 11:00:50 -0800206 EXPECT_TRUE(device_->store().GetStringProperty(
Ben Chanf024ef42013-09-20 14:21:38 -0700207 kBgscanMethodProperty, &method, &unused_error));
Darin Petkov4a66cc52012-06-15 10:08:29 +0200208 EXPECT_EQ(WiFi::kDefaultBgscanMethod, method);
209 EXPECT_TRUE(device_->bgscan_method_.empty());
mukesh agrawal8abd2f62012-01-30 14:56:14 -0800210}
211
Paul Stewart3c504012013-01-17 17:49:58 -0800212MATCHER_P(EndpointMatch, endpoint, "") {
213 return
214 arg->ssid() == endpoint->ssid() &&
215 arg->network_mode() == endpoint->network_mode() &&
216 arg->security_mode() == endpoint->security_mode();
217}
218
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700219
Paul Stewarte369ece2012-05-22 09:11:03 -0700220class WiFiObjectTest : public ::testing::TestWithParam<string> {
mukesh agrawal31950242011-07-14 11:53:38 -0700221 public:
Wade Guthriebb9fca22013-04-10 17:21:42 -0700222 explicit WiFiObjectTest(EventDispatcher *dispatcher)
Paul Stewarte369ece2012-05-22 09:11:03 -0700223 : event_dispatcher_(dispatcher),
Thieu Le6c1e3bb2013-02-06 15:20:35 -0800224 metrics_(NULL),
Paul Stewarte369ece2012-05-22 09:11:03 -0700225 manager_(&control_interface_, NULL, &metrics_, &glib_),
226 device_info_(&control_interface_, dispatcher, &metrics_, &manager_),
Chris Masone626719f2011-08-18 16:58:48 -0700227 wifi_(new WiFi(&control_interface_,
Paul Stewarte369ece2012-05-22 09:11:03 -0700228 dispatcher,
Thieu Le3426c8f2012-01-11 17:35:11 -0800229 &metrics_,
Chris Masone626719f2011-08-18 16:58:48 -0700230 &manager_,
231 kDeviceName,
232 kDeviceAddress,
Paul Stewartc67f0bd2013-12-06 12:14:50 -0800233 kInterfaceIndex)),
Paul Stewart3c504012013-01-17 17:49:58 -0800234 bss_counter_(0),
Ben Chan084faca2013-07-02 14:25:12 -0700235 dbus_service_proxy_(new MockDBusServiceProxy()),
mukesh agrawaldc42bb32011-07-28 10:40:26 -0700236 supplicant_process_proxy_(new NiceMock<MockSupplicantProcessProxy>()),
Ben Chanaf14d452014-02-04 17:31:55 -0800237 supplicant_bss_proxy_(new NiceMock<MockSupplicantBSSProxy>()),
238 dhcp_config_(new MockDHCPConfig(&control_interface_, kDeviceName)),
Ben Chan084faca2013-07-02 14:25:12 -0700239 dbus_manager_(new DBusManager()),
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700240 adaptor_(new DeviceMockAdaptor()),
Paul Stewart735eab52013-03-29 09:19:23 -0700241 eap_state_handler_(new NiceMock<MockSupplicantEAPStateHandler>()),
Paul Stewart3c504012013-01-17 17:49:58 -0800242 supplicant_interface_proxy_(
Ben Chanaf14d452014-02-04 17:31:55 -0800243 new NiceMock<MockSupplicantInterfaceProxy>()) {
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700244 InstallMockScanSession();
mukesh agrawal31950242011-07-14 11:53:38 -0700245 ::testing::DefaultValue< ::DBus::Path>::Set("/default/path");
mukesh agrawalc01f3982012-01-24 13:48:39 -0800246
Ben Chanaf14d452014-02-04 17:31:55 -0800247 ON_CALL(dhcp_provider_, CreateConfig(_, _, _, _, _))
248 .WillByDefault(Return(dhcp_config_));
249 ON_CALL(*dhcp_config_.get(), RequestIP()).WillByDefault(Return(true));
250
251 ON_CALL(proxy_factory_, CreateDBusServiceProxy())
252 .WillByDefault(ReturnAndReleasePointee(&dbus_service_proxy_));
253 ON_CALL(proxy_factory_, CreateSupplicantProcessProxy(_, _))
254 .WillByDefault(ReturnAndReleasePointee(&supplicant_process_proxy_));
255 ON_CALL(proxy_factory_, CreateSupplicantInterfaceProxy(_, _, _))
256 .WillByDefault(ReturnAndReleasePointee(&supplicant_interface_proxy_));
257 ON_CALL(proxy_factory_, CreateSupplicantBSSProxy(_, _, _))
258 .WillByDefault(ReturnAndReleasePointee(&supplicant_bss_proxy_));
259 ON_CALL(proxy_factory_, CreateSupplicantNetworkProxy(_, _))
260 .WillByDefault(ReturnNew<NiceMock<MockSupplicantNetworkProxy>>());
Wade Guthrie318445d2013-05-16 14:05:28 -0700261 Nl80211Message::SetMessageType(kNl80211FamilyId);
Gary Morainac1bdb42012-02-16 17:42:29 -0800262
Paul Stewart735eab52013-03-29 09:19:23 -0700263 // Transfers ownership.
264 manager_.dbus_manager_.reset(dbus_manager_);
265 wifi_->eap_state_handler_.reset(eap_state_handler_);
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200266
Paul Stewart3c504012013-01-17 17:49:58 -0800267 wifi_->provider_ = &wifi_provider_;
mukesh agrawal5c05b292012-03-07 10:12:52 -0800268 wifi_->time_ = &time_;
Wade Guthriebb9fca22013-04-10 17:21:42 -0700269 wifi_->netlink_manager_ = &netlink_manager_;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700270 wifi_->progressive_scan_enabled_ = true;
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700271 wifi_->adaptor_.reset(adaptor_); // Transfers ownership.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700272
273 // The following is only useful when a real |ScanSession| is used; it is
274 // ignored by |MockScanSession|.
275 wifi_->all_scan_frequencies_.insert(kRandomScanFrequency1);
276 wifi_->all_scan_frequencies_.insert(kRandomScanFrequency2);
277 wifi_->all_scan_frequencies_.insert(kRandomScanFrequency3);
mukesh agrawal31950242011-07-14 11:53:38 -0700278 }
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700279
280 virtual void SetUp() {
mukesh agrawal3ab56ac2012-05-31 14:41:43 -0700281 // EnableScopes... so that we can EXPECT_CALL for scoped log messages.
282 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
Christopher Wileyd34a47c2012-08-01 15:42:45 -0700283 ScopeLogger::GetInstance()->set_verbose_level(3);
Ben Chan084faca2013-07-02 14:25:12 -0700284 dbus_manager_->proxy_factory_ = &proxy_factory_;
Darin Petkovab565bb2011-10-06 02:55:51 -0700285 wifi_->proxy_factory_ = &proxy_factory_;
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700286 static_cast<Device *>(wifi_)->rtnl_handler_ = &rtnl_handler_;
287 wifi_->set_dhcp_provider(&dhcp_provider_);
Paul Stewart3c504012013-01-17 17:49:58 -0800288 ON_CALL(manager_, device_info()).WillByDefault(Return(&device_info_));
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200289 EXPECT_CALL(manager_, UpdateEnabledTechnologies()).Times(AnyNumber());
mukesh agrawalb20776f2012-02-10 16:00:36 -0800290 EXPECT_CALL(*supplicant_bss_proxy_, Die()).Times(AnyNumber());
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700291 }
292
293 virtual void TearDown() {
Paul Stewart3c504012013-01-17 17:49:58 -0800294 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(_))
295 .WillRepeatedly(Return(reinterpret_cast<WiFiService *>(NULL)));
Eric Shienbrood9a245532012-03-07 14:20:39 -0500296 wifi_->SelectService(NULL);
mukesh agrawalb20776f2012-02-10 16:00:36 -0800297 if (supplicant_bss_proxy_.get()) {
298 EXPECT_CALL(*supplicant_bss_proxy_, Die());
299 }
Darin Petkovab565bb2011-10-06 02:55:51 -0700300 wifi_->proxy_factory_ = NULL;
mukesh agrawal31950242011-07-14 11:53:38 -0700301 // must Stop WiFi instance, to clear its list of services.
302 // otherwise, the WiFi instance will not be deleted. (because
303 // services reference a WiFi instance, creating a cycle.)
Eric Shienbrood9a245532012-03-07 14:20:39 -0500304 wifi_->Stop(NULL, ResultCallback());
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700305 wifi_->set_dhcp_provider(NULL);
Ben Chan084faca2013-07-02 14:25:12 -0700306 dbus_manager_->Stop();
307 dbus_manager_->proxy_factory_ = NULL;
mukesh agrawal3ab56ac2012-05-31 14:41:43 -0700308 // Reset scope logging, to avoid interfering with other tests.
309 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
Christopher Wileyd34a47c2012-08-01 15:42:45 -0700310 ScopeLogger::GetInstance()->set_verbose_level(0);
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700311 }
312
Paul Stewart549d44c2012-07-03 12:40:25 -0700313 // Needs to be public since it is called via Invoke().
314 void StopWiFi() {
Paul Stewart549d44c2012-07-03 12:40:25 -0700315 wifi_->SetEnabled(false); // Stop(NULL, ResultCallback());
316 }
317
Christopher Wileyc6184482012-10-24 15:31:56 -0700318 // Needs to be public since it is called via Invoke().
319 void ThrowDBusError() {
320 throw DBus::Error("SomeDBusType", "A handy message");
321 }
Paul Stewart17d90652013-04-04 15:09:11 -0700322 void ResetPendingService() {
323 SetPendingService(NULL);
324 }
Christopher Wileyc6184482012-10-24 15:31:56 -0700325
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700326 size_t GetScanFrequencyCount() const {
327 return wifi_->all_scan_frequencies_.size();
328 }
329
330 void SetScanSize(int min, int max) {
331 wifi_->min_frequencies_to_scan_ = min;
332 wifi_->max_frequencies_to_scan_ = max;
333 }
334
335 // This clears WiFi::scan_session_, thereby allowing WiFi::Scan to create a
336 // real scan session.
337 void ClearScanSession() {
338 wifi_->scan_session_.reset();
339 }
340
341 bool IsScanSessionNull() {
342 return !wifi_->scan_session_;
343 }
344
345 void InstallMockScanSession() {
346 WiFiProvider::FrequencyCountList previous_frequencies;
347 std::set<uint16_t> available_frequencies;
348 ScanSession::FractionList fractions;
349 ScanSession::OnScanFailed null_callback;
350 scan_session_ = new MockScanSession(&netlink_manager_,
351 event_dispatcher_,
352 previous_frequencies,
353 available_frequencies,
354 0,
355 fractions,
356 0,
357 0,
Wade Guthrief22681f2013-05-31 11:46:31 -0700358 null_callback,
359 NULL);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700360 wifi_->scan_session_.reset(scan_session_);
361 }
362
363 // Or DisableProgressiveScan()...
364 void EnableFullScan() {
365 wifi_->progressive_scan_enabled_ = false;
366 }
367
Wade Guthrie7347bf22013-04-30 11:21:51 -0700368 void OnTriggerScanResponse(const Nl80211Message &message) {
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700369 wifi_->scan_session_->OnTriggerScanResponse(message);
370 }
371
Wade Guthrieb0def9f2013-07-12 13:49:18 -0700372 void SetScanState(WiFi::ScanState new_state,
373 WiFi::ScanMethod new_method,
374 const char *reason) {
375 wifi_->SetScanState(new_state, new_method, reason);
Wade Guthrieb9e0ee72013-05-31 09:23:30 -0700376 }
377
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700378 void VerifyScanState(WiFi::ScanState state, WiFi::ScanMethod method) const {
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700379 EXPECT_EQ(state, wifi_->scan_state_);
380 EXPECT_EQ(method, wifi_->scan_method_);
381 }
382
Wade Guthrie227c7742013-10-10 11:06:33 -0700383 void SetRoamThresholdMember(uint16 threshold) {
384 wifi_->roam_threshold_db_ = threshold;
385 }
386
387 bool SetRoamThreshold(uint16 threshold) {
388 return wifi_->SetRoamThreshold(threshold, nullptr);
389 }
390
391 uint16 GetRoamThreshold() const {
392 return wifi_->GetRoamThreshold(nullptr);
393 }
394
mukesh agrawal31950242011-07-14 11:53:38 -0700395 protected:
mukesh agrawal7ec71312011-11-10 02:08:26 +0000396 typedef scoped_refptr<MockWiFiService> MockWiFiServiceRefPtr;
397
Wade Guthrie2ef88ad2013-07-29 15:14:18 -0700398 // Simulate the course of events when the last endpoint of a service is
Paul Stewart3c504012013-01-17 17:49:58 -0800399 // removed.
400 class EndpointRemovalHandler {
Wade Guthriebb9fca22013-04-10 17:21:42 -0700401 public:
402 EndpointRemovalHandler(WiFiRefPtr wifi, const WiFiServiceRefPtr &service)
403 : wifi_(wifi), service_(service) {}
404 virtual ~EndpointRemovalHandler() {}
Paul Stewart3c504012013-01-17 17:49:58 -0800405
Wade Guthriebb9fca22013-04-10 17:21:42 -0700406 WiFiServiceRefPtr OnEndpointRemoved(
407 const WiFiEndpointConstRefPtr &endpoint) {
408 wifi_->DisassociateFromService(service_);
409 return service_;
410 }
Paul Stewart3c504012013-01-17 17:49:58 -0800411
412 private:
413 WiFiRefPtr wifi_;
414 WiFiServiceRefPtr service_;
415 };
416
417 EndpointRemovalHandler *MakeEndpointRemovalHandler(
Wade Guthriebb9fca22013-04-10 17:21:42 -0700418 const WiFiServiceRefPtr &service) {
Paul Stewart3c504012013-01-17 17:49:58 -0800419 return new EndpointRemovalHandler(wifi_, service);
420 }
mukesh agrawalb66c6462012-05-07 11:45:25 -0700421 void CancelScanTimer() {
422 wifi_->scan_timer_callback_.Cancel();
423 }
Paul Stewart3c504012013-01-17 17:49:58 -0800424 // This function creates a new endpoint with a mode set to |mode|. We
425 // synthesize new |path| and |bssid| values, since we don't really care
426 // what they are for unit tests. If "use_ssid" is true, we used the
427 // passed-in ssid, otherwise we create a synthesized value for it as well.
428 WiFiEndpointRefPtr MakeNewEndpoint(const char *mode,
429 bool use_ssid,
430 string *ssid,
431 string *path,
432 string *bssid) {
433 bss_counter_++;
434 if (!use_ssid) {
Ben Chana0ddf462014-02-06 11:32:42 -0800435 *ssid = StringPrintf("ssid%d", bss_counter_);
Paul Stewart3c504012013-01-17 17:49:58 -0800436 }
Ben Chana0ddf462014-02-06 11:32:42 -0800437 *path = StringPrintf("/interface/bss%d", bss_counter_);
438 *bssid = StringPrintf("00:00:00:00:00:%02x", bss_counter_);
Paul Stewart3c504012013-01-17 17:49:58 -0800439 WiFiEndpointRefPtr endpoint = MakeEndpointWithMode(*ssid, *bssid, mode);
440 EXPECT_CALL(wifi_provider_,
441 OnEndpointAdded(EndpointMatch(endpoint))).Times(1);
442 return endpoint;
443 }
444 WiFiEndpointRefPtr MakeEndpoint(const string &ssid, const string &bssid) {
445 return MakeEndpointWithMode(ssid, bssid, kNetworkModeInfrastructure);
446 }
447 WiFiEndpointRefPtr MakeEndpointWithMode(
448 const string &ssid, const string &bssid, const string &mode) {
449 return WiFiEndpoint::MakeOpenEndpoint(
450 &proxy_factory_, NULL, ssid, bssid, mode, 0, 0);
451 }
452 MockWiFiServiceRefPtr MakeMockServiceWithSSID(
453 vector<uint8_t> ssid, const std::string &security) {
454 return new NiceMock<MockWiFiService>(
455 &control_interface_,
456 event_dispatcher_,
457 &metrics_,
458 &manager_,
459 &wifi_provider_,
460 ssid,
Ben Chanf024ef42013-09-20 14:21:38 -0700461 kModeManaged,
Paul Stewart3c504012013-01-17 17:49:58 -0800462 security,
463 false);
464 }
465 MockWiFiServiceRefPtr MakeMockService(const std::string &security) {
466 return MakeMockServiceWithSSID(vector<uint8_t>(1, 'a'), security);
467 }
468 ::DBus::Path MakeNewEndpointAndService(int16_t signal_strength,
469 uint16 frequency,
470 const char *mode,
471 WiFiEndpointRefPtr *endpoint_ptr,
472 MockWiFiServiceRefPtr *service_ptr) {
473 string ssid;
474 ::DBus::Path path;
475 string bssid;
476 WiFiEndpointRefPtr endpoint =
477 MakeNewEndpoint(mode, false, &ssid, &path, &bssid);
478 MockWiFiServiceRefPtr service =
479 MakeMockServiceWithSSID(endpoint->ssid(), endpoint->security_mode());
480 EXPECT_CALL(wifi_provider_, FindServiceForEndpoint(EndpointMatch(endpoint)))
481 .WillRepeatedly(Return(service));
482 ON_CALL(*service, GetEndpointCount()).WillByDefault(Return(1));
483 ReportBSS(path, ssid, bssid, signal_strength, frequency, mode);
484 if (service_ptr) {
485 *service_ptr = service;
486 }
487 if (endpoint_ptr) {
488 *endpoint_ptr = endpoint;
489 }
490 return path;
491 }
492 ::DBus::Path AddEndpointToService(
493 WiFiServiceRefPtr service,
494 int16_t signal_strength,
495 uint16 frequency,
496 const char *mode,
497 WiFiEndpointRefPtr *endpoint_ptr) {
498 string ssid(service->ssid().begin(), service->ssid().end());
499 ::DBus::Path path;
500 string bssid;
501 WiFiEndpointRefPtr endpoint =
502 MakeNewEndpoint(mode, true, &ssid, &path, &bssid);
503 EXPECT_CALL(wifi_provider_, FindServiceForEndpoint(EndpointMatch(endpoint)))
504 .WillRepeatedly(Return(service));
505 ReportBSS(path, ssid, bssid, signal_strength, frequency, mode);
506 if (endpoint_ptr) {
507 *endpoint_ptr = endpoint;
508 }
509 return path;
510 }
511 void InitiateConnect(WiFiServiceRefPtr service) {
Paul Stewarta283e4e2013-10-22 20:50:14 -0700512 wifi_->ConnectTo(service);
Paul Stewart3c504012013-01-17 17:49:58 -0800513 }
514 void InitiateDisconnect(WiFiServiceRefPtr service) {
515 wifi_->DisconnectFrom(service);
516 }
517 MockWiFiServiceRefPtr SetupConnectingService(
518 const DBus::Path &network_path,
519 WiFiEndpointRefPtr *endpoint_ptr,
520 ::DBus::Path *bss_path_ptr) {
Paul Stewart3c504012013-01-17 17:49:58 -0800521 MockWiFiServiceRefPtr service;
522 WiFiEndpointRefPtr endpoint;
523 ::DBus::Path bss_path(MakeNewEndpointAndService(
524 0, 0, kNetworkModeAdHoc, &endpoint, &service));
Paul Stewarta283e4e2013-10-22 20:50:14 -0700525 if (!network_path.empty()) {
526 EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
527 EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_))
528 .WillOnce(Return(network_path));
529 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SelectNetwork(network_path));
530 }
Paul Stewart3c504012013-01-17 17:49:58 -0800531 EXPECT_CALL(*service, SetState(Service::kStateAssociating));
532 InitiateConnect(service);
533 Mock::VerifyAndClearExpectations(service);
534 EXPECT_FALSE(GetPendingTimeout().IsCancelled());
535 if (endpoint_ptr) {
536 *endpoint_ptr = endpoint;
537 }
538 if (bss_path_ptr) {
539 *bss_path_ptr = bss_path;
540 }
541 return service;
542 }
543
544 MockWiFiServiceRefPtr SetupConnectedService(
545 const DBus::Path &network_path,
546 WiFiEndpointRefPtr *endpoint_ptr,
547 ::DBus::Path *bss_path_ptr) {
548 WiFiEndpointRefPtr endpoint;
549 ::DBus::Path bss_path;
550 MockWiFiServiceRefPtr service =
551 SetupConnectingService(network_path, &endpoint, &bss_path);
552 if (endpoint_ptr) {
553 *endpoint_ptr = endpoint;
554 }
555 if (bss_path_ptr) {
556 *bss_path_ptr = bss_path;
557 }
558 EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
559 ReportCurrentBSSChanged(bss_path);
560 EXPECT_TRUE(GetPendingTimeout().IsCancelled());
561 Mock::VerifyAndClearExpectations(service);
562
563 EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
Paul Stewartbca08f82013-07-09 16:32:37 -0700564 EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
Paul Stewart75a68b92013-10-24 10:50:27 -0700565 EXPECT_CALL(*dhcp_provider(), CreateConfig(_, _, _, _, _))
566 .Times(AnyNumber());
Paul Stewart3c504012013-01-17 17:49:58 -0800567 EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
mukesh agrawala5dda0e2013-08-16 11:53:10 -0700568 EXPECT_CALL(wifi_provider_, IncrementConnectCount(_));
Paul Stewart0654ece2013-03-26 15:21:26 -0700569 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
Paul Stewart3c504012013-01-17 17:49:58 -0800570 Mock::VerifyAndClearExpectations(service);
571
572 EXPECT_EQ(service, GetCurrentService());
573 return service;
mukesh agrawal15908392011-11-16 18:29:25 +0000574 }
mukesh agrawalb66c6462012-05-07 11:45:25 -0700575 void FireScanTimer() {
576 wifi_->ScanTimerHandler();
577 }
Wade Guthrie2ef88ad2013-07-29 15:14:18 -0700578 void TriggerScan(WiFi::ScanMethod method) {
579 if (method == WiFi::kScanMethodFull) {
580 wifi_->Scan(Device::kFullScan, NULL, __func__);
581 } else {
582 wifi_->Scan(Device::kProgressiveScan, NULL, __func__);
583 }
Christopher Wileyc68c8672012-11-20 16:52:21 -0800584 }
mukesh agrawal15908392011-11-16 18:29:25 +0000585 const WiFiServiceRefPtr &GetCurrentService() {
586 return wifi_->current_service_;
587 }
Paul Stewartbc6e7392012-05-24 07:07:48 -0700588 void SetCurrentService(const WiFiServiceRefPtr &service) {
589 wifi_->current_service_ = service;
590 }
mukesh agrawal31950242011-07-14 11:53:38 -0700591 const WiFi::EndpointMap &GetEndpointMap() {
mukesh agrawal165e6142011-11-22 02:22:56 +0000592 return wifi_->endpoint_by_rpcid_;
mukesh agrawal31950242011-07-14 11:53:38 -0700593 }
mukesh agrawal15908392011-11-16 18:29:25 +0000594 const WiFiServiceRefPtr &GetPendingService() {
595 return wifi_->pending_service_;
596 }
Paul Stewart2b05e622012-07-13 20:38:44 -0700597 const base::CancelableClosure &GetPendingTimeout() {
598 return wifi_->pending_timeout_callback_;
599 }
Paul Stewart1aff7302012-08-04 20:04:47 -0700600 const base::CancelableClosure &GetReconnectTimeoutCallback() {
Paul Stewart44663922012-07-30 11:03:03 -0700601 return wifi_->reconnect_timeout_callback_;
602 }
Paul Stewart7cd45722013-08-12 14:50:14 -0700603 const string &GetSupplicantBSS() {
604 return wifi_->supplicant_bss_;
605 }
606 void SetSupplicantBSS(const string &bss) {
607 wifi_->supplicant_bss_ = bss;
608 }
Paul Stewart1aff7302012-08-04 20:04:47 -0700609 int GetReconnectTimeoutSeconds() {
610 return WiFi::kReconnectTimeoutSeconds;
611 }
mukesh agrawalb66c6462012-05-07 11:45:25 -0700612 const base::CancelableClosure &GetScanTimer() {
613 return wifi_->scan_timer_callback_;
614 }
mukesh agrawal31950242011-07-14 11:53:38 -0700615 // note: the tests need the proxies referenced by WiFi (not the
Paul Stewarte369ece2012-05-22 09:11:03 -0700616 // proxies instantiated by WiFiObjectTest), to ensure that WiFi
mukesh agrawal31950242011-07-14 11:53:38 -0700617 // sets up its proxies correctly.
618 SupplicantProcessProxyInterface *GetSupplicantProcessProxy() {
619 return wifi_->supplicant_process_proxy_.get();
620 }
Paul Stewart3c504012013-01-17 17:49:58 -0800621 MockSupplicantInterfaceProxy *GetSupplicantInterfaceProxyFromWiFi() {
mukesh agrawal8a3188d2011-12-01 20:56:44 +0000622 return dynamic_cast<MockSupplicantInterfaceProxy *>(
623 wifi_->supplicant_interface_proxy_.get());
mukesh agrawal31950242011-07-14 11:53:38 -0700624 }
Paul Stewart3c504012013-01-17 17:49:58 -0800625 // This function returns the supplicant interface proxy whether
626 // or not we have passed the instantiated object to the WiFi instance
627 // from WiFiObjectTest, so tests don't need to worry about when they
628 // set expectations relative to StartWiFi().
629 MockSupplicantInterfaceProxy *GetSupplicantInterfaceProxy() {
630 MockSupplicantInterfaceProxy *proxy = GetSupplicantInterfaceProxyFromWiFi();
631 return proxy ? proxy : supplicant_interface_proxy_.get();
632 }
mukesh agrawal7ec71312011-11-10 02:08:26 +0000633 const string &GetSupplicantState() {
634 return wifi_->supplicant_state_;
635 }
Paul Stewart835934a2012-12-06 19:27:09 -0800636 void ClearCachedCredentials(const WiFiService *service) {
637 return wifi_->ClearCachedCredentials(service);
638 }
Paul Stewart0427cc12013-03-25 13:50:39 -0700639 void NotifyEndpointChanged(const WiFiEndpointConstRefPtr &endpoint) {
640 wifi_->NotifyEndpointChanged(endpoint);
641 }
Ben Chan381fdcc2012-10-14 21:10:36 -0700642 bool RemoveNetwork(const ::DBus::Path &network) {
643 return wifi_->RemoveNetwork(network);
644 }
mukesh agrawal261daca2011-12-02 18:56:56 +0000645 void RemoveBSS(const ::DBus::Path &bss_path);
mukesh agrawal31950242011-07-14 11:53:38 -0700646 void ReportBSS(const ::DBus::Path &bss_path,
647 const string &ssid,
648 const string &bssid,
649 int16_t signal_strength,
Thieu Lee41a72d2012-02-06 20:46:51 +0000650 uint16 frequency,
mukesh agrawal31950242011-07-14 11:53:38 -0700651 const char *mode);
mukesh agrawalc01f3982012-01-24 13:48:39 -0800652 void ReportIPConfigComplete() {
Paul Stewartc5099532013-12-12 07:53:15 -0800653 wifi_->OnIPConfigUpdated(dhcp_config_);
mukesh agrawalc01f3982012-01-24 13:48:39 -0800654 }
Paul Stewartf6f96482013-07-12 12:49:15 -0700655 void ReportIPConfigFailure() {
656 wifi_->OnIPConfigFailure();
657 }
658 void ReportConnected() {
659 wifi_->OnConnected();
660 }
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700661 void ReportLinkUp() {
662 wifi_->LinkEvent(IFF_LOWER_UP, IFF_LOWER_UP);
663 }
mukesh agrawal31950242011-07-14 11:53:38 -0700664 void ReportScanDone() {
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700665 // Eliminate |scan_session| so |ScanDoneTask| doesn't launch another scan.
666 wifi_->scan_session_.reset();
667 wifi_->ScanDoneTask();
668 // Make a new |scan_session| so that future scanning is done with the mock.
669 InstallMockScanSession();
670 }
671 void ReportScanDoneKeepScanSession() {
mukesh agrawaldc42bb32011-07-28 10:40:26 -0700672 wifi_->ScanDoneTask();
mukesh agrawal31950242011-07-14 11:53:38 -0700673 }
mukesh agrawal15908392011-11-16 18:29:25 +0000674 void ReportCurrentBSSChanged(const string &new_bss) {
675 wifi_->CurrentBSSChanged(new_bss);
676 }
mukesh agrawal7ec71312011-11-10 02:08:26 +0000677 void ReportStateChanged(const string &new_state) {
678 wifi_->StateChanged(new_state);
679 }
Paul Stewart5581d072012-12-17 17:30:20 -0800680 void ReportWiFiDebugScopeChanged(bool enabled) {
681 wifi_->OnWiFiDebugScopeChanged(enabled);
682 }
Paul Stewart7cd45722013-08-12 14:50:14 -0700683 void RequestStationInfo() {
684 wifi_->RequestStationInfo();
685 }
686 void ReportReceivedStationInfo(const Nl80211Message &nl80211_message) {
687 wifi_->OnReceivedStationInfo(nl80211_message);
688 }
Paul Stewartbaf87072013-10-04 17:03:37 -0700689 KeyValueStore GetLinkStatistics() {
690 return wifi_->GetLinkStatistics(NULL);
691 }
mukesh agrawalcf24a242012-05-21 16:46:11 -0700692 void SetPendingService(const WiFiServiceRefPtr &service) {
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700693 wifi_->SetPendingService(service);
mukesh agrawalcf24a242012-05-21 16:46:11 -0700694 }
Paul Stewart11c224b2013-10-22 19:04:40 -0700695 void SetServiceNetworkRpcId(
696 const WiFiServiceRefPtr &service, const string &rpcid) {
697 wifi_->rpcid_by_service_[service.get()] = rpcid;
698 }
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700699 bool SetScanInterval(uint16_t interval_seconds, Error *error) {
700 return wifi_->SetScanInterval(interval_seconds, error);
mukesh agrawalb66c6462012-05-07 11:45:25 -0700701 }
Paul Stewarte369ece2012-05-22 09:11:03 -0700702 uint16_t GetScanInterval() {
703 return wifi_->GetScanInterval(NULL);
704 }
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200705 void StartWiFi(bool supplicant_present) {
Wade Guthriea5995cf2013-07-30 09:31:16 -0700706 EXPECT_CALL(netlink_manager_, SubscribeToEvents(
707 Nl80211Message::kMessageTypeString,
708 NetlinkManager::kEventTypeConfig));
709 EXPECT_CALL(netlink_manager_, SubscribeToEvents(
710 Nl80211Message::kMessageTypeString,
711 NetlinkManager::kEventTypeScan));
712 EXPECT_CALL(netlink_manager_, SubscribeToEvents(
713 Nl80211Message::kMessageTypeString,
714 NetlinkManager::kEventTypeRegulatory));
715 EXPECT_CALL(netlink_manager_, SubscribeToEvents(
716 Nl80211Message::kMessageTypeString,
717 NetlinkManager::kEventTypeMlme));
718 EXPECT_CALL(netlink_manager_, SendNl80211Message(
719 IsNl80211Command(kNl80211FamilyId, NL80211_CMD_GET_WIPHY), _, _));
720
Ben Chan084faca2013-07-02 14:25:12 -0700721 dbus_manager_->Start();
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200722 wifi_->supplicant_present_ = supplicant_present;
mukesh agrawalb66c6462012-05-07 11:45:25 -0700723 wifi_->SetEnabled(true); // Start(NULL, ResultCallback());
mukesh agrawal31950242011-07-14 11:53:38 -0700724 }
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200725 void StartWiFi() {
726 StartWiFi(true);
727 }
mukesh agrawal2f9df4e2012-08-08 12:29:20 -0700728 void OnAfterResume() {
729 wifi_->OnAfterResume();
730 }
731 void OnBeforeSuspend() {
732 wifi_->OnBeforeSuspend();
733 }
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200734 void OnSupplicantAppear() {
Ben Chan084faca2013-07-02 14:25:12 -0700735 wifi_->OnSupplicantAppear(WPASupplicant::kDBusAddr, ":1.7");
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200736 EXPECT_TRUE(wifi_->supplicant_present_);
737 }
738 void OnSupplicantVanish() {
Ben Chan084faca2013-07-02 14:25:12 -0700739 wifi_->OnSupplicantVanish(WPASupplicant::kDBusAddr);
Darin Petkov2b8e44e2012-06-25 15:13:26 +0200740 EXPECT_FALSE(wifi_->supplicant_present_);
741 }
742 bool GetSupplicantPresent() {
743 return wifi_->supplicant_present_;
744 }
Paul Stewart68735052014-02-11 09:16:09 -0800745 bool GetIsRoamingInProgress() {
746 return wifi_->is_roaming_in_progress_;
747 }
748 void SetIPConfig(const IPConfigRefPtr &ipconfig) {
749 return wifi_->set_ipconfig(ipconfig);
750 }
Darin Petkov4a66cc52012-06-15 10:08:29 +0200751 bool SetBgscanMethod(const string &method) {
752 ::DBus::Error error;
753 return DBusAdaptor::SetProperty(
754 wifi_->mutable_store(),
Ben Chanf024ef42013-09-20 14:21:38 -0700755 kBgscanMethodProperty,
Darin Petkov4a66cc52012-06-15 10:08:29 +0200756 DBusAdaptor::StringToVariant(method),
757 &error);
758 }
759
760 void AppendBgscan(WiFiService *service,
761 std::map<std::string, DBus::Variant> *service_params) {
762 wifi_->AppendBgscan(service, service_params);
763 }
764
Paul Stewartbc6e7392012-05-24 07:07:48 -0700765 void ReportCertification(const map<string, ::DBus::Variant> &properties) {
766 wifi_->CertificationTask(properties);
767 }
Paul Stewart10ccbb32012-04-26 15:59:30 -0700768
Paul Stewartdb0f9172012-11-30 16:48:09 -0800769 void ReportEAPEvent(const string &status, const string &parameter) {
770 wifi_->EAPEventTask(status, parameter);
771 }
772
Paul Stewarte369ece2012-05-22 09:11:03 -0700773 void RestartFastScanAttempts() {
774 wifi_->RestartFastScanAttempts();
775 }
776
Paul Stewart1aff7302012-08-04 20:04:47 -0700777 void StartReconnectTimer() {
778 wifi_->StartReconnectTimer();
779 }
780
781 void StopReconnectTimer() {
782 wifi_->StopReconnectTimer();
783 }
784
Paul Stewart3c508e12012-08-09 11:40:06 -0700785 void SetLinkMonitor(LinkMonitor *link_monitor) {
786 wifi_->set_link_monitor(link_monitor);
787 }
788
Paul Stewartbca08f82013-07-09 16:32:37 -0700789 bool SuspectCredentials(const WiFiServiceRefPtr &service,
Paul Stewart1369c2b2013-01-11 05:41:26 -0800790 Service::ConnectFailure *failure) {
791 return wifi_->SuspectCredentials(service, failure);
792 }
793
Paul Stewart3c508e12012-08-09 11:40:06 -0700794 void OnLinkMonitorFailure() {
795 wifi_->OnLinkMonitorFailure();
796 }
797
mukesh agrawalbebf1b82013-04-23 15:06:33 -0700798 bool SetBgscanShortInterval(const uint16 &interval, Error *error) {
799 return wifi_->SetBgscanShortInterval(interval, error);
800 }
801
802 bool SetBgscanSignalThreshold(const int32 &threshold, Error *error) {
803 return wifi_->SetBgscanSignalThreshold(threshold, error);
804 }
805
Paul Stewartdf4c7d62013-11-12 14:05:00 -0800806 bool TDLSDiscover(const string &peer) {
807 return wifi_->TDLSDiscover(peer);
808 }
809
810 bool TDLSSetup(const string &peer) {
811 return wifi_->TDLSSetup(peer);
812 }
813
814 string TDLSStatus(const string &peer) {
815 return wifi_->TDLSStatus(peer);
816 }
817
818 bool TDLSTeardown(const string &peer) {
819 return wifi_->TDLSTeardown(peer);
820 }
821
Paul Stewartc6fbad92013-11-13 14:50:52 -0800822 string PerformTDLSOperation(const string &operation,
823 const string &peer,
824 Error *error) {
825 return wifi_->PerformTDLSOperation(operation, peer, error);
826 }
827
Wade Guthriedf6d61b2013-07-17 11:43:55 -0700828 void TimeoutPendingConnection() {
829 wifi_->PendingTimeoutHandler();
830 }
831
Paul Stewart10ccbb32012-04-26 15:59:30 -0700832 NiceMockControl *control_interface() {
833 return &control_interface_;
834 }
835
Paul Stewart85aea152013-01-22 09:31:56 -0800836 MockMetrics *metrics() {
837 return &metrics_;
838 }
839
mukesh agrawal32399322011-09-01 10:53:43 -0700840 MockManager *manager() {
841 return &manager_;
842 }
Gary Moraind9f893f2012-02-06 10:03:40 -0800843
844 MockDeviceInfo *device_info() {
845 return &device_info_;
846 }
847
848 MockDHCPProvider *dhcp_provider() {
849 return &dhcp_provider_;
850 }
851
mukesh agrawal32399322011-09-01 10:53:43 -0700852 const WiFiConstRefPtr wifi() const {
853 return wifi_;
854 }
855
Ben Chanaf14d452014-02-04 17:31:55 -0800856 MockProxyFactory *proxy_factory() {
mukesh agrawalb20776f2012-02-10 16:00:36 -0800857 return &proxy_factory_;
858 }
859
Paul Stewart3c504012013-01-17 17:49:58 -0800860 MockWiFiProvider *wifi_provider() {
861 return &wifi_provider_;
862 }
863
Paul Stewarte369ece2012-05-22 09:11:03 -0700864 EventDispatcher *event_dispatcher_;
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -0700865 MockScanSession *scan_session_; // Owned by |wifi_|.
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -0700866 NiceMock<MockRTNLHandler> rtnl_handler_;
mukesh agrawal5c05b292012-03-07 10:12:52 -0800867 MockTime time_;
mukesh agrawal31950242011-07-14 11:53:38 -0700868
869 private:
mukesh agrawaldc42bb32011-07-28 10:40:26 -0700870 NiceMockControl control_interface_;
Thieu Le3426c8f2012-01-11 17:35:11 -0800871 MockMetrics metrics_;
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700872 MockGLib glib_;
Chris Masone2ae797d2011-08-23 20:41:00 -0700873 MockManager manager_;
mukesh agrawalc01f3982012-01-24 13:48:39 -0800874 MockDeviceInfo device_info_;
mukesh agrawal31950242011-07-14 11:53:38 -0700875 WiFiRefPtr wifi_;
Paul Stewart3c504012013-01-17 17:49:58 -0800876 NiceMock<MockWiFiProvider> wifi_provider_;
877 int bss_counter_;
mukesh agrawal31950242011-07-14 11:53:38 -0700878
879 // protected fields interspersed between private fields, due to
880 // initialization order
881 protected:
882 static const char kDeviceName[];
Chris Masone626719f2011-08-18 16:58:48 -0700883 static const char kDeviceAddress[];
mukesh agrawal31950242011-07-14 11:53:38 -0700884 static const char kNetworkModeAdHoc[];
885 static const char kNetworkModeInfrastructure[];
Paul Stewart44663922012-07-30 11:03:03 -0700886 static const char kBSSName[];
887 static const char kSSIDName[];
Wade Guthrie227c7742013-10-10 11:06:33 -0700888 static const uint16 kRoamThreshold;
mukesh agrawal31950242011-07-14 11:53:38 -0700889
Ben Chan084faca2013-07-02 14:25:12 -0700890 scoped_ptr<MockDBusServiceProxy> dbus_service_proxy_;
mukesh agrawaldc42bb32011-07-28 10:40:26 -0700891 scoped_ptr<MockSupplicantProcessProxy> supplicant_process_proxy_;
mukesh agrawalb20776f2012-02-10 16:00:36 -0800892 scoped_ptr<MockSupplicantBSSProxy> supplicant_bss_proxy_;
mukesh agrawalf2f68a52011-09-01 12:15:48 -0700893 MockDHCPProvider dhcp_provider_;
894 scoped_refptr<MockDHCPConfig> dhcp_config_;
Ben Chan084faca2013-07-02 14:25:12 -0700895 DBusManager *dbus_manager_;
Paul Stewart735eab52013-03-29 09:19:23 -0700896
897 // These pointers track mock objects owned by the WiFi device instance
898 // and manager so we can perform expectations against them.
Wade Guthrie0cf3c982013-05-29 09:11:35 -0700899 DeviceMockAdaptor *adaptor_;
Paul Stewart735eab52013-03-29 09:19:23 -0700900 MockSupplicantEAPStateHandler *eap_state_handler_;
Wade Guthriebb9fca22013-04-10 17:21:42 -0700901 MockNetlinkManager netlink_manager_;
mukesh agrawal31950242011-07-14 11:53:38 -0700902
903 private:
Paul Stewart3c504012013-01-17 17:49:58 -0800904 scoped_ptr<MockSupplicantInterfaceProxy> supplicant_interface_proxy_;
Ben Chanaf14d452014-02-04 17:31:55 -0800905 MockProxyFactory proxy_factory_;
mukesh agrawal31950242011-07-14 11:53:38 -0700906};
907
Paul Stewarte369ece2012-05-22 09:11:03 -0700908const char WiFiObjectTest::kDeviceName[] = "wlan0";
909const char WiFiObjectTest::kDeviceAddress[] = "000102030405";
910const char WiFiObjectTest::kNetworkModeAdHoc[] = "ad-hoc";
911const char WiFiObjectTest::kNetworkModeInfrastructure[] = "infrastructure";
Paul Stewart44663922012-07-30 11:03:03 -0700912const char WiFiObjectTest::kBSSName[] = "bss0";
913const char WiFiObjectTest::kSSIDName[] = "ssid0";
Wade Guthrie227c7742013-10-10 11:06:33 -0700914const uint16 WiFiObjectTest::kRoamThreshold = 32; // Arbitrary value.
mukesh agrawal31950242011-07-14 11:53:38 -0700915
Paul Stewarte369ece2012-05-22 09:11:03 -0700916void WiFiObjectTest::RemoveBSS(const ::DBus::Path &bss_path) {
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000917 wifi_->BSSRemovedTask(bss_path);
mukesh agrawal261daca2011-12-02 18:56:56 +0000918}
919
Paul Stewarte369ece2012-05-22 09:11:03 -0700920void WiFiObjectTest::ReportBSS(const ::DBus::Path &bss_path,
mukesh agrawal31950242011-07-14 11:53:38 -0700921 const string &ssid,
922 const string &bssid,
923 int16_t signal_strength,
Thieu Lee41a72d2012-02-06 20:46:51 +0000924 uint16 frequency,
mukesh agrawal31950242011-07-14 11:53:38 -0700925 const char *mode) {
926 map<string, ::DBus::Variant> bss_properties;
927
928 {
929 DBus::MessageIter writer(bss_properties["SSID"].writer());
930 writer << vector<uint8_t>(ssid.begin(), ssid.end());
931 }
932 {
933 string bssid_nosep;
934 vector<uint8_t> bssid_bytes;
Ben Chana0ddf462014-02-06 11:32:42 -0800935 base::RemoveChars(bssid, ":", &bssid_nosep);
mukesh agrawal31950242011-07-14 11:53:38 -0700936 base::HexStringToBytes(bssid_nosep, &bssid_bytes);
937
938 DBus::MessageIter writer(bss_properties["BSSID"].writer());
939 writer << bssid_bytes;
940 }
Paul Stewart0654ece2013-03-26 15:21:26 -0700941 bss_properties[WPASupplicant::kBSSPropertySignal].writer().
Thieu Lee41a72d2012-02-06 20:46:51 +0000942 append_int16(signal_strength);
Paul Stewart0654ece2013-03-26 15:21:26 -0700943 bss_properties[WPASupplicant::kBSSPropertyFrequency].writer().
Thieu Lee41a72d2012-02-06 20:46:51 +0000944 append_uint16(frequency);
Paul Stewart0654ece2013-03-26 15:21:26 -0700945 bss_properties[WPASupplicant::kBSSPropertyMode].writer().append_string(mode);
mukesh agrawalb4bc57d2011-12-07 01:07:47 +0000946 wifi_->BSSAddedTask(bss_path, bss_properties);
mukesh agrawal31950242011-07-14 11:53:38 -0700947}
948
Paul Stewarte369ece2012-05-22 09:11:03 -0700949// Most of our tests involve using a real EventDispatcher object.
950class WiFiMainTest : public WiFiObjectTest {
951 public:
952 WiFiMainTest() : WiFiObjectTest(&dispatcher_) {}
953
954 protected:
Wade Guthriea5995cf2013-07-30 09:31:16 -0700955 // A progressive scan requests one or more scans, each of which asks about a
956 // different batch of frequencies/channels.
957 enum WhichBatchOfProgressiveScan {
958 kFirstProgressiveScanBatch,
Wade Guthrie2ef88ad2013-07-29 15:14:18 -0700959 kOnlyFullScanBatch,
Wade Guthriea5995cf2013-07-30 09:31:16 -0700960 kNotFirstProgressiveScanBatch
961 };
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700962 void StartScan(WiFi::ScanMethod method) {
963 if (method == WiFi::kScanMethodFull) {
964 EnableFullScan();
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700965 }
966 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Ben Chanf024ef42013-09-20 14:21:38 -0700967 EXPECT_CALL(*adaptor_, EmitBoolChanged(kPoweredProperty, _)).
Wade Guthriea5995cf2013-07-30 09:31:16 -0700968 Times(AnyNumber());
Wade Guthrie2ef88ad2013-07-29 15:14:18 -0700969 // Using kFirstProgressiveScanBatch regardless of the method since
970 // kFOnlyFullScanBatch does exactly the same thing.
971 ExpectScanStart(method, false);
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700972 StartWiFi();
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700973 dispatcher_.DispatchPendingEvents();
974 VerifyScanState(WiFi::kScanScanning, method);
975 }
976
977 MockWiFiServiceRefPtr AttemptConnection(WiFi::ScanMethod method,
978 WiFiEndpointRefPtr *endpoint,
979 ::DBus::Path *bss_path) {
980 WiFiEndpointRefPtr dummy_endpoint;
981 if (!endpoint) {
982 endpoint = &dummy_endpoint; // If caller doesn't care about endpoint.
983 }
984
985 ::DBus::Path dummy_bss_path;
986 if (!bss_path) {
987 bss_path = &dummy_bss_path; // If caller doesn't care about bss_path.
988 }
989
Wade Guthriea5995cf2013-07-30 09:31:16 -0700990 ExpectScanStop();
991 ExpectConnecting();
Wade Guthrie9f4aa152013-07-29 16:03:14 -0700992 MockWiFiServiceRefPtr service =
993 SetupConnectingService(DBus::Path(), endpoint, bss_path);
994 ReportScanDoneKeepScanSession();
995 dispatcher_.DispatchPendingEvents();
996 VerifyScanState(WiFi::kScanConnecting, method);
997
998 return service;
999 }
1000
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001001 void ExpectScanStart(WiFi::ScanMethod method, bool is_continued) {
Wade Guthriea5995cf2013-07-30 09:31:16 -07001002 if (method == WiFi::kScanMethodProgressive) {
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001003 ASSERT_FALSE(IsScanSessionNull());
Wade Guthriea5995cf2013-07-30 09:31:16 -07001004 EXPECT_CALL(*scan_session_, HasMoreFrequencies());
1005 EXPECT_CALL(*scan_session_, InitiateScan());
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001006 } else {
1007 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
Wade Guthriea5995cf2013-07-30 09:31:16 -07001008 }
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001009 if (!is_continued) {
Ben Chanf024ef42013-09-20 14:21:38 -07001010 EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty,
Wade Guthriea5995cf2013-07-30 09:31:16 -07001011 true));
1012 EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_));
1013 }
1014 }
1015
1016 // Scanning can stop for any reason (including transitioning to connecting).
1017 void ExpectScanStop() {
Ben Chanf024ef42013-09-20 14:21:38 -07001018 EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
Wade Guthriea5995cf2013-07-30 09:31:16 -07001019 }
1020
1021 void ExpectConnecting() {
1022 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
1023 EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
1024 }
1025
1026 void ExpectConnected() {
1027 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
1028 ExpectScanIdle();
1029 }
1030
1031 void ExpectFoundNothing() {
1032 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
1033 EXPECT_CALL(*metrics(), ResetConnectTimer(_));
1034 ExpectScanIdle();
1035 }
1036
1037 void ExpectScanIdle() {
1038 EXPECT_CALL(*metrics(), ResetScanTimer(_));
1039 EXPECT_CALL(*metrics(), ResetConnectTimer(_)).RetiresOnSaturation();
1040 }
1041
Paul Stewarte369ece2012-05-22 09:11:03 -07001042 EventDispatcher dispatcher_;
1043};
1044
mukesh agrawal31950242011-07-14 11:53:38 -07001045TEST_F(WiFiMainTest, ProxiesSetUpDuringStart) {
1046 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
Paul Stewart3c504012013-01-17 17:49:58 -08001047 EXPECT_TRUE(GetSupplicantInterfaceProxyFromWiFi() == NULL);
mukesh agrawal31950242011-07-14 11:53:38 -07001048
1049 StartWiFi();
1050 EXPECT_FALSE(GetSupplicantProcessProxy() == NULL);
Paul Stewart3c504012013-01-17 17:49:58 -08001051 EXPECT_FALSE(GetSupplicantInterfaceProxyFromWiFi() == NULL);
mukesh agrawal31950242011-07-14 11:53:38 -07001052}
1053
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001054TEST_F(WiFiMainTest, SupplicantPresent) {
1055 EXPECT_FALSE(GetSupplicantPresent());
1056}
1057
Wade Guthrie227c7742013-10-10 11:06:33 -07001058TEST_F(WiFiMainTest, RoamThresholdProperty) {
1059 static const uint16_t kRoamThreshold16 = 16;
1060 static const uint16_t kRoamThreshold32 = 32;
1061
1062 StartWiFi(false); // No supplicant present.
1063 OnSupplicantAppear();
1064
1065 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
1066 SetRoamThreshold(kRoamThreshold16));
1067 EXPECT_TRUE(SetRoamThreshold(kRoamThreshold16));
1068 EXPECT_EQ(GetRoamThreshold(), kRoamThreshold16);
1069
1070 // Try a different number
1071 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
1072 SetRoamThreshold(kRoamThreshold32));
1073 EXPECT_TRUE(SetRoamThreshold(kRoamThreshold32));
1074 EXPECT_EQ(GetRoamThreshold(), kRoamThreshold32);
1075}
1076
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001077TEST_F(WiFiMainTest, OnSupplicantAppearStarted) {
1078 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
1079
Ben Chan084faca2013-07-02 14:25:12 -07001080 EXPECT_CALL(*dbus_service_proxy_.get(),
1081 GetNameOwner(WPASupplicant::kDBusAddr, _, _, _));
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001082 StartWiFi(false); // No supplicant present.
1083 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
1084
Wade Guthrie227c7742013-10-10 11:06:33 -07001085 SetRoamThresholdMember(kRoamThreshold);
1086 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveAllNetworks());
1087 EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(0));
1088 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetFastReauth(false));
1089 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetRoamThreshold(kRoamThreshold));
1090 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetScanInterval(_));
1091 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SetDisableHighBitrates(true));
1092
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001093 OnSupplicantAppear();
1094 EXPECT_FALSE(GetSupplicantProcessProxy() == NULL);
Darin Petkov9cd7ca12012-07-03 11:06:40 +02001095
1096 // If supplicant reappears while the device is started, the device should be
1097 // restarted.
1098 EXPECT_CALL(*manager(), DeregisterDevice(_));
1099 EXPECT_CALL(*manager(), RegisterDevice(_));
1100 OnSupplicantAppear();
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001101}
1102
1103TEST_F(WiFiMainTest, OnSupplicantAppearStopped) {
1104 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
1105
1106 OnSupplicantAppear();
1107 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
Darin Petkov9cd7ca12012-07-03 11:06:40 +02001108
1109 // If supplicant reappears while the device is stopped, the device should not
1110 // be restarted.
1111 EXPECT_CALL(*manager(), DeregisterDevice(_)).Times(0);
1112 OnSupplicantAppear();
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001113}
1114
1115TEST_F(WiFiMainTest, OnSupplicantVanishStarted) {
1116 EXPECT_TRUE(GetSupplicantProcessProxy() == NULL);
1117
1118 StartWiFi();
1119 EXPECT_FALSE(GetSupplicantProcessProxy() == NULL);
1120 EXPECT_TRUE(GetSupplicantPresent());
1121
1122 EXPECT_CALL(*manager(), DeregisterDevice(_));
1123 EXPECT_CALL(*manager(), RegisterDevice(_));
1124 OnSupplicantVanish();
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001125}
1126
1127TEST_F(WiFiMainTest, OnSupplicantVanishStopped) {
1128 OnSupplicantAppear();
1129 EXPECT_TRUE(GetSupplicantPresent());
1130 EXPECT_CALL(*manager(), DeregisterDevice(_)).Times(0);
1131 OnSupplicantVanish();
1132}
1133
Paul Stewart549d44c2012-07-03 12:40:25 -07001134TEST_F(WiFiMainTest, OnSupplicantVanishedWhileConnected) {
Paul Stewart3c504012013-01-17 17:49:58 -08001135 StartWiFi();
1136 WiFiEndpointRefPtr endpoint;
1137 WiFiServiceRefPtr service(
1138 SetupConnectedService(DBus::Path(), &endpoint, NULL));
Paul Stewart549d44c2012-07-03 12:40:25 -07001139 ScopedMockLog log;
1140 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
Christopher Wileyc6184482012-10-24 15:31:56 -07001141 EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
Paul Stewart549d44c2012-07-03 12:40:25 -07001142 EndsWith("silently resetting current_service_.")));
1143 EXPECT_CALL(*manager(), DeregisterDevice(_))
1144 .WillOnce(InvokeWithoutArgs(this, &WiFiObjectTest::StopWiFi));
Paul Stewart3c504012013-01-17 17:49:58 -08001145 scoped_ptr<EndpointRemovalHandler> handler(
1146 MakeEndpointRemovalHandler(service));
1147 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
1148 .WillOnce(Invoke(handler.get(),
1149 &EndpointRemovalHandler::OnEndpointRemoved));
1150 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
Paul Stewart549d44c2012-07-03 12:40:25 -07001151 EXPECT_CALL(*manager(), RegisterDevice(_));
1152 OnSupplicantVanish();
1153 EXPECT_TRUE(GetCurrentService() == NULL);
1154}
1155
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001156TEST_F(WiFiMainTest, CleanStart_FullScan) {
1157 EnableFullScan();
mukesh agrawal31950242011-07-14 11:53:38 -07001158 EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_));
1159 EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_))
1160 .Times(AnyNumber())
1161 .WillRepeatedly(Throw(
1162 DBus::Error(
1163 "fi.w1.wpa_supplicant1.InterfaceUnknown",
1164 "test threw fi.w1.wpa_supplicant1.InterfaceUnknown")));
mukesh agrawalb66c6462012-05-07 11:45:25 -07001165 EXPECT_TRUE(GetScanTimer().IsCancelled());
mukesh agrawal31950242011-07-14 11:53:38 -07001166 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001167 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
mukesh agrawal32399322011-09-01 10:53:43 -07001168 dispatcher_.DispatchPendingEvents();
mukesh agrawalb66c6462012-05-07 11:45:25 -07001169 EXPECT_FALSE(GetScanTimer().IsCancelled());
mukesh agrawal31950242011-07-14 11:53:38 -07001170}
1171
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001172TEST_F(WiFiMainTest, CleanStart) {
1173 EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_));
1174 EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_))
1175 .Times(AnyNumber())
1176 .WillRepeatedly(Throw(
1177 DBus::Error(
1178 "fi.w1.wpa_supplicant1.InterfaceUnknown",
1179 "test threw fi.w1.wpa_supplicant1.InterfaceUnknown")));
1180 EXPECT_TRUE(GetScanTimer().IsCancelled());
1181 StartWiFi();
1182 EXPECT_CALL(*scan_session_, InitiateScan());
1183 dispatcher_.DispatchPendingEvents();
1184 EXPECT_FALSE(GetScanTimer().IsCancelled());
1185}
1186
Paul Stewart835934a2012-12-06 19:27:09 -08001187TEST_F(WiFiMainTest, ClearCachedCredentials) {
Paul Stewart3c504012013-01-17 17:49:58 -08001188 StartWiFi();
Paul Stewart835934a2012-12-06 19:27:09 -08001189 DBus::Path network = "/test/path";
Paul Stewart3c504012013-01-17 17:49:58 -08001190 WiFiServiceRefPtr service(SetupConnectedService(network, NULL, NULL));
1191 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network));
Paul Stewart835934a2012-12-06 19:27:09 -08001192 ClearCachedCredentials(service);
1193}
1194
Paul Stewart0427cc12013-03-25 13:50:39 -07001195TEST_F(WiFiMainTest, NotifyEndpointChanged) {
1196 WiFiEndpointRefPtr endpoint =
1197 MakeEndpointWithMode("ssid", "00:00:00:00:00:00", kNetworkModeAdHoc);
1198 EXPECT_CALL(*wifi_provider(), OnEndpointUpdated(EndpointMatch(endpoint)));
1199 NotifyEndpointChanged(endpoint);
1200}
1201
Ben Chan381fdcc2012-10-14 21:10:36 -07001202TEST_F(WiFiMainTest, RemoveNetwork) {
1203 DBus::Path network = "/test/path";
Ben Chan381fdcc2012-10-14 21:10:36 -07001204 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001205 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network));
Ben Chan381fdcc2012-10-14 21:10:36 -07001206 EXPECT_TRUE(RemoveNetwork(network));
1207}
1208
1209TEST_F(WiFiMainTest, RemoveNetworkWhenSupplicantReturnsNetworkUnknown) {
1210 DBus::Path network = "/test/path";
Paul Stewart3c504012013-01-17 17:49:58 -08001211 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network))
Ben Chan381fdcc2012-10-14 21:10:36 -07001212 .WillRepeatedly(Throw(
1213 DBus::Error(
1214 "fi.w1.wpa_supplicant1.NetworkUnknown",
1215 "test threw fi.w1.wpa_supplicant1.NetworkUnknown")));
1216 StartWiFi();
1217 EXPECT_TRUE(RemoveNetwork(network));
1218}
1219
Arman Ugurayed8e6102012-11-29 14:47:20 -08001220TEST_F(WiFiMainTest, UseArpGateway) {
Paul Stewart75a68b92013-10-24 10:50:27 -07001221 EXPECT_CALL(dhcp_provider_, CreateConfig(kDeviceName, _, _, true, false))
Arman Ugurayed8e6102012-11-29 14:47:20 -08001222 .WillOnce(Return(dhcp_config_));
1223 const_cast<WiFi *>(wifi().get())->AcquireIPConfig();
1224}
1225
Ben Chan381fdcc2012-10-14 21:10:36 -07001226TEST_F(WiFiMainTest, RemoveNetworkWhenSupplicantReturnsInvalidArgs) {
1227 DBus::Path network = "/test/path";
Paul Stewart3c504012013-01-17 17:49:58 -08001228 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network))
Ben Chan381fdcc2012-10-14 21:10:36 -07001229 .WillRepeatedly(Throw(
1230 DBus::Error(
1231 "fi.w1.wpa_supplicant1.InvalidArgs",
1232 "test threw fi.w1.wpa_supplicant1.InvalidArgs")));
1233 StartWiFi();
1234 EXPECT_FALSE(RemoveNetwork(network));
1235}
1236
1237TEST_F(WiFiMainTest, RemoveNetworkWhenSupplicantReturnsUnknownError) {
1238 DBus::Path network = "/test/path";
Paul Stewart3c504012013-01-17 17:49:58 -08001239 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(network))
Ben Chan381fdcc2012-10-14 21:10:36 -07001240 .WillRepeatedly(Throw(
1241 DBus::Error(
1242 "fi.w1.wpa_supplicant1.UnknownError",
1243 "test threw fi.w1.wpa_supplicant1.UnknownError")));
1244 StartWiFi();
1245 EXPECT_FALSE(RemoveNetwork(network));
1246}
1247
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001248TEST_F(WiFiMainTest, Restart_FullScan) {
1249 EnableFullScan();
mukesh agrawal31950242011-07-14 11:53:38 -07001250 EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_))
1251 .Times(AnyNumber())
1252 .WillRepeatedly(Throw(
1253 DBus::Error(
1254 "fi.w1.wpa_supplicant1.InterfaceExists",
Darin Petkov2b8e44e2012-06-25 15:13:26 +02001255 "test threw fi.w1.wpa_supplicant1.InterfaceExists")));
mukesh agrawal31950242011-07-14 11:53:38 -07001256 EXPECT_CALL(*supplicant_process_proxy_, GetInterface(_));
Paul Stewart3c504012013-01-17 17:49:58 -08001257 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
mukesh agrawal31950242011-07-14 11:53:38 -07001258 StartWiFi();
mukesh agrawal32399322011-09-01 10:53:43 -07001259 dispatcher_.DispatchPendingEvents();
mukesh agrawal31950242011-07-14 11:53:38 -07001260}
1261
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001262TEST_F(WiFiMainTest, Restart) {
1263 EXPECT_CALL(*supplicant_process_proxy_, CreateInterface(_))
1264 .Times(AnyNumber())
1265 .WillRepeatedly(Throw(
1266 DBus::Error(
1267 "fi.w1.wpa_supplicant1.InterfaceExists",
1268 "test threw fi.w1.wpa_supplicant1.InterfaceExists")));
1269 EXPECT_CALL(*scan_session_, InitiateScan());
1270 StartWiFi();
1271 dispatcher_.DispatchPendingEvents();
1272}
1273
mukesh agrawal31950242011-07-14 11:53:38 -07001274TEST_F(WiFiMainTest, StartClearsState) {
Paul Stewart3c504012013-01-17 17:49:58 -08001275 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveAllNetworks());
1276 EXPECT_CALL(*GetSupplicantInterfaceProxy(), FlushBSS(_));
mukesh agrawal31950242011-07-14 11:53:38 -07001277 StartWiFi();
1278}
1279
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001280TEST_F(WiFiMainTest, NoScansWhileConnecting_FullScan) {
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001281 // Setup 'connecting' state.
1282 StartScan(WiFi::kScanMethodFull);
Paul Stewart3c504012013-01-17 17:49:58 -08001283 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001284
1285 ExpectScanStop();
1286 ExpectConnecting();
Ben Chanf024ef42013-09-20 14:21:38 -07001287 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001288 InitiateConnect(service);
1289 VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodFull);
1290
1291 // If we're connecting, we ignore scan requests and stay on channel.
Christopher Wileyc68c8672012-11-20 16:52:21 -08001292 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001293 TriggerScan(WiFi::kScanMethodFull);
Christopher Wileyc68c8672012-11-20 16:52:21 -08001294 dispatcher_.DispatchPendingEvents();
1295 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Paul Stewart3c504012013-01-17 17:49:58 -08001296 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001297
1298 // Terminate the scan.
1299 ExpectFoundNothing();
1300 TimeoutPendingConnection();
1301 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
1302
1303 // Start a fresh scan.
1304 ExpectScanStart(WiFi::kScanMethodFull, false);
1305 TriggerScan(WiFi::kScanMethodFull);
Christopher Wileyc68c8672012-11-20 16:52:21 -08001306 dispatcher_.DispatchPendingEvents();
1307 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Paul Stewart3c504012013-01-17 17:49:58 -08001308 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001309
Christopher Wileyc68c8672012-11-20 16:52:21 -08001310 // Similarly, ignore scans when our connected service is reconnecting.
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001311 ExpectScanStop();
1312 ExpectScanIdle();
Christopher Wileyc68c8672012-11-20 16:52:21 -08001313 SetPendingService(NULL);
1314 SetCurrentService(service);
Paul Stewart3c504012013-01-17 17:49:58 -08001315 EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(true));
Christopher Wileyc68c8672012-11-20 16:52:21 -08001316 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001317 TriggerScan(WiFi::kScanMethodFull);
Christopher Wileyc68c8672012-11-20 16:52:21 -08001318 dispatcher_.DispatchPendingEvents();
1319 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Paul Stewart3c504012013-01-17 17:49:58 -08001320 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001321
Christopher Wileyc68c8672012-11-20 16:52:21 -08001322 // But otherwise we'll honor the request.
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001323 EXPECT_CALL(*service, IsConnecting()).Times(AtLeast(2)).
1324 WillRepeatedly(Return(false));
1325 ExpectScanStart(WiFi::kScanMethodFull, false);
1326 TriggerScan(WiFi::kScanMethodFull);
Christopher Wileyc68c8672012-11-20 16:52:21 -08001327 dispatcher_.DispatchPendingEvents();
1328 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Paul Stewart3c504012013-01-17 17:49:58 -08001329 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001330
1331 // Silence messages from the destructor.
1332 ExpectScanStop();
1333 ExpectScanIdle();
Christopher Wileyc68c8672012-11-20 16:52:21 -08001334}
1335
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001336TEST_F(WiFiMainTest, NoScansWhileConnecting) {
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001337 // Setup 'connecting' state.
1338 StartScan(WiFi::kScanMethodProgressive);
1339 ExpectScanStop();
1340 ExpectConnecting();
Ben Chanf024ef42013-09-20 14:21:38 -07001341 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001342 InitiateConnect(service);
1343 VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
1344
1345 // If we're connecting, we ignore scan requests and stay on channel.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001346 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001347 TriggerScan(WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001348 dispatcher_.DispatchPendingEvents();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001349 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001350 Mock::VerifyAndClearExpectations(scan_session_);
1351
1352 // Terminate the scan.
1353 ExpectFoundNothing();
1354 TimeoutPendingConnection();
1355 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
1356
1357 // Start a fresh scan.
1358 InstallMockScanSession();
1359 ExpectScanStart(WiFi::kScanMethodProgressive, false);
1360 TriggerScan(WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001361 dispatcher_.DispatchPendingEvents();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001362 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001363 Mock::VerifyAndClearExpectations(scan_session_);
1364
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001365 // Similarly, ignore scans when our connected service is reconnecting.
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001366 ExpectScanStop();
1367 ExpectScanIdle();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001368 SetPendingService(NULL);
1369 SetCurrentService(service);
1370 EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(true));
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001371 InstallMockScanSession();
1372 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
1373 TriggerScan(WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001374 dispatcher_.DispatchPendingEvents();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001375 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001376 Mock::VerifyAndClearExpectations(scan_session_);
1377
1378 // Unlike Full scan, Progressive scan will reject attempts to scan while
1379 // we're connected.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001380 EXPECT_CALL(*service, IsConnecting()).WillOnce(Return(false));
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001381 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
1382 TriggerScan(WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001383 dispatcher_.DispatchPendingEvents();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001384 Mock::VerifyAndClearExpectations(service);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001385 Mock::VerifyAndClearExpectations(scan_session_);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001386}
1387
1388TEST_F(WiFiMainTest, ResumeStartsScanWhenIdle_FullScan) {
1389 EnableFullScan();
Paul Stewart3c504012013-01-17 17:49:58 -08001390 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
Gary Morainac1bdb42012-02-16 17:42:29 -08001391 StartWiFi();
1392 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08001393 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
mukesh agrawal5c05b292012-03-07 10:12:52 -08001394 ReportScanDone();
Gary Morainac1bdb42012-02-16 17:42:29 -08001395 ASSERT_TRUE(wifi()->IsIdle());
1396 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001397 OnAfterResume();
Gary Morainac1bdb42012-02-16 17:42:29 -08001398 dispatcher_.DispatchPendingEvents();
1399}
1400
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001401TEST_F(WiFiMainTest, ResumeStartsScanWhenIdle) {
1402 EXPECT_CALL(*scan_session_, InitiateScan());
1403 StartWiFi();
1404 dispatcher_.DispatchPendingEvents();
1405 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1406 ReportScanDone();
1407 ASSERT_TRUE(wifi()->IsIdle());
1408 dispatcher_.DispatchPendingEvents();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001409 OnAfterResume();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001410 EXPECT_TRUE(scan_session_ != NULL);
1411 InstallMockScanSession();
1412 EXPECT_CALL(*scan_session_, InitiateScan());
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001413 dispatcher_.DispatchPendingEvents();
1414}
1415
1416TEST_F(WiFiMainTest, SuspendDoesNotStartScan_FullScan) {
1417 EnableFullScan();
Paul Stewart3c504012013-01-17 17:49:58 -08001418 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
Gary Morainac1bdb42012-02-16 17:42:29 -08001419 StartWiFi();
1420 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08001421 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Gary Morainac1bdb42012-02-16 17:42:29 -08001422 ASSERT_TRUE(wifi()->IsIdle());
1423 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001424 OnBeforeSuspend();
Gary Morainac1bdb42012-02-16 17:42:29 -08001425 dispatcher_.DispatchPendingEvents();
1426}
1427
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001428TEST_F(WiFiMainTest, SuspendDoesNotStartScan) {
1429 EXPECT_CALL(*scan_session_, InitiateScan());
1430 StartWiFi();
1431 dispatcher_.DispatchPendingEvents();
1432 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1433 ASSERT_TRUE(wifi()->IsIdle());
1434 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
1435 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
1436 OnBeforeSuspend();
1437 dispatcher_.DispatchPendingEvents();
1438}
1439
1440TEST_F(WiFiMainTest, ResumeDoesNotStartScanWhenNotIdle_FullScan) {
1441 EnableFullScan();
Paul Stewart3c504012013-01-17 17:49:58 -08001442 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
Gary Morainac1bdb42012-02-16 17:42:29 -08001443 StartWiFi();
Gary Morainac1bdb42012-02-16 17:42:29 -08001444 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08001445 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1446 WiFiServiceRefPtr service(SetupConnectedService(DBus::Path(), NULL, NULL));
1447 EXPECT_FALSE(wifi()->IsIdle());
1448 ScopedMockLog log;
mukesh agrawal3ab56ac2012-05-31 14:41:43 -07001449 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001450 EXPECT_CALL(log, Log(_, _, EndsWith("already connecting or connected.")));
Gary Morainac1bdb42012-02-16 17:42:29 -08001451 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07001452 OnAfterResume();
Gary Morainac1bdb42012-02-16 17:42:29 -08001453 dispatcher_.DispatchPendingEvents();
1454}
1455
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001456TEST_F(WiFiMainTest, ResumeDoesNotStartScanWhenNotIdle) {
1457 EXPECT_CALL(*scan_session_, InitiateScan());
1458 StartWiFi();
1459 dispatcher_.DispatchPendingEvents();
1460 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1461 WiFiServiceRefPtr service(SetupConnectedService(DBus::Path(), NULL, NULL));
1462 EXPECT_FALSE(wifi()->IsIdle());
1463 ScopedMockLog log;
1464 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001465 EXPECT_CALL(log, Log(_, _, EndsWith("already connecting or connected.")));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001466 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001467 EXPECT_TRUE(IsScanSessionNull());
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001468 OnAfterResume();
1469 dispatcher_.DispatchPendingEvents();
1470}
1471
mukesh agrawal31950242011-07-14 11:53:38 -07001472TEST_F(WiFiMainTest, ScanResults) {
Paul Stewart3c504012013-01-17 17:49:58 -08001473 EXPECT_CALL(*wifi_provider(), OnEndpointAdded(_)).Times(5);
mukesh agrawal31950242011-07-14 11:53:38 -07001474 StartWiFi();
Thieu Lee41a72d2012-02-06 20:46:51 +00001475 ReportBSS("bss0", "ssid0", "00:00:00:00:00:00", 0, 0, kNetworkModeAdHoc);
mukesh agrawal31950242011-07-14 11:53:38 -07001476 ReportBSS(
Thieu Lee41a72d2012-02-06 20:46:51 +00001477 "bss1", "ssid1", "00:00:00:00:00:01", 1, 0, kNetworkModeInfrastructure);
mukesh agrawal31950242011-07-14 11:53:38 -07001478 ReportBSS(
Thieu Lee41a72d2012-02-06 20:46:51 +00001479 "bss2", "ssid2", "00:00:00:00:00:02", 2, 0, kNetworkModeInfrastructure);
mukesh agrawal31950242011-07-14 11:53:38 -07001480 ReportBSS(
Thieu Lee41a72d2012-02-06 20:46:51 +00001481 "bss3", "ssid3", "00:00:00:00:00:03", 3, 0, kNetworkModeInfrastructure);
1482 const uint16 frequency = 2412;
1483 ReportBSS("bss4", "ssid4", "00:00:00:00:00:04", 4, frequency,
1484 kNetworkModeAdHoc);
1485
1486 const WiFi::EndpointMap &endpoints_by_rpcid = GetEndpointMap();
1487 EXPECT_EQ(5, endpoints_by_rpcid.size());
1488
1489 WiFi::EndpointMap::const_iterator i;
1490 WiFiEndpointRefPtr endpoint;
1491 for (i = endpoints_by_rpcid.begin();
1492 i != endpoints_by_rpcid.end();
1493 ++i) {
1494 if (i->second->bssid_string() == "00:00:00:00:00:04")
1495 break;
1496 }
1497 ASSERT_TRUE(i != endpoints_by_rpcid.end());
1498 EXPECT_EQ(4, i->second->signal_strength());
1499 EXPECT_EQ(frequency, i->second->frequency());
1500 EXPECT_EQ("adhoc", i->second->network_mode());
mukesh agrawal31950242011-07-14 11:53:38 -07001501}
1502
mukesh agrawal31950242011-07-14 11:53:38 -07001503TEST_F(WiFiMainTest, ScanCompleted) {
1504 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001505 WiFiEndpointRefPtr ap0 = MakeEndpointWithMode("ssid0", "00:00:00:00:00:00",
1506 kNetworkModeAdHoc);
1507 WiFiEndpointRefPtr ap1 = MakeEndpoint("ssid1", "00:00:00:00:00:01");
1508 WiFiEndpointRefPtr ap2 = MakeEndpoint("ssid2", "00:00:00:00:00:02");
1509 EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap0))).Times(1);
1510 EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap1))).Times(1);
1511 EXPECT_CALL(*wifi_provider(), OnEndpointAdded(EndpointMatch(ap2))).Times(1);
1512 ReportBSS("bss0", ap0->ssid_string(), ap0->bssid_string(), 0, 0,
1513 kNetworkModeAdHoc);
1514 ReportBSS("bss1", ap1->ssid_string(), ap1->bssid_string(), 0, 0,
1515 kNetworkModeInfrastructure);
1516 ReportBSS("bss2", ap2->ssid_string(), ap2->bssid_string(), 0, 0,
1517 kNetworkModeInfrastructure);
mukesh agrawal31950242011-07-14 11:53:38 -07001518 ReportScanDone();
Paul Stewart3c504012013-01-17 17:49:58 -08001519 Mock::VerifyAndClearExpectations(wifi_provider());
1520
1521 EXPECT_CALL(*wifi_provider(), OnEndpointAdded(_)).Times(0);
mukesh agrawalb3857612012-01-18 16:23:29 -08001522
mukesh agrawale9adda12012-02-09 18:33:48 -08001523 // BSSes with SSIDs that start with NULL should be filtered.
Thieu Lee41a72d2012-02-06 20:46:51 +00001524 ReportBSS("bss3", string(1, 0), "00:00:00:00:00:03", 3, 0, kNetworkModeAdHoc);
mukesh agrawalb3857612012-01-18 16:23:29 -08001525
mukesh agrawale9adda12012-02-09 18:33:48 -08001526 // BSSes with empty SSIDs should be filtered.
1527 ReportBSS("bss3", string(), "00:00:00:00:00:03", 3, 0, kNetworkModeAdHoc);
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001528}
1529
1530TEST_F(WiFiMainTest, LoneBSSRemovedWhileConnected) {
1531 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001532 WiFiEndpointRefPtr endpoint;
1533 DBus::Path bss_path;
1534 WiFiServiceRefPtr service(
1535 SetupConnectedService(DBus::Path(), &endpoint, &bss_path));
1536 scoped_ptr<EndpointRemovalHandler> handler(
1537 MakeEndpointRemovalHandler(service));
1538 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
1539 .WillOnce(Invoke(handler.get(),
1540 &EndpointRemovalHandler::OnEndpointRemoved));
mukesh agrawal8a3188d2011-12-01 20:56:44 +00001541 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Paul Stewart3c504012013-01-17 17:49:58 -08001542 RemoveBSS(bss_path);
mukesh agrawal261daca2011-12-02 18:56:56 +00001543}
1544
1545TEST_F(WiFiMainTest, NonSolitaryBSSRemoved) {
1546 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001547 WiFiEndpointRefPtr endpoint;
1548 DBus::Path bss_path;
1549 WiFiServiceRefPtr service(
1550 SetupConnectedService(DBus::Path(), &endpoint, &bss_path));
1551 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
1552 .WillOnce(Return(reinterpret_cast<WiFiService *>(NULL)));
1553 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
1554 RemoveBSS(bss_path);
mukesh agrawal31950242011-07-14 11:53:38 -07001555}
1556
Paul Stewart835934a2012-12-06 19:27:09 -08001557TEST_F(WiFiMainTest, ReconnectPreservesDBusPath) {
Paul Stewart835934a2012-12-06 19:27:09 -08001558 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001559 DBus::Path kPath = "/test/path";
Paul Stewarta283e4e2013-10-22 20:50:14 -07001560 MockWiFiServiceRefPtr service(SetupConnectedService(kPath, NULL, NULL));
Paul Stewart835934a2012-12-06 19:27:09 -08001561
1562 // Return the service to a connectable state.
Paul Stewart3c504012013-01-17 17:49:58 -08001563 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Paul Stewart835934a2012-12-06 19:27:09 -08001564 InitiateDisconnect(service);
Paul Stewart3c504012013-01-17 17:49:58 -08001565 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1566
1567 // Complete the disconnection by reporting a BSS change.
Paul Stewart0654ece2013-03-26 15:21:26 -07001568 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
Paul Stewart835934a2012-12-06 19:27:09 -08001569
1570 // A second connection attempt should remember the DBus path associated
Paul Stewarta283e4e2013-10-22 20:50:14 -07001571 // with this service, and should not request new configuration parameters.
1572 EXPECT_CALL(*service, GetSupplicantConfigurationParameters()).Times(0);
Paul Stewart3c504012013-01-17 17:49:58 -08001573 EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_)).Times(0);
1574 EXPECT_CALL(*GetSupplicantInterfaceProxy(), SelectNetwork(kPath));
Paul Stewart835934a2012-12-06 19:27:09 -08001575 InitiateConnect(service);
1576}
1577
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001578TEST_F(WiFiMainTest, DisconnectPendingService) {
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001579 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001580 MockWiFiServiceRefPtr service(
1581 SetupConnectingService(DBus::Path(), NULL, NULL));
1582 EXPECT_TRUE(GetPendingService() == service.get());
1583 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Peter Qiu49438222014-03-14 14:21:09 -07001584 EXPECT_CALL(*service, SetFailure(_)).Times(0);
1585 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
1586 service->set_expecting_disconnect(true);
1587 InitiateDisconnect(service);
1588 Mock::VerifyAndClearExpectations(service.get());
1589 EXPECT_TRUE(GetPendingService() == NULL);
1590}
1591
1592TEST_F(WiFiMainTest, DisconnectPendingServiceWithFailure) {
1593 StartWiFi();
1594 MockWiFiServiceRefPtr service(
1595 SetupConnectingService(DBus::Path(), NULL, NULL));
1596 EXPECT_TRUE(GetPendingService() == service.get());
1597 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
1598 EXPECT_CALL(*service, SetFailure(Service::kFailureOutOfRange));
Paul Stewart3c504012013-01-17 17:49:58 -08001599 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001600 InitiateDisconnect(service);
Paul Stewart3c504012013-01-17 17:49:58 -08001601 Mock::VerifyAndClearExpectations(service.get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001602 EXPECT_TRUE(GetPendingService() == NULL);
1603}
1604
1605TEST_F(WiFiMainTest, DisconnectPendingServiceWithCurrent) {
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001606 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001607 MockWiFiServiceRefPtr service0(
1608 SetupConnectedService(DBus::Path(), NULL, NULL));
1609 EXPECT_EQ(service0, GetCurrentService());
1610 EXPECT_EQ(NULL, GetPendingService().get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001611
Paul Stewart3c504012013-01-17 17:49:58 -08001612 // We don't explicitly call Disconnect() while transitioning to a new
1613 // service. Instead, we use the side-effect of SelectNetwork (verified in
1614 // SetupConnectingService).
1615 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
1616 MockWiFiServiceRefPtr service1(
1617 SetupConnectingService("/new/path", NULL, NULL));
1618 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001619
1620 EXPECT_EQ(service0, GetCurrentService());
1621 EXPECT_EQ(service1, GetPendingService());
Paul Stewart3c504012013-01-17 17:49:58 -08001622 EXPECT_CALL(*service1, SetState(Service::kStateIdle)).Times(AtLeast(1));
1623 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001624 InitiateDisconnect(service1);
Paul Stewart3c504012013-01-17 17:49:58 -08001625 Mock::VerifyAndClearExpectations(service1.get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001626
1627 // |current_service_| will be unchanged until supplicant signals
1628 // that CurrentBSS has changed.
1629 EXPECT_EQ(service0, GetCurrentService());
1630 // |pending_service_| is updated immediately.
Paul Stewart3c504012013-01-17 17:49:58 -08001631 EXPECT_EQ(NULL, GetPendingService().get());
Paul Stewart2b05e622012-07-13 20:38:44 -07001632 EXPECT_TRUE(GetPendingTimeout().IsCancelled());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001633}
1634
1635TEST_F(WiFiMainTest, DisconnectCurrentService) {
Paul Stewart3c504012013-01-17 17:49:58 -08001636 StartWiFi();
1637 ::DBus::Path kPath("/fake/path");
1638 MockWiFiServiceRefPtr service(SetupConnectedService(kPath, NULL, NULL));
1639 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Peter Qiu49438222014-03-14 14:21:09 -07001640 service->set_expecting_disconnect(true);
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001641 InitiateDisconnect(service);
1642
1643 // |current_service_| should not change until supplicant reports
1644 // a BSS change.
1645 EXPECT_EQ(service, GetCurrentService());
Paul Stewart835934a2012-12-06 19:27:09 -08001646
1647 // Expect that the entry associated with this network will be disabled.
Ben Chanaf14d452014-02-04 17:31:55 -08001648 scoped_ptr<MockSupplicantNetworkProxy> network_proxy(
1649 new MockSupplicantNetworkProxy());
1650 EXPECT_CALL(*proxy_factory(),
1651 CreateSupplicantNetworkProxy(kPath, WPASupplicant::kDBusAddr))
1652 .WillOnce(ReturnAndReleasePointee(&network_proxy));
Paul Stewart835934a2012-12-06 19:27:09 -08001653 EXPECT_CALL(*network_proxy, SetEnabled(false));
Paul Stewart735eab52013-03-29 09:19:23 -07001654 EXPECT_CALL(*eap_state_handler_, Reset());
Paul Stewart3c504012013-01-17 17:49:58 -08001655 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(0);
Peter Qiu49438222014-03-14 14:21:09 -07001656 EXPECT_CALL(*service, SetFailure(_)).Times(0);
1657 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
1658 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
1659 EXPECT_EQ(NULL, GetCurrentService().get());
1660 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
1661}
1662
1663TEST_F(WiFiMainTest, DisconnectCurrentServiceWithFailure) {
1664 StartWiFi();
1665 ::DBus::Path kPath("/fake/path");
1666 MockWiFiServiceRefPtr service(SetupConnectedService(kPath, NULL, NULL));
1667 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
1668 InitiateDisconnect(service);
1669
1670 // |current_service_| should not change until supplicant reports
1671 // a BSS change.
1672 EXPECT_EQ(service, GetCurrentService());
1673
1674 // Expect that the entry associated with this network will be disabled.
1675 scoped_ptr<MockSupplicantNetworkProxy> network_proxy(
1676 new MockSupplicantNetworkProxy());
1677 EXPECT_CALL(*proxy_factory(),
1678 CreateSupplicantNetworkProxy(kPath, WPASupplicant::kDBusAddr))
1679 .WillOnce(ReturnAndReleasePointee(&network_proxy));
1680 EXPECT_CALL(*network_proxy, SetEnabled(false));
1681 EXPECT_CALL(*eap_state_handler_, Reset());
1682 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(0);
1683 EXPECT_CALL(*service, SetFailure(Service::kFailureOutOfRange));
1684 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
Paul Stewart0654ece2013-03-26 15:21:26 -07001685 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
Paul Stewart3c504012013-01-17 17:49:58 -08001686 EXPECT_EQ(NULL, GetCurrentService().get());
1687 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001688}
1689
Christopher Wileyc6184482012-10-24 15:31:56 -07001690TEST_F(WiFiMainTest, DisconnectCurrentServiceWithErrors) {
Paul Stewart3c504012013-01-17 17:49:58 -08001691 StartWiFi();
1692 DBus::Path kPath("/fake/path");
1693 WiFiServiceRefPtr service(SetupConnectedService(kPath, NULL, NULL));
1694 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect())
Christopher Wileyc6184482012-10-24 15:31:56 -07001695 .WillOnce(InvokeWithoutArgs(this, (&WiFiMainTest::ThrowDBusError)));
Paul Stewart3c504012013-01-17 17:49:58 -08001696 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(1);
Christopher Wileyc6184482012-10-24 15:31:56 -07001697 InitiateDisconnect(service);
1698
1699 // We may sometimes fail to disconnect via supplicant, and we patch up some
1700 // state when this happens.
1701 EXPECT_EQ(NULL, GetCurrentService().get());
1702 EXPECT_EQ(NULL, wifi()->selected_service().get());
1703}
1704
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001705TEST_F(WiFiMainTest, DisconnectCurrentServiceWithPending) {
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001706 StartWiFi();
Peter Qiu49438222014-03-14 14:21:09 -07001707 MockWiFiServiceRefPtr service0(SetupConnectedService(DBus::Path(),
1708 NULL, NULL));
1709 MockWiFiServiceRefPtr service1(SetupConnectingService(DBus::Path(),
1710 NULL, NULL));
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001711 EXPECT_EQ(service0, GetCurrentService());
1712 EXPECT_EQ(service1, GetPendingService());
Paul Stewart3c504012013-01-17 17:49:58 -08001713 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001714 InitiateDisconnect(service0);
1715
1716 EXPECT_EQ(service0, GetCurrentService());
1717 EXPECT_EQ(service1, GetPendingService());
Paul Stewart2b05e622012-07-13 20:38:44 -07001718 EXPECT_FALSE(GetPendingTimeout().IsCancelled());
Peter Qiu49438222014-03-14 14:21:09 -07001719
1720 EXPECT_CALL(*service0, SetState(Service::kStateIdle)).Times(AtLeast(1));
1721 EXPECT_CALL(*service0, SetFailure(_)).Times(0);
1722 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
1723
Paul Stewart2b05e622012-07-13 20:38:44 -07001724}
1725
Paul Stewart17d90652013-04-04 15:09:11 -07001726TEST_F(WiFiMainTest, TimeoutPendingServiceWithEndpoints) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07001727 StartScan(WiFi::kScanMethodProgressive);
Paul Stewart2b05e622012-07-13 20:38:44 -07001728 const base::CancelableClosure &pending_timeout = GetPendingTimeout();
1729 EXPECT_TRUE(pending_timeout.IsCancelled());
Wade Guthrie9f4aa152013-07-29 16:03:14 -07001730 MockWiFiServiceRefPtr service = AttemptConnection(
1731 WiFi::kScanMethodProgressive, nullptr, nullptr);
Wade Guthrie44f290d2013-05-28 10:16:25 -07001732
1733 // Timeout the connection attempt.
Paul Stewart2b05e622012-07-13 20:38:44 -07001734 EXPECT_FALSE(pending_timeout.IsCancelled());
1735 EXPECT_EQ(service, GetPendingService());
Paul Stewart17d90652013-04-04 15:09:11 -07001736 // Simulate a service with a wifi_ reference calling DisconnectFrom().
1737 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureOutOfRange, _))
1738 .WillOnce(InvokeWithoutArgs(this, &WiFiObjectTest::ResetPendingService));
1739 EXPECT_CALL(*service, HasEndpoints()).Times(0);
1740 // DisconnectFrom() should not be called directly from WiFi.
1741 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(0);
1742 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001743
Wade Guthrie44f290d2013-05-28 10:16:25 -07001744 // Innocuous redundant call to NotifyDeviceScanFinished.
Wade Guthriea5995cf2013-07-30 09:31:16 -07001745 ExpectFoundNothing();
Wade Guthrie44f290d2013-05-28 10:16:25 -07001746 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
Wade Guthriea5995cf2013-07-30 09:31:16 -07001747 NiceScopedMockLog log;
1748 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
1749 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001750 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
1751 EXPECT_CALL(log, Log(_, _,
1752 HasSubstr("-> PROGRESSIVE_FINISHED_NOCONNECTION")));
Paul Stewart3c504012013-01-17 17:49:58 -08001753 pending_timeout.callback().Run();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001754 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Paul Stewart17d90652013-04-04 15:09:11 -07001755 Mock::VerifyAndClearExpectations(service);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001756
1757 ScopeLogger::GetInstance()->set_verbose_level(0);
1758 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
Paul Stewart17d90652013-04-04 15:09:11 -07001759}
1760
1761TEST_F(WiFiMainTest, TimeoutPendingServiceWithoutEndpoints) {
1762 StartWiFi();
1763 const base::CancelableClosure &pending_timeout = GetPendingTimeout();
1764 EXPECT_TRUE(pending_timeout.IsCancelled());
1765 MockWiFiServiceRefPtr service(
1766 SetupConnectingService(DBus::Path(), NULL, NULL));
1767 EXPECT_FALSE(pending_timeout.IsCancelled());
1768 EXPECT_EQ(service, GetPendingService());
1769 // We expect the service to get a disconnect call, but in this scenario
1770 // the service does nothing.
1771 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureOutOfRange, _));
1772 EXPECT_CALL(*service, HasEndpoints()).WillOnce(Return(false));
1773 // DisconnectFrom() should be called directly from WiFi.
1774 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
1775 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
1776 pending_timeout.callback().Run();
1777 EXPECT_EQ(NULL, GetPendingService().get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001778}
1779
1780TEST_F(WiFiMainTest, DisconnectInvalidService) {
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001781 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001782 MockWiFiServiceRefPtr service;
1783 MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, NULL, &service);
1784 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect()).Times(0);
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001785 InitiateDisconnect(service);
1786}
1787
1788TEST_F(WiFiMainTest, DisconnectCurrentServiceFailure) {
Paul Stewart3c504012013-01-17 17:49:58 -08001789 StartWiFi();
1790 DBus::Path kPath("/fake/path");
1791 WiFiServiceRefPtr service(SetupConnectedService(kPath, NULL, NULL));
1792 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect())
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001793 .WillRepeatedly(Throw(
1794 DBus::Error(
1795 "fi.w1.wpa_supplicant1.NotConnected",
1796 "test threw fi.w1.wpa_supplicant1.NotConnected")));
Paul Stewart3c504012013-01-17 17:49:58 -08001797 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath));
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001798 InitiateDisconnect(service);
Paul Stewart3c504012013-01-17 17:49:58 -08001799 EXPECT_EQ(NULL, GetCurrentService().get());
mukesh agrawal0ed0f2e2011-12-05 20:36:17 +00001800}
1801
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -07001802TEST_F(WiFiMainTest, Stop) {
mukesh agrawalc01f3982012-01-24 13:48:39 -08001803 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001804 WiFiEndpointRefPtr endpoint0;
1805 ::DBus::Path kPath("/fake/path");
1806 WiFiServiceRefPtr service0(SetupConnectedService(kPath, &endpoint0, NULL));
1807 WiFiEndpointRefPtr endpoint1;
1808 MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, &endpoint1, NULL);
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -07001809
Paul Stewart3c504012013-01-17 17:49:58 -08001810 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint0)))
1811 .WillOnce(Return(reinterpret_cast<WiFiService *>(NULL)));
1812 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint1)))
1813 .WillOnce(Return(reinterpret_cast<WiFiService *>(NULL)));
1814 EXPECT_CALL(*GetSupplicantInterfaceProxy(), RemoveNetwork(kPath)).Times(1);
mukesh agrawalc01f3982012-01-24 13:48:39 -08001815 StopWiFi();
mukesh agrawalb66c6462012-05-07 11:45:25 -07001816 EXPECT_TRUE(GetScanTimer().IsCancelled());
mukesh agrawalc4f368f2012-06-04 19:45:52 -07001817 EXPECT_FALSE(wifi()->weak_ptr_factory_.HasWeakPtrs());
mukesh agrawal5c4dd0b2011-09-14 13:53:14 -07001818}
1819
Paul Stewart549d44c2012-07-03 12:40:25 -07001820TEST_F(WiFiMainTest, StopWhileConnected) {
Paul Stewart3c504012013-01-17 17:49:58 -08001821 StartWiFi();
1822 WiFiEndpointRefPtr endpoint;
1823 WiFiServiceRefPtr service(
1824 SetupConnectedService(DBus::Path(), &endpoint, NULL));
1825 scoped_ptr<EndpointRemovalHandler> handler(
1826 MakeEndpointRemovalHandler(service));
1827 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(EndpointMatch(endpoint)))
1828 .WillOnce(Invoke(handler.get(),
1829 &EndpointRemovalHandler::OnEndpointRemoved));
1830 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Paul Stewart549d44c2012-07-03 12:40:25 -07001831 StopWiFi();
1832 EXPECT_TRUE(GetCurrentService() == NULL);
1833}
1834
Paul Stewart44663922012-07-30 11:03:03 -07001835TEST_F(WiFiMainTest, ReconnectTimer) {
Paul Stewart3c504012013-01-17 17:49:58 -08001836 StartWiFi();
1837 MockWiFiServiceRefPtr service(
1838 SetupConnectedService(DBus::Path(), NULL, NULL));
1839 EXPECT_CALL(*service, IsConnected()).WillRepeatedly(Return(true));
Paul Stewart1aff7302012-08-04 20:04:47 -07001840 EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart0654ece2013-03-26 15:21:26 -07001841 ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
Paul Stewart1aff7302012-08-04 20:04:47 -07001842 EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart0654ece2013-03-26 15:21:26 -07001843 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
Paul Stewart1aff7302012-08-04 20:04:47 -07001844 EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart0654ece2013-03-26 15:21:26 -07001845 ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
Paul Stewart1aff7302012-08-04 20:04:47 -07001846 EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart44663922012-07-30 11:03:03 -07001847 ReportCurrentBSSChanged(kBSSName);
Paul Stewart1aff7302012-08-04 20:04:47 -07001848 EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart0654ece2013-03-26 15:21:26 -07001849 ReportStateChanged(WPASupplicant::kInterfaceStateDisconnected);
Paul Stewart1aff7302012-08-04 20:04:47 -07001850 EXPECT_FALSE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart3c504012013-01-17 17:49:58 -08001851 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Paul Stewart1aff7302012-08-04 20:04:47 -07001852 GetReconnectTimeoutCallback().callback().Run();
Paul Stewart3c504012013-01-17 17:49:58 -08001853 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Paul Stewart1aff7302012-08-04 20:04:47 -07001854 EXPECT_TRUE(GetReconnectTimeoutCallback().IsCancelled());
Paul Stewart44663922012-07-30 11:03:03 -07001855}
1856
Paul Stewartcb59fed2012-03-21 21:14:46 -07001857
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001858MATCHER_P(HasHiddenSSID_FullScan, ssid, "") {
Paul Stewarta41e38d2011-11-11 07:47:29 -08001859 map<string, DBus::Variant>::const_iterator it =
Paul Stewart0654ece2013-03-26 15:21:26 -07001860 arg.find(WPASupplicant::kPropertyScanSSIDs);
Paul Stewartced6a0b2011-11-08 15:32:04 -08001861 if (it == arg.end()) {
1862 return false;
1863 }
1864
1865 const DBus::Variant &ssids_variant = it->second;
1866 EXPECT_TRUE(DBusAdaptor::IsByteArrays(ssids_variant.signature()));
1867 const ByteArrays &ssids = it->second.operator ByteArrays();
1868 // A valid Scan containing a single hidden SSID should contain
1869 // two SSID entries: one containing the SSID we are looking for,
1870 // and an empty entry, signifying that we also want to do a
1871 // broadcast probe request for all non-hidden APs as well.
Paul Stewart3c504012013-01-17 17:49:58 -08001872 return ssids.size() == 2 && ssids[0] == ssid && ssids[1].empty();
1873}
1874
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001875MATCHER(HasNoHiddenSSID_FullScan, "") {
Paul Stewart3c504012013-01-17 17:49:58 -08001876 map<string, DBus::Variant>::const_iterator it =
Paul Stewart0654ece2013-03-26 15:21:26 -07001877 arg.find(WPASupplicant::kPropertyScanSSIDs);
Paul Stewart3c504012013-01-17 17:49:58 -08001878 return it == arg.end();
Paul Stewartced6a0b2011-11-08 15:32:04 -08001879}
1880
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001881TEST_F(WiFiMainTest, ScanHidden_FullScan) {
1882 EnableFullScan();
Paul Stewart3c504012013-01-17 17:49:58 -08001883 vector<uint8_t>kSSID(1, 'a');
1884 ByteArrays ssids;
1885 ssids.push_back(kSSID);
1886
Paul Stewartced6a0b2011-11-08 15:32:04 -08001887 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08001888 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList()).WillOnce(Return(ssids));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001889 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
1890 Scan(HasHiddenSSID_FullScan(kSSID)));
Paul Stewart3c504012013-01-17 17:49:58 -08001891 dispatcher_.DispatchPendingEvents();
1892}
1893
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001894// This test is slightly different from the test in scan_session_unittest.cc
1895// because this tests the piece of WiFi that builds the SSID list.
1896TEST_F(WiFiMainTest, ScanHidden) {
1897 // Clear the Mock ScanSession because hidden SSIDs are added when wifi
1898 // instantiates a new ScanSession (and it won't instantiate a new ScanSession
1899 // if there's already one there).
1900 ClearScanSession();
1901 vector<uint8_t>kSSID(1, 'a');
1902 ByteArrays ssids;
1903 ssids.push_back(kSSID);
1904
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001905 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList()).WillOnce(Return(ssids));
1906 StartWiFi();
1907 EXPECT_CALL(netlink_manager_,
Wade Guthrie7347bf22013-04-30 11:21:51 -07001908 SendNl80211Message(HasHiddenSSID(kNl80211FamilyId), _, _));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001909 dispatcher_.DispatchPendingEvents();
1910}
1911
1912TEST_F(WiFiMainTest, ScanNoHidden_FullScan) {
1913 EnableFullScan();
Paul Stewart3c504012013-01-17 17:49:58 -08001914 StartWiFi();
1915 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
1916 .WillOnce(Return(ByteArrays()));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001917 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(HasNoHiddenSSID_FullScan()));
1918 dispatcher_.DispatchPendingEvents();
1919}
1920
1921// This test is slightly different from the test in scan_session_unittest.cc
1922// because this tests the piece of WiFi that builds the SSID list.
1923TEST_F(WiFiMainTest, ScanNoHidden) {
1924 // Clear the Mock ScanSession because hidden SSIDs are added when wifi
1925 // instantiates a new ScanSession (and it won't instantiate a new ScanSession
1926 // if there's already one there).
1927 ClearScanSession();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001928 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
1929 .WillOnce(Return(ByteArrays()));
1930 StartWiFi();
1931 EXPECT_CALL(netlink_manager_,
Wade Guthrie7347bf22013-04-30 11:21:51 -07001932 SendNl80211Message(HasNoHiddenSSID(kNl80211FamilyId), _, _));
Paul Stewartced6a0b2011-11-08 15:32:04 -08001933 dispatcher_.DispatchPendingEvents();
1934}
1935
Paul Stewartfae4dae2012-09-13 07:43:32 -07001936TEST_F(WiFiMainTest, ScanWiFiDisabledAfterResume) {
1937 ScopedMockLog log;
1938 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
1939 EXPECT_CALL(log, Log(_, _, EndsWith(
1940 "Ignoring scan request while device is not enabled."))).Times(1);
Paul Stewart3c504012013-01-17 17:49:58 -08001941 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001942 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
Paul Stewartfae4dae2012-09-13 07:43:32 -07001943 StartWiFi();
1944 StopWiFi();
1945 // A scan is queued when WiFi resumes.
1946 OnAfterResume();
1947 dispatcher_.DispatchPendingEvents();
1948}
1949
mukesh agrawal1e570d42014-03-28 18:20:50 -07001950TEST_F(WiFiMainTest, ScanRejected) {
1951 StartWiFi();
1952 ReportScanDone();
1953 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
1954
1955 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_))
1956 .WillOnce(Throw(DBus::Error("don't care", "don't care")));
1957 TriggerScan(WiFi::kScanMethodFull);
1958 dispatcher_.DispatchPendingEvents();
1959 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
1960}
1961
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001962TEST_F(WiFiMainTest, ProgressiveScanFound) {
1963 // Set min & max scan frequency count to 1 so each scan will be of a single
1964 // frequency.
1965 SetScanSize(1, 1);
1966
1967 // Do the first scan (finds nothing).
Wade Guthrie9f4aa152013-07-29 16:03:14 -07001968 StartScan(WiFi::kScanMethodProgressive);
Paul Stewart7de7e022013-08-28 09:42:50 -07001969 EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_)).Times(0);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001970 ReportScanDoneKeepScanSession();
1971
1972 // Do the second scan (connects afterwards).
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07001973 ExpectScanStart(WiFi::kScanMethodProgressive, true);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001974 dispatcher_.DispatchPendingEvents();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001975 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001976 ReportScanDoneKeepScanSession();
1977
1978 // Connect after second scan.
Ben Chanf024ef42013-09-20 14:21:38 -07001979 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07001980 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
1981 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
1982 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Ben Chanf024ef42013-09-20 14:21:38 -07001983 EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001984 SetPendingService(service);
1985
1986 // Verify that the third scan aborts and there is no further scan.
1987 ScopedMockLog log;
1988 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
1989 EXPECT_CALL(log, Log(_, _, EndsWith(
1990 "Ignoring scan request while connecting to an AP."))).Times(1);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001991 dispatcher_.DispatchPendingEvents();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07001992 VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07001993}
1994
1995TEST_F(WiFiMainTest, ProgressiveScanNotFound) {
1996 // Set min & max scan frequency count to 1 so each scan will be of a single
1997 // frequency.
1998 SetScanSize(1, 1);
1999
Wade Guthrie44f290d2013-05-28 10:16:25 -07002000 // This test never connects
2001 EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _)).Times(0);
2002 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
2003
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002004 // Do the first scan (finds nothing).
Wade Guthrie9f4aa152013-07-29 16:03:14 -07002005 StartScan(WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002006 ReportScanDoneKeepScanSession();
2007
2008 // Do the second scan (finds nothing).
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002009 ExpectScanStart(WiFi::kScanMethodProgressive, true);
Paul Stewart7de7e022013-08-28 09:42:50 -07002010 EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_)).Times(0);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002011 dispatcher_.DispatchPendingEvents();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002012 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002013 ReportScanDoneKeepScanSession();
2014
2015 // Do the third scan. After (simulated) exhausting of search frequencies,
2016 // verify that this scan uses supplicant rather than internal (progressive)
2017 // scan.
2018 EXPECT_CALL(*scan_session_, HasMoreFrequencies()).WillOnce(Return(false));
2019 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
2020 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
2021 dispatcher_.DispatchPendingEvents();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002022 VerifyScanState(WiFi::kScanScanning,
2023 WiFi::kScanMethodProgressiveFinishedToFull);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002024
2025 // And verify that ScanDone reports a complete scan (i.e., the
2026 // wifi_::scan_session_ has truly been cleared).
Wade Guthriea5995cf2013-07-30 09:31:16 -07002027 ExpectScanStop();
2028 ExpectFoundNothing();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002029 ReportScanDoneKeepScanSession();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002030 dispatcher_.DispatchPendingEvents(); // Launch UpdateScanStateAfterScanDone
2031 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002032}
2033
2034TEST_F(WiFiMainTest, ProgressiveScanError) {
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002035 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
2036 ClearScanSession(); // Clear Mock ScanSession to get an actual ScanSession.
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002037 StartWiFi(); // Posts |ProgressiveScanTask|.
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002038
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002039 EXPECT_CALL(netlink_manager_, SendNl80211Message(
2040 IsNl80211Command(kNl80211FamilyId, NL80211_CMD_TRIGGER_SCAN), _, _));
2041 dispatcher_.DispatchPendingEvents(); // Executes |ProgressiveScanTask|.
2042
2043 // Calls |WiFi::OnFailedProgressiveScan| which calls |ScanTask|
2044 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(1);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002045 NewScanResultsMessage not_supposed_to_get_this_message;
2046 OnTriggerScanResponse(not_supposed_to_get_this_message);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002047 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressiveErrorToFull);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002048
2049 EXPECT_TRUE(IsScanSessionNull());
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002050
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002051 // Post and execute |UpdateScanStateAfterScanDone|.
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002052 ReportScanDoneKeepScanSession();
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002053 dispatcher_.DispatchPendingEvents();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002054 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002055}
2056
mukesh agrawal7ec71312011-11-10 02:08:26 +00002057TEST_F(WiFiMainTest, InitialSupplicantState) {
2058 EXPECT_EQ(WiFi::kInterfaceStateUnknown, GetSupplicantState());
2059}
2060
2061TEST_F(WiFiMainTest, StateChangeNoService) {
2062 // State change should succeed even if there is no pending Service.
Paul Stewart0654ece2013-03-26 15:21:26 -07002063 ReportStateChanged(WPASupplicant::kInterfaceStateScanning);
2064 EXPECT_EQ(WPASupplicant::kInterfaceStateScanning, GetSupplicantState());
mukesh agrawal7ec71312011-11-10 02:08:26 +00002065}
2066
2067TEST_F(WiFiMainTest, StateChangeWithService) {
2068 // Forward transition should trigger a Service state change.
2069 StartWiFi();
2070 dispatcher_.DispatchPendingEvents();
Ben Chanf024ef42013-09-20 14:21:38 -07002071 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
mukesh agrawal7ec71312011-11-10 02:08:26 +00002072 InitiateConnect(service);
2073 EXPECT_CALL(*service.get(), SetState(Service::kStateAssociating));
Paul Stewart0654ece2013-03-26 15:21:26 -07002074 ReportStateChanged(WPASupplicant::kInterfaceStateAssociated);
mukesh agrawal7ec71312011-11-10 02:08:26 +00002075 // Verify expectations now, because WiFi may report other state changes
2076 // when WiFi is Stop()-ed (during TearDown()).
2077 Mock::VerifyAndClearExpectations(service.get());
Gary Moraind9f893f2012-02-06 10:03:40 -08002078 EXPECT_CALL(*service.get(), SetState(_)).Times(AnyNumber());
mukesh agrawal7ec71312011-11-10 02:08:26 +00002079}
2080
2081TEST_F(WiFiMainTest, StateChangeBackwardsWithService) {
2082 // Some backwards transitions should not trigger a Service state change.
2083 // Supplicant state should still be updated, however.
Paul Stewart75a68b92013-10-24 10:50:27 -07002084 EXPECT_CALL(*dhcp_provider(), CreateConfig(_, _, _, _, _)).Times(AnyNumber());
Gary Moraind9f893f2012-02-06 10:03:40 -08002085 EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
mukesh agrawal7ec71312011-11-10 02:08:26 +00002086 StartWiFi();
2087 dispatcher_.DispatchPendingEvents();
Ben Chanf024ef42013-09-20 14:21:38 -07002088 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Paul Stewartbca08f82013-07-09 16:32:37 -07002089 EXPECT_CALL(*service, SetState(Service::kStateAssociating));
2090 EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
2091 EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
mukesh agrawal7ec71312011-11-10 02:08:26 +00002092 InitiateConnect(service);
Paul Stewart0654ece2013-03-26 15:21:26 -07002093 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
2094 ReportStateChanged(WPASupplicant::kInterfaceStateAuthenticating);
2095 EXPECT_EQ(WPASupplicant::kInterfaceStateAuthenticating,
mukesh agrawal7ec71312011-11-10 02:08:26 +00002096 GetSupplicantState());
2097 // Verify expectations now, because WiFi may report other state changes
2098 // when WiFi is Stop()-ed (during TearDown()).
Paul Stewart3c504012013-01-17 17:49:58 -08002099 Mock::VerifyAndClearExpectations(service);
2100 EXPECT_CALL(*service, SetState(_)).Times(AnyNumber());
mukesh agrawal7ec71312011-11-10 02:08:26 +00002101}
2102
Paul Stewarta47c3c62012-12-18 12:14:29 -08002103TEST_F(WiFiMainTest, ConnectToServiceWithoutRecentIssues) {
2104 MockSupplicantProcessProxy *process_proxy = supplicant_process_proxy_.get();
2105 StartWiFi();
2106 dispatcher_.DispatchPendingEvents();
Ben Chanf024ef42013-09-20 14:21:38 -07002107 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Paul Stewarta47c3c62012-12-18 12:14:29 -08002108 EXPECT_CALL(*process_proxy, GetDebugLevel()).Times(0);
2109 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
2110 EXPECT_CALL(*service.get(), HasRecentConnectionIssues())
2111 .WillOnce(Return(false));
2112 InitiateConnect(service);
2113}
2114
2115TEST_F(WiFiMainTest, ConnectToServiceWithRecentIssues) {
2116 // Turn of WiFi debugging, so the only reason we will turn on supplicant
2117 // debugging will be to debug a problematic connection.
2118 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
2119
2120 MockSupplicantProcessProxy *process_proxy = supplicant_process_proxy_.get();
2121 StartWiFi();
2122 dispatcher_.DispatchPendingEvents();
Ben Chanf024ef42013-09-20 14:21:38 -07002123 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Paul Stewarta47c3c62012-12-18 12:14:29 -08002124 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07002125 .WillOnce(Return(WPASupplicant::kDebugLevelInfo));
2126 EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelDebug))
Paul Stewarta47c3c62012-12-18 12:14:29 -08002127 .Times(1);
2128 EXPECT_CALL(*service.get(), HasRecentConnectionIssues())
2129 .WillOnce(Return(true));
2130 InitiateConnect(service);
2131 Mock::VerifyAndClearExpectations(process_proxy);
2132
2133 SetPendingService(NULL);
2134 SetCurrentService(service);
2135
2136 // When we disconnect from the troubled service, we should reduce the
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002137 // level of supplicant debugging.
Paul Stewarta47c3c62012-12-18 12:14:29 -08002138 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07002139 .WillOnce(Return(WPASupplicant::kDebugLevelDebug));
2140 EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelInfo))
Paul Stewarta47c3c62012-12-18 12:14:29 -08002141 .Times(1);
Paul Stewart0654ece2013-03-26 15:21:26 -07002142 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
Paul Stewarta47c3c62012-12-18 12:14:29 -08002143}
2144
mukesh agrawal15908392011-11-16 18:29:25 +00002145TEST_F(WiFiMainTest, CurrentBSSChangeConnectedToDisconnected) {
mukesh agrawal15908392011-11-16 18:29:25 +00002146 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002147 WiFiEndpointRefPtr endpoint;
2148 MockWiFiServiceRefPtr service =
2149 SetupConnectedService(DBus::Path(), &endpoint, NULL);
mukesh agrawal15908392011-11-16 18:29:25 +00002150
Peter Qiu49438222014-03-14 14:21:09 -07002151 EXPECT_CALL(*service, SetState(Service::kStateIdle)).Times(AtLeast(1));
Paul Stewart0654ece2013-03-26 15:21:26 -07002152 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
mukesh agrawal15908392011-11-16 18:29:25 +00002153 EXPECT_EQ(NULL, GetCurrentService().get());
2154 EXPECT_EQ(NULL, GetPendingService().get());
Paul Stewart68735052014-02-11 09:16:09 -08002155 EXPECT_FALSE(GetIsRoamingInProgress());
mukesh agrawal15908392011-11-16 18:29:25 +00002156}
2157
2158TEST_F(WiFiMainTest, CurrentBSSChangeConnectedToConnectedNewService) {
mukesh agrawal15908392011-11-16 18:29:25 +00002159 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002160 MockWiFiServiceRefPtr service0 =
2161 SetupConnectedService(DBus::Path(), NULL, NULL);
2162 MockWiFiServiceRefPtr service1;
2163 ::DBus::Path bss_path1(MakeNewEndpointAndService(
2164 0, 0, kNetworkModeAdHoc, NULL, &service1));
2165 EXPECT_EQ(service0.get(), GetCurrentService().get());
mukesh agrawal15908392011-11-16 18:29:25 +00002166
mukesh agrawalc01f3982012-01-24 13:48:39 -08002167 // Note that we deliberately omit intermediate supplicant states
2168 // (e.g. kInterfaceStateAssociating), on the theory that they are
2169 // unreliable. Specifically, they may be quashed if the association
2170 // completes before supplicant flushes its changed properties.
Paul Stewart3c504012013-01-17 17:49:58 -08002171 EXPECT_CALL(*service0, SetState(Service::kStateIdle)).Times(AtLeast(1));
2172 ReportCurrentBSSChanged(bss_path1);
2173 EXPECT_CALL(*service1, SetState(Service::kStateConfiguring));
Paul Stewartbca08f82013-07-09 16:32:37 -07002174 EXPECT_CALL(*service1, ResetSuspectedCredentialFailures());
mukesh agrawala5dda0e2013-08-16 11:53:10 -07002175 EXPECT_CALL(*wifi_provider(), IncrementConnectCount(_));
Paul Stewart0654ece2013-03-26 15:21:26 -07002176 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
Paul Stewart3c504012013-01-17 17:49:58 -08002177 EXPECT_EQ(service1.get(), GetCurrentService().get());
Paul Stewart68735052014-02-11 09:16:09 -08002178 EXPECT_FALSE(GetIsRoamingInProgress());
Paul Stewart3c504012013-01-17 17:49:58 -08002179 Mock::VerifyAndClearExpectations(service0);
2180 Mock::VerifyAndClearExpectations(service1);
mukesh agrawal15908392011-11-16 18:29:25 +00002181}
2182
Thieu Lee41a72d2012-02-06 20:46:51 +00002183TEST_F(WiFiMainTest, CurrentBSSChangedUpdateServiceEndpoint) {
Thieu Lee41a72d2012-02-06 20:46:51 +00002184 StartWiFi();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002185 dispatcher_.DispatchPendingEvents();
2186 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
2187
Paul Stewart3c504012013-01-17 17:49:58 -08002188 MockWiFiServiceRefPtr service =
2189 SetupConnectedService(DBus::Path(), NULL, NULL);
2190 WiFiEndpointRefPtr endpoint;
2191 ::DBus::Path bss_path =
2192 AddEndpointToService(service, 0, 0, kNetworkModeAdHoc, &endpoint);
2193 EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
2194 ReportCurrentBSSChanged(bss_path);
Paul Stewart68735052014-02-11 09:16:09 -08002195 EXPECT_TRUE(GetIsRoamingInProgress());
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002196 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Paul Stewart68735052014-02-11 09:16:09 -08002197
2198 // If we report a "completed" state change on a connected service after
2199 // wpa_supplicant has roamed, we should renew our IPConfig.
2200 scoped_refptr<MockIPConfig> ipconfig(
2201 new MockIPConfig(control_interface(), kDeviceName));
2202 SetIPConfig(ipconfig);
2203 EXPECT_CALL(*service, IsConnected()).WillOnce(Return(true));
2204 EXPECT_CALL(*ipconfig, RenewIP());
2205 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
2206 Mock::VerifyAndClearExpectations(ipconfig);
2207 EXPECT_FALSE(GetIsRoamingInProgress());
mukesh agrawal4eb4d782011-12-05 17:34:37 +00002208}
2209
mukesh agrawal8a3188d2011-12-01 20:56:44 +00002210TEST_F(WiFiMainTest, NewConnectPreemptsPending) {
mukesh agrawal8a3188d2011-12-01 20:56:44 +00002211 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002212 MockWiFiServiceRefPtr service0(
2213 SetupConnectingService(DBus::Path(), NULL, NULL));
2214 EXPECT_EQ(service0.get(), GetPendingService().get());
mukesh agrawal8a3188d2011-12-01 20:56:44 +00002215 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Paul Stewart3c504012013-01-17 17:49:58 -08002216 MockWiFiServiceRefPtr service1(
2217 SetupConnectingService(DBus::Path(), NULL, NULL));
2218 EXPECT_EQ(service1.get(), GetPendingService().get());
2219 EXPECT_EQ(NULL, GetCurrentService().get());
mukesh agrawal8a3188d2011-12-01 20:56:44 +00002220}
2221
2222TEST_F(WiFiMainTest, IsIdle) {
2223 StartWiFi();
2224 EXPECT_TRUE(wifi()->IsIdle());
Paul Stewart3c504012013-01-17 17:49:58 -08002225 MockWiFiServiceRefPtr service(
2226 SetupConnectingService(DBus::Path(), NULL, NULL));
mukesh agrawal8a3188d2011-12-01 20:56:44 +00002227 EXPECT_FALSE(wifi()->IsIdle());
2228}
2229
Darin Petkov4a66cc52012-06-15 10:08:29 +02002230MATCHER_P(WiFiAddedArgs, bgscan, "") {
Paul Stewart0654ece2013-03-26 15:21:26 -07002231 return ContainsKey(arg, WPASupplicant::kNetworkPropertyScanSSID) &&
Paul Stewart9d97b7d2014-03-13 21:47:03 -07002232 ContainsKey(arg, WPASupplicant::kNetworkPropertyDisableVHT) &&
Paul Stewart0654ece2013-03-26 15:21:26 -07002233 ContainsKey(arg, WPASupplicant::kNetworkPropertyBgscan) == bgscan;
mukesh agrawal4d0401c2012-01-06 16:05:31 -08002234}
2235
2236TEST_F(WiFiMainTest, AddNetworkArgs) {
mukesh agrawal4d0401c2012-01-06 16:05:31 -08002237 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002238 MockWiFiServiceRefPtr service;
2239 MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, NULL, &service);
Paul Stewarta283e4e2013-10-22 20:50:14 -07002240 EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
Paul Stewart3c504012013-01-17 17:49:58 -08002241 EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(WiFiAddedArgs(true)));
Paul Stewart0654ece2013-03-26 15:21:26 -07002242 EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodSimple));
mukesh agrawal4d0401c2012-01-06 16:05:31 -08002243 InitiateConnect(service);
2244}
2245
Darin Petkov4a66cc52012-06-15 10:08:29 +02002246TEST_F(WiFiMainTest, AddNetworkArgsNoBgscan) {
Darin Petkov4a66cc52012-06-15 10:08:29 +02002247 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002248 MockWiFiServiceRefPtr service;
2249 MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, NULL, &service);
Paul Stewarta283e4e2013-10-22 20:50:14 -07002250 EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
Paul Stewart3c504012013-01-17 17:49:58 -08002251 EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(WiFiAddedArgs(false)));
Darin Petkov4a66cc52012-06-15 10:08:29 +02002252 InitiateConnect(service);
2253}
2254
2255TEST_F(WiFiMainTest, AppendBgscan) {
2256 StartWiFi();
Ben Chanf024ef42013-09-20 14:21:38 -07002257 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Darin Petkov4a66cc52012-06-15 10:08:29 +02002258 {
2259 // 1 endpoint, default bgscan method -- background scan disabled.
2260 std::map<std::string, DBus::Variant> params;
Paul Stewart3c504012013-01-17 17:49:58 -08002261 EXPECT_CALL(*service, GetEndpointCount()).WillOnce(Return(1));
2262 AppendBgscan(service, &params);
2263 Mock::VerifyAndClearExpectations(service);
Paul Stewart0654ece2013-03-26 15:21:26 -07002264 EXPECT_FALSE(ContainsKey(params, WPASupplicant::kNetworkPropertyBgscan));
Darin Petkov4a66cc52012-06-15 10:08:29 +02002265 }
Darin Petkov4a66cc52012-06-15 10:08:29 +02002266 {
2267 // 2 endpoints, default bgscan method -- background scan frequency reduced.
2268 map<string, DBus::Variant> params;
Paul Stewart3c504012013-01-17 17:49:58 -08002269 EXPECT_CALL(*service, GetEndpointCount()).WillOnce(Return(2));
2270 AppendBgscan(service, &params);
2271 Mock::VerifyAndClearExpectations(service);
Darin Petkov4a66cc52012-06-15 10:08:29 +02002272 string config_string;
2273 EXPECT_TRUE(
2274 DBusProperties::GetString(params,
Paul Stewart0654ece2013-03-26 15:21:26 -07002275 WPASupplicant::kNetworkPropertyBgscan,
Darin Petkov4a66cc52012-06-15 10:08:29 +02002276 &config_string));
2277 vector<string> elements;
2278 base::SplitString(config_string, ':', &elements);
2279 ASSERT_EQ(4, elements.size());
2280 EXPECT_EQ(WiFi::kDefaultBgscanMethod, elements[0]);
2281 EXPECT_EQ(StringPrintf("%d", WiFi::kBackgroundScanIntervalSeconds),
2282 elements[3]);
2283 }
2284 {
2285 // Explicit bgscan method -- regular background scan frequency.
Paul Stewart0654ece2013-03-26 15:21:26 -07002286 EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodSimple));
Darin Petkov4a66cc52012-06-15 10:08:29 +02002287 std::map<std::string, DBus::Variant> params;
Paul Stewart3c504012013-01-17 17:49:58 -08002288 EXPECT_CALL(*service, GetEndpointCount()).Times(0);
2289 AppendBgscan(service, &params);
2290 Mock::VerifyAndClearExpectations(service);
Darin Petkov4a66cc52012-06-15 10:08:29 +02002291 string config_string;
2292 EXPECT_TRUE(
2293 DBusProperties::GetString(params,
Paul Stewart0654ece2013-03-26 15:21:26 -07002294 WPASupplicant::kNetworkPropertyBgscan,
Darin Petkov4a66cc52012-06-15 10:08:29 +02002295 &config_string));
2296 vector<string> elements;
2297 base::SplitString(config_string, ':', &elements);
2298 ASSERT_EQ(4, elements.size());
2299 EXPECT_EQ(StringPrintf("%d", WiFi::kDefaultScanIntervalSeconds),
2300 elements[3]);
2301 }
Christopher Wiley5c929e22012-07-16 14:06:04 -07002302 {
2303 // No scan method, simply returns without appending properties
Paul Stewart0654ece2013-03-26 15:21:26 -07002304 EXPECT_TRUE(SetBgscanMethod(WPASupplicant::kNetworkBgscanMethodNone));
Christopher Wiley5c929e22012-07-16 14:06:04 -07002305 std::map<std::string, DBus::Variant> params;
Paul Stewart3c504012013-01-17 17:49:58 -08002306 EXPECT_CALL(*service, GetEndpointCount()).Times(0);
Christopher Wiley5c929e22012-07-16 14:06:04 -07002307 AppendBgscan(service.get(), &params);
Paul Stewart3c504012013-01-17 17:49:58 -08002308 Mock::VerifyAndClearExpectations(service);
Christopher Wiley5c929e22012-07-16 14:06:04 -07002309 string config_string;
2310 EXPECT_FALSE(
2311 DBusProperties::GetString(params,
Paul Stewart0654ece2013-03-26 15:21:26 -07002312 WPASupplicant::kNetworkPropertyBgscan,
Christopher Wiley5c929e22012-07-16 14:06:04 -07002313 &config_string));
2314 }
Darin Petkov4a66cc52012-06-15 10:08:29 +02002315}
2316
mukesh agrawalc01f3982012-01-24 13:48:39 -08002317TEST_F(WiFiMainTest, StateAndIPIgnoreLinkEvent) {
2318 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002319 MockWiFiServiceRefPtr service(
2320 SetupConnectingService(DBus::Path(), NULL, NULL));
mukesh agrawalc01f3982012-01-24 13:48:39 -08002321 EXPECT_CALL(*service.get(), SetState(_)).Times(0);
2322 EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(0);
2323 ReportLinkUp();
2324
2325 // Verify expectations now, because WiFi may cause |service| state
2326 // changes during TearDown().
2327 Mock::VerifyAndClearExpectations(service);
mukesh agrawalc01f3982012-01-24 13:48:39 -08002328}
2329
2330TEST_F(WiFiMainTest, SupplicantCompletedAlreadyConnected) {
mukesh agrawalc01f3982012-01-24 13:48:39 -08002331 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002332 MockWiFiServiceRefPtr service(
2333 SetupConnectedService(DBus::Path(), NULL, NULL));
Christopher Wiley8f81e2a2012-10-17 16:51:32 -07002334 Mock::VerifyAndClearExpectations(dhcp_config_.get());
mukesh agrawalc01f3982012-01-24 13:48:39 -08002335 EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(0);
Christopher Wiley8f81e2a2012-10-17 16:51:32 -07002336 // Simulate a rekeying event from the AP. These show as transitions from
2337 // completed->completed from wpa_supplicant.
Paul Stewart0654ece2013-03-26 15:21:26 -07002338 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
Christopher Wiley5519e9e2013-01-08 16:55:56 -08002339 // When we get an IP, WiFi should enable high bitrates on the interface again.
Paul Stewart3c504012013-01-17 17:49:58 -08002340 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
2341 EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
2342 EXPECT_CALL(*manager(), device_info()).WillOnce(Return(device_info()));
Christopher Wiley8f81e2a2012-10-17 16:51:32 -07002343 ReportIPConfigComplete();
2344 // Similarly, rekeying events after we have an IP don't trigger L3
Christopher Wiley5519e9e2013-01-08 16:55:56 -08002345 // configuration. However, we treat all transitions to completed as potential
2346 // reassociations, so we will reenable high rates again here.
Paul Stewart3c504012013-01-17 17:49:58 -08002347 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
2348 EXPECT_CALL(*service, IsConnected()).WillOnce(Return(true));
2349 EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
Paul Stewart0654ece2013-03-26 15:21:26 -07002350 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
mukesh agrawalc01f3982012-01-24 13:48:39 -08002351}
2352
mukesh agrawalb20776f2012-02-10 16:00:36 -08002353TEST_F(WiFiMainTest, BSSAddedCreatesBSSProxy) {
mukesh agrawalb20776f2012-02-10 16:00:36 -08002354 // TODO(quiche): Consider using a factory for WiFiEndpoints, so that
2355 // we can test the interaction between WiFi and WiFiEndpoint. (Right
2356 // now, we're testing across multiple layers.)
2357 EXPECT_CALL(*supplicant_bss_proxy_, Die()).Times(AnyNumber());
2358 EXPECT_CALL(*proxy_factory(), CreateSupplicantBSSProxy(_, _, _));
2359 StartWiFi();
2360 ReportBSS("bss0", "ssid0", "00:00:00:00:00:00", 0, 0, kNetworkModeAdHoc);
2361}
2362
2363TEST_F(WiFiMainTest, BSSRemovedDestroysBSSProxy) {
2364 // TODO(quiche): As for BSSAddedCreatesBSSProxy, consider using a
2365 // factory for WiFiEndpoints.
mukesh agrawalb20776f2012-02-10 16:00:36 -08002366 // Get the pointer before we transfer ownership.
2367 MockSupplicantBSSProxy *proxy = supplicant_bss_proxy_.get();
2368 EXPECT_CALL(*proxy, Die());
2369 StartWiFi();
Paul Stewart3c504012013-01-17 17:49:58 -08002370 DBus::Path bss_path(
2371 MakeNewEndpointAndService(0, 0, kNetworkModeAdHoc, NULL, NULL));
2372 EXPECT_CALL(*wifi_provider(), OnEndpointRemoved(_))
2373 .WillOnce(Return(reinterpret_cast<WiFiService *>(NULL)));
2374 RemoveBSS(bss_path);
mukesh agrawalb20776f2012-02-10 16:00:36 -08002375 // Check this now, to make sure RemoveBSS killed the proxy (rather
2376 // than TearDown).
2377 Mock::VerifyAndClearExpectations(proxy);
2378}
2379
mukesh agrawal5c05b292012-03-07 10:12:52 -08002380TEST_F(WiFiMainTest, FlushBSSOnResume) {
2381 const struct timeval resume_time = {1, 0};
2382 const struct timeval scan_done_time = {6, 0};
mukesh agrawal5c05b292012-03-07 10:12:52 -08002383
2384 StartWiFi();
2385
2386 EXPECT_CALL(time_, GetTimeMonotonic(_))
2387 .WillOnce(DoAll(SetArgumentPointee<0>(resume_time), Return(0)))
2388 .WillOnce(DoAll(SetArgumentPointee<0>(scan_done_time), Return(0)));
Paul Stewart3c504012013-01-17 17:49:58 -08002389 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
mukesh agrawal5c05b292012-03-07 10:12:52 -08002390 FlushBSS(WiFi::kMaxBSSResumeAgeSeconds + 5));
mukesh agrawal2f9df4e2012-08-08 12:29:20 -07002391 OnAfterResume();
mukesh agrawal5c05b292012-03-07 10:12:52 -08002392 ReportScanDone();
2393}
2394
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002395TEST_F(WiFiMainTest, ScanTimerIdle_FullScan) {
2396 EnableFullScan();
mukesh agrawalb66c6462012-05-07 11:45:25 -07002397 StartWiFi();
2398 dispatcher_.DispatchPendingEvents();
2399 ReportScanDone();
2400 CancelScanTimer();
2401 EXPECT_TRUE(GetScanTimer().IsCancelled());
2402
Paul Stewart7de7e022013-08-28 09:42:50 -07002403 EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002404 dispatcher_.DispatchPendingEvents();
mukesh agrawalb66c6462012-05-07 11:45:25 -07002405 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_));
2406 FireScanTimer();
2407 dispatcher_.DispatchPendingEvents();
2408 EXPECT_FALSE(GetScanTimer().IsCancelled()); // Automatically re-armed.
2409}
2410
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002411TEST_F(WiFiMainTest, ScanTimerIdle) {
2412 StartWiFi();
2413 dispatcher_.DispatchPendingEvents();
2414 ReportScanDone();
2415 CancelScanTimer();
2416 EXPECT_TRUE(GetScanTimer().IsCancelled());
Wade Guthrie0cf3c982013-05-29 09:11:35 -07002417 dispatcher_.DispatchPendingEvents();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07002418 InstallMockScanSession();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002419 EXPECT_CALL(*scan_session_, InitiateScan());
2420 FireScanTimer();
2421 dispatcher_.DispatchPendingEvents();
2422 EXPECT_FALSE(GetScanTimer().IsCancelled()); // Automatically re-armed.
2423}
2424
mukesh agrawalb66c6462012-05-07 11:45:25 -07002425TEST_F(WiFiMainTest, ScanTimerScanning) {
2426 StartWiFi();
2427 dispatcher_.DispatchPendingEvents();
2428 CancelScanTimer();
2429 EXPECT_TRUE(GetScanTimer().IsCancelled());
2430
2431 // Should not call Scan, since we're already scanning.
2432 // (Scanning is triggered by StartWiFi.)
2433 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002434 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002435 FireScanTimer();
2436 dispatcher_.DispatchPendingEvents();
2437 EXPECT_FALSE(GetScanTimer().IsCancelled()); // Automatically re-armed.
2438}
2439
2440TEST_F(WiFiMainTest, ScanTimerConnecting) {
2441 StartWiFi();
2442 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08002443 MockWiFiServiceRefPtr service =
2444 SetupConnectingService(DBus::Path(), NULL, NULL);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002445 CancelScanTimer();
2446 EXPECT_TRUE(GetScanTimer().IsCancelled());
2447
2448 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002449 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002450 FireScanTimer();
2451 dispatcher_.DispatchPendingEvents();
2452 EXPECT_FALSE(GetScanTimer().IsCancelled()); // Automatically re-armed.
2453}
2454
2455TEST_F(WiFiMainTest, ScanTimerReconfigured) {
2456 StartWiFi();
2457 CancelScanTimer();
2458 EXPECT_TRUE(GetScanTimer().IsCancelled());
2459
mukesh agrawalbebf1b82013-04-23 15:06:33 -07002460 SetScanInterval(1, NULL);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002461 EXPECT_FALSE(GetScanTimer().IsCancelled());
2462}
2463
2464TEST_F(WiFiMainTest, ScanTimerResetOnScanDone) {
2465 StartWiFi();
2466 CancelScanTimer();
2467 EXPECT_TRUE(GetScanTimer().IsCancelled());
2468
2469 ReportScanDone();
2470 EXPECT_FALSE(GetScanTimer().IsCancelled());
2471}
2472
2473TEST_F(WiFiMainTest, ScanTimerStopOnZeroInterval) {
2474 StartWiFi();
2475 EXPECT_FALSE(GetScanTimer().IsCancelled());
2476
mukesh agrawalbebf1b82013-04-23 15:06:33 -07002477 SetScanInterval(0, NULL);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002478 EXPECT_TRUE(GetScanTimer().IsCancelled());
2479}
2480
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002481TEST_F(WiFiMainTest, ScanOnDisconnectWithHidden_FullScan) {
2482 EnableFullScan();
mukesh agrawalb66c6462012-05-07 11:45:25 -07002483 StartWiFi();
mukesh agrawalb66c6462012-05-07 11:45:25 -07002484 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08002485 SetupConnectedService(DBus::Path(), NULL, NULL);
2486 vector<uint8_t>kSSID(1, 'a');
2487 ByteArrays ssids;
2488 ssids.push_back(kSSID);
Wade Guthriea5995cf2013-07-30 09:31:16 -07002489 ExpectScanIdle();
Paul Stewart3c504012013-01-17 17:49:58 -08002490 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
2491 .WillRepeatedly(Return(ssids));
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002492 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
2493 Scan(HasHiddenSSID_FullScan(kSSID)));
2494 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
2495 dispatcher_.DispatchPendingEvents();
2496}
2497
2498TEST_F(WiFiMainTest, ScanOnDisconnectWithHidden) {
2499 StartWiFi();
2500 dispatcher_.DispatchPendingEvents();
2501 ReportScanDone();
2502 SetupConnectedService(DBus::Path(), NULL, NULL);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07002503 InstallMockScanSession();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002504 vector<uint8_t>kSSID(1, 'a');
2505 ByteArrays ssids;
2506 ssids.push_back(kSSID);
Wade Guthriea5995cf2013-07-30 09:31:16 -07002507 ExpectScanIdle();
Wade Guthrie5a4e2ef2013-04-30 12:51:39 -07002508 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
2509 .WillRepeatedly(Return(ssids));
2510 EXPECT_CALL(*scan_session_, InitiateScan());
Paul Stewart0654ece2013-03-26 15:21:26 -07002511 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002512 dispatcher_.DispatchPendingEvents();
2513}
2514
2515TEST_F(WiFiMainTest, NoScanOnDisconnectWithoutHidden) {
2516 StartWiFi();
mukesh agrawalb66c6462012-05-07 11:45:25 -07002517 dispatcher_.DispatchPendingEvents();
Paul Stewart3c504012013-01-17 17:49:58 -08002518 SetupConnectedService(DBus::Path(), NULL, NULL);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002519 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07002520 EXPECT_TRUE(IsScanSessionNull());
Paul Stewart3c504012013-01-17 17:49:58 -08002521 EXPECT_CALL(*wifi_provider(), GetHiddenSSIDList())
2522 .WillRepeatedly(Return(ByteArrays()));
Paul Stewart0654ece2013-03-26 15:21:26 -07002523 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
mukesh agrawalb66c6462012-05-07 11:45:25 -07002524 dispatcher_.DispatchPendingEvents();
2525}
2526
Paul Stewart3c508e12012-08-09 11:40:06 -07002527TEST_F(WiFiMainTest, LinkMonitorFailure) {
2528 StartWiFi();
2529 ScopedMockLog log;
2530 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
2531 MockLinkMonitor *link_monitor = new StrictMock<MockLinkMonitor>();
2532 SetLinkMonitor(link_monitor);
2533 EXPECT_CALL(*link_monitor, IsGatewayFound())
2534 .WillOnce(Return(false))
2535 .WillRepeatedly(Return(true));
2536 EXPECT_CALL(log, Log(logging::LOG_INFO, _,
2537 EndsWith("gateway was never found."))).Times(1);
Peter Qiudaa14ee2014-03-10 14:40:53 -07002538 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(0);
Paul Stewart3c508e12012-08-09 11:40:06 -07002539 OnLinkMonitorFailure();
2540 EXPECT_CALL(log, Log(logging::LOG_INFO, _,
Peter Qiudaa14ee2014-03-10 14:40:53 -07002541 EndsWith("Called Reattach()."))).Times(1);
2542 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(1);
Paul Stewart3c508e12012-08-09 11:40:06 -07002543 OnLinkMonitorFailure();
2544 OnSupplicantVanish();
Paul Stewart3c504012013-01-17 17:49:58 -08002545 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
Peter Qiudaa14ee2014-03-10 14:40:53 -07002546 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Reattach()).Times(0);
Paul Stewart3c508e12012-08-09 11:40:06 -07002547 EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
2548 EndsWith("Cannot reassociate."))).Times(1);
2549 OnLinkMonitorFailure();
2550}
2551
mukesh agrawalcf24a242012-05-21 16:46:11 -07002552TEST_F(WiFiMainTest, SuspectCredentialsOpen) {
Ben Chanf024ef42013-09-20 14:21:38 -07002553 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Paul Stewartbca08f82013-07-09 16:32:37 -07002554 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
2555 EXPECT_FALSE(SuspectCredentials(service, NULL));
mukesh agrawalcf24a242012-05-21 16:46:11 -07002556}
2557
Paul Stewartbca08f82013-07-09 16:32:37 -07002558TEST_F(WiFiMainTest, SuspectCredentialsWPA) {
Ben Chanf024ef42013-09-20 14:21:38 -07002559 MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
Paul Stewart0654ece2013-03-26 15:21:26 -07002560 ReportStateChanged(WPASupplicant::kInterfaceState4WayHandshake);
Paul Stewartbca08f82013-07-09 16:32:37 -07002561 EXPECT_CALL(*service, AddSuspectedCredentialFailure())
2562 .WillOnce(Return(false))
2563 .WillOnce(Return(true));
2564 EXPECT_FALSE(SuspectCredentials(service, NULL));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002565 Service::ConnectFailure failure;
Paul Stewartbca08f82013-07-09 16:32:37 -07002566 EXPECT_TRUE(SuspectCredentials(service, &failure));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002567 EXPECT_EQ(Service::kFailureBadPassphrase, failure);
mukesh agrawalcf24a242012-05-21 16:46:11 -07002568}
2569
Paul Stewartf6f96482013-07-12 12:49:15 -07002570TEST_F(WiFiMainTest, SuspectCredentialsWEP) {
2571 StartWiFi();
2572 dispatcher_.DispatchPendingEvents();
Ben Chanf024ef42013-09-20 14:21:38 -07002573 MockWiFiServiceRefPtr service = MakeMockService(kSecurityWep);
Wade Guthriea5995cf2013-07-30 09:31:16 -07002574 ExpectConnecting();
Paul Stewartf6f96482013-07-12 12:49:15 -07002575 InitiateConnect(service);
2576 SetCurrentService(service);
2577
2578 // These expectations are very much like SetupConnectedService except
2579 // that we verify that ResetSupsectCredentialFailures() is not called
2580 // on the service just because supplicant entered the Completed state.
2581 EXPECT_CALL(*service, SetState(Service::kStateConfiguring));
2582 EXPECT_CALL(*service, ResetSuspectedCredentialFailures()).Times(0);
Paul Stewart75a68b92013-10-24 10:50:27 -07002583 EXPECT_CALL(*dhcp_provider(), CreateConfig(_, _, _, _, _)).Times(AnyNumber());
Paul Stewartf6f96482013-07-12 12:49:15 -07002584 EXPECT_CALL(*dhcp_config_.get(), RequestIP()).Times(AnyNumber());
2585 EXPECT_CALL(*manager(), device_info()).WillRepeatedly(Return(device_info()));
2586 EXPECT_CALL(*device_info(), GetByteCounts(_, _, _))
2587 .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)));
2588 ReportStateChanged(WPASupplicant::kInterfaceStateCompleted);
2589
2590 Mock::VerifyAndClearExpectations(device_info());
2591 Mock::VerifyAndClearExpectations(service);
2592
2593 // Successful connect.
2594 EXPECT_CALL(*GetSupplicantInterfaceProxy(), EnableHighBitrates()).Times(1);
2595 EXPECT_CALL(*service, ResetSuspectedCredentialFailures());
2596 ReportConnected();
2597
2598 EXPECT_CALL(*device_info(), GetByteCounts(_, _, _))
2599 .WillOnce(DoAll(SetArgumentPointee<2>(1LL), Return(true)))
2600 .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)))
2601 .WillOnce(DoAll(SetArgumentPointee<2>(0LL), Return(true)));
2602
2603 // If there was an increased byte-count while we were timing out DHCP,
2604 // this should be considered a DHCP failure and not a credential failure.
2605 EXPECT_CALL(*service, ResetSuspectedCredentialFailures()).Times(0);
2606 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureDHCP, _));
2607 ReportIPConfigFailure();
2608 Mock::VerifyAndClearExpectations(service);
2609
2610 // Connection failed during DHCP but service does not (yet) believe this is
2611 // due to a passphrase issue.
2612 EXPECT_CALL(*service, AddSuspectedCredentialFailure())
2613 .WillOnce(Return(false));
2614 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureDHCP, _));
2615 ReportIPConfigFailure();
2616 Mock::VerifyAndClearExpectations(service);
2617
2618 // Connection failed during DHCP and service believes this is due to a
2619 // passphrase issue.
2620 EXPECT_CALL(*service, AddSuspectedCredentialFailure())
2621 .WillOnce(Return(true));
2622 EXPECT_CALL(*service,
2623 DisconnectWithFailure(Service::kFailureBadPassphrase, _));
2624 ReportIPConfigFailure();
2625}
2626
Paul Stewart1369c2b2013-01-11 05:41:26 -08002627TEST_F(WiFiMainTest, SuspectCredentialsEAPInProgress) {
Ben Chanf024ef42013-09-20 14:21:38 -07002628 MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
Paul Stewart735eab52013-03-29 09:19:23 -07002629 EXPECT_CALL(*eap_state_handler_, is_eap_in_progress())
2630 .WillOnce(Return(false))
2631 .WillOnce(Return(true))
2632 .WillOnce(Return(false))
2633 .WillOnce(Return(true));
Paul Stewartbca08f82013-07-09 16:32:37 -07002634 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
2635 EXPECT_FALSE(SuspectCredentials(service, NULL));
2636 Mock::VerifyAndClearExpectations(service);
2637
2638 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002639 Service::ConnectFailure failure;
Paul Stewartbca08f82013-07-09 16:32:37 -07002640 EXPECT_TRUE(SuspectCredentials(service, &failure));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002641 EXPECT_EQ(Service::kFailureEAPAuthentication, failure);
Paul Stewartbca08f82013-07-09 16:32:37 -07002642 Mock::VerifyAndClearExpectations(service);
2643
2644 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).Times(0);
2645 EXPECT_FALSE(SuspectCredentials(service, NULL));
2646 Mock::VerifyAndClearExpectations(service);
2647
2648 EXPECT_CALL(*service, AddSuspectedCredentialFailure())
2649 .WillOnce(Return(false));
2650 EXPECT_FALSE(SuspectCredentials(service, NULL));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002651}
2652
2653TEST_F(WiFiMainTest, SuspectCredentialsYieldFailureWPA) {
Ben Chanf024ef42013-09-20 14:21:38 -07002654 MockWiFiServiceRefPtr service = MakeMockService(kSecurityWpa);
mukesh agrawalcf24a242012-05-21 16:46:11 -07002655 SetPendingService(service);
Paul Stewart0654ece2013-03-26 15:21:26 -07002656 ReportStateChanged(WPASupplicant::kInterfaceState4WayHandshake);
mukesh agrawalcf24a242012-05-21 16:46:11 -07002657
Wade Guthriea5995cf2013-07-30 09:31:16 -07002658 ExpectScanIdle();
Paul Stewartbca08f82013-07-09 16:32:37 -07002659 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
Paul Stewartf2d60912012-07-15 08:37:30 -07002660 EXPECT_CALL(*service, SetFailure(Service::kFailureBadPassphrase));
Peter Qiu49438222014-03-14 14:21:09 -07002661 EXPECT_CALL(*service, SetState(Service::kStateIdle));
Paul Stewart735eab52013-03-29 09:19:23 -07002662 ScopedMockLog log;
mukesh agrawalcf24a242012-05-21 16:46:11 -07002663 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
Ben Chanf024ef42013-09-20 14:21:38 -07002664 EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith(kErrorBadPassphrase)));
Paul Stewart0654ece2013-03-26 15:21:26 -07002665 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
Paul Stewart1369c2b2013-01-11 05:41:26 -08002666}
2667
2668TEST_F(WiFiMainTest, SuspectCredentialsYieldFailureEAP) {
Ben Chanf024ef42013-09-20 14:21:38 -07002669 MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
Paul Stewart1369c2b2013-01-11 05:41:26 -08002670 SetCurrentService(service);
Paul Stewart1369c2b2013-01-11 05:41:26 -08002671
Paul Stewart735eab52013-03-29 09:19:23 -07002672 ScopedMockLog log;
2673 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
Peter Qiu49438222014-03-14 14:21:09 -07002674 EXPECT_CALL(*service, SetState(Service::kStateIdle));
Paul Stewart735eab52013-03-29 09:19:23 -07002675 // Ensure that we retrieve is_eap_in_progress() before resetting the
2676 // EAP handler's state.
2677 InSequence seq;
2678 EXPECT_CALL(*eap_state_handler_, is_eap_in_progress())
2679 .WillOnce(Return(true));
Paul Stewartbca08f82013-07-09 16:32:37 -07002680 EXPECT_CALL(*service, AddSuspectedCredentialFailure()).WillOnce(Return(true));
Paul Stewart735eab52013-03-29 09:19:23 -07002681 EXPECT_CALL(*service, SetFailure(Service::kFailureEAPAuthentication));
Paul Stewart1369c2b2013-01-11 05:41:26 -08002682 EXPECT_CALL(log, Log(logging::LOG_ERROR, _,
Ben Chan39a7beb2013-09-21 11:28:00 -07002683 EndsWith(kErrorEapAuthenticationFailed)));
Paul Stewart735eab52013-03-29 09:19:23 -07002684 EXPECT_CALL(*eap_state_handler_, Reset());
Paul Stewart0654ece2013-03-26 15:21:26 -07002685 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
mukesh agrawalcf24a242012-05-21 16:46:11 -07002686}
2687
Paul Stewarte369ece2012-05-22 09:11:03 -07002688// Scanning tests will use a mock of the event dispatcher instead of a real
2689// one.
Paul Stewart1aff7302012-08-04 20:04:47 -07002690class WiFiTimerTest : public WiFiObjectTest {
Paul Stewarte369ece2012-05-22 09:11:03 -07002691 public:
Paul Stewart1aff7302012-08-04 20:04:47 -07002692 WiFiTimerTest() : WiFiObjectTest(&mock_dispatcher_) {}
Paul Stewarte369ece2012-05-22 09:11:03 -07002693
2694 protected:
2695 void ExpectInitialScanSequence();
2696
2697 StrictMock<MockEventDispatcher> mock_dispatcher_;
2698};
2699
Paul Stewart1aff7302012-08-04 20:04:47 -07002700void WiFiTimerTest::ExpectInitialScanSequence() {
Paul Stewarte369ece2012-05-22 09:11:03 -07002701 // Choose a number of iterations some multiple higher than the fast scan
2702 // count.
2703 const int kScanTimes = WiFi::kNumFastScanAttempts * 4;
2704
2705 // Each time we call FireScanTimer() below, WiFi will post a task to actually
2706 // run Scan() on the wpa_supplicant proxy.
2707 EXPECT_CALL(mock_dispatcher_, PostTask(_))
2708 .Times(kScanTimes);
2709 {
2710 InSequence seq;
2711 // The scans immediately after the initial scan should happen at the short
2712 // interval. If we add the initial scan (not invoked in this function) to
2713 // the ones in the expectation below, we get WiFi::kNumFastScanAttempts at
2714 // the fast scan interval.
2715 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2716 _, WiFi::kFastScanIntervalSeconds * 1000))
2717 .Times(WiFi::kNumFastScanAttempts - 1)
2718 .WillRepeatedly(Return(true));
2719
2720 // After this, the WiFi device should use the normal scan interval.
2721 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2722 _, GetScanInterval() * 1000))
2723 .Times(kScanTimes - WiFi::kNumFastScanAttempts + 1)
2724 .WillRepeatedly(Return(true));
2725
2726 for (int i = 0; i < kScanTimes; i++) {
2727 FireScanTimer();
2728 }
2729 }
2730}
2731
Paul Stewart1aff7302012-08-04 20:04:47 -07002732TEST_F(WiFiTimerTest, FastRescan) {
Paul Stewarte369ece2012-05-22 09:11:03 -07002733 // This PostTask is a result of the call to Scan(NULL), and is meant to
2734 // post a task to call Scan() on the wpa_supplicant proxy immediately.
2735 EXPECT_CALL(mock_dispatcher_, PostTask(_));
2736 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2737 _, WiFi::kFastScanIntervalSeconds * 1000))
2738 .WillOnce(Return(true));
2739 StartWiFi();
2740
2741 ExpectInitialScanSequence();
2742
2743 // If we end up disconnecting, the sequence should repeat.
2744 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2745 _, WiFi::kFastScanIntervalSeconds * 1000))
2746 .WillOnce(Return(true));
2747 RestartFastScanAttempts();
2748
2749 ExpectInitialScanSequence();
2750}
2751
Paul Stewart1aff7302012-08-04 20:04:47 -07002752TEST_F(WiFiTimerTest, ReconnectTimer) {
2753 EXPECT_CALL(mock_dispatcher_, PostTask(_)).Times(AnyNumber());
2754 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
Paul Stewart3c504012013-01-17 17:49:58 -08002755 StartWiFi();
2756 SetupConnectedService(DBus::Path(), NULL, NULL);
Paul Stewart1aff7302012-08-04 20:04:47 -07002757 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2758
2759 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2760 _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
2761 StartReconnectTimer();
2762 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2763 StopReconnectTimer();
2764
2765 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2766 _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
2767 StartReconnectTimer();
2768 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2769 GetReconnectTimeoutCallback().callback().Run();
2770
2771 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2772 _, GetReconnectTimeoutSeconds() * 1000)).Times(1);
2773 StartReconnectTimer();
2774 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2775
2776 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2777 _, GetReconnectTimeoutSeconds() * 1000)).Times(0);
2778 StartReconnectTimer();
2779}
2780
Paul Stewart7cd45722013-08-12 14:50:14 -07002781TEST_F(WiFiTimerTest, RequestStationInfo) {
2782 EXPECT_CALL(mock_dispatcher_, PostTask(_)).Times(AnyNumber());
2783 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(AnyNumber());
2784
2785 // Setup a connected service here while we have the expectations above set.
2786 StartWiFi();
2787 MockWiFiServiceRefPtr service =
2788 SetupConnectedService(DBus::Path(), NULL, NULL);
2789 string connected_bss = GetSupplicantBSS();
2790 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2791
2792 EXPECT_CALL(netlink_manager_, SendNl80211Message(_, _, _)).Times(0);
2793 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(_, _)).Times(0);
2794 NiceScopedMockLog log;
2795
2796 // There is no current_service_.
2797 EXPECT_CALL(log, Log(_, _, HasSubstr("we are not connected")));
2798 SetCurrentService(NULL);
2799 RequestStationInfo();
2800
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07002801 // current_service_ is not connected.
Paul Stewart7cd45722013-08-12 14:50:14 -07002802 EXPECT_CALL(*service, IsConnected()).WillOnce(Return(false));
2803 SetCurrentService(service);
2804 EXPECT_CALL(log, Log(_, _, HasSubstr("we are not connected")));
2805 RequestStationInfo();
2806
2807 // Endpoint does not exist in endpoint_by_rpcid_.
2808 EXPECT_CALL(*service, IsConnected()).WillRepeatedly(Return(true));
2809 SetSupplicantBSS("/some/path/that/does/not/exist/in/endpoint_by_rpcid");
2810 EXPECT_CALL(log, Log(_, _, HasSubstr(
2811 "Can't get endpoint for current supplicant BSS")));
2812 RequestStationInfo();
2813 Mock::VerifyAndClearExpectations(&netlink_manager_);
2814 Mock::VerifyAndClearExpectations(&mock_dispatcher_);
2815
2816 // We successfully trigger a request to get the station and start a timer
2817 // for the next call.
2818 EXPECT_CALL(netlink_manager_, SendNl80211Message(
2819 IsNl80211Command(kNl80211FamilyId, NL80211_CMD_GET_STATION), _, _));
2820 EXPECT_CALL(mock_dispatcher_, PostDelayedTask(
2821 _, WiFi::kRequestStationInfoPeriodSeconds * 1000));
2822 SetSupplicantBSS(connected_bss);
2823 RequestStationInfo();
2824
2825 // Now test that a properly formatted New Station message updates strength.
2826 NewStationMessage new_station;
2827 new_station.attributes()->CreateRawAttribute(NL80211_ATTR_MAC, "BSSID");
2828
Paul Stewartbaf87072013-10-04 17:03:37 -07002829 // Confirm that up until now no link statistics exist.
2830 KeyValueStore link_statistics = GetLinkStatistics();
2831 EXPECT_TRUE(link_statistics.IsEmpty());
2832
Paul Stewart7cd45722013-08-12 14:50:14 -07002833 // Use a reference to the endpoint instance in the WiFi device instead of
2834 // the copy returned by SetupConnectedService().
2835 WiFiEndpointRefPtr endpoint = GetEndpointMap().begin()->second;
2836 new_station.attributes()->SetRawAttributeValue(
2837 NL80211_ATTR_MAC, ByteString::CreateFromHexString(endpoint->bssid_hex()));
2838 new_station.attributes()->CreateNestedAttribute(
2839 NL80211_ATTR_STA_INFO, "Station Info");
2840 AttributeListRefPtr station_info;
2841 new_station.attributes()->GetNestedAttributeList(
2842 NL80211_ATTR_STA_INFO, &station_info);
2843 station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL, "Signal");
Paul Stewartbaf87072013-10-04 17:03:37 -07002844 const int kSignalValue = -20;
Paul Stewart7cd45722013-08-12 14:50:14 -07002845 station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL, kSignalValue);
Paul Stewartbaf87072013-10-04 17:03:37 -07002846 station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL_AVG, "SignalAverage");
2847 const int kSignalAvgValue = -40;
2848 station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL_AVG,
2849 kSignalAvgValue);
2850 station_info->CreateU32Attribute(NL80211_STA_INFO_INACTIVE_TIME,
2851 "InactiveTime");
2852 const int32_t kInactiveTime = 100;
2853 station_info->SetU32AttributeValue(NL80211_STA_INFO_INACTIVE_TIME,
2854 kInactiveTime);
2855 station_info->CreateU32Attribute(NL80211_STA_INFO_RX_PACKETS,
2856 "ReceivedSuccesses");
2857 const int32_t kReceiveSuccesses = 200;
2858 station_info->SetU32AttributeValue(NL80211_STA_INFO_RX_PACKETS,
2859 kReceiveSuccesses);
2860 station_info->CreateU32Attribute(NL80211_STA_INFO_TX_FAILED,
2861 "TransmitFailed");
2862 const int32_t kTransmitFailed = 300;
2863 station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_FAILED,
2864 kTransmitFailed);
2865 station_info->CreateU32Attribute(NL80211_STA_INFO_TX_PACKETS,
2866 "TransmitSuccesses");
2867 const int32_t kTransmitSuccesses = 400;
2868 station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_PACKETS,
2869 kTransmitSuccesses);
2870 station_info->CreateU32Attribute(NL80211_STA_INFO_TX_RETRIES,
2871 "TransmitRetries");
2872 const int32_t kTransmitRetries = 500;
2873 station_info->SetU32AttributeValue(NL80211_STA_INFO_TX_RETRIES,
2874 kTransmitRetries);
2875 station_info->CreateNestedAttribute(NL80211_STA_INFO_TX_BITRATE,
2876 "Bitrate Info");
2877
2878 // Embed transmit bitrate info within the station info element.
2879 AttributeListRefPtr bitrate_info;
2880 station_info->GetNestedAttributeList(
2881 NL80211_STA_INFO_TX_BITRATE, &bitrate_info);
2882 bitrate_info->CreateU16Attribute(NL80211_RATE_INFO_BITRATE, "Bitrate");
2883 const int16_t kBitrate = 6005;
2884 bitrate_info->SetU16AttributeValue(NL80211_RATE_INFO_BITRATE, kBitrate);
2885 bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_MCS, "MCS");
2886 const int16_t kMCS = 7;
2887 bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_MCS, kMCS);
2888 bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_40_MHZ_WIDTH, "HT40");
2889 bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_40_MHZ_WIDTH, true);
2890 bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_SHORT_GI, "SGI");
2891 bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_SHORT_GI, false);
2892 station_info->SetNestedAttributeHasAValue(NL80211_STA_INFO_TX_BITRATE);
2893
Paul Stewart7cd45722013-08-12 14:50:14 -07002894 new_station.attributes()->SetNestedAttributeHasAValue(NL80211_ATTR_STA_INFO);
2895
2896 EXPECT_NE(kSignalValue, endpoint->signal_strength());
2897 EXPECT_CALL(*wifi_provider(), OnEndpointUpdated(EndpointMatch(endpoint)));
Peter Qiu8e430582014-04-30 14:12:37 -07002898 EXPECT_CALL(*metrics(), NotifyWifiTxBitrate(kBitrate/10));
Paul Stewart7cd45722013-08-12 14:50:14 -07002899 AttributeListConstRefPtr station_info_prime;
2900 ReportReceivedStationInfo(new_station);
2901 EXPECT_EQ(kSignalValue, endpoint->signal_strength());
Paul Stewartbaf87072013-10-04 17:03:37 -07002902
2903 link_statistics = GetLinkStatistics();
2904 ASSERT_FALSE(link_statistics.IsEmpty());
2905 ASSERT_TRUE(link_statistics.ContainsInt(kLastReceiveSignalDbmProperty));
2906 EXPECT_EQ(kSignalValue,
2907 link_statistics.GetInt(kLastReceiveSignalDbmProperty));
2908 ASSERT_TRUE(link_statistics.ContainsInt(kAverageReceiveSignalDbmProperty));
2909 EXPECT_EQ(kSignalAvgValue,
2910 link_statistics.GetInt(kAverageReceiveSignalDbmProperty));
2911 ASSERT_TRUE(link_statistics.ContainsUint(kInactiveTimeMillisecondsProperty));
2912 EXPECT_EQ(kInactiveTime,
2913 link_statistics.GetUint(kInactiveTimeMillisecondsProperty));
2914 ASSERT_TRUE(link_statistics.ContainsUint(kPacketReceiveSuccessesProperty));
2915 EXPECT_EQ(kReceiveSuccesses,
2916 link_statistics.GetUint(kPacketReceiveSuccessesProperty));
2917 ASSERT_TRUE(link_statistics.ContainsUint(kPacketTransmitFailuresProperty));
2918 EXPECT_EQ(kTransmitFailed,
2919 link_statistics.GetUint(kPacketTransmitFailuresProperty));
2920 ASSERT_TRUE(link_statistics.ContainsUint(kPacketTransmitSuccessesProperty));
2921 EXPECT_EQ(kTransmitSuccesses,
2922 link_statistics.GetUint(kPacketTransmitSuccessesProperty));
2923 ASSERT_TRUE(link_statistics.ContainsUint(kTransmitRetriesProperty));
2924 EXPECT_EQ(kTransmitRetries,
2925 link_statistics.GetUint(kTransmitRetriesProperty));
2926 EXPECT_EQ(StringPrintf("%d.%d MBit/s MCS %d 40MHz",
2927 kBitrate / 10, kBitrate % 10, kMCS),
2928 link_statistics.LookupString(kTransmitBitrateProperty, ""));
Peter Qiue50623a2014-04-28 14:35:16 -07002929
2930 // New station info with VHT rate parameters.
2931 NewStationMessage new_vht_station;
2932 new_vht_station.attributes()->CreateRawAttribute(NL80211_ATTR_MAC, "BSSID");
2933
2934 new_vht_station.attributes()->SetRawAttributeValue(
2935 NL80211_ATTR_MAC, ByteString::CreateFromHexString(endpoint->bssid_hex()));
2936 new_vht_station.attributes()->CreateNestedAttribute(
2937 NL80211_ATTR_STA_INFO, "Station Info");
2938 new_vht_station.attributes()->GetNestedAttributeList(
2939 NL80211_ATTR_STA_INFO, &station_info);
2940 station_info->CreateU8Attribute(NL80211_STA_INFO_SIGNAL, "Signal");
2941 station_info->SetU8AttributeValue(NL80211_STA_INFO_SIGNAL, kSignalValue);
2942 station_info->CreateNestedAttribute(NL80211_STA_INFO_TX_BITRATE,
2943 "Bitrate Info");
2944
2945 // Embed transmit VHT bitrate info within the station info element.
2946 station_info->GetNestedAttributeList(
2947 NL80211_STA_INFO_TX_BITRATE, &bitrate_info);
2948 bitrate_info->CreateU32Attribute(NL80211_RATE_INFO_BITRATE32, "Bitrate32");
2949 const int32_t kVhtBitrate = 70000;
2950 bitrate_info->SetU32AttributeValue(NL80211_RATE_INFO_BITRATE32, kVhtBitrate);
2951 bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_VHT_MCS, "VHT-MCS");
2952 const int8_t kVhtMCS = 7;
2953 bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_VHT_MCS, kVhtMCS);
2954 bitrate_info->CreateU8Attribute(NL80211_RATE_INFO_VHT_NSS, "VHT-NSS");
2955 const int8_t kVhtNSS = 1;
2956 bitrate_info->SetU8AttributeValue(NL80211_RATE_INFO_VHT_NSS, kVhtNSS);
2957 bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_80_MHZ_WIDTH, "VHT80");
2958 bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_80_MHZ_WIDTH, true);
2959 bitrate_info->CreateFlagAttribute(NL80211_RATE_INFO_SHORT_GI, "SGI");
2960 bitrate_info->SetFlagAttributeValue(NL80211_RATE_INFO_SHORT_GI, false);
2961 station_info->SetNestedAttributeHasAValue(NL80211_STA_INFO_TX_BITRATE);
2962
2963 new_vht_station.attributes()->SetNestedAttributeHasAValue(
2964 NL80211_ATTR_STA_INFO);
2965
Peter Qiu8e430582014-04-30 14:12:37 -07002966 EXPECT_CALL(*metrics(), NotifyWifiTxBitrate(kVhtBitrate/10));
2967
Peter Qiue50623a2014-04-28 14:35:16 -07002968 ReportReceivedStationInfo(new_vht_station);
2969
2970 link_statistics = GetLinkStatistics();
2971 EXPECT_EQ(StringPrintf("%d.%d MBit/s VHT-MCS %d 80MHz VHT-NSS %d",
2972 kVhtBitrate / 10, kVhtBitrate % 10, kVhtMCS, kVhtNSS),
2973 link_statistics.LookupString(kTransmitBitrateProperty, ""));
Paul Stewart7cd45722013-08-12 14:50:14 -07002974}
2975
Paul Stewartbc6e7392012-05-24 07:07:48 -07002976TEST_F(WiFiMainTest, EAPCertification) {
Ben Chanf024ef42013-09-20 14:21:38 -07002977 MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
Paul Stewartbc6e7392012-05-24 07:07:48 -07002978 EXPECT_CALL(*service, AddEAPCertification(_, _)).Times(0);
2979
2980 ScopedMockLog log;
2981 EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no current service.")));
2982 map<string, ::DBus::Variant> args;
2983 ReportCertification(args);
2984 Mock::VerifyAndClearExpectations(&log);
2985
2986 SetCurrentService(service);
2987 EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no depth parameter.")));
2988 ReportCertification(args);
2989 Mock::VerifyAndClearExpectations(&log);
2990
2991 const uint32 kDepth = 123;
Paul Stewart0654ece2013-03-26 15:21:26 -07002992 args[WPASupplicant::kInterfacePropertyDepth].writer().append_uint32(kDepth);
Paul Stewartbc6e7392012-05-24 07:07:48 -07002993
2994 EXPECT_CALL(log,
2995 Log(logging::LOG_ERROR, _, EndsWith("no subject parameter.")));
2996 ReportCertification(args);
2997 Mock::VerifyAndClearExpectations(&log);
2998
2999 const string kSubject("subject");
Paul Stewart0654ece2013-03-26 15:21:26 -07003000 args[WPASupplicant::kInterfacePropertySubject].writer()
Paul Stewartbc6e7392012-05-24 07:07:48 -07003001 .append_string(kSubject.c_str());
3002 EXPECT_CALL(*service, AddEAPCertification(kSubject, kDepth)).Times(1);
3003 ReportCertification(args);
3004}
3005
Paul Stewartdb0f9172012-11-30 16:48:09 -08003006TEST_F(WiFiMainTest, EAPEvent) {
Paul Stewart11c224b2013-10-22 19:04:40 -07003007 StartWiFi();
Paul Stewartdb0f9172012-11-30 16:48:09 -08003008 ScopedMockLog log;
3009 EXPECT_CALL(log, Log(logging::LOG_ERROR, _, EndsWith("no current service.")));
Paul Stewart735eab52013-03-29 09:19:23 -07003010 EXPECT_CALL(*eap_state_handler_, ParseStatus(_, _, _)).Times(0);
3011 const string kEAPStatus("eap-status");
3012 const string kEAPParameter("eap-parameter");
3013 ReportEAPEvent(kEAPStatus, kEAPParameter);
Paul Stewartdb0f9172012-11-30 16:48:09 -08003014 Mock::VerifyAndClearExpectations(&log);
3015 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3016
Ben Chanf024ef42013-09-20 14:21:38 -07003017 MockWiFiServiceRefPtr service = MakeMockService(kSecurity8021x);
Paul Stewartdb0f9172012-11-30 16:48:09 -08003018 EXPECT_CALL(*service, SetFailure(_)).Times(0);
Paul Stewart735eab52013-03-29 09:19:23 -07003019 EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _));
Paul Stewartdb0f9172012-11-30 16:48:09 -08003020 SetCurrentService(service);
Paul Stewart735eab52013-03-29 09:19:23 -07003021 ReportEAPEvent(kEAPStatus, kEAPParameter);
3022 Mock::VerifyAndClearExpectations(service);
3023 Mock::VerifyAndClearExpectations(eap_state_handler_);
Paul Stewartdb0f9172012-11-30 16:48:09 -08003024
Paul Stewart735eab52013-03-29 09:19:23 -07003025 EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
3026 .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailureOutOfRange),
3027 Return(false)));
3028 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailureOutOfRange, _));
3029 ReportEAPEvent(kEAPStatus, kEAPParameter);
Paul Stewart11c224b2013-10-22 19:04:40 -07003030
3031 MockEapCredentials *eap = new MockEapCredentials();
3032 service->eap_.reset(eap); // Passes ownership.
3033 const char kNetworkRpcId[] = "/service/network/rpcid";
3034 SetServiceNetworkRpcId(service, kNetworkRpcId);
3035 EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
3036 .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailurePinMissing),
3037 Return(false)));
3038 // We need a real string object since it will be returned by reference below.
3039 const string kEmptyPin;
3040 EXPECT_CALL(*eap, pin()).WillOnce(ReturnRef(kEmptyPin));
3041 EXPECT_CALL(*service, DisconnectWithFailure(Service::kFailurePinMissing, _));
3042 ReportEAPEvent(kEAPStatus, kEAPParameter);
3043
3044 EXPECT_CALL(*eap_state_handler_, ParseStatus(kEAPStatus, kEAPParameter, _))
3045 .WillOnce(DoAll(SetArgumentPointee<2>(Service::kFailurePinMissing),
3046 Return(false)));
3047 // We need a real string object since it will be returned by reference below.
3048 const string kPin("000000");
3049 EXPECT_CALL(*eap, pin()).WillOnce(ReturnRef(kPin));
3050 EXPECT_CALL(*service, DisconnectWithFailure(_, _)).Times(0);
3051 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
3052 NetworkReply(StrEq(kNetworkRpcId),
3053 StrEq(WPASupplicant::kEAPRequestedParameterPIN),
3054 Ref(kPin)));
3055 ReportEAPEvent(kEAPStatus, kEAPParameter);
Paul Stewartdb0f9172012-11-30 16:48:09 -08003056}
3057
mukesh agrawalc4f368f2012-06-04 19:45:52 -07003058TEST_F(WiFiMainTest, PendingScanDoesNotCrashAfterStop) {
3059 // Scan is one task that should be skipped after Stop. Others are
3060 // skipped by the same mechanism (invalidating weak pointers), so we
3061 // don't test them individually.
3062 //
3063 // Note that we can't test behavior by setting expectations on the
3064 // supplicant_interface_proxy_, since that is destroyed when we StopWiFi().
3065 StartWiFi();
3066 StopWiFi();
3067 dispatcher_.DispatchPendingEvents();
3068}
3069
Gaurav Shah6d2c72d2012-10-16 16:30:44 -07003070struct BSS {
3071 string bsspath;
3072 string ssid;
3073 string bssid;
3074 int16_t signal_strength;
3075 uint16 frequency;
3076 const char* mode;
3077};
3078
3079TEST_F(WiFiMainTest, GetGeolocationObjects) {
3080 BSS bsses[] = {
3081 {"bssid1", "ssid1", "00:00:00:00:00:00", 5, Metrics::kWiFiFrequency2412,
3082 kNetworkModeInfrastructure},
3083 {"bssid2", "ssid2", "01:00:00:00:00:00", 30, Metrics::kWiFiFrequency5170,
3084 kNetworkModeInfrastructure},
3085 // Same SSID but different BSSID is an additional geolocation object.
3086 {"bssid3", "ssid1", "02:00:00:00:00:00", 100, 0,
3087 kNetworkModeInfrastructure}
3088 };
3089 StartWiFi();
3090 vector<GeolocationInfo> objects;
3091 EXPECT_EQ(objects.size(), 0);
3092
3093 for (size_t i = 0; i < arraysize(bsses); ++i) {
3094 ReportBSS(bsses[i].bsspath, bsses[i].ssid, bsses[i].bssid,
3095 bsses[i].signal_strength, bsses[i].frequency, bsses[i].mode);
3096 objects = wifi()->GetGeolocationObjects();
3097 EXPECT_EQ(objects.size(), i + 1);
3098
3099 GeolocationInfo expected_info;
3100 expected_info.AddField(kGeoMacAddressProperty, bsses[i].bssid);
3101 expected_info.AddField(kGeoSignalStrengthProperty,
3102 StringPrintf("%d", bsses[i].signal_strength));
3103 expected_info.AddField(kGeoChannelProperty, StringPrintf(
3104 "%d", Metrics::WiFiFrequencyToChannel(bsses[i].frequency)));
3105 EXPECT_TRUE(objects[i].Equals(expected_info));
Wade Guthrie7347bf22013-04-30 11:21:51 -07003106 }
3107}
Gaurav Shah6d2c72d2012-10-16 16:30:44 -07003108
Paul Stewart5581d072012-12-17 17:30:20 -08003109TEST_F(WiFiMainTest, SetSupplicantDebugLevel) {
3110 MockSupplicantProcessProxy *process_proxy = supplicant_process_proxy_.get();
3111
3112 // With WiFi not yet started, nothing interesting (including a crash) should
3113 // happen.
3114 EXPECT_CALL(*process_proxy, GetDebugLevel()).Times(0);
3115 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
3116 ReportWiFiDebugScopeChanged(true);
3117
3118 // This unit test turns on WiFi debugging, so when we start WiFi, we should
3119 // check but not set the debug level if we return the "debug" level.
3120 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07003121 .WillOnce(Return(WPASupplicant::kDebugLevelDebug));
Paul Stewart5581d072012-12-17 17:30:20 -08003122 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
3123 StartWiFi();
3124 Mock::VerifyAndClearExpectations(process_proxy);
3125
3126 // If WiFi debugging is toggled and wpa_supplicant reports debugging
3127 // is set to some unmanaged level, WiFi should leave it alone.
3128 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07003129 .WillOnce(Return(WPASupplicant::kDebugLevelError))
3130 .WillOnce(Return(WPASupplicant::kDebugLevelError))
3131 .WillOnce(Return(WPASupplicant::kDebugLevelExcessive))
3132 .WillOnce(Return(WPASupplicant::kDebugLevelExcessive))
3133 .WillOnce(Return(WPASupplicant::kDebugLevelMsgDump))
3134 .WillOnce(Return(WPASupplicant::kDebugLevelMsgDump))
3135 .WillOnce(Return(WPASupplicant::kDebugLevelWarning))
3136 .WillOnce(Return(WPASupplicant::kDebugLevelWarning));
Paul Stewart5581d072012-12-17 17:30:20 -08003137 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
3138 ReportWiFiDebugScopeChanged(true);
3139 ReportWiFiDebugScopeChanged(false);
3140 ReportWiFiDebugScopeChanged(true);
3141 ReportWiFiDebugScopeChanged(false);
3142 ReportWiFiDebugScopeChanged(true);
3143 ReportWiFiDebugScopeChanged(false);
3144 ReportWiFiDebugScopeChanged(true);
3145 ReportWiFiDebugScopeChanged(false);
3146 Mock::VerifyAndClearExpectations(process_proxy);
3147
3148 // If WiFi debugging is turned off and wpa_supplicant reports debugging
3149 // is turned on, WiFi should turn supplicant debugging off.
3150 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07003151 .WillOnce(Return(WPASupplicant::kDebugLevelDebug));
3152 EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelInfo))
Paul Stewart5581d072012-12-17 17:30:20 -08003153 .Times(1);
3154 ReportWiFiDebugScopeChanged(false);
3155 Mock::VerifyAndClearExpectations(process_proxy);
3156
3157 // If WiFi debugging is turned on and wpa_supplicant reports debugging
3158 // is turned off, WiFi should turn supplicant debugging on.
3159 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07003160 .WillOnce(Return(WPASupplicant::kDebugLevelInfo));
3161 EXPECT_CALL(*process_proxy, SetDebugLevel(WPASupplicant::kDebugLevelDebug))
Paul Stewart5581d072012-12-17 17:30:20 -08003162 .Times(1);
3163 ReportWiFiDebugScopeChanged(true);
3164 Mock::VerifyAndClearExpectations(process_proxy);
3165
3166 // If WiFi debugging is already in the correct state, it should not be
3167 // changed.
3168 EXPECT_CALL(*process_proxy, GetDebugLevel())
Paul Stewart0654ece2013-03-26 15:21:26 -07003169 .WillOnce(Return(WPASupplicant::kDebugLevelDebug))
3170 .WillOnce(Return(WPASupplicant::kDebugLevelInfo));
Paul Stewart5581d072012-12-17 17:30:20 -08003171 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
3172 ReportWiFiDebugScopeChanged(true);
3173 ReportWiFiDebugScopeChanged(false);
3174
3175 // After WiFi is stopped, we shouldn't be calling the proxy.
3176 EXPECT_CALL(*process_proxy, GetDebugLevel()).Times(0);
3177 EXPECT_CALL(*process_proxy, SetDebugLevel(_)).Times(0);
3178 StopWiFi();
3179 ReportWiFiDebugScopeChanged(true);
3180 ReportWiFiDebugScopeChanged(false);
3181}
3182
Darin Petkov50cb78a2013-02-06 16:17:49 +01003183TEST_F(WiFiMainTest, LogSSID) {
3184 EXPECT_EQ("[SSID=]", WiFi::LogSSID(""));
3185 EXPECT_EQ("[SSID=foo\\x5b\\x09\\x5dbar]", WiFi::LogSSID("foo[\t]bar"));
3186}
3187
mukesh agrawalbebf1b82013-04-23 15:06:33 -07003188// Custom property setters should return false, and make no changes, if
3189// the new value is the same as the old value.
3190TEST_F(WiFiMainTest, CustomSetterNoopChange) {
3191 // SetBgscanShortInterval
3192 {
3193 Error error;
3194 static const uint16 kKnownScanInterval = 4;
3195 // Set to known value.
3196 EXPECT_TRUE(SetBgscanShortInterval(kKnownScanInterval, &error));
3197 EXPECT_TRUE(error.IsSuccess());
3198 // Set to same value.
3199 EXPECT_FALSE(SetBgscanShortInterval(kKnownScanInterval, &error));
3200 EXPECT_TRUE(error.IsSuccess());
3201 }
3202
3203 // SetBgscanSignalThreshold
3204 {
3205 Error error;
3206 static const int32 kKnownSignalThreshold = 4;
3207 // Set to known value.
3208 EXPECT_TRUE(SetBgscanSignalThreshold(kKnownSignalThreshold, &error));
3209 EXPECT_TRUE(error.IsSuccess());
3210 // Set to same value.
3211 EXPECT_FALSE(SetBgscanSignalThreshold(kKnownSignalThreshold, &error));
3212 EXPECT_TRUE(error.IsSuccess());
3213 }
3214
3215 // SetScanInterval
3216 {
3217 Error error;
3218 EXPECT_FALSE(SetScanInterval(GetScanInterval(), &error));
3219 EXPECT_TRUE(error.IsSuccess());
3220 }
3221}
3222
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003223// The following tests check the scan_state_ / scan_method_ state machine.
3224
3225TEST_F(WiFiMainTest, FullScanFindsNothing) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003226 StartScan(WiFi::kScanMethodFull);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003227 ReportScanDone();
Wade Guthriea5995cf2013-07-30 09:31:16 -07003228 ExpectScanStop();
3229 ExpectFoundNothing();
3230 NiceScopedMockLog log;
3231 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3232 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003233 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3234 EXPECT_CALL(log, Log(_, _, HasSubstr("FULL_NOCONNECTION ->")));
Paul Stewart7de7e022013-08-28 09:42:50 -07003235 EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003236 dispatcher_.DispatchPendingEvents(); // Launch UpdateScanStateAfterScanDone
3237 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3238
3239 ScopeLogger::GetInstance()->set_verbose_level(0);
3240 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3241}
3242
3243TEST_F(WiFiMainTest, FullScanConnectingToConnected) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003244 StartScan(WiFi::kScanMethodFull);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003245 WiFiEndpointRefPtr endpoint;
3246 ::DBus::Path bss_path;
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003247 MockWiFiServiceRefPtr service = AttemptConnection(WiFi::kScanMethodFull,
3248 &endpoint,
3249 &bss_path);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003250
3251 // Complete the connection.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003252 ExpectConnected();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003253 EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
Wade Guthriea5995cf2013-07-30 09:31:16 -07003254 NiceScopedMockLog log;
3255 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3256 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003257 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3258 EXPECT_CALL(log, Log(_, _, HasSubstr("-> FULL_CONNECTED")));
3259 ReportCurrentBSSChanged(bss_path);
3260 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3261
3262 ScopeLogger::GetInstance()->set_verbose_level(0);
3263 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3264}
3265
3266TEST_F(WiFiMainTest, ProgressiveScanConnectingToConnected) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003267 StartScan(WiFi::kScanMethodProgressive);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003268 WiFiEndpointRefPtr endpoint;
3269 ::DBus::Path bss_path;
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003270 MockWiFiServiceRefPtr service = AttemptConnection(
3271 WiFi::kScanMethodProgressive, &endpoint, &bss_path);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003272
3273 // Complete the connection.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003274 ExpectConnected();
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003275 EXPECT_CALL(*service, NotifyCurrentEndpoint(EndpointMatch(endpoint)));
Wade Guthriea5995cf2013-07-30 09:31:16 -07003276 NiceScopedMockLog log;
3277 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3278 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthrie0cf3c982013-05-29 09:11:35 -07003279 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3280 EXPECT_CALL(log, Log(_, _, HasSubstr("-> PROGRESSIVE_CONNECTED")));
3281 ReportCurrentBSSChanged(bss_path);
3282 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3283
3284 ScopeLogger::GetInstance()->set_verbose_level(0);
3285 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3286}
3287
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003288TEST_F(WiFiMainTest, ProgressiveScanConnectingToNotFound) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003289 StartScan(WiFi::kScanMethodProgressive);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003290 WiFiEndpointRefPtr endpoint;
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003291 MockWiFiServiceRefPtr service = AttemptConnection(
3292 WiFi::kScanMethodProgressive, &endpoint, nullptr);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003293
3294 // Simulate connection timeout.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003295 ExpectFoundNothing();
3296 EXPECT_CALL(*service,
3297 NotifyCurrentEndpoint(EndpointMatch(endpoint))).Times(0);
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003298 NiceScopedMockLog log;
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003299 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3300 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003301 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3302 EXPECT_CALL(log,
3303 Log(_, _, HasSubstr("-> PROGRESSIVE_FINISHED_NOCONNECTION")));
3304 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_)).Times(0);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003305 TimeoutPendingConnection();
3306 ScopeLogger::GetInstance()->set_verbose_level(0);
3307 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3308 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3309}
3310
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07003311TEST_F(WiFiMainTest, ScanStateUma) {
3312 EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
3313 Times(0);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003314 EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_));
Wade Guthrieb0def9f2013-07-12 13:49:18 -07003315 SetScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive, __func__);
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07003316
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003317 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_));
3318 EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
3319 SetScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive, __func__);
3320
Wade Guthriea5995cf2013-07-30 09:31:16 -07003321 ExpectScanIdle(); // After connected.
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003322 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07003323 EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _));
Wade Guthrieb0def9f2013-07-12 13:49:18 -07003324 SetScanState(WiFi::kScanConnected, WiFi::kScanMethodProgressive, __func__);
Wade Guthrieb9e0ee72013-05-31 09:23:30 -07003325}
3326
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003327TEST_F(WiFiMainTest, ScanStateNotScanningNoUma) {
3328 EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_)).Times(0);
3329 EXPECT_CALL(*metrics(), NotifyDeviceConnectStarted(_, _));
3330 SetScanState(WiFi::kScanConnecting, WiFi::kScanMethodNone, __func__);
3331
Wade Guthriea5995cf2013-07-30 09:31:16 -07003332 ExpectScanIdle(); // After connected.
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003333 EXPECT_CALL(*metrics(), NotifyDeviceConnectFinished(_));
3334 EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
3335 Times(0);
3336 SetScanState(WiFi::kScanConnected, WiFi::kScanMethodNone, __func__);
3337}
3338
3339TEST_F(WiFiMainTest, ConnectToServiceNotPending) {
3340 // Test for SetPendingService(NULL), condition a)
3341 // |ConnectTo|->|DisconnectFrom|.
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003342 StartScan(WiFi::kScanMethodProgressive);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003343
3344 // Setup pending service.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003345 ExpectScanStop();
3346 ExpectConnecting();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003347 MockWiFiServiceRefPtr service_pending(
3348 SetupConnectingService(DBus::Path(), NULL, NULL));
3349 EXPECT_EQ(service_pending.get(), GetPendingService().get());
3350
3351 // ConnectTo a different service than the pending one.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003352 ExpectConnecting();
3353 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Disconnect());
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003354 NiceScopedMockLog log;
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003355 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3356 ScopeLogger::GetInstance()->set_verbose_level(10);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003357 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3358 EXPECT_CALL(log, Log(_, _, HasSubstr("-> TRANSITION_TO_CONNECTING")));
3359 EXPECT_CALL(log, Log(_, _, HasSubstr("-> PROGRESSIVE_CONNECTING")));
3360 MockWiFiServiceRefPtr service_connecting(
3361 SetupConnectingService(DBus::Path(), NULL, NULL));
3362 ScopeLogger::GetInstance()->set_verbose_level(0);
3363 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3364 EXPECT_EQ(service_connecting.get(), GetPendingService().get());
3365 EXPECT_EQ(NULL, GetCurrentService().get());
3366 VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
Wade Guthriea5995cf2013-07-30 09:31:16 -07003367
3368 ExpectScanIdle(); // To silence messages from the destructor.
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003369}
3370
3371TEST_F(WiFiMainTest, ConnectToWithError) {
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003372 StartScan(WiFi::kScanMethodProgressive);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003373
Wade Guthriea5995cf2013-07-30 09:31:16 -07003374 ExpectScanIdle();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003375 EXPECT_CALL(*GetSupplicantInterfaceProxy(), AddNetwork(_)).
3376 WillOnce(Throw(
3377 DBus::Error(
3378 "fi.w1.wpa_supplicant1.InterfaceUnknown",
3379 "test threw fi.w1.wpa_supplicant1.InterfaceUnknown")));
3380 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_)).Times(0);
3381 EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
3382 Times(0);
Ben Chanf024ef42013-09-20 14:21:38 -07003383 EXPECT_CALL(*adaptor_, EmitBoolChanged(kScanningProperty, false));
3384 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Paul Stewarta283e4e2013-10-22 20:50:14 -07003385 EXPECT_CALL(*service, GetSupplicantConfigurationParameters());
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003386 InitiateConnect(service);
3387 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3388 EXPECT_TRUE(IsScanSessionNull());
3389}
3390
3391TEST_F(WiFiMainTest, ScanStateHandleDisconnect) {
3392 // Test for SetPendingService(NULL), condition d) Disconnect while scanning.
3393 // Start scanning.
Wade Guthrie9f4aa152013-07-29 16:03:14 -07003394 StartScan(WiFi::kScanMethodProgressive);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003395
3396 // Set the pending service.
3397 ReportScanDoneKeepScanSession();
Wade Guthriea5995cf2013-07-30 09:31:16 -07003398 ExpectScanStop();
3399 ExpectConnecting();
Ben Chanf024ef42013-09-20 14:21:38 -07003400 MockWiFiServiceRefPtr service = MakeMockService(kSecurityNone);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003401 SetPendingService(service);
3402 VerifyScanState(WiFi::kScanConnecting, WiFi::kScanMethodProgressive);
3403
3404 // Disconnect from the pending service.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003405 ExpectScanIdle();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003406 EXPECT_CALL(*metrics(), NotifyDeviceScanFinished(_)).Times(0);
3407 EXPECT_CALL(*metrics(), SendEnumToUMA(Metrics::kMetricScanResult, _, _)).
3408 Times(0);
3409 ReportCurrentBSSChanged(WPASupplicant::kCurrentBSSNull);
3410 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3411}
3412
3413TEST_F(WiFiMainTest, ConnectWhileNotScanning) {
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003414 // Setup WiFi but terminate scan.
Ben Chanf024ef42013-09-20 14:21:38 -07003415 EXPECT_CALL(*adaptor_, EmitBoolChanged(kPoweredProperty, _)).
Wade Guthriea5995cf2013-07-30 09:31:16 -07003416 Times(AnyNumber());
3417
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07003418 ExpectScanStart(WiFi::kScanMethodProgressive, false);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003419 StartWiFi();
Wade Guthriea5995cf2013-07-30 09:31:16 -07003420 dispatcher_.DispatchPendingEvents();
3421
3422 ExpectScanStop();
3423 ExpectFoundNothing();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003424 ReportScanDone();
3425 dispatcher_.DispatchPendingEvents();
Wade Guthriea5995cf2013-07-30 09:31:16 -07003426 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003427
3428 // Connecting.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003429 ExpectConnecting();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003430 EXPECT_CALL(*metrics(), NotifyDeviceScanStarted(_)).Times(0);
3431 WiFiEndpointRefPtr endpoint;
3432 ::DBus::Path bss_path;
Wade Guthriea5995cf2013-07-30 09:31:16 -07003433 NiceScopedMockLog log;
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003434 ScopeLogger::GetInstance()->EnableScopesByName("wifi");
3435 ScopeLogger::GetInstance()->set_verbose_level(10);
3436 EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber());
3437 EXPECT_CALL(log, Log(_, _, HasSubstr("-> TRANSITION_TO_CONNECTING"))).
3438 Times(0);
3439 EXPECT_CALL(log, Log(_, _, HasSubstr("-> CONNECTING (not scan related)")));
3440 MockWiFiServiceRefPtr service =
3441 SetupConnectingService(DBus::Path(), &endpoint, &bss_path);
3442
3443 // Connected.
Wade Guthriea5995cf2013-07-30 09:31:16 -07003444 ExpectConnected();
Wade Guthriedf6d61b2013-07-17 11:43:55 -07003445 EXPECT_CALL(log, Log(_, _, HasSubstr("-> CONNECTED (not scan related")));
3446 ReportCurrentBSSChanged(bss_path);
3447 ScopeLogger::GetInstance()->set_verbose_level(0);
3448 ScopeLogger::GetInstance()->EnableScopesByName("-wifi");
3449 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3450}
3451
Paul Stewart3bdd3aa2013-08-20 13:20:54 -07003452TEST_F(WiFiMainTest, BackgroundScan) {
3453 StartWiFi();
3454 SetupConnectedService(DBus::Path(), NULL, NULL);
3455 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3456
3457 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(1);
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07003458 TriggerScan(WiFi::kScanMethodFull);
Paul Stewart3bdd3aa2013-08-20 13:20:54 -07003459 dispatcher_.DispatchPendingEvents();
3460 VerifyScanState(WiFi::kScanBackgroundScanning, WiFi::kScanMethodFull);
3461
3462 ReportScanDone();
Paul Stewart7de7e022013-08-28 09:42:50 -07003463 EXPECT_CALL(*manager(), OnDeviceGeolocationInfoUpdated(_));
Paul Stewart3bdd3aa2013-08-20 13:20:54 -07003464 dispatcher_.DispatchPendingEvents(); // Launch UpdateScanStateAfterScanDone
3465 VerifyScanState(WiFi::kScanIdle, WiFi::kScanMethodNone);
3466}
3467
Wade Guthrie2ef88ad2013-07-29 15:14:18 -07003468TEST_F(WiFiMainTest, ProgressiveScanDuringFull) {
3469 StartScan(WiFi::kScanMethodFull);
3470
3471 // Now, try to slam-in a progressive scan.
3472 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
3473 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
3474 TriggerScan(WiFi::kScanMethodProgressive);
3475 dispatcher_.DispatchPendingEvents();
3476 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodFull);
3477
3478 // And, for the destructor.
3479 ExpectScanStop();
3480 ExpectScanIdle();
3481}
3482
3483TEST_F(WiFiMainTest, FullScanDuringProgressive) {
3484 StartScan(WiFi::kScanMethodProgressive);
3485
3486 // Now, try to slam-in a full scan.
3487 EXPECT_CALL(*scan_session_, InitiateScan()).Times(0);
3488 EXPECT_CALL(*GetSupplicantInterfaceProxy(), Scan(_)).Times(0);
3489 TriggerScan(WiFi::kScanMethodFull);
3490 dispatcher_.DispatchPendingEvents();
3491 VerifyScanState(WiFi::kScanScanning, WiFi::kScanMethodProgressive);
3492
3493 // And, for the destructor.
3494 ExpectScanStop();
3495 ExpectScanIdle();
3496}
3497
Paul Stewartc6fbad92013-11-13 14:50:52 -08003498TEST_F(WiFiMainTest, TDLSInterfaceFunctions) {
Paul Stewartdf4c7d62013-11-12 14:05:00 -08003499 StartWiFi();
3500 const char kPeer[] = "peer";
3501
3502 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSDiscover(StrEq(kPeer)))
3503 .WillOnce(Return())
3504 .WillOnce(Throw(
3505 DBus::Error(
3506 "fi.w1.wpa_supplicant1.UnknownError",
3507 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3508 EXPECT_TRUE(TDLSDiscover(kPeer));
3509 EXPECT_FALSE(TDLSDiscover(kPeer));
3510 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3511
3512 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSSetup(StrEq(kPeer)))
3513 .WillOnce(Return())
3514 .WillOnce(Throw(
3515 DBus::Error(
3516 "fi.w1.wpa_supplicant1.UnknownError",
3517 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3518 EXPECT_TRUE(TDLSSetup(kPeer));
3519 EXPECT_FALSE(TDLSSetup(kPeer));
3520 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3521
3522 const char kStatus[] = "peachy keen";
3523 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSStatus(StrEq(kPeer)))
3524 .WillOnce(Return(kStatus))
3525 .WillOnce(Throw(
3526 DBus::Error(
3527 "fi.w1.wpa_supplicant1.UnknownError",
3528 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3529 EXPECT_EQ(kStatus, TDLSStatus(kPeer));
3530 EXPECT_EQ("", TDLSStatus(kPeer));
3531 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3532
3533 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSTeardown(StrEq(kPeer)))
3534 .WillOnce(Return())
3535 .WillOnce(Throw(
3536 DBus::Error(
3537 "fi.w1.wpa_supplicant1.UnknownError",
3538 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3539 EXPECT_TRUE(TDLSTeardown(kPeer));
3540 EXPECT_FALSE(TDLSTeardown(kPeer));
3541 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3542}
3543
Paul Stewartc6fbad92013-11-13 14:50:52 -08003544TEST_F(WiFiMainTest, PerformTDLSOperation) {
3545 StartWiFi();
Paul Stewartc67f0bd2013-12-06 12:14:50 -08003546 const char kPeer[] = "00:11:22:33:44:55";
Paul Stewartc6fbad92013-11-13 14:50:52 -08003547
3548 {
3549 Error error;
3550 EXPECT_EQ("", PerformTDLSOperation("Do the thing", kPeer, &error));
3551 EXPECT_EQ(Error::kInvalidArguments, error.type());
3552 }
3553
Paul Stewartc67f0bd2013-12-06 12:14:50 -08003554 {
3555 Error error;
3556 EXPECT_EQ("", PerformTDLSOperation(kTDLSDiscoverOperation, "peer", &error));
3557 // This is not a valid IP address nor is it a MAC address.
3558 EXPECT_EQ(Error::kInvalidArguments, error.type());
3559 }
3560
3561 const char kAddress[] = "192.168.1.1";
3562 EXPECT_CALL(*manager(), device_info()).WillRepeatedly(Return(device_info()));
3563
3564 {
3565 // The provided IP address is not local.
3566 EXPECT_CALL(*device_info(), HasDirectConnectivityTo(kInterfaceIndex, _))
3567 .WillOnce(Return(false));
3568 Error error;
3569 EXPECT_EQ("", PerformTDLSOperation(kTDLSDiscoverOperation,
3570 kAddress, &error));
3571 EXPECT_EQ(Error::kInvalidArguments, error.type());
3572 Mock::VerifyAndClearExpectations(device_info());
3573 }
3574
3575 {
3576 // If the MAC address of the peer is in the ARP cache, we should
3577 // perform the TDLS operation on the resolved MAC.
3578 const char kResolvedMac[] = "00:11:22:33:44:55";
3579 const ByteString kMacBytes(
3580 WiFiEndpoint::MakeHardwareAddressFromString(kResolvedMac));
3581 EXPECT_CALL(*device_info(), HasDirectConnectivityTo(kInterfaceIndex, _))
3582 .WillOnce(Return(true));
3583 EXPECT_CALL(*device_info(), GetMACAddressOfPeer(kInterfaceIndex, _, _))
3584 .WillOnce(DoAll(SetArgumentPointee<2>(kMacBytes), Return(true)));
3585 EXPECT_CALL(*GetSupplicantInterfaceProxy(),
3586 TDLSDiscover(StrEq(kResolvedMac)));
3587 Error error;
3588 EXPECT_EQ("", PerformTDLSOperation(kTDLSDiscoverOperation,
3589 kAddress, &error));
3590 EXPECT_TRUE(error.IsSuccess());
3591 Mock::VerifyAndClearExpectations(device_info());
3592 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3593 }
3594
Paul Stewartc6fbad92013-11-13 14:50:52 -08003595 // This is the same test as TDLSInterfaceFunctions above, but using the
3596 // method called by the RPC adapter.
3597 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSDiscover(StrEq(kPeer)))
3598 .WillOnce(Return())
3599 .WillOnce(Throw(
3600 DBus::Error(
3601 "fi.w1.wpa_supplicant1.UnknownError",
3602 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3603 {
3604 Error error;
3605 EXPECT_EQ("", PerformTDLSOperation(kTDLSDiscoverOperation, kPeer, &error));
3606 EXPECT_TRUE(error.IsSuccess());
3607 }
3608 {
3609 Error error;
3610 EXPECT_EQ("", PerformTDLSOperation(kTDLSDiscoverOperation, kPeer, &error));
3611 EXPECT_EQ(Error::kOperationFailed, error.type());
3612 }
3613 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3614
3615 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSSetup(StrEq(kPeer)))
3616 .WillOnce(Return())
3617 .WillOnce(Throw(
3618 DBus::Error(
3619 "fi.w1.wpa_supplicant1.UnknownError",
3620 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3621 {
3622 Error error;
3623 EXPECT_EQ("", PerformTDLSOperation(kTDLSSetupOperation, kPeer, &error));
3624 EXPECT_TRUE(error.IsSuccess());
3625 }
3626 {
3627 Error error;
3628 EXPECT_EQ("", PerformTDLSOperation(kTDLSSetupOperation, kPeer, &error));
3629 EXPECT_EQ(Error::kOperationFailed, error.type());
3630 }
3631 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3632
3633
3634 const map<string, string> kTDLSStatusMap {
3635 { "Baby, I don't care", kTDLSUnknownState },
3636 { WPASupplicant::kTDLSStateConnected, kTDLSConnectedState },
3637 { WPASupplicant::kTDLSStateDisabled, kTDLSDisabledState },
3638 { WPASupplicant::kTDLSStatePeerDoesNotExist, kTDLSNonexistentState },
3639 { WPASupplicant::kTDLSStatePeerNotConnected, kTDLSDisconnectedState },
3640 };
3641
3642 for (const auto &it : kTDLSStatusMap) {
3643 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSStatus(StrEq(kPeer)))
3644 .WillOnce(Return(it.first));
3645 Error error;
3646 EXPECT_EQ(it.second,
3647 PerformTDLSOperation(kTDLSStatusOperation, kPeer, &error));
3648 EXPECT_TRUE(error.IsSuccess());
3649 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3650 }
3651
3652 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSStatus(StrEq(kPeer)))
3653 .WillOnce(Throw(
3654 DBus::Error(
3655 "fi.w1.wpa_supplicant1.UnknownError",
3656 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3657 {
3658 Error error;
3659 EXPECT_EQ("", PerformTDLSOperation(kTDLSStatusOperation, kPeer, &error));
3660 EXPECT_EQ(Error::kOperationFailed, error.type());
3661 }
3662 Mock::VerifyAndClearExpectations(GetSupplicantInterfaceProxy());
3663
3664 EXPECT_CALL(*GetSupplicantInterfaceProxy(), TDLSTeardown(StrEq(kPeer)))
3665 .WillOnce(Return())
3666 .WillOnce(Throw(
3667 DBus::Error(
3668 "fi.w1.wpa_supplicant1.UnknownError",
3669 "test threw fi.w1.wpa_supplicant1.UnknownError")));
3670 {
3671 Error error;
3672 EXPECT_EQ("", PerformTDLSOperation(kTDLSTeardownOperation, kPeer, &error));
3673 EXPECT_TRUE(error.IsSuccess());
3674 }
3675 {
3676 Error error;
3677 EXPECT_EQ("", PerformTDLSOperation(kTDLSTeardownOperation, kPeer, &error));
3678 EXPECT_EQ(Error::kOperationFailed, error.type());
3679 }
3680}
3681
Chris Masone853b81b2011-06-24 14:11:41 -07003682} // namespace shill